Skip to content

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

♻️ refactor(eval): move the testCase slice onto @lobechat/replica (#20688)

Arvin Xu49698befdd02
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
index cdea2a49fd0..485bf8bf8ca 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
@@ -8,7 +8,7 @@ import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { agentEvalService } from '@/services/agentEval';
-import { useEvalStore } from '@/store/eval';
+import { testCaseSelectors, useEvalStore } from '@/store/eval';
import { createDatasetCreateModal } from '../../../../features/DatasetCreateModal';
import { createDatasetEditModal } from '../../../../features/DatasetEditModal';
@@ -59,23 +59,24 @@ const DatasetsTab = memo<DatasetsTabProps>(
const useFetchTestCases = useEvalStore((s) => s.useFetchTestCases);
const refreshTestCases = useEvalStore((s) => s.refreshTestCases);
- // Fetch test cases for expanded dataset - use SWR return value directly
- const { data: testCaseData, isLoading: loading } = useFetchTestCases(
- expandedDs
- ? {
- datasetId: expandedDs,
- limit: pagination.pageSize,
- offset: (pagination.current - 1) * pagination.pageSize,
- }
- : { datasetId: '', limit: 0, offset: 0 },
- );
-
- const testCases = testCaseData?.data || [];
- const total = testCaseData?.total || 0;
+ // Fetch the expanded dataset's case page; the rows are read from the replica.
+ // One query for the fetch and the reads: the rows only show for this exact page.
+ const caseQuery = expandedDs
+ ? {
+ datasetId: expandedDs,
+ limit: pagination.pageSize,
+ offset: (pagination.current - 1) * pagination.pageSize,
+ }
+ : null;
+ useFetchTestCases(caseQuery);
+
+ const testCases = useEvalStore(testCaseSelectors.testCases(caseQuery));
+ const total = useEvalStore(testCaseSelectors.testCaseTotal(caseQuery));
+ const loading = useEvalStore(testCaseSelectors.isLoadingTestCases(caseQuery));
const handleRefreshTestCases = useCallback(
- async (datasetId: string) => {
- await refreshTestCases(datasetId);
+ async () => {
+ await refreshTestCases();
onRefresh();
},
[refreshTestCases, onRefresh],
@@ -158,7 +159,7 @@ const DatasetsTab = memo<DatasetsTabProps>(
try {
await agentEvalService.deleteTestCase(testCase.id);
toast.success(t('testCase.delete.success'));
- if (expandedDs) await refreshTestCases(expandedDs);
+ if (expandedDs) await refreshTestCases();
onRefresh();
} catch {
toast.error(t('testCase.delete.error'));
diff --git a/src/routes/(main)/eval/datasets/[datasetId]/index.tsx b/src/routes/(main)/eval/datasets/[datasetId]/index.tsx
index 148433f9f6f..949f59dd3b7 100644
--- a/src/routes/(main)/eval/datasets/[datasetId]/index.tsx
+++ b/src/routes/(main)/eval/datasets/[datasetId]/index.tsx
@@ -13,7 +13,7 @@ import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { agentEvalService } from '@/services/agentEval';
-import { runSelectors, useEvalStore } from '@/store/eval';
+import { runSelectors, testCaseSelectors, useEvalStore } from '@/store/eval';
import TestCasePreviewPanel from '../../bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewPanel';
import TestCaseTable from '../../bench/[benchmarkId]/features/DatasetsTab/TestCaseTable';
@@ -122,14 +122,16 @@ const DatasetDetail = memo(() => {
[runList],
);
- const { data: testCaseData } = useFetchTestCases({
+ // One query for the fetch and the read: the rows only show for this exact page.
+ const caseQuery = {
datasetId: datasetId!,
limit: pagination.pageSize,
offset: (pagination.current - 1) * pagination.pageSize,
- });
+ };
+ useFetchTestCases(caseQuery);
- const testCases = testCaseData?.data || [];
- const total = testCaseData?.total || 0;
+ const testCases = useEvalStore(testCaseSelectors.testCases(caseQuery));
+ const total = useEvalStore(testCaseSelectors.testCaseTotal(caseQuery));
const filteredCases = testCases.filter((c: any) => {
if (diffFilter !== 'all' && c.metadata?.difficulty !== diffFilter) return false;
@@ -157,7 +159,7 @@ const DatasetDetail = memo(() => {
const handleRefresh = useCallback(async () => {
if (datasetId) {
- await refreshTestCases(datasetId);
+ await refreshTestCases();
await refreshDatasetDetail(datasetId);
}
}, [datasetId, refreshTestCases, refreshDatasetDetail]);
diff --git a/src/routes/(main)/eval/features/TestCaseDetail/index.tsx b/src/routes/(main)/eval/features/TestCaseDetail/index.tsx
index 8bfe61b235f..67ce998a279 100644
--- a/src/routes/(main)/eval/features/TestCaseDetail/index.tsx
+++ b/src/routes/(main)/eval/features/TestCaseDetail/index.tsx
@@ -69,9 +69,10 @@ export interface TestCaseDetailProps {
testCase: {
datasetId: string;
content?: {
+ expected?: string;
input?: string;
messages?: Array<{ content?: unknown; role?: string }>;
- } & Record<string, unknown>;
+ };
evalConfig?: Record<string, unknown> | null;
evalMode?: string | null;
id: string;
@@ -117,7 +118,7 @@ const TestCaseDetail = memo<TestCaseDetailProps>(({ datasetName, testCase }) =>
if (!patch) return stop();
setSaving(true);
try {
- await updateTestCase(testCase.id, testCase.datasetId, patch);
+ await updateTestCase(testCase.id, patch);
stop();
} catch (error) {
toast.error((error as Error)?.message ?? t('testCaseDetail.saveFailed'));
diff --git a/src/store/eval/selectors.ts b/src/store/eval/selectors.ts
index 6c51e2ea999..985777ca27f 100644
--- a/src/store/eval/selectors.ts
+++ b/src/store/eval/selectors.ts
@@ -1,3 +1,4 @@
export { benchmarkSelectors } from './slices/benchmark/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/testCase/action.test.ts b/src/store/eval/slices/testCase/action.test.ts
new file mode 100644
index 00000000000..caa6c7c063a
--- /dev/null
+++ b/src/store/eval/slices/testCase/action.test.ts
@@ -0,0 +1,334 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * `eval/slices/testCase` is replica-backed: every visited case page and a single
+ * case detail paint from the persisted copy on the first frame, the network only
+ * confirms, each page keeps its own entry (so returning to a page repaints its
+ * cached rows instead of waiting on the network), and the mutation actions keep
+ * the same service calls they had before the move.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, 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 { testCaseSelectors } from '@/store/eval/slices/testCase/selectors';
+
+import { testCaseInitialState } from './initialState';
+import {
+ testCaseDetailResource,
+ type TestCaseListQuery,
+ testCaseListResource,
+} from './projection';
+
+vi.mock('@/services/agentEval', () => ({
+ agentEvalService: {
+ getTestCase: vi.fn(),
+ listTestCases: vi.fn(),
+ updateTestCase: vi.fn(),
+ },
+}));
+
+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 DATASET = 'dataset-1';
+const CASE = 'case-1';
+const PAGE: TestCaseListQuery = { datasetId: DATASET, limit: 10, offset: 0 };
+/** A second page of the same dataset: the same entry shape, another window. */
+const PAGE_2: TestCaseListQuery = { ...PAGE, offset: 10 };
+const OTHER_PAGES: TestCaseListQuery[] = [
+ { datasetId: 'ds-a', limit: 5, offset: 0 },
+ { datasetId: 'ds-b', limit: 5, offset: 0 },
+];
+
+const testCase = (id: string, extra: Record<string, unknown> = {}): any => ({
+ content: { input: `input-${id}` },
+ datasetId: DATASET,
+ evalConfig: {},
+ evalMode: 'rubric',
+ id,
+ metadata: {},
+ sortOrder: 1,
+ ...extra,
+});
+
+const okList = (data: any[]) => ({ data, total: data.length }) as any;
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const listKey = (query: TestCaseListQuery) => testCaseListResource.storageKey(query);
+const LIST_KEY = listKey(PAGE);
+const PAGE_2_KEY = listKey(PAGE_2);
+const DETAIL_KEY = testCaseDetailResource.storageKey(CASE);
+const OTHER_KEYS = OTHER_PAGES.map(listKey);
+
+describe('eval testCase slice replicas', () => {
+ 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-test-case-user-${randomUUID()}:personal`);
+ act(() => useEvalStore.setState(testCaseInitialState));
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ [DETAIL_KEY, LIST_KEY, PAGE_2_KEY, ...OTHER_KEYS].map((queryKey) =>
+ testCaseListResource.storage!.remove({ queryKey, scope: value }),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted case page before the network answers', async () => {
+ await testCaseListResource.storage!.set(
+ { queryKey: LIST_KEY, scope },
+ {
+ data: { items: [testCase(CASE, { content: { input: 'Cached' } })], total: 1 },
+ updatedAt: 1,
+ },
+ );
+ vi.mocked(agentEvalService.listTestCases).mockImplementation(pending);
+
+ const sync = renderHook(() => useEvalStore((s) => s.useFetchTestCases)(PAGE), { wrapper });
+ const rows = renderHook(() => useEvalStore(testCaseSelectors.testCases(PAGE)));
+
+ await waitFor(() => expect(rows.result.current[0]?.content?.input).toBe('Cached'));
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ // The count rides the page itself, so a hydrated page paints the pager too.
+ expect(testCaseSelectors.testCaseTotal(PAGE)(useEvalStore.getState())).toBe(1);
+ });
+
+ it('replaces the case page with the server response and persists it', async () => {
+ vi.mocked(agentEvalService.listTestCases).mockResolvedValue(
+ okList([testCase(CASE, { content: { input: 'Server' } })]),
+ );
+
+ renderHook(() => useEvalStore((s) => s.useFetchTestCases)(PAGE), { wrapper });
+
+ await waitFor(() =>
+ expect(useEvalStore.getState().testCaseListMap[LIST_KEY]?.items?.[0]?.content?.input).toBe(
+ 'Server',
+ ),
+ );
+ expect(agentEvalService.listTestCases).toHaveBeenCalledWith(PAGE);
+ await waitFor(async () =>
+ expect(
+ (await testCaseListResource.storage!.get({ queryKey: LIST_KEY, scope }))?.data,
+ ).toEqual({ items: [testCase(CASE, { content: { input: 'Server' } })], total: 1 }),
+ );
+ });
+
+ it('keeps each dataset’s case page under its own key', async () => {
+ vi.mocked(agentEvalService.listTestCases).mockImplementation(async ({ datasetId }: any) =>
+ okList([testCase(`${datasetId}-c`, { content: { input: datasetId } })]),
+ );
+
+ renderHook(
+ () => {
+ useEvalStore((s) => s.useFetchTestCases)(OTHER_PAGES[0]);
+ useEvalStore((s) => s.useFetchTestCases)(OTHER_PAGES[1]);
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => {
+ const state = useEvalStore.getState();
+ expect(state.testCaseListMap[OTHER_KEYS[0]]?.items?.[0]?.content?.input).toBe('ds-a');
+ expect(state.testCaseListMap[OTHER_KEYS[1]]?.items?.[0]?.content?.input).toBe('ds-b');
+ });
+ });
+
+ it('keeps the previous page cached while the next page is in flight, then fails', async () => {
+ vi.mocked(agentEvalService.listTestCases).mockResolvedValueOnce(okList([testCase('page-1')]));
+
+ const sync = renderHook(
+ (query: TestCaseListQuery) => useEvalStore((s) => s.useFetchTestCases)(query),
+ { initialProps: PAGE, wrapper },
+ );
+ await waitFor(() =>
+ expect(testCaseSelectors.testCases(PAGE)(useEvalStore.getState())[0]?.id).toBe('page-1'),
+ );
+
+ // Page 2 is still in flight, then fails: it is its own (empty) entry.
+ let reject!: (error: Error) => void;
+ vi.mocked(agentEvalService.listTestCases).mockImplementationOnce(
+ () => new Promise((_, r) => (reject = r)),
+ );
+ sync.rerender(PAGE_2);
+ await waitFor(() => expect(agentEvalService.listTestCases).toHaveBeenCalledWith(PAGE_2));
+
+ const state = () => useEvalStore.getState();
+ expect(state().testCaseListMap[LIST_KEY]?.items?.[0]?.id).toBe('page-1');
+ expect(testCaseSelectors.testCases(PAGE_2)(state())).toEqual([]);
+ expect(testCaseSelectors.isLoadingTestCases(PAGE_2)(state())).toBe(true);
+
+ await act(async () => reject(new Error('network')));
+ await waitFor(() => expect(sync.result.current.error).toBeTruthy());
+ expect(testCaseSelectors.testCases(PAGE_2)(state())).toEqual([]);
+ // The dataset-wide count stays usable for the pager meanwhile.
+ expect(testCaseSelectors.testCaseTotal(PAGE_2)(state())).toBe(1);
+ });
+
+ it('paints a page from cache again when returning to it', async () => {
+ vi.mocked(agentEvalService.listTestCases).mockImplementation(async (query: any) =>
+ okList([testCase(query.offset === 0 ? 'page-1' : 'page-2')]),
+ );
+
+ const sync = renderHook(
+ (query: TestCaseListQuery) => useEvalStore((s) => s.useFetchTestCases)(query),
+ { initialProps: PAGE, wrapper },
+ );
+ await waitFor(() =>
+ expect(testCaseSelectors.testCases(PAGE)(useEvalStore.getState())[0]?.id).toBe('page-1'),
+ );
+ sync.rerender(PAGE_2);
+ await waitFor(() =>
+ expect(testCaseSelectors.testCases(PAGE_2)(useEvalStore.getState())[0]?.id).toBe('page-2'),
+ );
+
+ // Back to page 1 with the network refusing to answer: its own entry is still
+ // cached, so the rows paint instead of the table sitting empty.
+ vi.mocked(agentEvalService.listTestCases).mockImplementation(pending);
+ sync.rerender(PAGE);
+
+ const state = () => useEvalStore.getState();
+ expect(testCaseSelectors.testCases(PAGE)(state())[0]?.id).toBe('page-1');
+ expect(testCaseSelectors.isLoadingTestCases(PAGE)(state())).toBe(false);
+ expect(testCaseSelectors.testCases(PAGE_2)(state())[0]?.id).toBe('page-2');
+ });
+
+ it('keeps the hydrated count when switching to an uncached page', async () => {
+ await testCaseListResource.storage!.set(
+ { queryKey: LIST_KEY, scope },
+ { data: { items: [testCase(CASE)], total: 7 }, updatedAt: 1 },
+ );
+ // Page 1 is restored from storage and the network never answers.
+ vi.mocked(agentEvalService.listTestCases).mockImplementation(pending);
+
+ const sync = renderHook(
+ (query: TestCaseListQuery) => useEvalStore((s) => s.useFetchTestCases)(query),
+ { initialProps: PAGE, wrapper },
+ );
+ await waitFor(() =>
+ expect(testCaseSelectors.testCaseTotal(PAGE)(useEvalStore.getState())).toBe(7),
+ );
+
+ // Page 2 has no local copy yet, but the dataset count is still known.
+ sync.rerender(PAGE_2);
+ const state = () => useEvalStore.getState();
+ expect(testCaseSelectors.testCases(PAGE_2)(state())).toEqual([]);
+ expect(testCaseSelectors.testCaseTotal(PAGE_2)(state())).toBe(7);
+ });
+
+ it('disables the sync when no dataset is requested', async () => {
+ renderHook(() => useEvalStore((s) => s.useFetchTestCases)(null), { wrapper });
+
+ await act(() => new Promise((resolve) => setTimeout(resolve, 20)));
+ expect(agentEvalService.listTestCases).not.toHaveBeenCalled();
+ });
+
+ it('hydrates a case detail by id and revalidates it through the same entry', async () => {
+ await testCaseDetailResource.storage!.set(
+ { queryKey: DETAIL_KEY, scope },
+ { data: testCase(CASE, { content: { input: 'Cached case' } }), updatedAt: 1 },
+ );
+ vi.mocked(agentEvalService.getTestCase).mockImplementation(pending);
+
+ const hook = renderHook(() => useEvalStore((s) => s.useFetchTestCase)(CASE), { wrapper });
+
+ await waitFor(() => expect(hook.result.current.data?.content?.input).toBe('Cached case'));
+ expect(agentEvalService.getTestCase).toHaveBeenCalledWith(CASE);
+ });
+
+ it('refreshTestCases revalidates the loaded case pages', async () => {
+ vi.mocked(agentEvalService.listTestCases).mockResolvedValue(okList([testCase(CASE)]));
+
+ renderHook(() => useEvalStore((s) => s.useFetchTestCases)(PAGE), { wrapper });
+ await waitFor(() => expect(agentEvalService.listTestCases).toHaveBeenCalledTimes(1));
+
+ vi.mocked(agentEvalService.listTestCases).mockResolvedValue(okList([]));
+ await act(() => useEvalStore.getState().refreshTestCases());
+
+ await waitFor(() =>
+ expect(useEvalStore.getState().testCaseListMap[LIST_KEY]?.items).toEqual([]),
+ );
+ });
+
+ it('refreshes the detail and the loaded pages after updateTestCase', async () => {
+ vi.mocked(agentEvalService.getTestCase).mockResolvedValue(
+ testCase(CASE, { content: { input: 'Before' } }) as any,
+ );
+ vi.mocked(agentEvalService.listTestCases).mockResolvedValue(
+ okList([testCase(CASE, { content: { input: 'Before' } })]),
+ );
+
+ renderHook(
+ () => {
+ useEvalStore((s) => s.useFetchTestCase)(CASE);
+ useEvalStore((s) => s.useFetchTestCases)(PAGE);
+ },
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(useEvalStore.getState().testCaseDetailMap[CASE]?.content?.input).toBe('Before'),
+ );
+
+ vi.mocked(agentEvalService.updateTestCase).mockResolvedValue(undefined as any);
+ vi.mocked(agentEvalService.getTestCase).mockResolvedValue(
+ testCase(CASE, { content: { input: 'After' } }) as any,
+ );
+ vi.mocked(agentEvalService.listTestCases).mockResolvedValue(
+ okList([testCase(CASE, { content: { input: 'After' } })]),
+ );
+
+ await act(() =>
+ useEvalStore.getState().updateTestCase(CASE, { content: { input: 'After' } }),
+ );
+
+ expect(agentEvalService.updateTestCase).toHaveBeenCalledWith({
+ content: { input: 'After' },
+ id: CASE,
+ });
+ await waitFor(() =>
+ expect(useEvalStore.getState().testCaseDetailMap[CASE]?.content?.input).toBe('After'),
+ );
+ await waitFor(() =>
+ expect(useEvalStore.getState().testCaseListMap[LIST_KEY]?.items?.[0]?.content?.input).toBe(
+ 'After',
+ ),
+ );
+ });
+});
diff --git a/src/store/eval/slices/testCase/action.ts b/src/store/eval/slices/testCase/action.ts
index 7e194d3368f..bd416d38471 100644
--- a/src/store/eval/slices/testCase/action.ts
+++ b/src/store/eval/slices/testCase/action.ts
@@ -1,46 +1,114 @@
-import type { SWRResponse } from 'swr';
-
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { evalKeys } from '@/libs/swr/keys';
+import {
+ createReplicaSlice,
+ recordLens,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+} 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 { setNamespace } from '@/utils/storeDebug';
+
+import {
+ datasetIdOfPageKey,
+ type TestCaseDetail,
+ testCaseDetailResource,
+ type TestCaseListQuery,
+ testCaseListQueryKey,
+ testCaseListResource,
+ type TestCaseListValue,
+} from './projection';
+
+const n = setNamespace('evalTestCase');
type Setter = StoreSetter<EvalStore>;
+/** Pre-migration `useFetchTestCase` return shape, backed by the detail replica. */
+export interface TestCaseDetailSyncResult {
+ /** The case once it has settled (hydrated or fetched), else `undefined`. */
+ data: TestCaseDetail | undefined;
+ error: unknown;
+ /** First load in flight with nothing settled yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`, kept for the pre-migration call site. */
+ mutate: () => Promise<unknown>;
+}
+
+/**
+ * Where the case pages live, plus the dataset count derived from them.
+ *
+ * Every committed page — hydrated from storage or answered by the network —
+ * refreshes its dataset's count in the SAME commit. Keeping it derived means a
+ * page restored from IndexedDB publishes its cached total too; without that,
+ * switching from a hydrated page to a page with no local copy yet would fall
+ * back to a count nobody wrote and collapse the pager to 0.
+ */
+const testCasePageLens: ReplicaLens<EvalStore, TestCaseListValue> = {
+ clear: () => ({ testCaseListMap: {}, testCaseTotalMap: {} }),
+ get: (state, key) => state.testCaseListMap[key],
+ keys: (state) => Object.keys(state.testCaseListMap),
+ set: (state, key, data) => {
+ const testCaseListMap = { ...state.testCaseListMap };
+ let testCaseTotalMap = state.testCaseTotalMap;
+ if (data === undefined) {
+ delete testCaseListMap[key];
+ } else {
+ testCaseListMap[key] = data;
+ const datasetId = datasetIdOfPageKey(key);
+ if (datasetId) testCaseTotalMap = { ...testCaseTotalMap, [datasetId]: data.total };
+ }
+ return { testCaseListMap, testCaseTotalMap };
+ },
+};
+
export const createTestCaseSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
new TestCaseActionImpl(set, get, _api);
export class TestCaseActionImpl {
readonly #get: () => EvalStore;
- readonly #set: Setter;
+ readonly #detail;
+ readonly #list;
constructor(set: Setter, get: () => EvalStore, _api?: unknown) {
void _api;
- this.#set = set;
this.#get = get;
- }
-
- getTestCaseById = (id: string): any | undefined => {
- return this.#get().testCaseDetailCache[id];
- };
- getTestCasesByDatasetId = (datasetId: string): any[] => {
- return this.#get().testCasesCache[datasetId]?.data || [];
- };
-
- getTestCasesTotalByDatasetId = (datasetId: string): number => {
- return this.#get().testCasesCache[datasetId]?.total || 0;
- };
+ // Two local-first resources over the test-case entity, each owning ONE store
+ // location (selectors keep reading those maps):
+ // - `#list`: the visited case pages → `testCaseListMap[pageKey]`, with the
+ // dataset counts derived into `testCaseTotalMap`
+ // - `#detail`: a case addressed by id → `testCaseDetailMap[id]`
+ this.#list = createReplicaSlice(testCaseListResource, {
+ actionPrefix: n('testCaseList'),
+ fetcher: ({ datasetId, limit, offset }) =>
+ agentEvalService.listTestCases({ datasetId, limit, offset }),
+ get,
+ merge: (response) => ({ items: response.data, total: response.total }),
+ set,
+ stateKey: 'testCaseListReplica',
+ view: testCasePageLens,
+ });
+ this.#detail = createReplicaSlice(testCaseDetailResource, {
+ actionPrefix: n('testCaseDetail'),
+ fetcher: (id) => agentEvalService.getTestCase(id),
+ get,
+ set,
+ stateKey: 'testCaseDetailReplica',
+ view: recordLens<EvalStore, TestCaseDetail>('testCaseDetailMap'),
+ });
+ }
- isLoadingTestCases = (datasetId: string): boolean => {
- return this.#get().loadingTestCaseIds.includes(datasetId);
+ refreshTestCaseDetail = async (id: string): Promise<void> => {
+ await this.#detail.revalidate(id);
};
- refreshTestCases = async (datasetId: string): Promise<void> => {
- await mutate(
- (key) => Array.isArray(key) && key[0] === evalKeys.testCases.root && key[1] === datasetId,
- );
+ /**
+ * Revalidate the loaded case pages. Pages are separate entries and a case
+ * write can move rows across page boundaries, so every loaded page is
+ * revalidated rather than only the one the caller happens to be looking at.
+ */
+ refreshTestCases = async (): Promise<void> => {
+ await this.#list.revalidate();
};
/**
@@ -50,69 +118,45 @@ export class TestCaseActionImpl {
*/
updateTestCase = async (
id: string,
- datasetId: string,
data: {
content?: { expected?: string; input?: string };
evalConfig?: { criteria?: string };
},
): Promise<void> => {
await agentEvalService.updateTestCase({ id, ...data });
- await mutate(evalKeys.testCaseDetail(id));
- await this.refreshTestCases(datasetId);
+ await Promise.all([this.refreshTestCaseDetail(id), this.refreshTestCases()]);
};
/**
- * A test case on its own, not as a row of a dataset page — the case detail
- * route is reachable directly, so it cannot rely on the list being loaded.
+ * Fetch orchestration only; read the case from `testCaseDetailMap`. Keeps the
+ * pre-migration `{ data, error, isLoading, mutate }` shape so the detail
+ * route's NOT_FOUND handling is unchanged.
*/
- useFetchTestCase = (id?: string): SWRResponse => {
- return useClientDataSWR(
- id ? evalKeys.testCaseDetail(id) : null,
- () => agentEvalService.getTestCase(id!),
- {
- onSuccess: (data: any) => {
- this.#set(
- (state) => ({
- testCaseDetailCache: { ...state.testCaseDetailCache, [data.id]: data },
- }),
- false,
- `useFetchTestCase/success/${id}`,
- );
- },
- },
- );
+ useFetchTestCase = (id?: string): TestCaseDetailSyncResult => {
+ // 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.testCaseDetailMap[id] : undefined));
+ const sync = this.#detail.useSync(id ?? null);
+ const data = id ? this.#get().testCaseDetailMap[id] : undefined;
+ return {
+ data,
+ error: sync.error,
+ // A failed first load is neither loading nor settled: gate on the error so
+ // the route falls through to its error state instead of a skeleton.
+ isLoading: data === undefined && !sync.error,
+ mutate: sync.revalidate,
+ };
};
- useFetchTestCases = (params: {
- datasetId: string;
- limit?: number;
- offset?: number;
- }): SWRResponse => {
- const { datasetId, limit = 10, offset = 0 } = params;
-
- return useClientDataSWR(
- datasetId ? evalKeys.testCases(datasetId, limit, offset) : null,
- () => agentEvalService.listTestCases({ datasetId, limit, offset }),
- {
- onSuccess: (data: any) => {
- this.#set(
- (state) => ({
- loadingTestCaseIds: state.loadingTestCaseIds.filter((id) => id !== datasetId),
- testCasesCache: {
- ...state.testCasesCache,
- [datasetId]: {
- data: data.data,
- pagination: { limit, offset },
- total: data.total,
- },
- },
- }),
- false,
- `useFetchTestCases/success/${datasetId}`,
- );
- },
- },
- );
+ /**
+ * Fetch orchestration only; read the rows with `testCaseSelectors.testCases(query)`.
+ * `null` disables the sync — the collapsed dataset card asks for no cases.
+ */
+ useFetchTestCases = (query: TestCaseListQuery | null): ReplicaSyncResult => {
+ // Subscribe so a replica commit re-renders the consumer; the rows themselves
+ // are read through the selectors.
+ useEvalStore((s) => (query ? s.testCaseListMap[testCaseListQueryKey(query)] : undefined));
+ return this.#list.useSync(query?.datasetId ? query : null);
};
}
diff --git a/src/store/eval/slices/testCase/initialState.ts b/src/store/eval/slices/testCase/initialState.ts
index 77fc6fdd04b..62281e2dcc7 100644
--- a/src/store/eval/slices/testCase/initialState.ts
+++ b/src/store/eval/slices/testCase/initialState.ts
@@ -1,19 +1,28 @@
-interface TestCaseCacheItem {
- data: any[];
- pagination: { limit: number; offset: number };
- total: number;
-}
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type { TestCaseDetail, TestCaseListValue } from './projection';
export interface TestCaseSliceState {
- // Map to cache test cases by datasetId
- loadingTestCaseIds: string[];
- /** A single test case addressed by its own id, for the case detail page. */
- testCaseDetailCache: Record<string, any>;
- testCasesCache: Record<string, TestCaseCacheItem>;
+ /** Replica view of a test case addressed by its own id, for the case detail page. */
+ testCaseDetailMap: Record<string, TestCaseDetail>;
+ /** Replica bookkeeping of `testCaseDetailMap`. */
+ testCaseDetailReplica: ReplicaState<TestCaseDetail>;
+ /** Replica view of the visited case pages, one entry per page query (`testCaseListQueryKey`). */
+ testCaseListMap: Record<string, TestCaseListValue>;
+ /** Replica bookkeeping of `testCaseListMap`. */
+ testCaseListReplica: ReplicaState<TestCaseListValue>;
+ /**
+ * The dataset-wide case count, as the latest page response reported it. It
+ * lives beside the per-page entries so that switching to a page whose rows are
+ * still loading never collapses the pager to 0.
+ */
+ testCaseTotalMap: Record<string, number>;
}
export const testCaseInitialState: TestCaseSliceState = {
- loadingTestCaseIds: [],
- testCaseDetailCache: {},
- testCasesCache: {},
+ testCaseDetailMap: {},
+ testCaseDetailReplica: createReplicaState(),
+ testCaseListMap: {},
+ testCaseListReplica: createReplicaState(),
+ testCaseTotalMap: {},
};
diff --git a/src/store/eval/slices/testCase/projection.ts b/src/store/eval/slices/testCase/projection.ts
new file mode 100644
index 00000000000..4c3ef5be172
--- /dev/null
+++ b/src/store/eval/slices/testCase/projection.ts
@@ -0,0 +1,63 @@
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import type { agentEvalService } from '@/services/agentEval';
+
+type ListTestCasesResponse = Awaited<ReturnType<typeof agentEvalService.listTestCases>>;
+type GetTestCaseResponse = Awaited<ReturnType<typeof agentEvalService.getTestCase>>;
+
+/** A test case row as the case list returns it. */
+export type TestCaseListItem = ListTestCasesResponse['data'][number];
+/** The single case the detail route renders; `getTestCase` returns the row itself. */
+export type TestCaseDetail = GetTestCaseResponse;
+
+/** Everything that decides which case rows a page holds. */
+export interface TestCaseListQuery {
+ datasetId: string;
+ limit?: number;
+ offset?: number;
+}
+
+export interface TestCaseListValue {
+ items: TestCaseListItem[];
+ total: number;
+}
+
+/**
+ * Entry key of one page: the whole query, not just the dataset. A dataset view
+ * shows a single page at a time, but every visited page keeps its own entry —
+ * and its own persisted row — so returning to a page paints its cached rows
+ * again instead of leaving the table empty until the network answers.
+ */
+export const testCaseListQueryKey = (query: TestCaseListQuery) => stableQueryKey(query);
+
+export const testCaseListResource = defineReplica<
+ TestCaseListQuery,
+ TestCaseListValue,
+ ListTestCasesResponse
+>({
+ key: testCaseListQueryKey,
+ name: 'evalTestCaseList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** By-id test-case detail cache (`testCaseDetailMap[id]`). */
+export const testCaseDetailResource = defineReplica<string, TestCaseDetail, GetTestCaseResponse>({
+ key: (id) => id,
+ name: 'evalTestCaseDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * The dataset a page key belongs to. A page key is its query's JSON, so the
+ * owning dataset can be read back where only the key is at hand — the page lens
+ * mirrors each committed page's count into `testCaseTotalMap`.
+ */
+export const datasetIdOfPageKey = (key: string): string | undefined => {
+ try {
+ const parsed = JSON.parse(key) as { datasetId?: string } | null;
+ return parsed?.datasetId;
+ } catch {
+ return undefined;
+ }
+};
diff --git a/src/store/eval/slices/testCase/selectors.ts b/src/store/eval/slices/testCase/selectors.ts
new file mode 100644
index 00000000000..a9a8a9a5d65
--- /dev/null
+++ b/src/store/eval/slices/testCase/selectors.ts
@@ -0,0 +1,37 @@
+import type { EvalStore } from '@/store/eval/store';
+
+import { type TestCaseListItem, type TestCaseListQuery, testCaseListQueryKey } from './projection';
+
+/** Stable empty array so a selector never returns a fresh reference on every read. */
+const EMPTY_TEST_CASES: TestCaseListItem[] = [];
+
+/**
+ * The requested page has no local copy yet (`undefined` is the loading signal) —
+ * the table / collapsible card keeps its skeleton until first paint. Every page
+ * is its own entry, so a page whose request is still in flight (or failed) is
+ * loading even while another page of the same dataset is cached.
+ */
+const isLoadingTestCases = (query?: TestCaseListQuery | null) => (s: EvalStore) =>
+ !!query && s.testCaseListMap[testCaseListQueryKey(query)] === undefined;
+
+/** The rows of the requested page. */
+const testCases = (query?: TestCaseListQuery | null) => (s: EvalStore) =>
+ (query ? s.testCaseListMap[testCaseListQueryKey(query)]?.items : undefined) ?? EMPTY_TEST_CASES;
+
+/**
+ * The dataset-wide case count. Every page response counts the whole dataset, so
+ * the requested page's own value paints it first (a hydrated page included,
+ * without waiting for the network); a page that has not loaded yet falls back to
+ * the last count a response reported, which keeps the pager from collapsing.
+ */
+const testCaseTotal = (query?: TestCaseListQuery | null) => (s: EvalStore) => {
+ if (!query) return 0;
+ const page = s.testCaseListMap[testCaseListQueryKey(query)];
+ return page?.total ?? s.testCaseTotalMap[query.datasetId] ?? 0;
+};
+
+export const testCaseSelectors = {
+ isLoadingTestCases,
+ testCases,
+ testCaseTotal,
+};