🤯 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(eval): move the dataset slice onto @lobechat/replica (#20685)
Arvin Xud4f369d6df88
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 923e7804331..da71d194170 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -475,10 +475,7 @@ export const discoverKeys = {export const evalKeys = {benchmarkDetail: def('eval:benchmarkDetail', (id: string) => ['eval:benchmarkDetail', id]),benchmarks: def('eval:benchmarks', () => ['eval:benchmarks']),- datasetDetail: def('eval:datasetDetail', (id: string) => ['eval:datasetDetail', id]),datasetRuns: def('eval:datasetRuns', (datasetId: string) => ['eval:datasetRuns', datasetId]),- datasetsAll: def('eval:datasetsAll', () => ['eval:datasetsAll']),- datasets: def('eval:datasets', (benchmarkId: string) => ['eval:datasets', benchmarkId]),runDetail: def('eval:runDetail', (id: string) => ['eval:runDetail', id]),runResults: def('eval:runResults', (id: string) => ['eval:runResults', id]),runs: def('eval:runs', (benchmarkId?: string) => ['eval:runs', benchmarkId]),diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsxindex 9fe4eadbd62..52877f5c6ae 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/DatasetList.tsx@@ -16,7 +16,7 @@ import NavItem from '@/features/NavPanel/components/NavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-import { useEvalStore } from '@/store/eval';+import { datasetSelectors, useEvalStore } from '@/store/eval';interface DatasetListProps {activeKey: string;@@ -27,8 +27,8 @@ interface DatasetListProps {const DatasetList = memo<DatasetListProps>(({ activeKey, benchmarkId, itemKey }) => {const { t } = useTranslation('eval');const navigate = useWorkspaceAwareNavigate();- const datasetList = useEvalStore((s) => s.datasetList);- const isLoading = useEvalStore((s) => s.isLoadingDatasets);+ const datasetList = useEvalStore(datasetSelectors.datasetList(benchmarkId));+ const isLoading = useEvalStore(datasetSelectors.isLoadingDatasetList(benchmarkId));return (<AccordionItem value={itemKey}>diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsxindex 139418f23fd..f0dde829464 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/DatasetCard.tsx@@ -6,7 +6,7 @@ import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-import { agentEvalService } from '@/services/agentEval';+import { useEvalStore } from '@/store/eval';import { DATASET_PRESETS } from '../../../../config/datasetPresets';import TestCaseEmptyState from './TestCaseEmptyState';@@ -167,6 +167,7 @@ const DatasetCard = memo<DatasetCardProps>(onRun,}) => {const { t } = useTranslation('eval');+ const deleteDataset = useEvalStore((s) => s.deleteDataset);const handleDelete = useCallback(() => {confirmModal({@@ -175,7 +176,7 @@ const DatasetCard = memo<DatasetCardProps>(okText: t('common.delete'),onOk: async () => {try {- await agentEvalService.deleteDataset(dataset.id);+ await deleteDataset(dataset.id);toast.success(t('dataset.delete.success'));onRefresh();} catch {@@ -184,7 +185,7 @@ const DatasetCard = memo<DatasetCardProps>(},title: t('common.delete'),});- }, [dataset.id, onRefresh, t]);+ }, [dataset.id, deleteDataset, onRefresh, t]);return (<Block className={styles.card} variant={'outlined'}>diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsxindex 618990d89fe..11993619b2d 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx@@ -23,7 +23,7 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaimport { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { agentService } from '@/services/agent';-import { useEvalStore } from '@/store/eval';+import { datasetSelectors, useEvalStore } from '@/store/eval';const DEFAULT_MAX_STEPS = 100;const DEFAULT_TIMEOUT_MINUTES = 30;@@ -106,7 +106,7 @@ const RunCreateContent: FC<RunCreateContentProps> = ({const activeWorkspaceSlug = useActiveWorkspaceSlug();const createRun = useEvalStore((s) => s.createRun);const startRun = useEvalStore((s) => s.startRun);- const datasetList = useEvalStore((s) => s.datasetList);+ const datasetList = useEvalStore(datasetSelectors.datasetList(benchmarkId));const isDatasetMode = !!datasetId && !!datasetName;const form = useForm<RunCreateFormValues>({initialValues: {diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsxindex b8fc7705ec6..4cc04cd45f9 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx@@ -24,7 +24,7 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaimport { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { agentService } from '@/services/agent';-import { useEvalStore } from '@/store/eval';+import { datasetSelectors, useEvalStore } from '@/store/eval';const MAX_TIMEOUT_MINUTES = 240;@@ -72,7 +72,7 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, runconst activeWorkspaceSlug = useActiveWorkspaceSlug();const { benchmarkId } = useParams<{ benchmarkId: string }>();const updateRun = useEvalStore((s) => s.updateRun);- const datasetList = useEvalStore((s) => s.datasetList);+ const datasetList = useEvalStore(datasetSelectors.datasetList(benchmarkId));const [agents, setAgents] = useState<AgentOption[]>([]);const [loadingAgents, setLoadingAgents] = useState(false);diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/index.tsxindex 3bc31fedd08..ccd6276ffb4 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx@@ -21,7 +21,7 @@ import { useParams } from 'react-router';import AsyncError from '@/components/AsyncError';import { RouteLoading } from '@/components/Skeleton/RouteSegment';-import { runSelectors, useEvalStore } from '@/store/eval';+import { datasetSelectors, runSelectors, useEvalStore } from '@/store/eval';import BenchmarkHeader from './features/BenchmarkHeader';import DatasetsTab from './features/DatasetsTab';@@ -84,8 +84,8 @@ const BenchmarkDetail = memo(() => {benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,);const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);- const datasets = useEvalStore((s) => s.datasetList);- const isLoadingDatasets = useEvalStore((s) => s.isLoadingDatasets);+ const datasets = useEvalStore(datasetSelectors.datasetList(benchmarkId));+ const isLoadingDatasets = useEvalStore(datasetSelectors.isLoadingDatasetList(benchmarkId));const refreshDatasets = useEvalStore((s) => s.refreshDatasets);const useFetchRuns = useEvalStore((s) => s.useFetchRuns);const runList = useEvalStore(runSelectors.runList(benchmarkId));diff --git a/src/routes/(main)/eval/datasets/[datasetId]/index.tsx b/src/routes/(main)/eval/datasets/[datasetId]/index.tsxindex 949f59dd3b7..ff09d250d38 100644--- a/src/routes/(main)/eval/datasets/[datasetId]/index.tsx+++ b/src/routes/(main)/eval/datasets/[datasetId]/index.tsx@@ -107,6 +107,7 @@ const DatasetDetail = memo(() => {const runList = useEvalStore(runSelectors.datasetRunList(datasetId!));const refreshTestCases = useEvalStore((s) => s.refreshTestCases);const refreshDatasetDetail = useEvalStore((s) => s.refreshDatasetDetail);+ const deleteDataset = useEvalStore((s) => s.deleteDataset);const { data: dataset, error, isLoading, mutate } = useFetchDatasetDetail(datasetId);// Nullable: a dataset accumulated from captured cases belongs to no benchmark.@@ -192,7 +193,7 @@ const DatasetDetail = memo(() => {okText: t('common.delete'),onOk: async () => {try {- await agentEvalService.deleteDataset(datasetId!);+ await deleteDataset(datasetId!);toast.success(t('dataset.delete.success'));navigate(benchmarkId ? `/eval/bench/${benchmarkId}` : '/eval');} catch {@@ -201,7 +202,7 @@ const DatasetDetail = memo(() => {},title: t('common.delete'),});- }, [benchmarkId, datasetId, navigate, t]);+ }, [benchmarkId, datasetId, deleteDataset, navigate, t]);// Skeleton → error → (resolved-null) blank, replacing a bare `return null`// that flashed blank on the happy path and stayed permanently blank on adiff --git a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsxindex 5173ab10985..fc050a06999 100644--- a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx+++ b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx@@ -91,10 +91,10 @@ const styles = createStaticStyles(({ css }) => ({export interface DatasetEditContentProps {dataset: {- description?: string;+ description?: string | null;evalMode?: string | null;id: string;- metadata?: Record<string, unknown>;+ metadata?: Record<string, unknown> | null;name: string;};formId: string;diff --git a/src/store/eval/selectors.ts b/src/store/eval/selectors.tsindex 985777ca27f..147425fc773 100644--- a/src/store/eval/selectors.ts+++ b/src/store/eval/selectors.ts@@ -1,4 +1,5 @@export { benchmarkSelectors } from './slices/benchmark/selectors';+export { datasetSelectors } from './slices/dataset/selectors';export { experimentSelectors } from './slices/experiment/selectors';export { runSelectors } from './slices/run/selectors';export { testCaseSelectors } from './slices/testCase/selectors';diff --git a/src/store/eval/slices/dataset/action.test.ts b/src/store/eval/slices/dataset/action.test.tsnew file mode 100644index 00000000000..45e336b69da--- /dev/null+++ b/src/store/eval/slices/dataset/action.test.ts@@ -0,0 +1,201 @@+/**+ * @vitest-environment happy-dom+ *+ * The dataset lists (benchmark-scoped + scope-wide) and the dataset detail are+ * `@lobechat/replica` resources. These tests pin the fetch orchestration at the+ * boundary: which service call each hook registers, the pre-migration return+ * shapes, and that the refresh actions revalidate the replica sync instead of a+ * hand-written SWR `mutate`.+ */+import { renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope, createReplicaState } from '@/libs/replica';+import { useEvalStore } from '@/store/eval';++vi.mock('@/services/agentEval', () => ({+ agentEvalService: {+ getDataset: vi.fn(),+ listAllDatasets: vi.fn(),+ listDatasets: vi.fn(),+ },+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+}));++const resetStore = () => {+ useEvalStore.setState({+ datasetDetailMap: {},+ datasetDetailReplica: createReplicaState(),+ datasetListMap: {},+ datasetListReplica: createReplicaState(),+ });+};++/** The replica network sync of a resource, as registered with the SWR driver. */+const syncCalls = async (name: 'evalDatasetDetail' | 'evalDatasetList') => {+ const { useClientDataSWR } = await import('@/libs/swr');+ return vi+ .mocked(useClientDataSWR)+ .mock.calls.filter(+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,+ )+ .map(([key, fetcher, options]) => ({+ fetcher: fetcher as () => Promise<any>,+ key: key as unknown[],+ options: options as {+ onError?: (error: unknown) => void;+ onSuccess?: (data: unknown) => void;+ },+ }));+};++/** Capture the `mutate` matchers a refresh registered. */+const revalidationMatchers = async () => {+ const { mutate } = await import('@/libs/swr');+ return vi+ .mocked(mutate)+ .mock.calls.map(([arg]) => arg)+ .filter((arg): arg is (key: unknown) => boolean => typeof arg === 'function');+};++describe('DatasetAction replica wiring', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetStore();+ });++ // Undo per-test `cacheScope` spies so a scope switch never leaks into the next test.+ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('useFetchDatasets', () => {+ it('registers a benchmark sync and fetches that benchmark’s datasets', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.listDatasets).mockResolvedValue([] as any);++ renderHook(() => useEvalStore.getState().useFetchDatasets('bench-1'));++ const [list] = await syncCalls('evalDatasetList');+ expect(list).toBeDefined();+ await list.fetcher();+ expect(agentEvalService.listDatasets).toHaveBeenCalledWith('bench-1');+ expect(agentEvalService.listAllDatasets).not.toHaveBeenCalled();+ });++ it('is inert while no benchmark id is given', () => {+ const { result } = renderHook(() => useEvalStore.getState().useFetchDatasets(undefined));+ expect(typeof result.current.revalidate).toBe('function');+ });+ });++ describe('useFetchAllDatasets', () => {+ it('registers the scope-wide sync and lists every dataset', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.listAllDatasets).mockResolvedValue([] as any);++ renderHook(() => useEvalStore.getState().useFetchAllDatasets());++ const [list] = await syncCalls('evalDatasetList');+ expect(list).toBeDefined();+ await list.fetcher();+ expect(agentEvalService.listAllDatasets).toHaveBeenCalledTimes(1);+ expect(agentEvalService.listDatasets).not.toHaveBeenCalled();+ });++ it('returns the pre-migration { data, isLoading, mutate } shape', () => {+ const { result } = renderHook(() => useEvalStore.getState().useFetchAllDatasets());+ expect(result.current).toMatchObject({ data: undefined, isLoading: true });+ expect(typeof result.current.mutate).toBe('function');+ });+ });++ describe('useFetchDatasetDetail', () => {+ it('registers a detail sync keyed by id and fetches that page', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.getDataset).mockResolvedValue({ id: 'd1' } as any);++ renderHook(() => useEvalStore.getState().useFetchDatasetDetail('d1'));++ const [detail] = await syncCalls('evalDatasetDetail');+ expect(detail).toBeDefined();+ await detail.fetcher();+ expect(agentEvalService.getDataset).toHaveBeenCalledWith('d1');+ });++ it('applies a late NOT_FOUND to the scope its request was raised under, not the active one', async () => {+ const getScope = vi.spyOn(cacheScope, 'get').mockReturnValue('user:ws-a');+ const useScope = vi.spyOn(cacheScope, 'use').mockReturnValue('user:ws-a');+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);++ // A request for d1 is issued under workspace A…+ const { rerender } = renderHook(() => useEvalStore.getState().useFetchDatasetDetail('d1'));+ const fromA = (await syncCalls('evalDatasetDetail')).find((call) =>+ call.key.includes('user:ws-a'),+ );++ // …the user switches to workspace B, where the same id resolves.+ getScope.mockReturnValue('user:ws-b');+ useScope.mockReturnValue('user:ws-b');+ rerender();+ const fromB = (await syncCalls('evalDatasetDetail')).find((call) =>+ call.key.includes('user:ws-b'),+ );+ fromB.options.onSuccess?.({ id: 'd1', name: 'In B' });+ expect(useEvalStore.getState().datasetDetailMap.d1?.name).toBe('In B');++ // A's request finally answers NOT_FOUND: it belongs to A, so B's entry stays.+ fromA.options.onError?.({ data: { code: 'NOT_FOUND' } });++ expect(useEvalStore.getState().datasetDetailMap.d1?.name).toBe('In B');+ });++ it('returns the pre-migration { data, error, isLoading, mutate } shape and is inert without an id', () => {+ const { result } = renderHook(() => useEvalStore.getState().useFetchDatasetDetail(undefined));+ expect(result.current.data).toBeUndefined();+ expect(result.current.error).toBeUndefined();+ expect(typeof result.current.mutate).toBe('function');+ });+ });++ describe('refreshDatasets / refreshDatasetDetail', () => {+ it('revalidates one benchmark list entry through its replica sync', async () => {+ await useEvalStore.getState().refreshDatasets('bench-1');+ const matchers = await revalidationMatchers();+ expect(+ matchers.some((m) =>+ m([+ 'replica:sync',+ 'evalDatasetList',+ 1,+ 'anon:personal',+ 'bench-1',+ { benchmarkId: 'bench-1' },+ ]),+ ),+ ).toBe(true);+ });++ it('revalidates one detail entry by id', async () => {+ await useEvalStore.getState().refreshDatasetDetail('d1');+ const matchers = await revalidationMatchers();+ expect(+ matchers.some((m) =>+ m(['replica:sync', 'evalDatasetDetail', 1, 'anon:personal', 'd1', 'd1']),+ ),+ ).toBe(true);+ });+ });++ it('no longer exposes the retired reducer internals', () => {+ const state = useEvalStore.getState() as Record<string, unknown>;+ expect(state.internal_dispatchDatasetDetail).toBeUndefined();+ expect(state.internal_updateDatasetDetailLoading).toBeUndefined();+ expect(state.isLoadingDatasets).toBeUndefined();+ expect(state.loadingDatasetDetailIds).toBeUndefined();+ });+});diff --git a/src/store/eval/slices/dataset/action.ts b/src/store/eval/slices/dataset/action.tsindex 32fb048ad7b..181e2d16cad 100644--- a/src/store/eval/slices/dataset/action.ts+++ b/src/store/eval/slices/dataset/action.ts@@ -1,100 +1,172 @@+import type { AgentEvalDataset, AgentEvalDatasetListItem } from '@lobechat/types';import isEqual from 'fast-deep-equal';-import { type SWRResponse } from 'swr';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { evalKeys } from '@/libs/swr/keys';+import {+ arrayEntity,+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaSyncResult,+ singleEntity,+} from '@/libs/replica';import { agentEvalService } from '@/services/agentEval';-import { type EvalStore } from '@/store/eval/store';+import { type EvalStore, useEvalStore } from '@/store/eval/store';import { type StoreSetter } from '@/store/types';+import { isTrpcErrorCode } from '@/utils/trpcError';-import { type DatasetDetailDispatch, datasetDetailReducer } from './reducer';+import {+ ALL_DATASETS_KEY,+ datasetDetailResource,+ datasetListResource,+ toDatasetDetail,+} from './projection';type Setter = StoreSetter<EvalStore>;+/** The scope-wide list takes no params; the literal keeps `useSync` active. */+const ALL_DATASETS_PARAMS = {} as Record<string, never>;++/** Pre-migration `useFetchAllDatasets` return shape, backed by the scope-wide entry. */+export interface DatasetListSyncResult extends ReplicaSyncResult {+ /** The list once it has settled (hydrated or fetched), else `undefined`. */+ data: AgentEvalDatasetListItem[] | undefined;+ /** First load in flight with nothing settled yet. */+ isLoading: boolean;+ /** Alias of `revalidate`, kept for the pre-migration call sites. */+ mutate: () => Promise<unknown>;+}++/** Pre-migration `useFetchDatasetDetail` return shape, backed by the detail replica. */+export interface DatasetDetailSyncResult {+ /** The dataset once it has settled (hydrated or fetched), else `undefined`. */+ data: AgentEvalDataset | undefined;+ error: unknown;+ /** First load in flight with nothing settled yet. */+ isLoading: boolean;+ /** Alias of `revalidate`, kept for the pre-migration call sites. */+ mutate: () => Promise<unknown>;+}+export const createDatasetSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>new DatasetActionImpl(set, get, _api);export class DatasetActionImpl {+ readonly #detail;+ /** One dataset across both resources: a delete drops it from lists and detail alike. */+ readonly #entity;readonly #get: () => EvalStore;- readonly #set: Setter;+ readonly #list;constructor(set: Setter, get: () => EvalStore, _api?: unknown) {void _api;- this.#set = set;this.#get = get;++ // Two local-first resources over the dataset entity, each owning ONE store+ // location (the selectors keep reading those maps):+ // - `#list`: benchmark-scoped lists + the scope-wide list → `datasetListMap`+ // - `#detail`: by-id dataset page → `datasetDetailMap`+ this.#list = createReplicaSlice(datasetListResource, {+ actionPrefix: 'datasetList',+ entity: arrayEntity<AgentEvalDatasetListItem>((dataset) => dataset.id),+ fetcher: ({ benchmarkId }) =>+ benchmarkId+ ? agentEvalService.listDatasets(benchmarkId)+ : agentEvalService.listAllDatasets(),+ get,+ set,+ stateKey: 'datasetListReplica',+ view: recordLens<EvalStore, AgentEvalDatasetListItem[]>('datasetListMap'),+ });+ this.#detail = createReplicaSlice(datasetDetailResource, {+ actionPrefix: 'datasetDetail',+ entity: singleEntity<AgentEvalDataset>((dataset) => dataset.id),+ fetcher: async (id) => toDatasetDetail(await agentEvalService.getDataset(id)),+ get,+ // Every response is a fresh object: an unchanged revalidation (focus,+ // reconnect, manual refresh) must not repaint the detail view.+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'datasetDetailReplica',+ view: recordLens<EvalStore, AgentEvalDataset>('datasetDetailMap'),+ });+ this.#entity = linkReplicaEntity<AgentEvalDataset>([this.#list, this.#detail]);}+ /**+ * Delete a dataset on the server, then drop it from every list and its+ * persisted detail. Clearing only the server row would leave the IndexedDB+ * detail to repaint the deleted dataset on the next visit.+ */+ deleteDataset = async (id: string): Promise<void> => {+ await agentEvalService.deleteDataset(id);+ this.#entity.remove(id);+ };+refreshDatasetDetail = async (id: string): Promise<void> => {- await mutate(evalKeys.datasetDetail(id));+ await this.#detail.revalidate(id);};refreshDatasets = async (benchmarkId: string): Promise<void> => {- await mutate(evalKeys.datasets(benchmarkId));+ await this.#list.revalidate(benchmarkId);};- useFetchDatasetDetail = (id?: string): SWRResponse =>- useClientDataSWR(- id ? evalKeys.datasetDetail(id) : null,- () => agentEvalService.getDataset(id!),- {- onSuccess: (data: any) => {- this.#get().internal_dispatchDatasetDetail({- id: id!,- type: 'setDatasetDetail',- value: data,- });- this.#get().internal_updateDatasetDetailLoading(id!, false);- },- },- );-- useFetchDatasets = (benchmarkId?: string): SWRResponse =>- useClientDataSWR(- benchmarkId ? evalKeys.datasets(benchmarkId) : null,- () => agentEvalService.listDatasets(benchmarkId!),- {- onSuccess: (data: any) => {- this.#set(- {- datasetList: data,- isLoadingDatasets: false,- },- false,- 'useFetchDatasets/success',- );- },+ /**+ * Fetch orchestration only (the dataset is read from `datasetDetailMap`).+ * Keeps the pre-migration `{ data, error, isLoading, mutate }` shape.+ */+ useFetchDatasetDetail = (id?: string): DatasetDetailSyncResult => {+ const sync = this.#detail.useSync(id ?? null, {+ // A dataset deleted by another client keeps answering NOT_FOUND, and the+ // persisted detail would otherwise keep painting it — `AsyncBoundary` sees+ // `data` defined and swallows the fetch error. NOT_FOUND is definitive, so+ // drop the cached row and let the page settle on its error state; any+ // transient failure keeps the persisted copy on screen. The removal uses+ // the request's captured key + scope: a late 404 from a workspace the user+ // has left purges that workspace's row, never the entry now on screen. The+ // replica's removal guard keeps a hydrate already in flight from+ // repainting the dropped row.+ onError: (error, { key, scope }) => {+ if (!key || !isTrpcErrorCode(error, 'NOT_FOUND')) return;+ this.#detail.remove(key, scope);},- );+ });+ // Subscribe so a replica commit (hydrate or server replace) re-renders the+ // consumer; the value itself is read through the store below.+ useEvalStore((s) => (id ? s.datasetDetailMap[id] : undefined));+ const data = id ? this.#get().datasetDetailMap[id] : undefined;+ return {+ data,+ error: sync.error,+ // A failed first load is neither loading nor settled: gate on the error+ // so the page falls through to its error state instead of a skeleton.+ isLoading: data === undefined && !sync.error,+ mutate: sync.revalidate,+ };+ };++ /**+ * Fetch orchestration only; read the rows with `datasetSelectors.datasetList`.+ */+ useFetchDatasets = (benchmarkId?: string): ReplicaSyncResult =>+ this.#list.useSync(benchmarkId ? { benchmarkId } : null);/*** Every dataset. Without this a dataset is only reachable through its* benchmark, so one belonging to none could be created but never found.+ * Keeps the pre-migration `{ data, isLoading }` shape.*/- useFetchAllDatasets = (): SWRResponse =>- useClientDataSWR(evalKeys.datasetsAll(), () => agentEvalService.listAllDatasets());-- internal_dispatchDatasetDetail = (payload: DatasetDetailDispatch): void => {- const currentMap = this.#get().datasetDetailMap;- const nextMap = datasetDetailReducer(currentMap, payload);-- if (isEqual(nextMap, currentMap)) return;-- this.#set({ datasetDetailMap: nextMap }, false, `dispatchDatasetDetail/${payload.type}`);- };-- internal_updateDatasetDetailLoading = (id: string, loading: boolean): void => {- this.#set(- (state) => {- if (loading) {- return { loadingDatasetDetailIds: [...state.loadingDatasetDetailIds, id] };- }- return {- loadingDatasetDetailIds: state.loadingDatasetDetailIds.filter((i) => i !== id),- };- },- false,- 'updateDatasetDetailLoading',- );+ useFetchAllDatasets = (): DatasetListSyncResult => {+ // Subscribe so a replica commit re-renders the consumer (sidebar / overview);+ // the value itself is read through the store below.+ useEvalStore((s) => s.datasetListMap[ALL_DATASETS_KEY]);+ const sync = this.#list.useSync(ALL_DATASETS_PARAMS);+ const data = this.#get().datasetListMap[ALL_DATASETS_KEY];+ return {+ ...sync,+ data,+ isLoading: data === undefined && !sync.error,+ mutate: sync.revalidate,+ };};}diff --git a/src/store/eval/slices/dataset/initialState.ts b/src/store/eval/slices/dataset/initialState.tsindex a4a80af04b0..790ca39c553 100644--- a/src/store/eval/slices/dataset/initialState.ts+++ b/src/store/eval/slices/dataset/initialState.ts@@ -1,15 +1,25 @@import { type AgentEvalDataset, type AgentEvalDatasetListItem } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+export interface DatasetSliceState {+ /** Replica view of the dataset pages, one entry per dataset id. */datasetDetailMap: Record<string, AgentEvalDataset>;- datasetList: AgentEvalDatasetListItem[];- isLoadingDatasets: boolean;- loadingDatasetDetailIds: string[];+ /** Replica bookkeeping of `datasetDetailMap`. */+ datasetDetailReplica: ReplicaState<AgentEvalDataset>;+ /**+ * Replica view of the dataset lists, keyed by scope: one entry per benchmark+ * id, plus `all` for every dataset of the active scope. A missing entry is+ * the loading signal.+ */+ datasetListMap: Record<string, AgentEvalDatasetListItem[]>;+ /** Replica bookkeeping of `datasetListMap`. */+ datasetListReplica: ReplicaState<AgentEvalDatasetListItem[]>;}export const datasetInitialState: DatasetSliceState = {datasetDetailMap: {},- datasetList: [],- isLoadingDatasets: true,- loadingDatasetDetailIds: [],+ datasetDetailReplica: createReplicaState(),+ datasetListMap: {},+ datasetListReplica: createReplicaState(),};diff --git a/src/store/eval/slices/dataset/projection.ts b/src/store/eval/slices/dataset/projection.tsnew file mode 100644index 00000000000..880b6a06d23--- /dev/null+++ b/src/store/eval/slices/dataset/projection.ts@@ -0,0 +1,46 @@+import type { AgentEvalDataset, AgentEvalDatasetListItem } from '@lobechat/types';++import { defineReplica } from '@/libs/replica';+import type { agentEvalService } from '@/services/agentEval';++/** The server returns the dataset list rows directly (no `{ data }` wrapper). */+type DatasetListResponse = Awaited<ReturnType<typeof agentEvalService.listDatasets>>;+/** `getDataset` returns the dataset row plus its `testCases`; the view keeps the row. */+type DatasetDetailResponse = Awaited<ReturnType<typeof agentEvalService.getDataset>>;++/**+ * Drops the embedded `testCases` from a `getDataset` response. The page pages+ * test cases separately, so persisting them here would write an unbounded,+ * redundant collection to the store and IndexedDB on every detail visit.+ */+export const toDatasetDetail = ({+ testCases: _testCases,+ ...dataset+}: DatasetDetailResponse): AgentEvalDataset => dataset as AgentEvalDataset;++/** Entry key of the scope-wide list, beside every benchmark id. */+export const ALL_DATASETS_KEY = 'all';++/**+ * Datasets keyed by scope (`datasetListMap[benchmarkId | 'all']`): one entry per+ * benchmark, plus one scope-wide entry. Both come from the same `listDatasets`+ * query with different filters, so they share a single replica instead of two.+ */+export const datasetListResource = defineReplica<+ { benchmarkId?: string },+ AgentEvalDatasetListItem[],+ DatasetListResponse+>({+ key: ({ benchmarkId }) => benchmarkId ?? ALL_DATASETS_KEY,+ name: 'evalDatasetList',+ storage: 'indexedDB',+ version: 1,+});++/** One dataset page, keyed by the route param (`datasetDetailMap[id]`). */+export const datasetDetailResource = defineReplica<string, AgentEvalDataset>({+ key: (id) => id,+ name: 'evalDatasetDetail',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/eval/slices/dataset/reducer.ts b/src/store/eval/slices/dataset/reducer.tsdeleted file mode 100644index bdf18bebe47..00000000000--- a/src/store/eval/slices/dataset/reducer.ts+++ /dev/null@@ -1,55 +0,0 @@-import { type AgentEvalDataset } from '@lobechat/types';-import { produce } from 'immer';--type SetDatasetDetailAction = {- id: string;- type: 'setDatasetDetail';- value: AgentEvalDataset;-};--type UpdateDatasetDetailAction = {- id: string;- type: 'updateDatasetDetail';- value: Partial<AgentEvalDataset>;-};--type DeleteDatasetDetailAction = {- id: string;- type: 'deleteDatasetDetail';-};--export type DatasetDetailDispatch =- | SetDatasetDetailAction- | UpdateDatasetDetailAction- | DeleteDatasetDetailAction;--export const datasetDetailReducer = (- state: Record<string, AgentEvalDataset> = {},- payload: DatasetDetailDispatch,-): Record<string, AgentEvalDataset> => {- switch (payload.type) {- case 'setDatasetDetail': {- return produce(state, (draft) => {- draft[payload.id] = payload.value;- });- }-- case 'updateDatasetDetail': {- return produce(state, (draft) => {- if (draft[payload.id]) {- draft[payload.id] = { ...draft[payload.id], ...payload.value };- }- });- }-- case 'deleteDatasetDetail': {- return produce(state, (draft) => {- delete draft[payload.id];- });- }-- default: {- return state;- }- }-};diff --git a/src/store/eval/slices/dataset/replica.test.ts b/src/store/eval/slices/dataset/replica.test.tsnew file mode 100644index 00000000000..9cd0e1785c2--- /dev/null+++ b/src/store/eval/slices/dataset/replica.test.ts@@ -0,0 +1,369 @@+/**+ * @vitest-environment happy-dom+ *+ * The dataset lists (benchmark-scoped + scope-wide) and the dataset detail are+ * `@lobechat/replica` resources whose views are `datasetListMap` /+ * `datasetDetailMap`. This suite drives the real replica sync through SWR (no+ * mocked fetch hook) to show the behaviour the migration must preserve: a+ * persisted list paints while the network answers, a server response settles+ * and persists the view, each benchmark keeps its own entry, the scope-wide+ * list has its own key, a detail page fills its map entry, and a cache-scope+ * switch drops the previous identity's rows.+ */+import { randomUUID } from 'node:crypto';++import type { AgentEvalDatasetListItem } 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 { agentEvalService } from '@/services/agentEval';+import { useEvalStore } from '@/store/eval';++import { ALL_DATASETS_KEY, datasetDetailResource, datasetListResource } from './projection';++const ALL_PARAMS = {} as Record<string, never>;+const BENCH = 'bench-1';+const DETAIL_ID = 'd1';++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ // `shouldRetryOnError: false`: a NOT_FOUND revalidation must settle now, not+ // through SWR's backoff timers.+ { value: { dedupingInterval: 0, provider: () => new Map(), shouldRetryOnError: false } },+ createElement(MutateBridge),+ children,+ );++const BENCH_STORAGE_KEY = datasetListResource.storageKey({ benchmarkId: BENCH });+const ALL_STORAGE_KEY = datasetListResource.storageKey(ALL_PARAMS);+const DETAIL_STORAGE_KEY = datasetDetailResource.storageKey(DETAIL_ID);++const listRow = (id: string, name: string) =>+ ({+ benchmarkId: BENCH,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id,+ identifier: id,+ name,+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ }) as AgentEvalDatasetListItem;++/** Never-resolving fetch: what the store holds can only have come from storage. */+const pending = () => new Promise<never>(() => {});++const renderBenchList = (benchmarkId: string = BENCH) =>+ renderHook(() => useEvalStore.getState().useFetchDatasets(benchmarkId), { wrapper });+const renderAllList = () =>+ renderHook(() => useEvalStore.getState().useFetchAllDatasets(), { wrapper });+const renderDetail = (id: string) =>+ renderHook(() => useEvalStore.getState().useFetchDatasetDetail(id), { wrapper });++const benchList = (benchmarkId: string = BENCH) =>+ useEvalStore.getState().datasetListMap[benchmarkId];++describe('dataset replica', () => {+ const scopes = new Set<string>();+ let scope = '';++ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`eval-user-${randomUUID()}:personal`);+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) => [+ datasetListResource.storage!.remove({ queryKey: BENCH_STORAGE_KEY, scope: value }),+ datasetListResource.storage!.remove({ queryKey: ALL_STORAGE_KEY, scope: value }),+ datasetDetailResource.storage!.remove({ queryKey: DETAIL_STORAGE_KEY, scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted benchmark list before the network answers', async () => {+ await datasetListResource.storage!.set(+ { queryKey: BENCH_STORAGE_KEY, scope },+ { data: [listRow('d1', 'Cached')], updatedAt: 1 },+ );+ vi.spyOn(agentEvalService, 'listDatasets').mockImplementation(pending);++ renderBenchList();++ await waitFor(() => expect(benchList()?.[0]?.name).toBe('Cached'));+ });++ it('settles the benchmark list from the server and persists it', async () => {+ vi.spyOn(agentEvalService, 'listDatasets').mockResolvedValue([listRow('d1', 'MMLU')]);++ renderBenchList();++ await waitFor(() => expect(benchList()?.[0]?.name).toBe('MMLU'));+ expect(agentEvalService.listDatasets).toHaveBeenCalledWith(BENCH);+ await waitFor(async () =>+ expect(+ (await datasetListResource.storage!.get({ queryKey: BENCH_STORAGE_KEY, scope }))?.data?.[0]+ ?.name,+ ).toBe('MMLU'),+ );+ });++ it('keeps each benchmark’s list under its own key', async () => {+ vi.spyOn(agentEvalService, 'listDatasets').mockImplementation(+ async (benchmarkId: string) => [listRow(`${benchmarkId}-row`, benchmarkId)] as any,+ );++ renderHook(+ () => {+ useEvalStore.getState().useFetchDatasets('bench-a');+ useEvalStore.getState().useFetchDatasets('bench-b');+ },+ { wrapper },+ );++ await waitFor(() => {+ expect(benchList('bench-a')?.[0]?.name).toBe('bench-a');+ expect(benchList('bench-b')?.[0]?.name).toBe('bench-b');+ });+ });++ it('reads the scope-wide list from its own entry', async () => {+ const listAll = vi+ .spyOn(agentEvalService, 'listAllDatasets')+ .mockResolvedValue([listRow('d1', 'Every')]);+ const listBenchmark = vi.spyOn(agentEvalService, 'listDatasets');++ renderAllList();++ await waitFor(() =>+ expect(useEvalStore.getState().datasetListMap[ALL_DATASETS_KEY]?.[0]?.name).toBe('Every'),+ );+ expect(listAll).toHaveBeenCalledTimes(1);+ expect(listBenchmark).not.toHaveBeenCalled();+ });++ it('fills the detail map from the server', async () => {+ vi.spyOn(agentEvalService, 'getDataset').mockResolvedValue({+ id: DETAIL_ID,+ name: 'MMLU',+ } as any);++ renderDetail(DETAIL_ID);++ await waitFor(() =>+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]?.name).toBe('MMLU'),+ );+ expect(agentEvalService.getDataset).toHaveBeenCalledWith(DETAIL_ID);+ });++ it('keeps the detail reference when a revalidation answers an unchanged dataset', async () => {+ const getDataset = vi+ .spyOn(agentEvalService, 'getDataset')+ .mockResolvedValue({ id: DETAIL_ID, name: 'MMLU' } as any);++ renderDetail(DETAIL_ID);+ await waitFor(() =>+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]?.name).toBe('MMLU'),+ );+ const before = useEvalStore.getState().datasetDetailMap[DETAIL_ID];++ // Same content, fresh object — what every TRPC response is.+ getDataset.mockResolvedValue({ id: DETAIL_ID, name: 'MMLU' } as any);+ await act(() => useEvalStore.getState().refreshDatasetDetail(DETAIL_ID));+ await waitFor(() => expect(getDataset).toHaveBeenCalledTimes(2));++ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]).toBe(before);+ });++ it('keeps embedded test cases out of the stored and persisted detail', async () => {+ vi.spyOn(agentEvalService, 'getDataset').mockResolvedValue({+ id: DETAIL_ID,+ name: 'MMLU',+ testCases: [{ id: 'tc-1' }, { id: 'tc-2' }],+ } as any);++ renderDetail(DETAIL_ID);++ await waitFor(() =>+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]?.name).toBe('MMLU'),+ );+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]).not.toHaveProperty('testCases');+ await waitFor(async () => {+ const persisted = await datasetDetailResource.storage!.get({+ queryKey: DETAIL_STORAGE_KEY,+ scope,+ });+ expect(persisted?.data).toEqual({ id: DETAIL_ID, name: 'MMLU' });+ });+ });++ it('drops a persisted detail when its revalidation answers NOT_FOUND', async () => {+ const getDataset = vi+ .spyOn(agentEvalService, 'getDataset')+ .mockResolvedValue({ id: DETAIL_ID, name: 'MMLU' } as any);++ renderDetail(DETAIL_ID);+ await waitFor(() =>+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]?.name).toBe('MMLU'),+ );+ await waitFor(async () =>+ expect(+ (await datasetDetailResource.storage!.get({ queryKey: DETAIL_STORAGE_KEY, scope }))?.data,+ ).toEqual({ id: DETAIL_ID, name: 'MMLU' }),+ );++ // Deleted elsewhere: every read now answers NOT_FOUND. The persisted row+ // must not keep the page painting a dataset that no longer exists.+ getDataset.mockRejectedValue({ data: { code: 'NOT_FOUND' } });+ await act(async () => {+ await useEvalStore+ .getState()+ .refreshDatasetDetail(DETAIL_ID)+ .catch(() => {});+ });++ await waitFor(() =>+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]).toBeUndefined(),+ );+ await waitFor(async () =>+ expect(+ await datasetDetailResource.storage!.get({ queryKey: DETAIL_STORAGE_KEY, scope }),+ ).toBeUndefined(),+ );+ });++ it('keeps a deleted dataset gone when its hydrate lands after NOT_FOUND', async () => {+ const getDataset = vi+ .spyOn(agentEvalService, 'getDataset')+ .mockRejectedValue({ data: { code: 'NOT_FOUND' } });++ // Cold revisit: a stale row is still in storage, but its read only finishes+ // after the 404 has already evicted the entry.+ const storage = datasetDetailResource.storage!;+ await storage.set(+ { queryKey: DETAIL_STORAGE_KEY, scope },+ { data: { id: DETAIL_ID, name: 'Cached' } as any, updatedAt: 1 },+ );+ const originalGet = storage.get.bind(storage);+ // The snapshot the in-flight hydrate is holding while the 404 lands.+ const staleRow = await originalGet({ queryKey: DETAIL_STORAGE_KEY, scope });+ let detailReads = 0;+ let releaseRead!: () => void;+ const held = new Promise<void>((resolve) => (releaseRead = resolve));+ vi.spyOn(storage, 'get').mockImplementation((key) => {+ if (key.queryKey !== DETAIL_STORAGE_KEY) return originalGet(key);+ detailReads += 1;+ return held.then(() => staleRow);+ });++ const { result } = renderDetail(DETAIL_ID);++ // The definitive NOT_FOUND settles first…+ await waitFor(() => expect(getDataset).toHaveBeenCalled());+ await waitFor(() => expect(result.current.error).toBeTruthy());++ // …then the stale snapshot the hydrate already read lands.+ await act(async () => {+ releaseRead();+ await new Promise((resolve) => setTimeout(resolve, 0));+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ // The hydration did read a row, but the late stale value must not repaint it.+ expect(detailReads).toBeGreaterThan(0);+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]).toBeUndefined();+ await waitFor(async () =>+ expect(await originalGet({ queryKey: DETAIL_STORAGE_KEY, scope })).toBeUndefined(),+ );+ });++ it('drops a deleted dataset from its persisted detail and every list', async () => {+ vi.spyOn(agentEvalService, 'getDataset').mockResolvedValue({+ id: DETAIL_ID,+ name: 'MMLU',+ } as any);+ vi.spyOn(agentEvalService, 'listDatasets').mockResolvedValue([+ listRow(DETAIL_ID, 'MMLU'),+ listRow('d2', 'Other'),+ ]);+ const deleteDataset = vi.spyOn(agentEvalService, 'deleteDataset').mockResolvedValue({} as any);++ renderDetail(DETAIL_ID);+ renderBenchList();+ await waitFor(() => {+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]?.name).toBe('MMLU');+ expect(benchList()).toHaveLength(2);+ });+ await waitFor(async () =>+ expect(+ (await datasetDetailResource.storage!.get({ queryKey: DETAIL_STORAGE_KEY, scope }))?.data,+ ).toEqual({ id: DETAIL_ID, name: 'MMLU' }),+ );++ await act(() => useEvalStore.getState().deleteDataset(DETAIL_ID));++ expect(deleteDataset).toHaveBeenCalledWith(DETAIL_ID);+ expect(useEvalStore.getState().datasetDetailMap[DETAIL_ID]).toBeUndefined();+ expect(benchList()?.map((row) => row.id)).toEqual(['d2']);+ // The next visit must not hydrate the deleted dataset back.+ await waitFor(async () =>+ expect(+ await datasetDetailResource.storage!.get({ queryKey: DETAIL_STORAGE_KEY, scope }),+ ).toBeUndefined(),+ );+ await waitFor(async () =>+ expect(+ (await datasetListResource.storage!.get({ queryKey: BENCH_STORAGE_KEY, scope }))?.data?.map(+ (row) => row.id,+ ),+ ).toEqual(['d2']),+ );+ });++ it('repaints the refreshed benchmark list after a mutation', async () => {+ const listDatasets = vi+ .spyOn(agentEvalService, 'listDatasets')+ .mockResolvedValue([listRow('d1', 'Before')]);+ renderBenchList();+ await waitFor(() => expect(benchList()?.[0]?.name).toBe('Before'));++ listDatasets.mockResolvedValue([listRow('d1', 'After')]);+ await act(() => useEvalStore.getState().refreshDatasets(BENCH));++ await waitFor(() => expect(benchList()?.[0]?.name).toBe('After'));+ });++ it('drops the previous scope’s lists on a cache-scope switch', async () => {+ vi.spyOn(agentEvalService, 'listDatasets').mockResolvedValue([listRow('d1', 'Personal')]);+ const { rerender } = renderBenchList();+ await waitFor(() => expect(benchList()).toHaveLength(1));++ // Switch identity: the new scope's rows are still in flight.+ useScope(`${scope.split(':')[0]}:ws-1`);+ vi.mocked(agentEvalService.listDatasets).mockImplementation(pending);+ rerender();++ expect(useEvalStore.getState().datasetListMap[BENCH]).toBeUndefined();+ });+});diff --git a/src/store/eval/slices/dataset/selectors.ts b/src/store/eval/slices/dataset/selectors.tsnew file mode 100644index 00000000000..ced3e661e6c--- /dev/null+++ b/src/store/eval/slices/dataset/selectors.ts@@ -0,0 +1,34 @@+import type { AgentEvalDatasetListItem } from '@lobechat/types';++import type { EvalStore } from '@/store/eval/store';++import { ALL_DATASETS_KEY } from './projection';++/** Stable empty array so a selector never returns a fresh reference on every read. */+const EMPTY_DATASETS: AgentEvalDatasetListItem[] = [];++/**+ * Datasets of one benchmark. The scope-wide list is read through+ * `useFetchAllDatasets` / {@link datasetSelectors.allDatasets}.+ */+const datasetList = (benchmarkId?: string) => (s: EvalStore) =>+ (benchmarkId ? s.datasetListMap[benchmarkId] : undefined) ?? EMPTY_DATASETS;++/** Every dataset of the active scope (the scope-wide list entry). */+const allDatasets = (s: EvalStore) => s.datasetListMap[ALL_DATASETS_KEY] ?? EMPTY_DATASETS;++/**+ * The benchmark list has no local copy yet (`undefined` is the loading+ * signal) — the sidebar / datasets tab keep their skeleton until the first paint.+ */+const isLoadingDatasetList = (benchmarkId?: string) => (s: EvalStore) =>+ !!benchmarkId && s.datasetListMap[benchmarkId] === undefined;++const getDatasetById = (id: string) => (s: EvalStore) => s.datasetDetailMap[id];++export const datasetSelectors = {+ allDatasets,+ datasetList,+ getDatasetById,+ isLoadingDatasetList,+};