🤯 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 run slice onto @lobechat/replica (#20671)
Arvin Xu66725e3be7ce
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsxindex c93d5470a48..f35b436a6aa 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/RunList.tsx@@ -50,8 +50,8 @@ interface RunListProps {const RunList = memo<RunListProps>(({ activeKey, benchmarkId, itemKey }) => {const { t } = useTranslation('eval');const navigate = useWorkspaceAwareNavigate();- const runList = useEvalStore(runSelectors.runList);- const isLoading = useEvalStore(runSelectors.isLoadingRuns);+ const runList = useEvalStore(runSelectors.runList(benchmarkId));+ const isLoading = useEvalStore(runSelectors.isLoadingRuns(benchmarkId));const sortedRuns = useMemo(() =>diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsxindex 48aba3a0dec..0c9a82349d0 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx@@ -47,7 +47,7 @@ const RunsTab = memo<RunsTabProps>(({ benchmarkId }) => {const { t } = useTranslation('eval');const [statusFilter, setStatusFilter] = useState<string>('all');const useFetchRuns = useEvalStore((s) => s.useFetchRuns);- const runList = useEvalStore(runSelectors.runList);+ const runList = useEvalStore(runSelectors.runList(benchmarkId));const refreshRuns = useEvalStore((s) => s.refreshRuns);useFetchRuns(benchmarkId);diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/index.tsxindex dff1fc74acc..3bc31fedd08 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/index.tsx@@ -88,7 +88,7 @@ const BenchmarkDetail = memo(() => {const isLoadingDatasets = useEvalStore((s) => s.isLoadingDatasets);const refreshDatasets = useEvalStore((s) => s.refreshDatasets);const useFetchRuns = useEvalStore((s) => s.useFetchRuns);- const runList = useEvalStore(runSelectors.runList);+ const runList = useEvalStore(runSelectors.runList(benchmarkId));const { error, isLoading, mutate } = useFetchBenchmarkDetail(benchmarkId);useFetchDatasets(benchmarkId);diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsxindex 0a6cdf169d8..e27b42f6629 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx@@ -35,10 +35,10 @@ const CaseDetail = memo(() => {const pollingConfig = { refreshInterval: isActive ? POLLING_INTERVAL : 0 };useFetchRunDetail(runId!, pollingConfig);const {- data: resultsData,error: resultsError,- isLoading: isLoadingResults,- mutate: mutateResults,+ isHydrated: resultsHydrated,+ isValidating: resultsValidating,+ revalidate: revalidateResults,} = useFetchRunResults(runId!, pollingConfig);const runDetail = useEvalStore(runSelectors.getRunDetailById(runId!));@@ -97,13 +97,13 @@ const CaseDetail = memo(() => {// failed fetch (ux Read §1.1). A page-level failure gets a reason + Reload.return (<AsyncBoundary- data={resultsData}+ data={runResults}error={resultsError}errorVariant={'page'}isEmpty={!caseResult}- isLoading={isLoadingResults}+ isLoading={!resultsHydrated || resultsValidating}loading={<RouteLoading />}- onRetry={() => mutateResults()}+ onRetry={() => void revalidateResults()}>{caseResult && (<Flexbox height="100%" style={{ overflow: 'hidden' }}>diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsxindex c5a0a195964..39a15617ac5 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx@@ -78,7 +78,7 @@ const RunDetail = memo(() => {const pollingConfig = { refreshInterval: isActive ? POLLING_INTERVAL : 0 };- const { error, isLoading, mutate } = useFetchRunDetail(runId!, pollingConfig);+ const { error, isHydrated, isValidating, revalidate } = useFetchRunDetail(runId!, pollingConfig);useFetchRunResults(runId!, pollingConfig);const hasResults = !!runResults?.results?.length;@@ -109,9 +109,9 @@ const RunDetail = memo(() => {error={error}errorVariant={'page'}isEmpty={!runDetail}- isLoading={isLoading}+ isLoading={!isHydrated || isValidating}loading={<RouteLoading />}- onRetry={() => mutate()}+ onRetry={() => void revalidate()}>{runDetail && (<Flexbox gap={24} padding={24} style={{ margin: '0 auto', maxWidth: 1440, width: '100%' }}>diff --git a/src/store/eval/slices/run/action.test.ts b/src/store/eval/slices/run/action.test.tsnew file mode 100644index 00000000000..876bff2433e--- /dev/null+++ b/src/store/eval/slices/run/action.test.ts@@ -0,0 +1,277 @@+/**+ * @vitest-environment happy-dom+ *+ * `eval/slices/run` is replica-backed: the benchmark / dataset run lists, the+ * run detail and the run results all paint from the persisted copy on the first+ * frame, the network only confirms, a delete fans out to every loaded copy, and+ * the mutation actions keep the same service calls they had before the move.+ */+import { randomUUID } from 'node:crypto';++import type { AgentEvalRunDetail, AgentEvalRunListItem } from '@lobechat/types';+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 { runSelectors } from '@/store/eval/slices/run/selectors';++import { runInitialState } from './initialState';+import {+ benchmarkRunListResource,+ datasetRunListResource,+ runDetailResource,+ runResultsResource,+} from './projection';++vi.mock('@/services/agentEval', () => ({+ agentEvalService: {+ abortRun: vi.fn(),+ batchResumeRunCases: vi.fn(),+ createRun: vi.fn(),+ deleteRun: vi.fn(),+ getRunDetails: vi.fn(),+ getRunResults: vi.fn(),+ listRuns: vi.fn(),+ retryRunCase: vi.fn(),+ retryRunErrors: vi.fn(),+ resumeRunCase: vi.fn(),+ startRun: vi.fn(),+ updateRun: 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 BENCH = 'bench-1';+const DATASET = 'dataset-1';+const RUN = 'run-1';++const run = (id: string, extra: Partial<AgentEvalRunListItem> = {}): AgentEvalRunListItem =>+ ({+ datasetId: DATASET,+ id,+ status: 'idle',+ createdAt: new Date(1),+ updatedAt: new Date(1),+ ...extra,+ }) as AgentEvalRunListItem;++const detailOf = (item: AgentEvalRunListItem): AgentEvalRunDetail =>+ ({ ...item, topics: [] }) as AgentEvalRunDetail;++const okList = (data: AgentEvalRunListItem[]) => ({ data, total: data.length });++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const BENCH_KEY = benchmarkRunListResource.storageKey({ benchmarkId: BENCH });+const DATASET_KEY = datasetRunListResource.storageKey({ datasetId: DATASET });+const DETAIL_KEY = runDetailResource.storageKey(RUN);++describe('eval run 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-run-user-${randomUUID()}:personal`);+ act(() => useEvalStore.setState(runInitialState));+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) =>+ [BENCH_KEY, DATASET_KEY, DETAIL_KEY, runResultsResource.storageKey(RUN)].map((queryKey) =>+ benchmarkRunListResource.storage!.remove({ queryKey, scope: value }),+ ),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted benchmark run list before the network answers', async () => {+ await benchmarkRunListResource.storage!.set(+ { queryKey: BENCH_KEY, scope },+ { data: [run('r1', { name: 'Cached' })], updatedAt: 1 },+ );+ vi.mocked(agentEvalService.listRuns).mockImplementation(pending);++ const sync = renderHook(() => useEvalStore((s) => s.useFetchRuns)(BENCH), { wrapper });+ const list = renderHook(() => useEvalStore(runSelectors.runList(BENCH)));++ await waitFor(() => expect(list.result.current.map((r) => r.name)).toEqual(['Cached']));+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('replaces the benchmark run list with the server response and persists it', async () => {+ vi.mocked(agentEvalService.listRuns).mockResolvedValue(+ okList([run('r1', { name: 'Server' })]) as any,+ );++ renderHook(() => useEvalStore((s) => s.useFetchRuns)(BENCH), { wrapper });++ await waitFor(() =>+ expect(useEvalStore.getState().runListMap[BENCH]?.[0]?.name).toBe('Server'),+ );+ expect(agentEvalService.listRuns).toHaveBeenCalledWith({ benchmarkId: BENCH });+ await waitFor(async () =>+ expect(+ (await benchmarkRunListResource.storage!.get({ queryKey: BENCH_KEY, scope }))?.data,+ ).toEqual([run('r1', { name: 'Server' })]),+ );+ });++ it('keeps each benchmark’s run list under its own key', async () => {+ vi.mocked(agentEvalService.listRuns).mockImplementation(+ async ({ benchmarkId }: { benchmarkId?: string }) =>+ okList([run(`${benchmarkId}-run`, { name: benchmarkId })]) as any,+ );++ renderHook(+ () => {+ useEvalStore((s) => s.useFetchRuns)('bench-a');+ useEvalStore((s) => s.useFetchRuns)('bench-b');+ },+ { wrapper },+ );++ await waitFor(() => {+ const state = useEvalStore.getState();+ expect(state.runListMap['bench-a']?.[0]?.name).toBe('bench-a');+ expect(state.runListMap['bench-b']?.[0]?.name).toBe('bench-b');+ });+ });++ it('hydrates run detail by id and revalidates it through the same entry', async () => {+ await runDetailResource.storage!.set(+ { queryKey: DETAIL_KEY, scope },+ { data: detailOf(run(RUN, { name: 'Cached run' })), updatedAt: 1 },+ );+ vi.mocked(agentEvalService.getRunDetails).mockImplementation(pending);++ renderHook(() => useEvalStore((s) => s.useFetchRunDetail)(RUN), { wrapper });++ await waitFor(() => expect(useEvalStore.getState().runDetailMap[RUN]?.name).toBe('Cached run'));+ expect(agentEvalService.getRunDetails).toHaveBeenCalledWith(RUN);+ });++ it('refreshes a run detail after a mutation through the service', async () => {+ vi.mocked(agentEvalService.getRunDetails).mockResolvedValue(+ detailOf(run(RUN, { status: 'running' })) as any,+ );+ vi.mocked(agentEvalService.startRun).mockResolvedValue(undefined as any);++ renderHook(() => useEvalStore((s) => s.useFetchRunDetail)(RUN), { wrapper });+ await waitFor(() => expect(useEvalStore.getState().runDetailMap[RUN]).toBeDefined());++ vi.mocked(agentEvalService.getRunDetails).mockResolvedValue(+ detailOf(run(RUN, { status: 'completed' })) as any,+ );++ await act(() => useEvalStore.getState().startRun(RUN));++ expect(agentEvalService.startRun).toHaveBeenCalledWith(RUN, undefined);+ await waitFor(() =>+ expect(useEvalStore.getState().runDetailMap[RUN]?.status).toBe('completed'),+ );+ });++ it('removes a deleted run from the list and its detail copy', async () => {+ vi.mocked(agentEvalService.listRuns).mockResolvedValue(+ okList([run(RUN, { name: 'Doomed' })]) as any,+ );+ vi.mocked(agentEvalService.getRunDetails).mockResolvedValue(+ detailOf(run(RUN, { name: 'Doomed' })) as any,+ );++ renderHook(+ () => {+ useEvalStore((s) => s.useFetchRuns)(BENCH);+ useEvalStore((s) => s.useFetchRunDetail)(RUN);+ },+ { wrapper },+ );+ await waitFor(() => {+ expect(useEvalStore.getState().runListMap[BENCH]).toHaveLength(1);+ expect(useEvalStore.getState().runDetailMap[RUN]).toBeDefined();+ });++ vi.mocked(agentEvalService.deleteRun).mockResolvedValue({ success: true } as any);+ vi.mocked(agentEvalService.listRuns).mockResolvedValue(okList([]) as any);++ await act(() => useEvalStore.getState().deleteRun(RUN));++ expect(agentEvalService.deleteRun).toHaveBeenCalledWith(RUN);+ expect(useEvalStore.getState().runListMap[BENCH]).toEqual([]);+ expect(useEvalStore.getState().runDetailMap[RUN]).toBeUndefined();+ });++ it('scopes the dataset run list by datasetId', async () => {+ vi.mocked(agentEvalService.listRuns).mockResolvedValue(+ okList([run('r9', { name: 'DS run' })]) as any,+ );++ renderHook(() => useEvalStore((s) => s.useFetchDatasetRuns)(DATASET), { wrapper });++ await waitFor(() =>+ expect(useEvalStore.getState().datasetRunListMap[DATASET]?.[0]?.name).toBe('DS run'),+ );+ expect(agentEvalService.listRuns).toHaveBeenCalledWith({ datasetId: DATASET });+ });++ it('creates a run and refreshes the mounted benchmark run list', async () => {+ vi.mocked(agentEvalService.listRuns).mockResolvedValue(okList([run('r1')]) as any);+ vi.mocked(agentEvalService.createRun).mockResolvedValue({ id: 'r2' } as any);++ renderHook(() => useEvalStore((s) => s.useFetchRuns)(BENCH), { wrapper });+ await waitFor(() =>+ expect(agentEvalService.listRuns).toHaveBeenCalledWith({ benchmarkId: BENCH }),+ );+ vi.mocked(agentEvalService.listRuns).mockClear();+ vi.mocked(agentEvalService.listRuns).mockResolvedValue(+ okList([run('r1'), run('r2', { name: 'New run' })]) as any,+ );++ const created = await act(() =>+ useEvalStore.getState().createRun({ datasetId: DATASET, name: 'New run' }),+ );++ expect(created).toEqual({ id: 'r2' });+ expect(agentEvalService.createRun).toHaveBeenCalledWith({+ datasetId: DATASET,+ name: 'New run',+ });+ // `createRun` revalidates the benchmark list that is currently mounted.+ expect(agentEvalService.listRuns).toHaveBeenCalledWith({ benchmarkId: BENCH });+ await waitFor(() =>+ expect(useEvalStore.getState().runListMap[BENCH]?.map((r) => r.id)).toEqual(['r1', 'r2']),+ );+ });+});diff --git a/src/store/eval/slices/run/action.ts b/src/store/eval/slices/run/action.tsindex 64337bc3789..9fcb28f1097 100644--- a/src/store/eval/slices/run/action.ts+++ b/src/store/eval/slices/run/action.ts@@ -1,17 +1,37 @@-import type { EvalRunInputConfig } 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 type {+ AgentEvalRunDetail,+ AgentEvalRunListItem,+ AgentEvalRunResults,+ EvalRunInputConfig,+} from '@lobechat/types';++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 StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import {+ benchmarkRunListResource,+ datasetRunListResource,+ runDetailResource,+ runResultsResource,+} from './projection';-import { type RunDetailDispatch, runDetailReducer } from './reducer';+const n = setNamespace('evalRun');type Setter = StoreSetter<EvalStore>;+/** Only the scheduling knob callers pass today; `useSync` accepts the full schedule. */+type FetchConfig = { refreshInterval?: number };+export const createRunSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>new RunActionImpl(set, get, _api);@@ -19,15 +39,76 @@ export class RunActionImpl {readonly #get: () => EvalStore;readonly #set: Setter;+ /**+ * Four local-first resources over the run entity, each owning ONE store+ * location (selectors keep reading those maps):+ * - `#benchmarkRunList`: sidebar + RunsTab → `runListMap[benchmarkId]`+ * - `#datasetRunList`: dataset page → `datasetRunListMap[datasetId]`+ * - `#runDetail`: by-id detail → `runDetailMap[runId]`+ * - `#runResults`: by-id case results → `runResultsMap[runId]`+ * `#runEntity` fans a run-level change (delete / update) out to whichever+ * list and detail currently hold that run.+ */+ readonly #benchmarkRunList;+ readonly #datasetRunList;+ readonly #runDetail;+ readonly #runResults;+ readonly #runEntity;+constructor(set: Setter, get: () => EvalStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;++ this.#benchmarkRunList = createReplicaSlice(benchmarkRunListResource, {+ actionPrefix: n('benchmarkRunList'),+ entity: arrayEntity<AgentEvalRunListItem>((run) => run.id),+ fetcher: ({ benchmarkId }) => agentEvalService.listRuns({ benchmarkId }),+ get,+ merge: (response) => response.data,+ set,+ stateKey: 'runListReplica',+ view: recordLens<EvalStore, AgentEvalRunListItem[]>('runListMap'),+ });+ this.#datasetRunList = createReplicaSlice(datasetRunListResource, {+ actionPrefix: n('datasetRunList'),+ entity: arrayEntity<AgentEvalRunListItem>((run) => run.id),+ fetcher: ({ datasetId }) => agentEvalService.listRuns({ datasetId }),+ get,+ merge: (response) => response.data,+ set,+ stateKey: 'datasetRunListReplica',+ view: recordLens<EvalStore, AgentEvalRunListItem[]>('datasetRunListMap'),+ });+ this.#runDetail = createReplicaSlice(runDetailResource, {+ actionPrefix: n('runDetail'),+ // The detail is a superset of the list row: the same run is patched here+ // and in the lists when a mutation fans out through `#runEntity`.+ entity: singleEntity<AgentEvalRunDetail, AgentEvalRunListItem>((run) => run.id),+ fetcher: (runId) => agentEvalService.getRunDetails(runId),+ get,+ set,+ stateKey: 'runDetailReplica',+ view: recordLens<EvalStore, AgentEvalRunDetail>('runDetailMap'),+ });+ this.#runResults = createReplicaSlice(runResultsResource, {+ actionPrefix: n('runResults'),+ fetcher: (runId) => agentEvalService.getRunResults(runId),+ get,+ set,+ stateKey: 'runResultsReplica',+ view: recordLens<EvalStore, AgentEvalRunResults>('runResultsMap'),+ });+ this.#runEntity = linkReplicaEntity<AgentEvalRunListItem>([+ this.#benchmarkRunList,+ this.#datasetRunList,+ this.#runDetail,+ ]);}abortRun = async (id: string): Promise<void> => {await agentEvalService.abortRun(id);- await this.#get().refreshRunDetail(id);+ await this.refreshRunDetail(id);};createRun = async (params: {@@ -38,7 +119,7 @@ export class RunActionImpl {parentRunId?: string;targetAgentId?: string;}): Promise<any> => {- this.#set({ isCreatingRun: true }, false, 'createRun/start');+ this.#set({ isCreatingRun: true }, false, n('createRun/start'));try {const result = await agentEvalService.createRun(params);// Experiment-scoped runs are served by the experiment detail payload;@@ -46,73 +127,33 @@ export class RunActionImpl {if (params.experimentId) {await this.#get().refreshExperimentDetail(params.experimentId);} else {- await this.#get().refreshRuns();+ await this.refreshRuns();}return result;} finally {- this.#set({ isCreatingRun: false }, false, 'createRun/end');+ this.#set({ isCreatingRun: false }, false, n('createRun/end'));}};deleteRun = async (id: string): Promise<void> => {await agentEvalService.deleteRun(id);- this.#get().internal_dispatchRunDetail({ id, type: 'deleteRunDetail' });- await this.#get().refreshRuns();- };-- internal_dispatchRunDetail = (payload: RunDetailDispatch): void => {- const currentMap = this.#get().runDetailMap;- const nextMap = runDetailReducer(currentMap, payload);-- if (isEqual(nextMap, currentMap)) return;-- this.#set({ runDetailMap: nextMap }, false, `dispatchRunDetail/${payload.type}`);- };-- internal_updateRunDetailLoading = (id: string, loading: boolean): void => {- this.#set(- (state) => {- if (loading) {- return { loadingRunDetailIds: [...state.loadingRunDetailIds, id] };- }- return {- loadingRunDetailIds: state.loadingRunDetailIds.filter((i) => i !== id),- };- },- false,- 'updateRunDetailLoading',- );- };-- internal_updateRunResultLoading = (id: string, loading: boolean): void => {- this.#set(- (state) => {- if (loading) {- return { loadingRunResultIds: [...state.loadingRunResultIds, id] };- }- return {- loadingRunResultIds: state.loadingRunResultIds.filter((i) => i !== id),- };- },- false,- 'updateRunResultLoading',- );+ // Drop the run from every list / detail copy that currently holds it, plus+ // its (unlinked) result payload.+ this.#runEntity.remove(id);+ this.#runResults.remove(id);+ await this.refreshRuns();};refreshDatasetRuns = async (datasetId: string): Promise<void> => {- await mutate(evalKeys.datasetRuns(datasetId));+ await this.#datasetRunList.revalidate(datasetId);};refreshRunDetail = async (id: string): Promise<void> => {- await mutate(evalKeys.runDetail(id));+ await this.#runDetail.revalidate(id);};refreshRuns = async (benchmarkId?: string): Promise<void> => {- if (benchmarkId) {- await mutate(evalKeys.runs(benchmarkId));- } else {- await mutate((key) => Array.isArray(key) && key[0] === evalKeys.runs.root);- }+ await this.#benchmarkRunList.revalidate(benchmarkId);};batchResumeRunCases = async (@@ -120,27 +161,27 @@ export class RunActionImpl {targets: Array<{ testCaseId: string; threadId?: string }>,): Promise<void> => {await agentEvalService.batchResumeRunCases(runId, targets);- await Promise.all([this.#get().refreshRunDetail(runId), mutate(evalKeys.runResults(runId))]);+ await Promise.all([this.refreshRunDetail(runId), this.#runResults.revalidate(runId)]);};retryRunCase = async (runId: string, testCaseId: string): Promise<void> => {await agentEvalService.retryRunCase(runId, testCaseId);- await this.#get().refreshRunDetail(runId);+ await this.refreshRunDetail(runId);};resumeRunCase = async (runId: string, testCaseId: string, threadId?: string): Promise<void> => {await agentEvalService.resumeRunCase(runId, testCaseId, threadId);- await this.#get().refreshRunDetail(runId);+ await this.refreshRunDetail(runId);};retryRunErrors = async (id: string): Promise<void> => {await agentEvalService.retryRunErrors(id);- await this.#get().refreshRunDetail(id);+ await this.refreshRunDetail(id);};startRun = async (id: string, force?: boolean): Promise<void> => {await agentEvalService.startRun(id, force);- await this.#get().refreshRunDetail(id);+ await this.refreshRunDetail(id);};updateRun = async (params: {@@ -151,70 +192,22 @@ export class RunActionImpl {targetAgentId?: string | null;}): Promise<any> => {const result = await agentEvalService.updateRun(params);- await this.#get().refreshRunDetail(params.id);- await this.#get().refreshRuns();+ await this.refreshRunDetail(params.id);+ await this.refreshRuns();return result;};- useFetchRunDetail = (id: string, config?: { refreshInterval?: number }): SWRResponse =>- useClientDataSWR(id ? evalKeys.runDetail(id) : null, () => agentEvalService.getRunDetails(id), {- ...config,- onSuccess: (data: any) => {- this.#get().internal_dispatchRunDetail({- id,- type: 'setRunDetail',- value: data,- });- this.#get().internal_updateRunDetailLoading(id, false);- },- });+ useFetchRunDetail = (id: string, config?: FetchConfig): ReplicaSyncResult =>+ this.#runDetail.useSync(id || null, config);++ useFetchRunResults = (id: string, config?: FetchConfig): ReplicaSyncResult =>+ this.#runResults.useSync(id || null, config);++ useFetchDatasetRuns = (datasetId?: string): ReplicaSyncResult =>+ this.#datasetRunList.useSync(datasetId ? { datasetId } : null);- useFetchRunResults = (id: string, config?: { refreshInterval?: number }): SWRResponse =>- useClientDataSWR(- id ? evalKeys.runResults(id) : null,- () => agentEvalService.getRunResults(id),- {- ...config,- onSuccess: (data: any) => {- this.#set(- (state) => ({- runResultsMap: { ...state.runResultsMap, [id]: data },- }),- false,- 'useFetchRunResults/success',- );- this.#get().internal_updateRunResultLoading(id, false);- },- },- );-- useFetchDatasetRuns = (datasetId?: string): SWRResponse =>- useClientDataSWR(- datasetId ? evalKeys.datasetRuns(datasetId) : null,- () => agentEvalService.listRuns({ datasetId: datasetId! }),- {- onSuccess: (data: any) => {- this.#set(- (state) => ({- datasetRunListMap: { ...state.datasetRunListMap, [datasetId!]: data.data },- }),- false,- 'useFetchDatasetRuns/success',- );- },- },- );-- useFetchRuns = (benchmarkId?: string): SWRResponse =>- useClientDataSWR(- benchmarkId ? evalKeys.runs(benchmarkId) : null,- () => agentEvalService.listRuns({ benchmarkId: benchmarkId! }),- {- onSuccess: (data: any) => {- this.#set({ isLoadingRuns: false, runList: data.data }, false, 'useFetchRuns/success');- },- },- );+ useFetchRuns = (benchmarkId?: string): ReplicaSyncResult =>+ this.#benchmarkRunList.useSync(benchmarkId ? { benchmarkId } : null);}export type RunAction = Pick<RunActionImpl, keyof RunActionImpl>;diff --git a/src/store/eval/slices/run/initialState.ts b/src/store/eval/slices/run/initialState.tsindex 4634d040740..7c5ee55c448 100644--- a/src/store/eval/slices/run/initialState.ts+++ b/src/store/eval/slices/run/initialState.ts@@ -4,31 +4,42 @@ import type {AgentEvalRunResults,} from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+export interface RunSliceState {/*** Map of run lists keyed by datasetId* Caches dataset-scoped run lists for multiple dataset detail pages*/datasetRunListMap: Record<string, AgentEvalRunListItem[]>;+ /** Local-first bookkeeping for `datasetRunListMap`. */+ datasetRunListReplica: ReplicaState<AgentEvalRunListItem[]>;isCreatingRun: boolean;- isLoadingRuns: boolean;- loadingRunDetailIds: string[];- loadingRunResultIds: string[];+ /** By-id run detail cache (`runDetailMap[runId]`). */runDetailMap: Record<string, AgentEvalRunDetail>;+ /** Local-first bookkeeping for `runDetailMap`. */+ runDetailReplica: ReplicaState<AgentEvalRunDetail>;/**- * Benchmark-level run list (all runs, used by sidebar and benchmark detail)+ * Benchmark-level run list keyed by benchmarkId+ * (all runs, used by sidebar and benchmark detail)*/- runList: AgentEvalRunListItem[];+ runListMap: Record<string, AgentEvalRunListItem[]>;+ /** Local-first bookkeeping for `runListMap`. */+ runListReplica: ReplicaState<AgentEvalRunListItem[]>;+ /** By-id run results cache (`runResultsMap[runId]`). */runResultsMap: Record<string, AgentEvalRunResults>;+ /** Local-first bookkeeping for `runResultsMap`. */+ runResultsReplica: ReplicaState<AgentEvalRunResults>;}export const runInitialState: RunSliceState = {datasetRunListMap: {},+ datasetRunListReplica: createReplicaState(),isCreatingRun: false,- isLoadingRuns: true,- loadingRunDetailIds: [],- loadingRunResultIds: [],runDetailMap: {},- runList: [],+ runDetailReplica: createReplicaState(),+ runListMap: {},+ runListReplica: createReplicaState(),runResultsMap: {},+ runResultsReplica: createReplicaState(),};diff --git a/src/store/eval/slices/run/projection.ts b/src/store/eval/slices/run/projection.tsnew file mode 100644index 00000000000..9027236396e--- /dev/null+++ b/src/store/eval/slices/run/projection.ts@@ -0,0 +1,60 @@+import type {+ AgentEvalRunDetail,+ AgentEvalRunListItem,+ AgentEvalRunResults,+} from '@lobechat/types';++import { defineReplica } from '@/libs/replica';+import type { agentEvalService } from '@/services/agentEval';++type ListRunsResponse = Awaited<ReturnType<typeof agentEvalService.listRuns>>;+/**+ * The server's `getRunDetails` payload is wider than the `AgentEvalRunDetail`+ * contract (its nested dataset keeps a nullable `benchmarkId`). The view still+ * exposes `AgentEvalRunDetail`; the engine folds the response in as-is.+ */+type RunDetailResponse = Awaited<ReturnType<typeof agentEvalService.getRunDetails>>;++/**+ * Benchmark-level run list, one entry per benchmark (`runListMap[benchmarkId]`).+ * The single `listRuns` endpoint serves both this and the dataset-scoped list,+ * but they render in different places, so each gets its own entry key.+ */+export const benchmarkRunListResource = defineReplica<+ { benchmarkId: string },+ AgentEvalRunListItem[],+ ListRunsResponse+>({+ key: ({ benchmarkId }) => benchmarkId,+ name: 'evalBenchmarkRunList',+ storage: 'indexedDB',+ version: 1,+});++/** Dataset-scoped run list, one entry per dataset (`datasetRunListMap[datasetId]`). */+export const datasetRunListResource = defineReplica<+ { datasetId: string },+ AgentEvalRunListItem[],+ ListRunsResponse+>({+ key: ({ datasetId }) => datasetId,+ name: 'evalDatasetRunList',+ storage: 'indexedDB',+ version: 1,+});++/** By-id run detail cache (`runDetailMap[runId]`). */+export const runDetailResource = defineReplica<string, AgentEvalRunDetail, RunDetailResponse>({+ key: (runId) => runId,+ name: 'evalRunDetail',+ storage: 'indexedDB',+ version: 1,+});++/** By-id run results cache (`runResultsMap[runId]`). */+export const runResultsResource = defineReplica<string, AgentEvalRunResults, AgentEvalRunResults>({+ key: (runId) => runId,+ name: 'evalRunResults',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/eval/slices/run/reducer.ts b/src/store/eval/slices/run/reducer.tsdeleted file mode 100644index f2f4dd27824..00000000000--- a/src/store/eval/slices/run/reducer.ts+++ /dev/null@@ -1,52 +0,0 @@-import type { AgentEvalRunDetail } from '@lobechat/types';-import { produce } from 'immer';--type SetRunDetailAction = {- id: string;- type: 'setRunDetail';- value: AgentEvalRunDetail;-};--type UpdateRunDetailAction = {- id: string;- type: 'updateRunDetail';- value: Partial<AgentEvalRunDetail>;-};--type DeleteRunDetailAction = {- id: string;- type: 'deleteRunDetail';-};--export type RunDetailDispatch = SetRunDetailAction | UpdateRunDetailAction | DeleteRunDetailAction;--export const runDetailReducer = (- state: Record<string, AgentEvalRunDetail> = {},- payload: RunDetailDispatch,-): Record<string, AgentEvalRunDetail> => {- switch (payload.type) {- case 'setRunDetail': {- return produce(state, (draft) => {- draft[payload.id] = payload.value;- });- }-- case 'updateRunDetail': {- return produce(state, (draft) => {- if (draft[payload.id]) {- draft[payload.id] = { ...draft[payload.id], ...payload.value };- }- });- }-- case 'deleteRunDetail': {- return produce(state, (draft) => {- delete draft[payload.id];- });- }-- default: {- return state;- }- }-};diff --git a/src/store/eval/slices/run/selectors.ts b/src/store/eval/slices/run/selectors.tsindex 327b5711776..ca241114ecb 100644--- a/src/store/eval/slices/run/selectors.ts+++ b/src/store/eval/slices/run/selectors.ts@@ -1,17 +1,28 @@+import type { AgentEvalRunListItem } from '@lobechat/types';+import type { EvalStore } from '@/store/eval/store';-const runList = (s: EvalStore) => s.runList;+/** Stable empty array so a selector never returns a fresh reference on every read. */+const EMPTY_RUNS: AgentEvalRunListItem[] = [];++const runList = (benchmarkId?: string) => (s: EvalStore) =>+ (benchmarkId ? s.runListMap[benchmarkId] : undefined) ?? EMPTY_RUNS;+const datasetRunList = (datasetId: string) => (s: EvalStore) =>- s.datasetRunListMap[datasetId] || [];+ s.datasetRunListMap[datasetId] ?? EMPTY_RUNS;+const isCreatingRun = (s: EvalStore) => s.isCreatingRun;-const isLoadingRuns = (s: EvalStore) => s.isLoadingRuns;++/**+ * The benchmark run list has no local copy yet (`undefined` is the loading+ * signal) — the sidebar / RunsTab keep their skeleton until the first paint.+ */+const isLoadingRuns = (benchmarkId?: string) => (s: EvalStore) =>+ !!benchmarkId && s.runListMap[benchmarkId] === undefined;const getRunDetailById = (id: string) => (s: EvalStore) => s.runDetailMap[id];const getRunResultsById = (id: string) => (s: EvalStore) => s.runResultsMap[id];-const isLoadingRunDetail = (id: string) => (s: EvalStore) => s.loadingRunDetailIds.includes(id);-const isLoadingRunResults = (id: string) => (s: EvalStore) => s.loadingRunResultIds.includes(id);-const isRunActive = (id: string) => (s: EvalStore) => {const run = s.runDetailMap[id];return run?.status === 'running' || run?.status === 'pending';@@ -22,8 +33,6 @@ export const runSelectors = {getRunDetailById,getRunResultsById,isCreatingRun,- isLoadingRunDetail,- isLoadingRunResults,isLoadingRuns,isRunActive,runList,