π€― 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(verify): move acceptance lists and comments onto @lobechat/replica (#22747)
Arvin Xuf97762817208
diff --git a/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx b/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsxindex 31518e088ff..a4b1133814d 100644--- a/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx+++ b/src/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory.tsx@@ -18,9 +18,8 @@ import { useSearchParams } from 'react-router';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useSingleton } from '@/hooks/useSingleton';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { hasVisualEvidence } from '../Evidence/evidence';@@ -194,7 +193,7 @@ const AcceptanceCheckInventory = ({try {await action();await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();return true;} catch (cause) {console.error('[acceptance:review]', cause);diff --git a/src/features/Acceptance/Viewer/Checks/AcceptanceCheckOwnerToolbar.tsx b/src/features/Acceptance/Viewer/Checks/AcceptanceCheckOwnerToolbar.tsxindex c23462a9cb6..f8cc72188c9 100644--- a/src/features/Acceptance/Viewer/Checks/AcceptanceCheckOwnerToolbar.tsx+++ b/src/features/Acceptance/Viewer/Checks/AcceptanceCheckOwnerToolbar.tsx@@ -5,9 +5,8 @@ import { Plus, Sparkles } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { hasVisualEvidence } from '../Evidence/evidence';@@ -44,7 +43,7 @@ const AcceptanceCheckOwnerToolbar = () => {const saveStanding = async (checklist: typeof standing) => {await verifyService.saveAcceptanceChecklist(subjectType, data.subject.id, checklist);await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();toast.success(t('acceptance.checkCreate.saved'));};diff --git a/src/features/Acceptance/Viewer/Comments/hooks.ts b/src/features/Acceptance/Viewer/Comments/hooks.tsindex f0da2c2fb58..1be41ce6f34 100644--- a/src/features/Acceptance/Viewer/Comments/hooks.ts+++ b/src/features/Acceptance/Viewer/Comments/hooks.ts@@ -6,6 +6,7 @@ import type {import { useCallback, useMemo } from 'react';import { acceptanceCommentService } from '@/services/acceptanceComment';+import { useVerifyStore } from '@/store/verify';import {groupCommentThreads,@@ -19,13 +20,15 @@ const EMPTY: AcceptanceCommentList = { canApprove: false, canComment: false, ite/*** The whole discussion of one acceptance, read once and shared by every- * consumer on the page through the SWR key. Mutations revalidate the list;- * the bundle itself never changes because of a comment.+ * consumer on the page through the verify store's comment replica. Mutations+ * re-read the discussion; the bundle itself never changes because of a comment.*/export const useAcceptanceComments = (acceptanceId: string | undefined) => {- const swr = useAcceptanceCommentList(acceptanceId);- const data = swr.data ?? EMPTY;- const { mutate } = swr;+ const list = useAcceptanceCommentList(acceptanceId);+ const data = list.data ?? EMPTY;+ const mutate = useCallback(async () => {+ if (acceptanceId) await useVerifyStore.getState().refreshAcceptanceComments(acceptanceId);+ }, [acceptanceId]);const threads = useMemo(() => groupCommentThreads(data.items), [data.items]);const approvals = useMemo(() => summarizeApprovals(data.items), [data.items]);@@ -68,20 +71,15 @@ export const useAcceptanceComments = (acceptanceId: string | undefined) => {const react = useCallback(async (id: string, emoji: string, on: boolean) => {if (!acceptanceId) return;- await mutate(- async () => {- await acceptanceCommentService.react(id, emoji, on);- // Read back rather than trusting the guess: the count also moves when- // someone else reacts, and the names behind it are only known here.- return acceptanceCommentService.list(acceptanceId);- },- {- optimisticData: (current) => toggleReaction(current ?? EMPTY, id, emoji, on),- revalidate: false,- },+ // Read back rather than trusting the guess: the count also moves when+ // someone else reacts, and the names behind it are only known here.+ await useVerifyStore.getState().optimisticAcceptanceComments(+ acceptanceId,+ (current) => toggleReaction(current, id, emoji, on),+ () => acceptanceCommentService.react(id, emoji, on),);},- [acceptanceId, mutate],+ [acceptanceId],);const setResolved = useCallback(async (id: string, resolved: boolean) => {@@ -102,9 +100,9 @@ export const useAcceptanceComments = (acceptanceId: string | undefined) => {* back to `canComment: false` and tells the owner to sign in, which is* both wrong and unactionable.*/- error: swr.error as Error | undefined,+ error: list.error as Error | undefined,create,- isLoading: swr.isLoading,+ isLoading: list.isLoading,items: data.items,participants,react,diff --git a/src/features/Acceptance/Viewer/Comments/useAcceptanceCommentList.ts b/src/features/Acceptance/Viewer/Comments/useAcceptanceCommentList.tsindex 04008849734..8913f62cd0b 100644--- a/src/features/Acceptance/Viewer/Comments/useAcceptanceCommentList.ts+++ b/src/features/Acceptance/Viewer/Comments/useAcceptanceCommentList.ts@@ -1,13 +1,30 @@import type { AcceptanceCommentList } from '@lobechat/types';-import { useClientDataSWR } from '@/libs/swr';-import { acceptanceCommentKeys } from '@/libs/swr/keys';-import { acceptanceCommentService } from '@/services/acceptanceComment';--/** Read access only. Hosts that display discussion need not mount its write actions. */-export const useAcceptanceCommentList = (acceptanceId?: string) =>- useClientDataSWR<AcceptanceCommentList>(- acceptanceId ? acceptanceCommentKeys.list(acceptanceId) : null,- () => acceptanceCommentService.list(acceptanceId!),- { revalidateOnFocus: true },+import { useVerifyStore, verifySelectors } from '@/store/verify';++/**+ * Read access only. Hosts that display discussion need not mount its write+ * actions. Reads the verify store's replica of `acceptanceCommentMap`, so a+ * reload paints the last discussion before the network answers.+ */+export const useAcceptanceCommentList = (acceptanceId?: string) => {+ const useFetchAcceptanceComments = useVerifyStore((s) => s.useFetchAcceptanceComments);+ const sync = useFetchAcceptanceComments(acceptanceId);+ const entry: AcceptanceCommentList | undefined = useVerifyStore(+ verifySelectors.acceptanceComments(acceptanceId),);+ const confirmed = useVerifyStore(verifySelectors.isAcceptanceCommentsConfirmed(acceptanceId));++ // A restored empty discussion is only the last session's answer: until the+ // server confirms it, it reads as loading rather than "no comments yet".+ const data = entry && (entry.items.length > 0 || confirmed) ? entry : undefined;+ // A failed background refresh keeps the last discussion on screen.+ const error = data ? undefined : sync.error;++ return {+ data,+ error,+ isLoading: !!acceptanceId && !data && !error,+ mutate: sync.revalidate,+ };+};diff --git a/src/features/Acceptance/Viewer/Focus/AcceptanceFocusWorkspace.tsx b/src/features/Acceptance/Viewer/Focus/AcceptanceFocusWorkspace.tsxindex 2ef09b52c46..c888f7a464f 100644--- a/src/features/Acceptance/Viewer/Focus/AcceptanceFocusWorkspace.tsx+++ b/src/features/Acceptance/Viewer/Focus/AcceptanceFocusWorkspace.tsx@@ -5,9 +5,8 @@ import { useTranslation } from 'react-i18next';import { useLocation, useParams, useSearchParams } from 'react-router';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { openAddCheckModal } from '../Checks/AddCheckModal';@@ -44,7 +43,7 @@ const AcceptanceFocusWorkspace = () => {if (subjectType === 'site') return;await verifyService.saveAcceptanceChecklist(subjectType, data.subject.id, checklist);await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();toast.success(t('acceptance.checkCreate.saved'));};@@ -115,7 +114,7 @@ const AcceptanceFocusWorkspace = () => {try {await verifyService.reviewChecks({ id: data.acceptance.id, ...input });await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();return true;} catch (cause) {console.error('[acceptance:review]', cause);diff --git a/src/features/Acceptance/Viewer/Gate/GateReview.tsx b/src/features/Acceptance/Viewer/Gate/GateReview.tsxindex 95880b2a3cc..58031c7484c 100644--- a/src/features/Acceptance/Viewer/Gate/GateReview.tsx+++ b/src/features/Acceptance/Viewer/Gate/GateReview.tsx@@ -28,9 +28,8 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { GoalDecisionAsker } from '@/features/AgentGoals/GoalDecision';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { useAcceptanceComments } from '../Comments/hooks';@@ -385,7 +384,7 @@ const GateDecision = memo<{try {await action();await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();onDecided?.(decision);} catch (cause) {toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceGoalEdit.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceGoalEdit.tsxindex e8e4305ab6e..400ae6ba829 100644--- a/src/features/Acceptance/Viewer/Header/AcceptanceGoalEdit.tsx+++ b/src/features/Acceptance/Viewer/Header/AcceptanceGoalEdit.tsx@@ -4,9 +4,8 @@ import { ActionIcon, toast } from '@lobehub/ui';import { PencilLine } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { useAcceptanceBundle } from '../useAcceptanceBundle';@@ -39,7 +38,7 @@ const AcceptanceGoalEdit = () => {throw cause;}await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();},});};diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsxindex a88fa495d73..f3bd1337c8d 100644--- a/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsx+++ b/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsx@@ -5,9 +5,8 @@ import { Check, Share2 } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useAcceptanceOrigin } from '@/features/Acceptance/origin';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { useAcceptanceBundle } from '../useAcceptanceBundle';@@ -73,7 +72,7 @@ const AcceptanceShare = () => {try {await verifyService.setAcceptanceVisibility(acceptanceId, visibility);await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();toast.success(t('acceptance.share.saved'));} catch (error) {toast.error(t('acceptance.actionError'));diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceStatusControl.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceStatusControl.tsxindex 1d2f9a78f00..fbe2726da7a 100644--- a/src/features/Acceptance/Viewer/Header/AcceptanceStatusControl.tsx+++ b/src/features/Acceptance/Viewer/Header/AcceptanceStatusControl.tsx@@ -5,9 +5,8 @@ import { Icon, toast } from '@lobehub/ui';import { CircleCheck, RotateCcw, X } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { getAcceptanceStatusActions } from '../statusActions';@@ -26,7 +25,7 @@ const AcceptanceStatusControl = () => {try {await verifyService.updateAcceptanceStatus(data.acceptance.id, status);await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();toast.success(t('acceptance.workspace.statusSuccess'));} catch {toast.error(t('acceptance.workspace.statusError'));diff --git a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsxindex 69e326b1da4..fbad99a2d12 100644--- a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx+++ b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx@@ -7,9 +7,8 @@ import { useTranslation } from 'react-i18next';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useIsHydrated } from '@/hooks/useIsHydrated';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { isException } from '../Checks/checkState';@@ -112,7 +111,7 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {try {await action();await mutate();- void globalMutate(isAcceptanceListKey);+ void useVerifyStore.getState().refreshAcceptanceLists();return true;} catch (cause) {console.error('[acceptance:decision]', cause);diff --git a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsxindex e4deae9cf1d..b1dbb81d696 100644--- a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx+++ b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx@@ -330,6 +330,7 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(isLoadingMore,items: pagedItems,loadMore,+ loadMoreError,...pagedRest} = useAcceptanceListInfinite(searching ? null : filter, listQuery);@@ -577,6 +578,13 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(failedIds.push(...chunks[index]);});+ // Every row that did not fail is gone server-side; drop it from the+ // persisted lists too so a reload cannot repaint it.+ const failed = new Set(failedIds);+ useVerifyStore+ .getState()+ .removeAcceptancesFromLists(targets.filter((id) => !failed.has(id)));+// The open acceptance just stopped existing β leave its dead route// rather than letting the detail pane render a 404.const redirect = acceptanceRedirectAfterDelete(@@ -896,6 +904,13 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>({isLoadingMore && (<SkeletonList rows={2} style={{ paddingBlock: 4, paddingInline: 0 }} />)}+ {Boolean(loadMoreError) && !isLoadingMore && (+ <Center paddingBlock={8}>+ <button {...stylex.props(styles.retryBtn)} type={'button'} onClick={loadMore}>+ {t('workspace.retry')}+ </button>+ </Center>+ )}</>)}</div>diff --git a/src/features/Acceptance/Workspace/AcceptanceRow.tsx b/src/features/Acceptance/Workspace/AcceptanceRow.tsxindex d28c379ed3a..96c9fea7919 100644--- a/src/features/Acceptance/Workspace/AcceptanceRow.tsx+++ b/src/features/Acceptance/Workspace/AcceptanceRow.tsx@@ -225,6 +225,8 @@ const AcceptanceRow = memo<{setMutating(true);try {const summary = await verifyService.mergeAcceptance(item.id, targetId);+ // The merged-away entry no longer exists; a reload must not repaint it.+ useVerifyStore.getState().removeAcceptancesFromLists([item.id]);if (active) navigate(acceptanceOverviewPath(targetId, routeBase), { replace: true });await Promise.all([onChanged(),@@ -251,6 +253,7 @@ const AcceptanceRow = memo<{setMutating(true);try {await verifyService.deleteAcceptance(item.id, purge);+ useVerifyStore.getState().removeAcceptancesFromLists([item.id]);if (active) navigate(acceptanceListPath(routeBase), { replace: true });await onChanged();toast.success(t('acceptance.workspace.deleteSuccess'));diff --git a/src/features/Acceptance/Workspace/MergeAcceptanceModal.tsx b/src/features/Acceptance/Workspace/MergeAcceptanceModal.tsxindex f65a03879bc..84e35616d35 100644--- a/src/features/Acceptance/Workspace/MergeAcceptanceModal.tsx+++ b/src/features/Acceptance/Workspace/MergeAcceptanceModal.tsx@@ -151,11 +151,11 @@ interface MergeContentProps {const MergeContent = memo<MergeContentProps>(({ onConfirm, source }) => {const { t: translate } = useTranslation('verify');const { close } = useModalContext();- // Revalidate on open: the dialog is a decision surface, and the list's own- // invalidations do not reach this wider window's cache key.+ // Revalidate on open: the dialog is a decision surface, so it does not ride+ // the list's shared dedupe window.const { data, error, isLoading, mutate } = useAcceptanceList(true, {+ fresh: true,limit: TARGET_WINDOW,- revalidateOnMount: true,});const [query, setQuery] = useState('');const [targetId, setTargetId] = useState<string | null>(null);diff --git a/src/features/Acceptance/Workspace/useAcceptanceListFilterMenu.tsx b/src/features/Acceptance/Workspace/useAcceptanceListFilterMenu.tsxindex 54ec284dddd..40f5b338f3f 100644--- a/src/features/Acceptance/Workspace/useAcceptanceListFilterMenu.tsx+++ b/src/features/Acceptance/Workspace/useAcceptanceListFilterMenu.tsx@@ -62,10 +62,9 @@ export const useAcceptanceListFilterMenu = ({// Projects load the first time the submenu opens β or right away when a// persisted project filter needs its name for the label.const [projectsRequested, setProjectsRequested] = useState(false);- const { data: projectData, error: projectError } = useAcceptanceProjectOptions(+ const { error: projectError, projects } = useAcceptanceProjectOptions(!hostProjectId && (projectsRequested || typeof facets.projectId === 'string'),);- const projects = projectData?.data;const withValue = (title: string, value?: string) => (value ? `${title} Β· ${value}` : title);diff --git a/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsx b/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsxindex f796c7b64ea..9939ff7d84f 100644--- a/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsx+++ b/src/features/Acceptance/Workspace/useAcceptanceProjectMenuItem.tsx@@ -7,20 +7,11 @@ import { useState } from 'react';import { useTranslation } from 'react-i18next';import { openCreateProjectModal } from '@/features/Projects/CreateProjectModal';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { projectService } from '@/services/project';+import { type ProjectListItem, useLoadedProjectList, useProjectStore } from '@/store/project';+import { PROJECT_LIST_KEY } from '@/store/project/projection';import { buildAcceptanceProjectMenuState } from './acceptanceProjectOptions';-/**- * Read and invalidation go through the same pair on purpose: `useClientDataSWR`- * and the scoped `mutate` both run the key through `augmentKey`, so workspace- * scoping stays symmetric. Plain `swr`'s global mutate cannot reach this cache- * at all (the app installs a custom provider), and hand-scoping the key here- * would double-augment it.- */-const PROJECT_OPTIONS_KEY = ['acceptance:projectOptions'];-interface AcceptanceProjectMenuParams {/** The project the acceptance is filed under, if any. */currentProjectId?: string | null;@@ -55,13 +46,23 @@ interface AcceptanceProjectMenu {* menu offers.*//**- * The caller's projects for acceptance menus, read only once `requested` β the- * filing submenu and the list's project filter share one cache entry.+ * The caller's projects for acceptance menus: the project store's list replica,+ * which the sidebar already keeps (and persists), synced only once `requested`.+ * A restored empty list is not "no projects" until the server confirms it.*/-export const useAcceptanceProjectOptions = (requested: boolean) =>- useClientDataSWR(requested ? PROJECT_OPTIONS_KEY : null, () => projectService.listAll(), {- revalidateOnFocus: false,- });+export const useAcceptanceProjectOptions = (+ requested: boolean,+): { error: unknown; projects: ProjectListItem[] | undefined } => {+ const useFetchProjectList = useProjectStore((s) => s.useFetchProjectList);+ const { error } = useFetchProjectList(requested);+ const loaded = useLoadedProjectList();+ const confirmed = useProjectStore(+ (s) => s.projectListReplica.entries[PROJECT_LIST_KEY]?.source === 'server',+ );+ const projects = loaded && (loaded.length > 0 || confirmed) ? loaded : undefined;+ // A failed background refresh keeps the last list on screen.+ return { error: projects ? undefined : error, projects };+};export const useAcceptanceProjectMenu = ({currentProjectId,@@ -71,13 +72,9 @@ export const useAcceptanceProjectMenu = ({const { t } = useTranslation('verify');const [requested, setRequested] = useState(false);- const { data, error } = useAcceptanceProjectOptions(requested);+ const { error, projects } = useAcceptanceProjectOptions(requested);- const state = buildAcceptanceProjectMenuState({- currentProjectId,- error,- projects: data?.data,- });+ const state = buildAcceptanceProjectMenuState({ currentProjectId, error, projects });const placeholder = (key: string, label: string): DropdownItem[] => [{ disabled: true, key, label },@@ -107,9 +104,7 @@ export const useAcceptanceProjectMenu = ({onClick: () =>openCreateProjectModal({onCreated: (project) => {- // This row's submenu is already subscribed, so nothing refetches it- // on the next open β the new project has to be pushed into the cache.- void mutate(PROJECT_OPTIONS_KEY);+ // `createProject` already put the new project into the list replica.onSelect(project.id);},}),diff --git a/src/features/Acceptance/Workspace/useAcceptanceProjectOptions.test.ts b/src/features/Acceptance/Workspace/useAcceptanceProjectOptions.test.tsnew file mode 100644index 00000000000..c697622bf2f--- /dev/null+++ b/src/features/Acceptance/Workspace/useAcceptanceProjectOptions.test.ts@@ -0,0 +1,67 @@+/**+ * @vitest-environment happy-dom+ *+ * The acceptance project menus read the project store's list replica instead of+ * fetching `project.listAll` again under their own cache key.+ */+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { projectService } from '@/services/project';+import { useProjectStore } from '@/store/project';++import { useAcceptanceProjectOptions } from './useAcceptanceProjectMenuItem';++const project = (id: string) => ({ id, name: id }) as never;++const seed = (items: unknown[] | undefined, source?: 'server' | 'storage', error?: unknown) => {+ act(() =>+ useProjectStore.setState({+ projectListMap: items ? { all: items as never } : {},+ projectListReplica: {+ entries: source ? { all: { pending: [], source, updatedAt: 1 } } : {},+ } as never,+ useFetchProjectList: () =>+ ({ error, isHydrated: true, isValidating: false, revalidate: vi.fn() }) as never,+ }),+ );+};++describe('useAcceptanceProjectOptions', () => {+ beforeEach(() => {+ vi.spyOn(projectService, 'listAll').mockResolvedValue({ data: [] } as never);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('reuses the project list replica without a request of its own', () => {+ seed([project('p1')], 'server');++ const { result } = renderHook(() => useAcceptanceProjectOptions(true));++ expect(result.current.projects?.map((item) => item.id)).toEqual(['p1']);+ expect(projectService.listAll).not.toHaveBeenCalled();+ });++ it('treats a restored empty project list as loading until the server confirms it', () => {+ seed([], 'storage');+ const { result, rerender } = renderHook(() => useAcceptanceProjectOptions(true));+ // "No projects yet" would invite creating a duplicate of one the user owns.+ expect(result.current.projects).toBeUndefined();++ seed([], 'server');+ rerender();+ expect(result.current.projects).toEqual([]);+ });++ it('keeps the last projects when a background refresh fails', () => {+ seed([project('p1')], 'storage', new Error('offline'));++ const { result } = renderHook(() => useAcceptanceProjectOptions(true));++ expect(result.current.projects?.map((item) => item.id)).toEqual(['p1']);+ expect(result.current.error).toBeUndefined();+ });+});diff --git a/src/features/Acceptance/acceptanceFirstPaint.test.ts b/src/features/Acceptance/acceptanceFirstPaint.test.tsnew file mode 100644index 00000000000..789aab038bf--- /dev/null+++ b/src/features/Acceptance/acceptanceFirstPaint.test.ts@@ -0,0 +1,122 @@+/**+ * @vitest-environment happy-dom+ *+ * Reload behavior of the acceptance list panel, the workspace shell's list read+ * and the discussion: with last session's rows in IndexedDB, the first frame+ * shows them while the network is still out. Only public hooks and the app's+ * storage adapter are imported, so the same assertions run against the+ * pre-replica SWR hooks (which painted a skeleton instead).+ */+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 { useAcceptanceList, useAcceptanceListInfinite } from '@/features/Acceptance/hooks';+import { useAcceptanceCommentList } from '@/features/Acceptance/Viewer/Comments/useAcceptanceCommentList';+import { AppIndexedDBStorage, cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { acceptanceCommentService } from '@/services/acceptanceComment';+import { verifyService } from '@/services/verify';++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,+ );++/** The persisted rows the replicas write: `replica:<name>:v<version>`. */+const storageOf = (name: string) =>+ new AppIndexedDBStorage<any>({ namespace: `replica:${name}:v1` });++const row = (id: string) => ({ id, subject: { title: id }, subjectId: `subject-${id}` });++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+};++describe('acceptance first paint after reload', () => {+ let scope = '';++ beforeEach(() => {+ scope = `first-paint-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it('paints the list panel feed from storage, then the server answer', async () => {+ await storageOf('acceptancePage').set(+ { queryKey: 'all|||', scope },+ {+ data: { currentPage: 0, hasMore: false, items: [row('stored')], nextCursor: null },+ updatedAt: 1,+ },+ );+ const network = deferred<unknown>();+ vi.spyOn(verifyService, 'listAcceptancePage').mockReturnValue(network.promise as never);++ const { result } = renderHook(() => useAcceptanceListInfinite('all'), { wrapper });++ await waitFor(() => expect(result.current.items.map((item) => item.id)).toEqual(['stored']));+ expect(result.current.isLoadingInitial).toBe(false);++ await act(async () => network.resolve({ items: [row('fresh')], nextCursor: null }));+ await waitFor(() => expect(result.current.items.map((item) => item.id)).toEqual(['fresh']));+ });++ it('paints the workspace list read from storage, then the server answer', async () => {+ await storageOf('acceptanceList').set(+ { queryKey: 'all|||||', scope },+ { data: [row('stored')], updatedAt: 1 },+ );+ const network = deferred<unknown>();+ vi.spyOn(verifyService, 'listAcceptances').mockReturnValue(network.promise as never);++ const { result } = renderHook(() => useAcceptanceList(true, { filter: 'all' }), { wrapper });++ await waitFor(() => expect(result.current.data?.map((item) => item.id)).toEqual(['stored']));+ expect(result.current.isLoading).toBe(false);++ await act(async () => network.resolve([row('fresh')]));+ await waitFor(() => expect(result.current.data?.map((item) => item.id)).toEqual(['fresh']));+ });++ it('paints the discussion from storage, then the server answer', async () => {+ const list = (id: string) => ({ canApprove: false, canComment: true, items: [{ id }] });+ await storageOf('acceptanceComment').set(+ { queryKey: 'acc-1', scope },+ { data: list('stored'), updatedAt: 1 },+ );+ const network = deferred<unknown>();+ vi.spyOn(acceptanceCommentService, 'list').mockReturnValue(network.promise as never);++ const { result } = renderHook(() => useAcceptanceCommentList('acc-1'), { wrapper });++ await waitFor(() => expect(result.current.data?.items[0]?.id).toBe('stored'));+ expect(result.current.isLoading).toBe(false);++ await act(async () => network.resolve(list('fresh')));+ await waitFor(() => expect(result.current.data?.items[0]?.id).toBe('fresh'));+ });+});diff --git a/src/features/Acceptance/hooks.test.ts b/src/features/Acceptance/hooks.test.tsindex 17f0daa8e24..5d88bccd969 100644--- a/src/features/Acceptance/hooks.test.ts+++ b/src/features/Acceptance/hooks.test.ts@@ -3,7 +3,7 @@ import type { PropsWithChildren } from 'react';import { createElement } from 'react';import type { Cache } from 'swr';import { SWRConfig } from 'swr';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { verifyService } from '@/services/verify';@@ -15,20 +15,12 @@ import {useVerifyReportBundle,} from './hooks';-const useSWRInfiniteMock = vi.hoisted(() => vi.fn());--vi.mock('swr/infinite', () => ({ default: useSWRInfiniteMock }));-const createSWRWrapper = (cache: Cache) =>function SWRTestWrapper({ children }: PropsWithChildren) {return createElement(SWRConfig, { value: { provider: () => cache } }, children);};describe('Verify data hooks', () => {- beforeEach(() => {- useSWRInfiniteMock.mockReset();- });-afterEach(() => {vi.restoreAllMocks();});diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.tsindex b1395ddf786..f1059d40de2 100644--- a/src/features/Acceptance/hooks.ts+++ b/src/features/Acceptance/hooks.ts@@ -1,36 +1,25 @@import type { CreatableAcceptanceSubjectType } from '@lobechat/types';-import { useCallback, useEffect, useRef, useState } from 'react';-import useSWRInfinite from 'swr/infinite';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useClientDataSWR } from '@/libs/swr';import { verifyKeys } from '@/libs/swr/keys';import { documentService } from '@/services/document';import type {AcceptanceBySubject,AcceptanceListFilter,- AcceptanceListPage,+ AcceptanceListItem,AcceptanceListQuery,} from '@/services/verify';import { verifyService } from '@/services/verify';import { useVerifyStore, verifySelectors } from '@/store/verify';+import type { AcceptanceListParams, AcceptancePageParams } from '@/store/verify/projection';-const ACCEPTANCE_PAGE_SIZE = 30;const VERIFY_REPORT_SWR_CONFIG = {revalidateIfStale: false,revalidateOnFocus: false,revalidateOnReconnect: false,} as const;-// The acceptance bundle is a LIVE decision surface β rounds run and reviews land-// while the reviewer is away β so unlike the immutable report snapshots it-// revalidates on focus/reconnect. Coming back to the tab shows the current state-// without a manual refresh (focus is throttled by SWR's default 5s).-const ACCEPTANCE_BUNDLE_SWR_CONFIG = {- revalidateOnFocus: true,- revalidateOnReconnect: true,-} as const;-/*** Poll until the aggregate exists AND stops moving.*@@ -143,46 +132,53 @@ export const useAcceptanceBySubject = (};};+const EMPTY_ITEMS: AcceptanceListItem[] = [];+/**- * The caller's recent acceptance aggregates (with subject headers) β the list- * panel. `limit` widens the recency window for surfaces that must reach further- * back than the panel does (the merge target picker).+ * The caller's recent acceptance aggregates (with subject headers), read from+ * the verify store's replica of `acceptanceListMap`. `limit` widens the recency+ * window for surfaces that must reach further back than the panel does (the+ * merge target picker); `fresh` skips the shared dedupe window on mount.*- * A widened window is its own SWR key. Mutations invalidate the whole- * `verify:acceptances` key family so every filter / limit / search variant- * revalidates together.+ * Every write revalidates all list entries together+ * (`useVerifyStore.getState().refreshAcceptanceLists()`).*/export const useAcceptanceList = (enabled: boolean,options?: AcceptanceListQuery & {+ fresh?: boolean;limit?: number;q?: string;- revalidateOnMount?: boolean;},-) =>- useClientDataSWR(- enabled- ? verifyKeys.acceptances(options?.limit, options?.q, {- filter: options?.filter,- projectId: options?.projectId,- scope: options?.scope,- source: options?.source,- })- : null,- () =>- verifyService.listAcceptances({+) => {+ const params: AcceptanceListParams | null = enabled+ ? {filter: options?.filter,limit: options?.limit,projectId: options?.projectId,q: options?.q,scope: options?.scope,source: options?.source,- }),- {- ...VERIFY_REPORT_SWR_CONFIG,- ...(options?.revalidateOnMount ? { revalidateOnMount: true } : {}),- },- );+ }+ : null;+ const useFetchAcceptanceList = useVerifyStore((s) => s.useFetchAcceptanceList);+ const sync = useFetchAcceptanceList(params, { fresh: options?.fresh });+ const entry = useVerifyStore(verifySelectors.acceptanceList(params));+ const confirmed = useVerifyStore(verifySelectors.isAcceptanceListConfirmed(params));++ // A restored empty list is only the last session's answer: until the server+ // confirms it, "no acceptances" is still loading (not onboarding or an empty state).+ const data = entry && (entry.length > 0 || confirmed) ? entry : undefined;+ // A failed background refresh keeps the last list on screen.+ const error = data ? undefined : sync.error;++ return {+ data,+ error,+ isLoading: enabled && !data && !error,+ mutate: sync.revalidate,+ };+};/** Rounds, evidence files and bytes a delete would purge. Pass null to skip. */export const useAcceptancePurgePreview = (acceptanceId: string | null) =>@@ -194,101 +190,58 @@ export const useAcceptancePurgePreview = (acceptanceId: string | null) =>/*** The panel's scroll feed: keyset pages, newest first, with the in-progress /- * completed split applied server-side (see `acceptance.listPage`).+ * completed split applied server-side (see `acceptance.listPage`), read from+ * the verify store's paged replica (`acceptancePageMap`). The head page+ * survives a reload, so the panel paints its last rows before the network.** A `null` filter disables the feed entirely β that is how the panel hands off- * to the flat search read. Changing the filter starts a fresh key series, so the- * loaded depth collapses back to one page rather than cascading a refetch of as- * many pages as the previous view had open.+ * to the flat search read. Switching to a feed collapses it back to its head+ * page rather than refetching as many pages as an earlier visit had open.*/export const useAcceptanceListInfinite = (filter: AcceptanceListFilter | null,query: Omit<AcceptanceListQuery, 'filter'> = {},) => {- const workspaceId = useActiveWorkspaceId();const { projectId, scope, source } = query;-- const getKey = useCallback(- (_index: number, previous: AcceptanceListPage | null) => {- if (previous && previous.nextCursor === null) return null;- if (!filter) return null;- return verifyKeys.acceptancePage(- workspaceId ?? undefined,- { filter, projectId, scope, source },- previous?.nextCursor ?? undefined,- );- },- [filter, projectId, scope, source, workspaceId],- );-- const { data, error, isLoading, mutate, setSize, size } = useSWRInfinite(- getKey,- // Read the narrowing from the closure, not the key: the key spells the- // unfiled project as a sentinel string, the server wants `null`.- (key: readonly string[]) =>- verifyService.listAcceptancePage({- cursor: key.at(-1) || undefined,- filter: filter ?? undefined,- limit: ACCEPTANCE_PAGE_SIZE,- projectId,- scope,- source,- }),- { ...VERIFY_REPORT_SWR_CONFIG, revalidateFirstPage: false },+ const params = useMemo<AcceptancePageParams | null>(+ () => (filter ? { filter, projectId, scope, source } : null),+ [filter, projectId, scope, source],);+ const useFetchAcceptancePage = useVerifyStore((s) => s.useFetchAcceptancePage);+ const sync = useFetchAcceptancePage(params);+ const entry = useVerifyStore(verifySelectors.acceptancePage(params));+ const confirmed = useVerifyStore(verifySelectors.isAcceptancePageConfirmed(params));useEffect(() => {- setSize(1);- }, [filter, projectId, scope, source, workspaceId, setSize]);+ if (params) useVerifyStore.getState().collapseAcceptancePage(params);+ }, [params]);const loadMore = useCallback(() => {- void setSize((s) => s + 1);- }, [setSize]);-- // SWR leaves a failed/pending page's slot `undefined`, so guard the holes.- const items = data?.flatMap((page) => page?.items ?? []) ?? [];- const lastLoadedPage = data?.findLast(Boolean);- const reachedEnd = lastLoadedPage ? lastLoadedPage.nextCursor === null : false;- const hasLoadedPages = data !== undefined;+ if (params) void useVerifyStore.getState().loadMoreAcceptancePage(params);+ }, [params]);- const isLoadingInitial = !error && isLoading && !hasLoadedPages;- const isLoadingMore =- !error && hasLoadedPages && size > 0 && typeof data[size - 1] === 'undefined';+ // A restored empty head is not a settled "no acceptances" until the server says so.+ const settled = !!entry && (entry.items.length > 0 || confirmed);+ const items = settled ? entry.items : EMPTY_ITEMS;+ // A failed background refresh keeps the rows on screen; only a feed with+ // nothing to show reads as failed.+ const error = settled ? undefined : sync.error;+ const loadMoreError = settled ? entry.loadMoreError : undefined;return {error,- // Pause the sentinel while an error is showing so it cannot hot-loop the- // failed page; the panel offers a manual retry instead.- hasMore: !reachedEnd && !error,- isLoadingInitial,- isLoadingMore,+ // Pause the sentinel while a page error is showing so it cannot hot-loop+ // the failed page; the panel offers a manual retry instead.+ hasMore: settled && entry.hasMore && !loadMoreError,+ isLoadingInitial: !!params && !settled && !error,+ isLoadingMore: settled && !!entry.isLoadingMore,items,loadMore,- mutate,+ loadMoreError,+ mutate: sync.revalidate,};};-/**- * Acceptance status for a known subject set β one read for a whole list.- *- * Not `useAcceptanceList`: that feed is capped at the newest rows across every- * subject type, so any subject pushed past the cap would read as having no- * acceptance at all. Revalidates on focus like the bundle, because a delivery- * that lands while the tab sits open has to show up without a reload.- */-export const useAcceptanceStatuses = (- subjectType: CreatableAcceptanceSubjectType,- subjectIds: string[],- enabled = true,-) =>- useClientDataSWR(- enabled && subjectIds.length > 0- ? verifyKeys.acceptanceStatuses(subjectType, subjectIds)- : null,- () => verifyService.listAcceptanceStatuses(subjectType, subjectIds),- ACCEPTANCE_BUNDLE_SWR_CONFIG,- );-/** Model / token / latency for an LLM verifier judgment. Pass null to skip. */export const useVerifierTracing = (tracingId: string | null | undefined) =>useClientDataSWR(tracingId ? verifyKeys.tracing(tracingId) : null, () =>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsxindex 8b2ff69a81d..fdcda592069 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx@@ -46,6 +46,7 @@ import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';import { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';+import { useVerifyStore } from '@/store/verify';import GoalRoundTimeline from './GoalRoundTimeline';import { resolveTaskAcceptanceRequirement } from './resolveTaskAcceptanceProjection';@@ -217,6 +218,8 @@ const TaskAcceptance = memo<TaskAcceptanceProps>(({ variant = 'default' }) => {verifyCriteriaIds: null,});await verifyService.deleteAcceptance(acceptanceSubject.id, purge);+ useVerifyStore.getState().removeAcceptancesFromLists([acceptanceSubject.id]);+ void useVerifyStore.getState().refreshAcceptanceLists();await mutateSubject();},});diff --git a/src/features/Portal/Acceptance/useMoreMenu.ts b/src/features/Portal/Acceptance/useMoreMenu.tsindex 524fb81476a..1e144d11244 100644--- a/src/features/Portal/Acceptance/useMoreMenu.ts+++ b/src/features/Portal/Acceptance/useMoreMenu.ts@@ -6,8 +6,6 @@ import { useAcceptanceBundle } from '@/features/Acceptance/hooks';import { openAcceptanceDeleteConfirm } from '@/features/Acceptance/Workspace/AcceptanceDeleteConfirm';import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';import { usePermission } from '@/hooks/usePermission';-import { mutate as globalMutate } from '@/libs/swr';-import { isAcceptanceListKey } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';import { useChatStore } from '@/store/chat';import { useVerifyStore } from '@/store/verify';@@ -32,7 +30,7 @@ export const useAcceptanceMoreMenu = (): PortalMoreMenuConfig | undefined => {const refreshAll = () =>Promise.all([useVerifyStore.getState().refreshAcceptanceBundle(acceptanceId),- globalMutate(isAcceptanceListKey),+ useVerifyStore.getState().refreshAcceptanceLists(),]);return {@@ -46,7 +44,8 @@ export const useAcceptanceMoreMenu = (): PortalMoreMenuConfig | undefined => {await verifyService.deleteAcceptance(acceptanceId, purge);// Close the panel first: the bundle it shows no longer exists.clearPortalStack();- await globalMutate(isAcceptanceListKey);+ useVerifyStore.getState().removeAcceptancesFromLists([acceptanceId]);+ await useVerifyStore.getState().refreshAcceptanceLists();toast.success(t('acceptance.workspace.deleteSuccess'));},title,diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.tsindex c96f8049f78..2d2cb411a34 100644--- a/src/libs/swr/keys.frozen.test.ts+++ b/src/libs/swr/keys.frozen.test.ts@@ -14,7 +14,6 @@ import * as keyRegistry from './keys';*/const LEGACY_SWR_KEYS = ['acceptanceCollaborationKeys.conversation',- 'acceptanceCommentKeys.list','agentConfigKeys.search','agentHomeKeys.topics','agentSignalKeys.receipts',@@ -179,10 +178,7 @@ const LEGACY_SWR_KEYS = ['userMemoryKeys.preferences','userMemoryKeys.retrieve','userMemoryKeys.tags',- 'verifyKeys.acceptancePage','verifyKeys.acceptancePurgePreview',- 'verifyKeys.acceptanceStatuses',- 'verifyKeys.acceptances','verifyKeys.criteria','verifyKeys.instruction','verifyKeys.reportBundle',diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 01d973e594c..80b34ff75c8 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -2,14 +2,7 @@ import { replicaKeys } from 'local-replica';import { unstable_serialize } from 'swr';import { describe, expect, it } from 'vitest';-import {- documentCommentKeys,- isAcceptanceListKey,- isDocumentCommentKeyForEvent,- recentKeys,- verifyKeys,- workKeys,-} from './keys';+import { documentCommentKeys, isDocumentCommentKeyForEvent, recentKeys, workKeys } from './keys';import { CACHE_TIERS } from './localStorageProvider';describe('recentKeys', () => {@@ -56,39 +49,6 @@ describe('replica sync keys', () => {});});-describe('isAcceptanceListKey', () => {- it('matches every Acceptance list variant without matching detail keys', () => {- expect(isAcceptanceListKey(['verify:acceptances', '', '', 'active'])).toBe(true);- expect(isAcceptanceListKey(['verify:acceptances', '100', 'needle', 'all', 'workspace-1'])).toBe(- true,- );- expect(isAcceptanceListKey(['verify:acceptancePurgePreview', 'acceptance-1'])).toBe(false);- });-- it('keeps project-scoped acceptance feeds in separate cache entries', () => {- expect(- verifyKeys.acceptances(undefined, undefined, { filter: 'all', projectId: 'project-1' }),- ).not.toEqual(- verifyKeys.acceptances(undefined, undefined, { filter: 'all', projectId: 'project-2' }),- );- expect(- verifyKeys.acceptancePage('workspace-1', { filter: 'all', projectId: 'project-1' }),- ).not.toEqual(- verifyKeys.acceptancePage('workspace-1', { filter: 'all', projectId: 'project-2' }),- );- });-- it('keeps the unfiled, scope and source narrowings in separate cache entries', () => {- const base = { filter: 'all' };- const page = (query: Parameters<typeof verifyKeys.acceptancePage>[1]) =>- verifyKeys.acceptancePage('workspace-1', query);-- expect(page({ ...base, projectId: null })).not.toEqual(page(base));- expect(page({ ...base, scope: 'participated' })).not.toEqual(page(base));- expect(page({ ...base, source: 'goal' })).not.toEqual(page({ ...base, source: 'task' }));- });-});-describe('workKeys', () => {it('keeps the Resources Private and Workspace galleries in separate cache entries', () => {expect(workKeys.workspace('workspace-1', 'all', null, 'private')).not.toEqual(diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 9cb5f97c856..148454defeb 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -161,14 +161,6 @@ export const topicKeys = {),};-// ---- acceptance comment --------------------------------------------------export const acceptanceCommentKeys = {- list: def('acceptanceComment:list', (acceptanceId: string) => [- 'acceptanceComment:list',- acceptanceId,- ]),-};-// ---- acceptance collaboration -------------------------------------------export const acceptanceCollaborationKeys = {conversation: def('acceptanceCollaboration:conversation', (acceptanceId: string) => [@@ -670,59 +662,11 @@ export const expertiseKeys = {rules: def('expertise:rules', () => ['expertise:rules']),};-/** The Acceptance list narrowing as key parts β mirrors `AcceptanceListQuery`. */-interface AcceptanceListKeyQuery {- filter?: string;- projectId?: string | null;- scope?: string;- source?: string;-}--const acceptanceListKeyParts = ({ filter, projectId, scope, source }: AcceptanceListKeyQuery) => [- filter ?? '',- // `null` (no project) and `undefined` (any project) are different reads.- projectId === null ? '~none' : (projectId ?? ''),- scope ?? '',- source ?? '',-];-export const verifyKeys = {- /** Statuses for a known subject set. Ids are sorted+joined so the key is order-free. */- acceptanceStatuses: def(- 'verify:acceptanceStatuses',- (subjectType: string, subjectIds: string[]) => [- 'verify:acceptanceStatuses',- subjectType,- [...subjectIds].sort().join(','),- ],- ),- /**- * One scroll page of the list panel. Keyed by workspace + the status split +- * the cursor.- */acceptancePurgePreview: def('verify:acceptancePurgePreview', (acceptanceId: string) => ['verify:acceptancePurgePreview',acceptanceId,]),- acceptancePage: def(- 'verify:acceptancePage',- (workspaceId: string | undefined, query: AcceptanceListKeyQuery, cursor?: string) => [- 'verify:acceptancePage',- workspaceId ?? '',- ...acceptanceListKeyParts(query),- cursor ?? '',- ],- ),- /** Query inputs are part of the key so server-side list filtering never reuses stale rows. */- acceptances: def(- 'verify:acceptances',- (limit?: number, q?: string, query: AcceptanceListKeyQuery = {}) => [- 'verify:acceptances',- String(limit ?? ''),- q ?? '',- ...acceptanceListKeyParts(query),- ],- ),criteria: def('verify:criteria', () => ['verify:criteria']),instruction: def('verify:instruction', (documentId: string) => ['verify:instruction',@@ -746,15 +690,6 @@ export const verifyKeys = {tracing: def('verify:tracing', (tracingId: string) => ['verify:tracing', tracingId]),};-/**- * Match every cached Acceptance list read β the flat window's filter / limit /- * search variants AND every loaded page of the panel's scroll feed. A write has- * no idea how deep the panel has scrolled, so it invalidates the whole family.- */-export const isAcceptanceListKey = (key: unknown): boolean =>- Array.isArray(key) &&- (key[0] === verifyKeys.acceptances.root || key[0] === verifyKeys.acceptancePage.root);-// ---- inbox / notifications ----------------------------------------------export const inboxKeys = {navigationCounts: def('inbox:navigationCounts', (workspaceId: string | null) => [@@ -1084,7 +1019,6 @@ export const swrKeys = {tool: toolKeys,topic: topicKeys,acceptanceCollaboration: acceptanceCollaborationKeys,- acceptanceComment: acceptanceCommentKeys,documentComment: documentCommentKeys,documentLike: documentLikeKeys,topicAction: topicActionKeys,diff --git a/src/store/verify/acceptanceList.replica.test.ts b/src/store/verify/acceptanceList.replica.test.tsnew file mode 100644index 00000000000..e790b73bcc4--- /dev/null+++ b/src/store/verify/acceptanceList.replica.test.ts@@ -0,0 +1,351 @@+/**+ * @vitest-environment happy-dom+ *+ * The acceptance list reads (`acceptanceListMap`, the panel's paged feed in+ * `acceptancePageMap`) and each acceptance's discussion (`acceptanceCommentMap`)+ * are replicas persisted to IndexedDB: a reload paints the last rows before the+ * network answers, then the server's answer replaces them.+ */+import { randomUUID } from 'node:crypto';++import type { AcceptanceCommentList } 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 { useAcceptanceList, useAcceptanceListInfinite } from '@/features/Acceptance/hooks';+import { useAcceptanceCommentList } from '@/features/Acceptance/Viewer/Comments/useAcceptanceCommentList';+import { cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { acceptanceCommentService } from '@/services/acceptanceComment';+import type { AcceptanceListItem } from '@/services/verify';+import { verifyService } from '@/services/verify';++import { useVerifyStore } from './index';+import { initialState } from './initialState';+import {+ acceptanceCommentResource,+ acceptanceListKey,+ type AcceptanceListParams,+ acceptanceListResource,+ type AcceptancePageData,+ acceptancePageKey,+ type AcceptancePageParams,+ acceptancePageResource,+} from './projection';++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 row = (id: string, title = id) =>+ ({ id, subject: { title }, subjectId: `subject-${id}` }) as unknown as AcceptanceListItem;++const pageData = (items: AcceptanceListItem[]): AcceptancePageData => ({+ currentPage: 0,+ hasMore: false,+ items,+ nextCursor: null,+});++const comments = (ids: string[]): AcceptanceCommentList =>+ ({+ canApprove: false,+ canComment: true,+ items: ids.map((id) => ({ content: id, id })),+ }) as unknown as AcceptanceCommentList;++/** A fetch the test settles by hand: the first frame can only come from storage. */+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 FEED: AcceptancePageParams = { filter: 'all' };+const ALL: AcceptanceListParams = { filter: 'all' };++describe('acceptance list and comment replicas', () => {+ let scope = '';++ const pageStorage = acceptancePageResource.storage!;+ const listStorage = acceptanceListResource.storage!;+ const commentStorage = acceptanceCommentResource.storage!;++ const persistPage = (params: AcceptancePageParams, data: AcceptancePageData, at = scope) =>+ pageStorage.set(+ { queryKey: acceptancePageResource.storageKey(params), scope: at },+ { data, updatedAt: 1 },+ );+ const persistList = (params: AcceptanceListParams, data: AcceptanceListItem[], at = scope) =>+ listStorage.set(+ { queryKey: acceptanceListResource.storageKey(params), scope: at },+ { data, updatedAt: 1 },+ );+ const storedPage = async (params: AcceptancePageParams) =>+ (await pageStorage.get({ queryKey: acceptancePageResource.storageKey(params), scope }))?.data;+ const storedList = async (params: AcceptanceListParams) =>+ (await listStorage.get({ queryKey: acceptanceListResource.storageKey(params), scope }))?.data;++ beforeEach(() => {+ scope = `acceptance-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useVerifyStore.setState(initialState, false));+ });++ afterEach(async () => {+ cleanup();+ // Each test runs in a fresh random scope; only the index rows are shared names.+ for (const storage of [pageStorage, listStorage, commentStorage]) {+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope });+ }+ vi.restoreAllMocks();+ });++ it('paints the persisted feed head before the network answers, then refreshes it', async () => {+ await persistPage(FEED, pageData([row('a1', 'Stored')]));+ const network = deferred<{ items: AcceptanceListItem[]; nextCursor: string | null }>();+ vi.spyOn(verifyService, 'listAcceptancePage').mockReturnValue(network.promise as never);++ const { result } = renderHook(() => useAcceptanceListInfinite('all'), { wrapper });++ // The list panel has its last rows on the first painted frame after reload.+ await waitFor(() => expect(result.current.items.map((item) => item.id)).toEqual(['a1']));+ expect(result.current.isLoadingInitial).toBe(false);++ await act(async () => network.resolve({ items: [row('a2'), row('a1')], nextCursor: null }));+ await waitFor(() => expect(result.current.items.map((item) => item.id)).toEqual(['a2', 'a1']));+ });++ it('reads a restored empty feed as loading until the server confirms it', async () => {+ await persistPage(FEED, pageData([]));+ const network = deferred<{ items: AcceptanceListItem[]; nextCursor: string | null }>();+ vi.spyOn(verifyService, 'listAcceptancePage').mockReturnValue(network.promise as never);++ const { result } = renderHook(() => useAcceptanceListInfinite('all'), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().acceptancePageMap['all|||']).toBeDefined(),+ );+ // An empty snapshot from the last session is not "no acceptances" yet.+ expect(result.current.isLoadingInitial).toBe(true);++ await act(async () => network.resolve({ items: [], nextCursor: null }));+ await waitFor(() => expect(result.current.isLoadingInitial).toBe(false));+ expect(result.current.items).toEqual([]);+ });++ it('keeps the rows on screen when a background refresh fails', async () => {+ await persistPage(FEED, pageData([row('a1')]));+ const network = deferred<never>();+ vi.spyOn(verifyService, 'listAcceptancePage').mockReturnValue(network.promise as never);++ const { result } = renderHook(() => useAcceptanceListInfinite('all'), { wrapper });+ await waitFor(() => expect(result.current.items).toHaveLength(1));++ await act(async () => {+ network.reject(new Error('offline'));+ await network.promise.catch(() => {});+ });+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(result.current.items.map((item) => item.id)).toEqual(['a1']);+ expect(result.current.error).toBeUndefined();+ });++ it('drops a deleted acceptance from every list and from storage', async () => {+ await persistPage(FEED, pageData([row('a1'), row('a2')]));+ await persistList(ALL, [row('a1'), row('a2')]);+ vi.spyOn(verifyService, 'listAcceptancePage').mockReturnValue(new Promise(() => {}) as never);+ vi.spyOn(verifyService, 'listAcceptances').mockReturnValue(new Promise(() => {}) as never);++ const feed = renderHook(() => useAcceptanceListInfinite('all'), { wrapper });+ const list = renderHook(() => useAcceptanceList(true, ALL), { wrapper });+ await waitFor(() => expect(feed.result.current.items).toHaveLength(2));+ await waitFor(() => expect(list.result.current.data).toHaveLength(2));++ act(() => useVerifyStore.getState().removeAcceptancesFromLists(['a1']));++ expect(feed.result.current.items.map((item) => item.id)).toEqual(['a2']);+ expect(list.result.current.data?.map((item) => item.id)).toEqual(['a2']);+ // A reload must not paint the deleted row back from IndexedDB.+ await waitFor(async () =>+ expect((await storedPage(FEED))?.items.map((item) => item.id)).toEqual(['a2']),+ );+ await waitFor(async () =>+ expect((await storedList(ALL))?.map((item) => item.id)).toEqual(['a2']),+ );+ });++ it('paints the persisted flat list and gates a restored empty one behind the server', async () => {+ await persistList(ALL, [row('a1')]);+ await persistList({ filter: 'all', projectId: 'p1' }, []);+ const network = deferred<AcceptanceListItem[]>();+ vi.spyOn(verifyService, 'listAcceptances').mockReturnValue(network.promise);++ const filled = renderHook(() => useAcceptanceList(true, ALL), { wrapper });+ const empty = renderHook(() => useAcceptanceList(true, { filter: 'all', projectId: 'p1' }), {+ wrapper,+ });++ await waitFor(() => expect(filled.result.current.data?.map((item) => item.id)).toEqual(['a1']));+ await waitFor(() =>+ expect(+ useVerifyStore.getState().acceptanceListMap[+ acceptanceListKey({ filter: 'all', projectId: 'p1' })+ ],+ ).toEqual([]),+ );+ // Onboarding / empty states read `data`: a restored empty list must not show them.+ expect(empty.result.current.data).toBeUndefined();+ expect(empty.result.current.isLoading).toBe(true);++ await act(async () => network.resolve([]));+ await waitFor(() => expect(empty.result.current.data).toEqual([]));+ expect(empty.result.current.isLoading).toBe(false);+ });++ it('keeps search results in memory only', async () => {+ vi.spyOn(verifyService, 'listAcceptances').mockResolvedValue([row('hit')]);+ const search: AcceptanceListParams = { filter: 'all', q: 'needle' };++ const { result } = renderHook(() => useAcceptanceList(true, search), { wrapper });+ await waitFor(() => expect(result.current.data?.map((item) => item.id)).toEqual(['hit']));+ await new Promise((resolve) => setTimeout(resolve, 50));++ expect(await storedList(search)).toBeUndefined();+ });++ it('sends one request for callers that mount the same list together', async () => {+ const listAcceptances = vi.spyOn(verifyService, 'listAcceptances').mockResolvedValue([]);++ // The workspace shell, then the list panel's empty-state probe a moment later.+ const { rerender } = renderHook(+ ({ late }: { late: boolean }) => {+ useAcceptanceList(true, ALL);+ useAcceptanceList(true, ALL);+ useAcceptanceList(late, ALL);+ },+ { initialProps: { late: false }, wrapper },+ );+ await waitFor(() => expect(listAcceptances).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 20));+ rerender({ late: true });+ await new Promise((resolve) => setTimeout(resolve, 50));++ expect(listAcceptances).toHaveBeenCalledOnce();+ });++ it('never shows the previous identity rows after a scope switch', async () => {+ const other = `acceptance-other-${randomUUID()}:personal`;+ await persistPage(FEED, pageData([row('mine')]));+ await persistPage(FEED, pageData([row('theirs')]), other);+ vi.spyOn(verifyService, 'listAcceptancePage').mockReturnValue(new Promise(() => {}) as never);++ const { result, rerender } = renderHook(() => useAcceptanceListInfinite('all'), { wrapper });+ await waitFor(() => expect(result.current.items.map((item) => item.id)).toEqual(['mine']));++ scope = other;+ rerender();+ await waitFor(() => expect(result.current.items.map((item) => item.id)).toEqual(['theirs']));+ expect(result.current.items.some((item) => item.id === 'mine')).toBe(false);++ await pageStorage.remove({ queryKey: REPLICA_INDEX_KEY, scope: other });+ });++ it('keys every list narrowing apart', () => {+ expect(acceptancePageKey({ filter: 'all', projectId: 'p1' })).not.toBe(+ acceptancePageKey({ filter: 'all', projectId: 'p2' }),+ );+ expect(acceptancePageKey({ filter: 'all', projectId: null })).not.toBe(+ acceptancePageKey({ filter: 'all' }),+ );+ expect(acceptancePageKey({ filter: 'all', scope: 'participated' })).not.toBe(+ acceptancePageKey({ filter: 'all' }),+ );+ expect(acceptanceListKey({ filter: 'all', limit: 200 })).not.toBe(+ acceptanceListKey({ filter: 'all' }),+ );+ expect(acceptanceListKey({ filter: 'all', q: 'x' })).not.toBe(+ acceptanceListKey({ filter: 'all' }),+ );+ });++ describe('discussion', () => {+ const persistComments = (acceptanceId: string, data: AcceptanceCommentList) =>+ commentStorage.set(+ { queryKey: acceptanceCommentResource.storageKey(acceptanceId), scope },+ { data, updatedAt: 1 },+ );++ it('paints the persisted discussion before the network answers, then refreshes it', async () => {+ await persistComments('acc-1', comments(['c1']));+ const network = deferred<AcceptanceCommentList>();+ vi.spyOn(acceptanceCommentService, 'list').mockReturnValue(network.promise);++ const { result } = renderHook(() => useAcceptanceCommentList('acc-1'), { wrapper });++ await waitFor(() =>+ expect(result.current.data?.items.map((item) => item.id)).toEqual(['c1']),+ );+ expect(result.current.isLoading).toBe(false);++ await act(async () => network.resolve(comments(['c1', 'c2'])));+ await waitFor(() => expect(result.current.data?.items).toHaveLength(2));+ });++ it('reads a restored empty discussion as loading until the server confirms it', async () => {+ await persistComments('acc-2', comments([]));+ const network = deferred<AcceptanceCommentList>();+ vi.spyOn(acceptanceCommentService, 'list').mockReturnValue(network.promise);++ const { result } = renderHook(() => useAcceptanceCommentList('acc-2'), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().acceptanceCommentMap['acc-2']).toBeDefined(),+ );+ expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(true);++ await act(async () => network.resolve(comments([])));+ await waitFor(() => expect(result.current.data?.items).toEqual([]));+ });++ it('rolls a failed optimistic change back to the confirmed discussion', async () => {+ vi.spyOn(acceptanceCommentService, 'list').mockResolvedValue(comments(['c1']));+ const { result } = renderHook(() => useAcceptanceCommentList('acc-3'), { wrapper });+ await waitFor(() => expect(result.current.data?.items).toHaveLength(1));++ await act(async () => {+ await useVerifyStore+ .getState()+ .optimisticAcceptanceComments(+ 'acc-3',+ (current) => ({ ...current, items: [] }),+ () => Promise.reject(new Error('denied')),+ )+ .catch(() => {});+ });++ expect(result.current.data?.items.map((item) => item.id)).toEqual(['c1']);+ });+ });+});diff --git a/src/store/verify/action.ts b/src/store/verify/action.tsindex c7bb7b9f11f..c07deacbe31 100644--- a/src/store/verify/action.ts+++ b/src/store/verify/action.ts@@ -1,12 +1,23 @@-import type { CreatableAcceptanceSubjectType, VerifyRubricConfig } from '@lobechat/types';+import type {+ AcceptanceCommentList,+ CreatableAcceptanceSubjectType,+ VerifyRubricConfig,+} from '@lobechat/types';import { debounce } from 'es-toolkit/compat';import isEqual from 'fast-deep-equal';import { type StateCreator } from 'zustand';import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@/const/index';-import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';+import {+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaPageResult,+ type ReplicaSyncResult,+} from '@/libs/replica';+import { acceptanceCommentService } from '@/services/acceptanceComment';import { documentService } from '@/services/document';-import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';+import type { AcceptanceBundle, AcceptanceBySubject, AcceptanceListItem } from '@/services/verify';import { verifyService } from '@/services/verify';import { type StoreSetter } from '@/store/types';import { flattenActions } from '@/store/utils/flattenActions';@@ -17,6 +28,15 @@ import {acceptanceBundleResource,acceptanceBySubjectKey,acceptanceBySubjectResource,+ acceptanceCommentResource,+ acceptanceListEntity,+ acceptanceListKey,+ type AcceptanceListParams,+ acceptanceListResource,+ type AcceptancePageData,+ acceptancePageKey,+ type AcceptancePageParams,+ acceptancePageResource,toPersistedVerifyRun,verifyRunResource,type VerifyRunSnapshot,@@ -31,6 +51,19 @@ type Setter = StoreSetter<Store>;const acceptanceBundleLens = recordLens<Store, AcceptanceBundle>('acceptanceBundleMap');const acceptanceBySubjectLens = recordLens<Store, AcceptanceBySubject>('acceptanceBySubjectMap');const verifyRunLens = recordLens<Store, VerifyRunSnapshot>('verifyRunMap');+const acceptanceCommentLens = recordLens<Store, AcceptanceCommentList>('acceptanceCommentMap');+const acceptanceListLens = recordLens<Store, AcceptanceListItem[]>('acceptanceListMap');+const acceptancePageLens = recordLens<Store, AcceptancePageData>('acceptancePageMap');++/** Server page size of the list panel's scroll feed. */+export const ACCEPTANCE_PAGE_SIZE = 30;++/**+ * The workspace shell, the list panel's empty-state probe and the merge picker+ * can mount the same list read together; one request answers all of them.+ * Explicit revalidations (after a write, a retry) are not deduped.+ */+const ACCEPTANCE_LIST_DEDUPE_MS = 10_000;/*** The verify store owns the write-back loop for the delivery-check config@@ -47,6 +80,14 @@ export class ActionImpl {readonly #bySubject;/** The Agent Run verify card replica, behind `verifyRunMap[operationId]`. */readonly #run;+ /** The flat acceptance list reads, behind `acceptanceListMap`. */+ readonly #list;+ /** The list panel's keyset feeds, behind `acceptancePageMap`. */+ readonly #page;+ /** One acceptance row in every list and feed that holds it. */+ readonly #listEntity;+ /** Each acceptance's discussion, behind `acceptanceCommentMap[acceptanceId]`. */+ readonly #comments;/** Pending writes coalesced per id and flushed together on a debounce. */#pendingCriteria = new Map<string, VerifyCriterionEdit>();@@ -106,8 +147,132 @@ export class ActionImpl {toPersisted: toPersistedVerifyRun,view: verifyRunLens,});+ this.#list = createReplicaSlice(acceptanceListResource, {+ actionPrefix: 'acceptanceList',+ entity: acceptanceListEntity,+ fetcher: (params) => verifyService.listAcceptances(params),+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'acceptanceListReplica',+ view: acceptanceListLens,+ });+ this.#page = createReplicaSlice(acceptancePageResource, {+ actionPrefix: 'acceptancePage',+ fetcher: this.#fetchAcceptancePage,+ get,+ set,+ stateKey: 'acceptancePageReplica',+ view: acceptancePageLens,+ });+ this.#listEntity = linkReplicaEntity<AcceptanceListItem>([this.#list, this.#page]);+ this.#comments = createReplicaSlice(acceptanceCommentResource, {+ actionPrefix: 'acceptanceComment',+ fetcher: (acceptanceId) => acceptanceCommentService.list(acceptanceId),+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'acceptanceCommentReplica',+ view: acceptanceCommentLens,+ });}+ /** One scroll page of the list panel: `cursor` undefined = the head (newest first). */+ #fetchAcceptancePage = async (+ params: AcceptancePageParams,+ cursor?: string,+ ): Promise<ReplicaPageResult<AcceptanceListItem, string>> => {+ const { items, nextCursor } = await verifyService.listAcceptancePage({+ ...params,+ cursor,+ limit: ACCEPTANCE_PAGE_SIZE,+ });+ return { items, nextCursor };+ };++ /**+ * Fetch orchestration only; the caller reads the rows through+ * `acceptanceListMap` (`verifySelectors.acceptanceList`). A persisted browse+ * paints first; search entries live in memory only.+ */+ useFetchAcceptanceList = (+ params: AcceptanceListParams | null,+ options: { enabled?: boolean; fresh?: boolean } = {},+ ): ReplicaSyncResult =>+ this.#list.useSync(params, {+ // A decision surface (the merge picker) asks for a fresh read on open.+ dedupingInterval: options.fresh ? 0 : ACCEPTANCE_LIST_DEDUPE_MS,+ enabled: options.enabled ?? true,+ });++ /**+ * Fetch orchestration only; the caller reads the feed through+ * `acceptancePageMap` (`verifySelectors.acceptancePage`). `null` disables the+ * feed β the panel hands off to the flat search read.+ */+ useFetchAcceptancePage = (params: AcceptancePageParams | null): ReplicaSyncResult =>+ this.#page.useSync(params, { dedupingInterval: ACCEPTANCE_LIST_DEDUPE_MS });++ /** Pull the next page of one scroll feed. */+ loadMoreAcceptancePage = async (params: AcceptancePageParams): Promise<void> => {+ await this.#page.loadMore(acceptancePageKey(params), params);+ };++ /**+ * Switching back to a feed starts again from its head page instead of the+ * depth an earlier visit had scrolled to.+ */+ collapseAcceptancePage = (params: AcceptancePageParams): void => {+ this.#page.collapse(acceptancePageKey(params));+ };++ /** Re-read every acceptance list and feed of the active scope (after any write). */+ refreshAcceptanceLists = async (): Promise<void> => {+ await Promise.all([this.#list.revalidate(), this.#page.revalidate()]);+ };++ /** Re-read one flat list entry. */+ refreshAcceptanceList = async (params: AcceptanceListParams): Promise<void> => {+ await this.#list.revalidate(acceptanceListKey(params));+ };++ /**+ * Drop deleted / merged-away acceptances from every list and feed, in memory+ * and in the persisted rows, so a reload cannot paint them back before the+ * revalidation lands.+ */+ removeAcceptancesFromLists = (acceptanceIds: string[]): void => {+ for (const id of acceptanceIds) this.#listEntity.remove(id);+ };++ /**+ * Fetch orchestration only; the caller reads the discussion through+ * `acceptanceCommentMap` (`verifySelectors.acceptanceComments`).+ */+ useFetchAcceptanceComments = (acceptanceId?: string | null): ReplicaSyncResult =>+ this.#comments.useSync(acceptanceId || null, {+ dedupingInterval: ACCEPTANCE_LIST_DEDUPE_MS,+ revalidateOnFocus: true,+ });++ /** Re-read one acceptance's discussion (after a comment write). */+ refreshAcceptanceComments = async (acceptanceId: string): Promise<void> => {+ await this.#comments.revalidate(acceptanceId);+ };++ /**+ * Apply a discussion change on screen at once and settle it with the server's+ * read-back; a failed write rolls back to the confirmed discussion.+ */+ optimisticAcceptanceComments = async (+ acceptanceId: string,+ apply: (current: AcceptanceCommentList) => AcceptanceCommentList,+ serverCall: () => Promise<unknown>,+ ): Promise<void> => {+ await this.#comments.optimistic(acceptanceId, apply, serverCall);+ await this.refreshAcceptanceComments(acceptanceId);+ };+/** Re-read one acceptance bundle (after a review, merge, delete or status sweep). */refreshAcceptanceBundle = async (acceptanceId: string): Promise<void> => {await this.#bundle.revalidate(acceptanceId);diff --git a/src/store/verify/initialState.ts b/src/store/verify/initialState.tsindex 84b401df124..d1609fb99aa 100644--- a/src/store/verify/initialState.ts+++ b/src/store/verify/initialState.ts@@ -1,9 +1,14 @@-import type { VerifierType, VerifyOnFailStrategy, VerifyRubricConfig } from '@lobechat/types';+import type {+ AcceptanceCommentList,+ VerifierType,+ VerifyOnFailStrategy,+ VerifyRubricConfig,+} from '@lobechat/types';import { createReplicaState, type ReplicaState } from '@/libs/replica';-import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';+import type { AcceptanceBundle, AcceptanceBySubject, AcceptanceListItem } from '@/services/verify';-import type { VerifyRunSnapshot } from './projection';+import type { AcceptancePageData, VerifyRunSnapshot } from './projection';/** The criterion fields the portal can edit. */export interface VerifyCriterionEdit {@@ -23,6 +28,18 @@ export interface State {acceptanceBySubjectMap: Record<string, AcceptanceBySubject>;/** Replica bookkeeping of `acceptanceBySubjectMap`. */acceptanceBySubjectReplica: ReplicaState<AcceptanceBySubject>;+ /** Replica view of each acceptance's discussion, keyed by acceptance id. */+ acceptanceCommentMap: Record<string, AcceptanceCommentList>;+ /** Replica bookkeeping of `acceptanceCommentMap`. */+ acceptanceCommentReplica: ReplicaState<AcceptanceCommentList>;+ /** Replica view of the flat acceptance list reads, keyed by `acceptanceListKey`. */+ acceptanceListMap: Record<string, AcceptanceListItem[]>;+ /** Replica bookkeeping of `acceptanceListMap`. */+ acceptanceListReplica: ReplicaState<AcceptanceListItem[]>;+ /** Replica view of the list panel's scroll feeds, keyed by `acceptancePageKey`. */+ acceptancePageMap: Record<string, AcceptancePageData>;+ /** Replica bookkeeping of `acceptancePageMap`. */+ acceptancePageReplica: ReplicaState<AcceptancePageData>;/*** Per-criterion edit overlay, keyed by `verify_criteria.id`. Holds the* user's in-flight edits so the UI reflects them immediately while they are@@ -55,6 +72,12 @@ export const initialState: State = {acceptanceBundleReplica: createReplicaState(),acceptanceBySubjectMap: {},acceptanceBySubjectReplica: createReplicaState(),+ acceptanceCommentMap: {},+ acceptanceCommentReplica: createReplicaState(),+ acceptanceListMap: {},+ acceptanceListReplica: createReplicaState(),+ acceptancePageMap: {},+ acceptancePageReplica: createReplicaState(),criterionEdits: {},instructionEdits: {},rubricConfigEdits: {},diff --git a/src/store/verify/projection.ts b/src/store/verify/projection.tsindex 5881e61abd4..5c9cf539e6f 100644--- a/src/store/verify/projection.ts+++ b/src/store/verify/projection.ts@@ -1,8 +1,22 @@-import type { CreatableAcceptanceSubjectType } from '@lobechat/types';+import type { AcceptanceCommentList, CreatableAcceptanceSubjectType } from '@lobechat/types';import type { VerifyCheckResultItem } from '@/database/schemas/verify';-import { AppIndexedDBStorage, defineReplica } from '@/libs/replica';-import type { AcceptanceBundle, AcceptanceBySubject, VerifyStateResponse } from '@/services/verify';+import {+ AppIndexedDBStorage,+ arrayEntity,+ definePagedReplica,+ defineReplica,+ type ReplicaEntityAdapter,+ type ReplicaPagedData,+} from '@/libs/replica';+import type {+ AcceptanceBundle,+ AcceptanceBySubject,+ AcceptanceListFilter,+ AcceptanceListItem,+ AcceptanceListQuery,+ VerifyStateResponse,+} from '@/services/verify';/*** The Acceptance aggregate of one acceptance id (`acceptanceBundleMap[id]`):@@ -137,3 +151,107 @@ export const verifyRunResource = defineReplica<string, VerifyRunSnapshot>({}),version: VERIFY_RUN_VERSION,});++/** The list narrowing a list entry was read under (everything but search and paging). */+export interface AcceptanceListParams extends AcceptanceListQuery {+ /** Widen the recency window (server-capped) β the merge picker asks for more. */+ limit?: number;+ /** A search term; search entries stay in memory only. */+ q?: string;+}++/** `null` (no project) and `undefined` (any project) are different reads. */+const acceptanceProjectKey = (projectId: string | null | undefined) =>+ projectId === null ? '~none' : (projectId ?? '');++/**+ * Entry key of one acceptance list read (`acceptanceListMap[key]`): every+ * dimension the server filters on. The scope (user + workspace) partitions the+ * replica itself, so a key never carries the workspace.+ */+export const acceptanceListKey = ({+ filter,+ limit,+ projectId,+ q,+ scope,+ source,+}: AcceptanceListParams = {}): string =>+ [+ filter ?? '',+ acceptanceProjectKey(projectId),+ scope ?? '',+ source ?? '',+ limit === undefined ? '' : String(limit),+ q ? `q:${q}` : '',+ ].join('|');++/** Search results answer one typed query; they are never repainted after a reload. */+const isSearchListKey = (key: string) => key.includes('|q:');++/** Acceptance list rows are addressed by the acceptance id. */+export const acceptanceListEntity: ReplicaEntityAdapter<AcceptanceListItem[], AcceptanceListItem> =+ arrayEntity<AcceptanceListItem>((item) => item.id);++/**+ * The caller's recent acceptances under one narrowing (`acceptanceListMap`):+ * the workspace shell's onboarding probe, the merge target picker and the list+ * panel's search. A reload paints the last browse from IndexedDB, then+ * revalidates; search entries are memory-only.+ */+export const acceptanceListResource = defineReplica<AcceptanceListParams, AcceptanceListItem[]>({+ key: acceptanceListKey,+ name: 'acceptanceList',+ persist: { maxEntries: 20 },+ persistKey: (key) => !isSearchListKey(key),+ storage: 'indexedDB',+ version: 1,+});++/** One view of the list panel's scroll feed: the status split and the narrowing. */+export type AcceptancePageParams = Omit<AcceptanceListQuery, 'filter'> & {+ filter: AcceptanceListFilter;+};++export type AcceptancePageData = ReplicaPagedData<AcceptanceListItem, string>;++/** Entry key of one scroll feed (`acceptancePageMap[key]`). */+export const acceptancePageKey = ({ filter, projectId, scope, source }: AcceptancePageParams) =>+ [filter, acceptanceProjectKey(projectId), scope ?? '', source ?? ''].join('|');++/**+ * The list panel's keyset feed, newest first (`acceptancePageMap`). Only the+ * head page survives a reload, so the first frame shows what the first network+ * page would, never a stale tail.+ */+export const acceptancePageResource = definePagedReplica<+ AcceptancePageParams,+ AcceptanceListItem,+ string,+ AcceptancePageData+>({+ key: acceptancePageKey,+ name: 'acceptancePage',+ paging: {+ direction: 'forward',+ getId: (item) => item.id,+ mode: 'cursor',+ persist: { pages: 1 },+ },+ persist: { maxEntries: 20 },+ storage: 'indexedDB',+ version: 1,+});++/**+ * The discussion of one acceptance (`acceptanceCommentMap[acceptanceId]`):+ * comments, approvals, reactions and the caller's comment permissions. LRU-capped+ * because every opened acceptance would otherwise keep its thread.+ */+export const acceptanceCommentResource = defineReplica<string, AcceptanceCommentList>({+ key: (acceptanceId) => acceptanceId,+ name: 'acceptanceComment',+ persist: { maxEntries: 30 },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/verify/selectors.ts b/src/store/verify/selectors.tsindex b6d419fe0ec..b91783da50f 100644--- a/src/store/verify/selectors.ts+++ b/src/store/verify/selectors.ts@@ -2,6 +2,12 @@ import type { VerifyRubricConfig } from '@lobechat/types';import { type Store } from './action';import { type VerifyCriterionEdit } from './initialState';+import {+ acceptanceListKey,+ type AcceptanceListParams,+ acceptancePageKey,+ type AcceptancePageParams,+} from './projection';const EMPTY_EDIT: VerifyCriterionEdit = {};const EMPTY_RUBRIC_CONFIG: VerifyRubricConfig = {};@@ -12,6 +18,27 @@ const acceptanceBundle = (acceptanceId?: string | null) => (s: Store) =>const acceptanceBySubject = (subjectType: string, subjectId?: string | null) => (s: Store) =>subjectId ? s.acceptanceBySubjectMap[`${subjectType}:${subjectId}`] : undefined;+const acceptanceList = (params?: AcceptanceListParams | null) => (s: Store) =>+ params ? s.acceptanceListMap[acceptanceListKey(params)] : undefined;++/** The server answered this list read in this session (not only the persisted copy). */+const isAcceptanceListConfirmed = (params?: AcceptanceListParams | null) => (s: Store) =>+ !!params && s.acceptanceListReplica.entries[acceptanceListKey(params)]?.source === 'server';++const acceptancePage = (params?: AcceptancePageParams | null) => (s: Store) =>+ params ? s.acceptancePageMap[acceptancePageKey(params)] : undefined;++/** The server answered this feed's head page in this session. */+const isAcceptancePageConfirmed = (params?: AcceptancePageParams | null) => (s: Store) =>+ !!params && s.acceptancePageReplica.entries[acceptancePageKey(params)]?.source === 'server';++const acceptanceComments = (acceptanceId?: string | null) => (s: Store) =>+ acceptanceId ? s.acceptanceCommentMap[acceptanceId] : undefined;++/** The server answered this discussion in this session. */+const isAcceptanceCommentsConfirmed = (acceptanceId?: string | null) => (s: Store) =>+ !!acceptanceId && s.acceptanceCommentReplica.entries[acceptanceId]?.source === 'server';+const criterionEdit = (criterionId?: string) => (s: Store) =>(criterionId ? s.criterionEdits[criterionId] : undefined) ?? EMPTY_EDIT;@@ -30,8 +57,14 @@ const verifyRun = (operationId?: string | null) => (s: Store) =>export const verifySelectors = {acceptanceBundle,acceptanceBySubject,+ acceptanceComments,+ acceptanceList,+ acceptancePage,criterionEdit,instructionEdit,+ isAcceptanceCommentsConfirmed,+ isAcceptanceListConfirmed,+ isAcceptancePageConfirmed,rubricConfigEdit,rubricTitleEdit,verifyRun,