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): migrate benchmark slice to @lobechat/replica (#20674)

Arvin Xued10e0d31871
diff --git a/src/store/eval/slices/benchmark/action.test.ts b/src/store/eval/slices/benchmark/action.test.ts
new file mode 100644
index 00000000000..3a53b754bbc
--- /dev/null
+++ b/src/store/eval/slices/benchmark/action.test.ts
@@ -0,0 +1,186 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The benchmark list and detail are `@lobechat/replica` resources. These tests
+ * pin the fetch orchestration and the write paths (create / update / delete)
+ * at the boundary: which service call each action makes and that the replica
+ * network sync is revalidated instead of a hand-written SWR `mutate`.
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createReplicaState } from '@/libs/replica';
+import { useEvalStore } from '@/store/eval';
+
+vi.mock('@/services/agentEval', () => ({
+ agentEvalService: {
+ createBenchmark: vi.fn(),
+ deleteBenchmark: vi.fn(),
+ getBenchmark: vi.fn(),
+ listBenchmarks: vi.fn(),
+ updateBenchmark: vi.fn(),
+ },
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const resetStore = () => {
+ useEvalStore.setState({
+ benchmarkDetailMap: {},
+ benchmarkDetailReplica: createReplicaState(),
+ benchmarkList: [],
+ benchmarkListInit: false,
+ benchmarkListReplica: createReplicaState(),
+ });
+};
+
+/** The replica network sync of a resource, as registered with the SWR driver. */
+const syncCalls = async (name: 'evalBenchmarkDetail' | 'evalBenchmarkList') => {
+ 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]) => ({ fetcher: fetcher as () => Promise<any>, key: key as unknown[] }));
+};
+
+/** 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');
+};
+
+const scope = () => useEvalStore.getState().benchmarkList;
+
+describe('BenchmarkAction replica wiring', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetStore();
+ });
+
+ describe('useFetchBenchmarks', () => {
+ it('registers one list sync and fetches through the service', async () => {
+ const { agentEvalService } = await import('@/services/agentEval');
+ vi.mocked(agentEvalService.listBenchmarks).mockResolvedValue([] as any);
+
+ renderHook(() => useEvalStore.getState().useFetchBenchmarks());
+
+ const [list] = await syncCalls('evalBenchmarkList');
+ expect(list).toBeDefined();
+ await list.fetcher();
+ expect(agentEvalService.listBenchmarks).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns the pre-migration { data, isLoading, error, mutate } shape', () => {
+ const { result } = renderHook(() => useEvalStore.getState().useFetchBenchmarks());
+ expect(result.current).toMatchObject({ data: undefined, isLoading: true });
+ expect(typeof result.current.mutate).toBe('function');
+ });
+ });
+
+ describe('useFetchBenchmarkDetail', () => {
+ it('registers a detail sync keyed by id and fetches that page', async () => {
+ const { agentEvalService } = await import('@/services/agentEval');
+ vi.mocked(agentEvalService.getBenchmark).mockResolvedValue({ id: 'b1' } as any);
+
+ renderHook(() => useEvalStore.getState().useFetchBenchmarkDetail('b1'));
+
+ const [detail] = await syncCalls('evalBenchmarkDetail');
+ expect(detail).toBeDefined();
+ await detail.fetcher();
+ expect(agentEvalService.getBenchmark).toHaveBeenCalledWith('b1');
+ });
+
+ it('is inert while no id is given', () => {
+ const { result } = renderHook(() =>
+ useEvalStore.getState().useFetchBenchmarkDetail(undefined),
+ );
+ expect(typeof result.current.mutate).toBe('function');
+ });
+ });
+
+ describe('refreshBenchmarks / refreshBenchmarkDetail', () => {
+ it('revalidates the list replica instead of a hand-written SWR key', async () => {
+ await useEvalStore.getState().refreshBenchmarks();
+ const matchers = await revalidationMatchers();
+ expect(
+ matchers.some((m) =>
+ m(['replica:sync', 'evalBenchmarkList', 1, 'anon:personal', 'all', {}]),
+ ),
+ ).toBe(true);
+ });
+
+ it('revalidates one detail entry by id', async () => {
+ await useEvalStore.getState().refreshBenchmarkDetail('b1');
+ const matchers = await revalidationMatchers();
+ expect(
+ matchers.some((m) =>
+ m(['replica:sync', 'evalBenchmarkDetail', 1, 'anon:personal', 'b1', 'b1']),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe('createBenchmark', () => {
+ it('creates through the service with rubrics defaulted, then refreshes the list', async () => {
+ const { agentEvalService } = await import('@/services/agentEval');
+ vi.mocked(agentEvalService.createBenchmark).mockResolvedValue({ id: 'b1' } as any);
+
+ const result = await useEvalStore.getState().createBenchmark({
+ identifier: 'mmlu',
+ name: 'MMLU',
+ });
+
+ expect(agentEvalService.createBenchmark).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'mmlu', name: 'MMLU', rubrics: [] }),
+ );
+ expect(result).toEqual({ id: 'b1' });
+ const matchers = await revalidationMatchers();
+ expect(matchers.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('deleteBenchmark', () => {
+ it('deletes through the service and drops the benchmark from the detail cache', async () => {
+ const { agentEvalService } = await import('@/services/agentEval');
+ vi.mocked(agentEvalService.deleteBenchmark).mockResolvedValue(undefined as any);
+ useEvalStore.setState({
+ benchmarkDetailMap: { b1: { id: 'b1', name: 'MMLU' } as any },
+ });
+
+ await useEvalStore.getState().deleteBenchmark('b1');
+
+ expect(agentEvalService.deleteBenchmark).toHaveBeenCalledWith('b1');
+ expect(useEvalStore.getState().benchmarkDetailMap.b1).toBeUndefined();
+ });
+ });
+
+ describe('updateBenchmark', () => {
+ it('optimistically patches the detail and then updates through the service', async () => {
+ const { agentEvalService } = await import('@/services/agentEval');
+ vi.mocked(agentEvalService.updateBenchmark).mockResolvedValue({ id: 'b1' } as any);
+ useEvalStore.setState({
+ benchmarkDetailMap: { b1: { id: 'b1', name: 'Old' } as any },
+ });
+
+ await useEvalStore.getState().updateBenchmark({ id: 'b1', identifier: 'mmlu', name: 'New' });
+
+ expect(agentEvalService.updateBenchmark).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'b1', name: 'New' }),
+ );
+ expect(useEvalStore.getState().benchmarkDetailMap.b1?.name).toBe('New');
+ });
+ });
+
+ it('scopes the replica list to the active identity', () => {
+ useEvalStore.setState({ benchmarkList: [{ id: 'b1' } as any], benchmarkListInit: true });
+ expect(scope()).toHaveLength(1);
+ });
+});
diff --git a/src/store/eval/slices/benchmark/action.ts b/src/store/eval/slices/benchmark/action.ts
index b0fc1ab16b4..8e2608a7d90 100644
--- a/src/store/eval/slices/benchmark/action.ts
+++ b/src/store/eval/slices/benchmark/action.ts
@@ -1,27 +1,101 @@
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 ReplicaLens,
+ 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 BenchmarkDetailDispatch, benchmarkDetailReducer } from './reducer';
+import {
+ BENCHMARK_LIST_KEY,
+ type BenchmarkDetail,
+ benchmarkDetailResource,
+ type BenchmarkListItem,
+ benchmarkListResource,
+} from './projection';
type Setter = StoreSetter<EvalStore>;
+/** The list has no params; the literal keeps `useSync` active with one entry. */
+const LIST_PARAMS = {} as Record<string, never>;
+
+/**
+ * The benchmark list keeps its long-standing flat field (`benchmarkList`) as the
+ * replica view, gated by `benchmarkListInit` so a loaded-but-empty list stays
+ * distinguishable from one that was never fetched (the sidebar's skeleton gate).
+ */
+const benchmarkListLens: ReplicaLens<EvalStore, BenchmarkListItem[]> = {
+ clear: () => ({ benchmarkList: [], benchmarkListInit: false }),
+ get: (state) => (state.benchmarkListInit ? state.benchmarkList : undefined),
+ keys: (state) => (state.benchmarkListInit ? [BENCHMARK_LIST_KEY] : []),
+ set: (_state, _key, data) =>
+ data
+ ? { benchmarkList: data, benchmarkListInit: true }
+ : { benchmarkList: [], benchmarkListInit: false },
+};
+
+/** Pre-migration `useFetchBenchmarks` return shape, backed by the list replica. */
+export interface BenchmarkListSyncResult extends ReplicaSyncResult {
+ /** The list once it has settled (hydrated or fetched), else `undefined`. */
+ data: BenchmarkListItem[] | 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 `useFetchBenchmarkDetail` return shape, backed by the detail replica. */
+export interface BenchmarkDetailSyncResult {
+ 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 createBenchmarkSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>
new BenchmarkActionImpl(set, get, _api);
export class BenchmarkActionImpl {
+ readonly #detail;
+ 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;
+ this.#list = createReplicaSlice(benchmarkListResource, {
+ actionPrefix: 'benchmarkList',
+ entity: arrayEntity<BenchmarkListItem>((benchmark) => benchmark.id),
+ fetcher: () => agentEvalService.listBenchmarks(),
+ get,
+ set,
+ stateKey: 'benchmarkListReplica',
+ view: benchmarkListLens,
+ });
+ this.#detail = createReplicaSlice(benchmarkDetailResource, {
+ actionPrefix: 'benchmarkDetail',
+ entity: singleEntity<BenchmarkDetail>((benchmark) => benchmark.id),
+ fetcher: (id) => agentEvalService.getBenchmark(id),
+ get,
+ // An unchanged page must not repaint the detail view.
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ set,
+ stateKey: 'benchmarkDetailReplica',
+ view: recordLens<EvalStore, BenchmarkDetail>('benchmarkDetailMap'),
+ });
+ // The same benchmark lives in the list and in its detail page: an edit or a
+ // delete patches both copies at once.
+ this.#entity = linkReplicaEntity<BenchmarkListItem>([this.#list, this.#detail]);
}
createBenchmark = async (params: {
@@ -32,39 +106,23 @@ export class BenchmarkActionImpl {
rubrics?: any[];
tags?: string[];
}): Promise<any> => {
- this.#set({ isCreatingBenchmark: true }, false, 'createBenchmark/start');
- try {
- const result = await agentEvalService.createBenchmark({
- description: params.description,
- identifier: params.identifier,
- metadata: params.metadata,
- name: params.name,
- rubrics: params.rubrics ?? [],
- tags: params.tags,
- });
- await this.#get().refreshBenchmarks();
- return result;
- } finally {
- this.#set({ isCreatingBenchmark: false }, false, 'createBenchmark/end');
- }
+ const result = await agentEvalService.createBenchmark({
+ description: params.description,
+ identifier: params.identifier,
+ metadata: params.metadata,
+ name: params.name,
+ rubrics: params.rubrics ?? [],
+ tags: params.tags,
+ });
+ await this.refreshBenchmarks();
+ return result;
};
deleteBenchmark = async (id: string): Promise<void> => {
- this.#set({ isDeletingBenchmark: true }, false, 'deleteBenchmark/start');
- try {
- await agentEvalService.deleteBenchmark(id);
- await this.#get().refreshBenchmarks();
- } finally {
- this.#set({ isDeletingBenchmark: false }, false, 'deleteBenchmark/end');
- }
- };
-
- refreshBenchmarkDetail = async (id: string): Promise<void> => {
- await mutate(evalKeys.benchmarkDetail(id));
- };
-
- refreshBenchmarks = async (): Promise<void> => {
- await mutate(evalKeys.benchmarks());
+ await agentEvalService.deleteBenchmark(id);
+ // Drop the row from the list and the detail cache at once, then converge.
+ this.#entity.remove(id);
+ await this.refreshBenchmarks();
};
updateBenchmark = async (params: {
@@ -75,82 +133,70 @@ export class BenchmarkActionImpl {
name: string;
tags?: string[];
}): Promise<void> => {
- const { id } = params;
-
- this.#get().internal_dispatchBenchmarkDetail({
- id,
- type: 'updateBenchmarkDetail',
- value: params,
- });
-
- this.#get().internal_updateBenchmarkDetailLoading(id, true);
-
- try {
- await agentEvalService.updateBenchmark({
- description: params.description,
- id: params.id,
- identifier: params.identifier,
- metadata: params.metadata,
- name: params.name,
- tags: params.tags,
- });
-
- await this.#get().refreshBenchmarks();
- await this.#get().refreshBenchmarkDetail(id);
- } finally {
- this.#get().internal_updateBenchmarkDetailLoading(id, false);
- }
- };
-
- useFetchBenchmarkDetail = (id?: string): SWRResponse =>
- useClientDataSWR(
- id ? evalKeys.benchmarkDetail(id) : null,
- () => agentEvalService.getBenchmark(id!),
- {
- onSuccess: (data: any) => {
- this.#get().internal_dispatchBenchmarkDetail({
- id: id!,
- type: 'setBenchmarkDetail',
- value: data,
- });
- this.#get().internal_updateBenchmarkDetailLoading(id!, false);
- },
- },
+ // Optimistic on every copy; the refetch below reconciles server-owned fields.
+ await this.#entity.optimistic(
+ params.id,
+ (benchmark) => ({ ...benchmark, ...params }),
+ () =>
+ agentEvalService.updateBenchmark({
+ description: params.description,
+ id: params.id,
+ identifier: params.identifier,
+ metadata: params.metadata,
+ name: params.name,
+ tags: params.tags,
+ }),
);
+ await Promise.all([this.refreshBenchmarks(), this.refreshBenchmarkDetail(params.id)]);
+ };
- useFetchBenchmarks = (): SWRResponse =>
- useClientDataSWR(evalKeys.benchmarks(), () => agentEvalService.listBenchmarks(), {
- onSuccess: (data: any) => {
- this.#set(
- { benchmarkList: data, benchmarkListInit: true, isLoadingBenchmarkList: false },
- false,
- 'useFetchBenchmarks/success',
- );
- },
- });
-
- internal_dispatchBenchmarkDetail = (payload: BenchmarkDetailDispatch): void => {
- const currentMap = this.#get().benchmarkDetailMap;
- const nextMap = benchmarkDetailReducer(currentMap, payload);
+ refreshBenchmarkDetail = async (id: string): Promise<void> => {
+ await this.#detail.revalidate(id);
+ };
- if (isEqual(nextMap, currentMap)) return;
+ refreshBenchmarks = async (): Promise<void> => {
+ await this.#list.revalidate();
+ };
- this.#set({ benchmarkDetailMap: nextMap }, false, `dispatchBenchmarkDetail/${payload.type}`);
+ /**
+ * Fetch orchestration only (the value is read from the store). Keeps the
+ * pre-migration `{ data, error, isLoading, mutate }` shape so the overview's
+ * `AsyncBoundary` and its retry keep working unchanged.
+ */
+ useFetchBenchmarks = (): BenchmarkListSyncResult => {
+ // Subscribe so a replica commit (hydrate or server replace) re-renders the
+ // consumer; the value itself is read through the store below.
+ useEvalStore((s) => s.benchmarkListInit);
+ const sync = this.#list.useSync(LIST_PARAMS);
+ const { benchmarkList, benchmarkListInit } = this.#get();
+ return {
+ ...sync,
+ data: benchmarkListInit ? benchmarkList : undefined,
+ isLoading: !sync.isHydrated || (sync.isValidating && !benchmarkListInit),
+ mutate: sync.revalidate,
+ };
};
- internal_updateBenchmarkDetailLoading = (id: string, loading: boolean): void => {
- this.#set(
- (state) => {
- if (loading) {
- return { loadingBenchmarkDetailIds: [...state.loadingBenchmarkDetailIds, id] };
- }
- return {
- loadingBenchmarkDetailIds: state.loadingBenchmarkDetailIds.filter((i) => i !== id),
- };
+ /**
+ * Fetch orchestration only (the page is read from `benchmarkDetailMap`).
+ * Keeps the pre-migration `{ error, isLoading, mutate }` shape.
+ */
+ useFetchBenchmarkDetail = (id?: string): BenchmarkDetailSyncResult => {
+ const sync = this.#detail.useSync(id ?? null, {
+ // A benchmark deleted elsewhere answers NOT_FOUND, yet a hydrated copy
+ // would keep the page painting it (the route only shows the error when
+ // the map entry is absent), even across reloads. NOT_FOUND is
+ // definitive: drop the cached detail and its persisted row. Transient
+ // failures keep the cached page on screen.
+ onError: (error) => {
+ if (id && isTrpcErrorCode(error, 'NOT_FOUND')) this.#detail.remove(id);
},
- false,
- 'updateBenchmarkDetailLoading',
- );
+ });
+ return {
+ error: sync.error,
+ isLoading: !sync.isHydrated || sync.isValidating,
+ mutate: sync.revalidate,
+ };
};
}
diff --git a/src/store/eval/slices/benchmark/initialState.ts b/src/store/eval/slices/benchmark/initialState.ts
index 45b9350b88a..ca72912b6ce 100644
--- a/src/store/eval/slices/benchmark/initialState.ts
+++ b/src/store/eval/slices/benchmark/initialState.ts
@@ -1,23 +1,28 @@
-import { type AgentEvalBenchmark, type AgentEvalBenchmarkListItem } from '@lobechat/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type { BenchmarkDetail, BenchmarkListItem } from './projection';
export interface BenchmarkSliceState {
- benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
- benchmarkList: AgentEvalBenchmarkListItem[];
+ /** Replica view of the benchmark details, one entry per benchmark id. */
+ benchmarkDetailMap: Record<string, BenchmarkDetail>;
+ /** Replica bookkeeping of `benchmarkDetailMap`. */
+ benchmarkDetailReplica: ReplicaState<BenchmarkDetail>;
+ /** Replica view of the benchmark list (one entry per cache scope). */
+ benchmarkList: BenchmarkListItem[];
+ /**
+ * Whether the list has ever been hydrated or fetched. Keeps a loaded-but-
+ * empty list distinguishable from one that was never loaded, so the sidebar
+ * shows its skeleton instead of a premature empty state.
+ */
benchmarkListInit: boolean;
- isCreatingBenchmark: boolean;
- isDeletingBenchmark: boolean;
- isLoadingBenchmarkList: boolean;
- isUpdatingBenchmark: boolean;
- loadingBenchmarkDetailIds: string[];
+ /** Replica bookkeeping of `benchmarkList`. */
+ benchmarkListReplica: ReplicaState<BenchmarkListItem[]>;
}
export const benchmarkInitialState: BenchmarkSliceState = {
benchmarkDetailMap: {},
+ benchmarkDetailReplica: createReplicaState(),
benchmarkList: [],
benchmarkListInit: false,
- isCreatingBenchmark: false,
- isDeletingBenchmark: false,
- isLoadingBenchmarkList: true,
- isUpdatingBenchmark: false,
- loadingBenchmarkDetailIds: [],
+ benchmarkListReplica: createReplicaState(),
};
diff --git a/src/store/eval/slices/benchmark/projection.ts b/src/store/eval/slices/benchmark/projection.ts
new file mode 100644
index 00000000000..b1ad097912b
--- /dev/null
+++ b/src/store/eval/slices/benchmark/projection.ts
@@ -0,0 +1,40 @@
+import { defineReplica } from '@/libs/replica';
+import type { agentEvalService } from '@/services/agentEval';
+
+type BenchmarkListResponse = Awaited<ReturnType<typeof agentEvalService.listBenchmarks>>;
+type BenchmarkDetailResponse = Awaited<ReturnType<typeof agentEvalService.getBenchmark>>;
+
+/** A benchmark row as any loaded list holds it (list columns + computed counts). */
+export type BenchmarkListItem = BenchmarkListResponse[number];
+/** One benchmark page — the full row the detail page renders. */
+export type BenchmarkDetail = BenchmarkDetailResponse;
+
+/**
+ * The benchmark list has one entry per cache scope: there are no query params,
+ * so the overview, the sidebar and the header switcher all read the same list.
+ */
+export const BENCHMARK_LIST_KEY = 'all';
+
+/** Every benchmark of the active scope (the flat `benchmarkList` view). */
+export const benchmarkListResource = defineReplica<
+ Record<string, never>,
+ BenchmarkListItem[],
+ BenchmarkListResponse
+>({
+ key: () => BENCHMARK_LIST_KEY,
+ name: 'evalBenchmarkList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** One benchmark page, keyed by the route param (`benchmarkDetailMap[id]`). */
+export const benchmarkDetailResource = defineReplica<
+ string,
+ BenchmarkDetail,
+ BenchmarkDetailResponse
+>({
+ key: (id) => id,
+ name: 'evalBenchmarkDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/eval/slices/benchmark/reducer.ts b/src/store/eval/slices/benchmark/reducer.ts
deleted file mode 100644
index be14026924a..00000000000
--- a/src/store/eval/slices/benchmark/reducer.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { type AgentEvalBenchmark } from '@lobechat/types';
-import { produce } from 'immer';
-
-type SetBenchmarkDetailAction = {
- id: string;
- type: 'setBenchmarkDetail';
- value: AgentEvalBenchmark;
-};
-
-type UpdateBenchmarkDetailAction = {
- id: string;
- type: 'updateBenchmarkDetail';
- value: Partial<AgentEvalBenchmark>;
-};
-
-type DeleteBenchmarkDetailAction = {
- id: string;
- type: 'deleteBenchmarkDetail';
-};
-
-export type BenchmarkDetailDispatch =
- | SetBenchmarkDetailAction
- | UpdateBenchmarkDetailAction
- | DeleteBenchmarkDetailAction;
-
-export const benchmarkDetailReducer = (
- state: Record<string, AgentEvalBenchmark> = {},
- payload: BenchmarkDetailDispatch,
-): Record<string, AgentEvalBenchmark> => {
- switch (payload.type) {
- case 'setBenchmarkDetail': {
- return produce(state, (draft) => {
- draft[payload.id] = payload.value;
- });
- }
-
- case 'updateBenchmarkDetail': {
- return produce(state, (draft) => {
- if (draft[payload.id]) {
- draft[payload.id] = { ...draft[payload.id], ...payload.value };
- }
- });
- }
-
- case 'deleteBenchmarkDetail': {
- return produce(state, (draft) => {
- delete draft[payload.id];
- });
- }
-
- default: {
- return state;
- }
- }
-};
diff --git a/src/store/eval/slices/benchmark/replica.test.ts b/src/store/eval/slices/benchmark/replica.test.ts
new file mode 100644
index 00000000000..9b2103677b4
--- /dev/null
+++ b/src/store/eval/slices/benchmark/replica.test.ts
@@ -0,0 +1,195 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The benchmark list and detail are `@lobechat/replica` resources whose views
+ * are the eval store's flat `benchmarkList` / `benchmarkDetailMap` fields. 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 the view, a detail page fills its
+ * map entry, and a cache-scope switch drops the previous identity's rows.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { agentEvalService } from '@/services/agentEval';
+import { useEvalStore } from '@/store/eval';
+
+import { benchmarkDetailResource, benchmarkListResource } from './projection';
+
+const LIST_PARAMS = {} as Record<string, never>;
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const LIST_STORAGE_KEY = benchmarkListResource.storageKey(LIST_PARAMS);
+const DETAIL_STORAGE_KEY = benchmarkDetailResource.storageKey('b1');
+
+const listRow = (id: string, name: string) =>
+ ({
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ id,
+ identifier: id,
+ isSystem: false,
+ name,
+ }) as any;
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const renderListSync = () =>
+ renderHook(() => useEvalStore.getState().useFetchBenchmarks(), { wrapper });
+const renderDetailSync = (id: string) =>
+ renderHook(() => useEvalStore.getState().useFetchBenchmarkDetail(id), { wrapper });
+
+describe('benchmark 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].map((value) =>
+ benchmarkListResource.storage!.remove({ queryKey: LIST_STORAGE_KEY, scope: value }),
+ ),
+ );
+ await Promise.all(
+ [...scopes].map((value) =>
+ benchmarkDetailResource.storage!.remove({ queryKey: DETAIL_STORAGE_KEY, scope: value }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted list before the network answers', async () => {
+ await benchmarkListResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [listRow('b1', 'Cached')], updatedAt: 1 },
+ );
+ vi.spyOn(agentEvalService, 'listBenchmarks').mockImplementation(pending);
+
+ renderListSync();
+
+ await waitFor(() => expect(useEvalStore.getState().benchmarkListInit).toBe(true));
+ expect(useEvalStore.getState().benchmarkList[0].name).toBe('Cached');
+ });
+
+ it('settles the list (and marks it init) from the server', async () => {
+ vi.spyOn(agentEvalService, 'listBenchmarks').mockResolvedValue([listRow('b1', 'MMLU')]);
+
+ renderListSync();
+
+ await waitFor(() => expect(useEvalStore.getState().benchmarkListInit).toBe(true));
+ expect(useEvalStore.getState().benchmarkList).toHaveLength(1);
+ expect(useEvalStore.getState().benchmarkList[0].name).toBe('MMLU');
+ });
+
+ it('drops the previous scope’s list on a cache-scope switch', async () => {
+ vi.spyOn(agentEvalService, 'listBenchmarks').mockResolvedValue([listRow('b1', 'Personal')]);
+ const { rerender } = renderListSync();
+ await waitFor(() => expect(useEvalStore.getState().benchmarkList).toHaveLength(1));
+
+ // Switch identity: the new scope's rows are still in flight.
+ useScope(`${scope.split(':')[0]}:ws-1`);
+ vi.mocked(agentEvalService.listBenchmarks).mockImplementation(pending);
+ rerender();
+
+ expect(useEvalStore.getState().benchmarkList).toEqual([]);
+ expect(useEvalStore.getState().benchmarkListInit).toBe(false);
+ });
+
+ it('fills the detail map from the server', async () => {
+ vi.spyOn(agentEvalService, 'getBenchmark').mockResolvedValue({ id: 'b1', name: 'MMLU' } as any);
+
+ renderDetailSync('b1');
+
+ await waitFor(() => expect(useEvalStore.getState().benchmarkDetailMap.b1).toBeDefined());
+ expect(useEvalStore.getState().benchmarkDetailMap.b1.name).toBe('MMLU');
+ });
+
+ it('drops a hydrated detail and its persisted row on NOT_FOUND', async () => {
+ await benchmarkDetailResource.storage!.set(
+ { queryKey: DETAIL_STORAGE_KEY, scope },
+ { data: { id: 'b1', name: 'Cached' } as any, updatedAt: 1 },
+ );
+ let rejectFetch: (error: unknown) => void = () => {};
+ vi.spyOn(agentEvalService, 'getBenchmark').mockImplementation(
+ () => new Promise((_, reject) => (rejectFetch = reject)),
+ );
+
+ renderDetailSync('b1');
+ await waitFor(() => expect(useEvalStore.getState().benchmarkDetailMap.b1?.name).toBe('Cached'));
+
+ await act(async () => {
+ rejectFetch(Object.assign(new Error('Benchmark not found'), { data: { code: 'NOT_FOUND' } }));
+ });
+
+ await waitFor(() => expect(useEvalStore.getState().benchmarkDetailMap.b1).toBeUndefined());
+ await waitFor(async () =>
+ expect(
+ await benchmarkDetailResource.storage!.get({ queryKey: DETAIL_STORAGE_KEY, scope }),
+ ).toBeUndefined(),
+ );
+ });
+
+ it('keeps a hydrated detail on a transient fetch failure', async () => {
+ await benchmarkDetailResource.storage!.set(
+ { queryKey: DETAIL_STORAGE_KEY, scope },
+ { data: { id: 'b1', name: 'Cached' } as any, updatedAt: 1 },
+ );
+ const getBenchmark = vi
+ .spyOn(agentEvalService, 'getBenchmark')
+ .mockRejectedValue(
+ Object.assign(new Error('boom'), { data: { code: 'INTERNAL_SERVER_ERROR' } }),
+ );
+
+ const { result } = renderDetailSync('b1');
+ await waitFor(() => expect(result.current.error).toBeDefined());
+ expect(getBenchmark).toHaveBeenCalled();
+
+ expect(useEvalStore.getState().benchmarkDetailMap.b1?.name).toBe('Cached');
+ });
+
+ it('repaints the refreshed list after a mutation', async () => {
+ const listBenchmarks = vi
+ .spyOn(agentEvalService, 'listBenchmarks')
+ .mockResolvedValue([listRow('b1', 'Before')]);
+ renderListSync();
+ await waitFor(() => expect(useEvalStore.getState().benchmarkList).toHaveLength(1));
+
+ listBenchmarks.mockResolvedValue([listRow('b1', 'After')]);
+ await act(() => useEvalStore.getState().refreshBenchmarks());
+
+ await waitFor(() => expect(useEvalStore.getState().benchmarkList[0].name).toBe('After'));
+ });
+});
diff --git a/src/store/eval/slices/benchmark/selectors.ts b/src/store/eval/slices/benchmark/selectors.ts
index 065a34ef6dc..35ec08825ac 100644
--- a/src/store/eval/slices/benchmark/selectors.ts
+++ b/src/store/eval/slices/benchmark/selectors.ts
@@ -2,15 +2,10 @@ import type { EvalStore } from '@/store/eval/store';
const benchmarkList = (s: EvalStore) => s.benchmarkList;
const isBenchmarkListInit = (s: EvalStore) => s.benchmarkListInit;
-const isLoadingBenchmarkList = (s: EvalStore) => s.isLoadingBenchmarkList;
-const isCreatingBenchmark = (s: EvalStore) => s.isCreatingBenchmark;
-const getBenchmarkById = (id: string) => (s: EvalStore) =>
- s.benchmarkList.find((b: any) => b.id === id);
+const getBenchmarkById = (id: string) => (s: EvalStore) => s.benchmarkList.find((b) => b.id === id);
export const benchmarkSelectors = {
benchmarkList,
getBenchmarkById,
isBenchmarkListInit,
- isCreatingBenchmark,
- isLoadingBenchmarkList,
};