🤯 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 experiment slice onto @lobechat/replica (#20678)
Arvin Xu6394b859cbf7
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 2a222bdb1a4..6141890f78e 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -644,8 +644,6 @@ export const evalKeys = {datasetRuns: def('eval:datasetRuns', (datasetId: string) => ['eval:datasetRuns', datasetId]),datasetsAll: def('eval:datasetsAll', () => ['eval:datasetsAll']),datasets: def('eval:datasets', (benchmarkId: string) => ['eval:datasets', benchmarkId]),- experimentDetail: def('eval:experimentDetail', (id: string) => ['eval:experimentDetail', id]),- experiments: def('eval:experiments', () => ['eval:experiments']),runDetail: def('eval:runDetail', (id: string) => ['eval:runDetail', id]),runResults: def('eval:runResults', (id: string) => ['eval:runResults', id]),runs: def('eval:runs', (benchmarkId?: string) => ['eval:runs', benchmarkId]),diff --git a/src/store/eval/slices/experiment/action.test.ts b/src/store/eval/slices/experiment/action.test.tsnew file mode 100644index 00000000000..75965f57bd9--- /dev/null+++ b/src/store/eval/slices/experiment/action.test.ts@@ -0,0 +1,220 @@+/**+ * @vitest-environment happy-dom+ *+ * The experiment list and detail are `@lobechat/replica` resources whose views+ * are the eval store's flat `experimentList` / `experimentDetailMap` fields.+ * 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: {+ createExperiment: vi.fn(),+ deleteExperiment: vi.fn(),+ getExperiment: vi.fn(),+ listExperiments: vi.fn(),+ updateExperiment: vi.fn(),+ },+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+}));++const resetStore = () => {+ useEvalStore.setState({+ experimentDetailMap: {},+ experimentDetailReplica: createReplicaState(),+ experimentList: [],+ experimentListInit: false,+ experimentListReplica: createReplicaState(),+ });+};++/** The replica network sync of a resource, as registered with the SWR driver. */+const syncCalls = async (name: 'evalExperimentDetail' | 'evalExperimentList') => {+ 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');+};++describe('ExperimentAction replica wiring', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetStore();+ });++ describe('useFetchExperiments', () => {+ it('registers one list sync and fetches through the service', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.listExperiments).mockResolvedValue({+ data: [],+ success: true,+ } as any);++ renderHook(() => useEvalStore.getState().useFetchExperiments());++ const [list] = await syncCalls('evalExperimentList');+ expect(list).toBeDefined();+ await list.fetcher();+ expect(agentEvalService.listExperiments).toHaveBeenCalledTimes(1);+ });++ it('returns the pre-migration { data, isLoading, error, mutate } shape', () => {+ const { result } = renderHook(() => useEvalStore.getState().useFetchExperiments());+ expect(result.current).toMatchObject({ data: undefined, isLoading: true });+ expect(typeof result.current.mutate).toBe('function');+ });++ it('exposes the settled list through `data` once the store has init', () => {+ useEvalStore.setState({+ experimentList: [{ id: 'e1', name: 'Sweep' } as any],+ experimentListInit: true,+ });+ const { result } = renderHook(() => useEvalStore.getState().useFetchExperiments());+ expect(result.current.data).toEqual([{ id: 'e1', name: 'Sweep' }]);+ expect(result.current.isLoading).toBe(false);+ });+ });++ describe('useFetchExperimentDetail', () => {+ it('registers a detail sync keyed by id and fetches that page', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.getExperiment).mockResolvedValue({+ data: { id: 'e1', name: 'Sweep' },+ success: true,+ } as any);++ renderHook(() => useEvalStore.getState().useFetchExperimentDetail('e1'));++ const [detail] = await syncCalls('evalExperimentDetail');+ expect(detail).toBeDefined();+ await detail.fetcher();+ expect(agentEvalService.getExperiment).toHaveBeenCalledWith('e1');+ });++ it('is inert while no id is given', () => {+ const { result } = renderHook(() => useEvalStore.getState().useFetchExperimentDetail());+ expect(typeof result.current.mutate).toBe('function');+ });+ });++ describe('refreshExperiments / refreshExperimentDetail', () => {+ it('revalidates the list replica instead of a hand-written SWR key', async () => {+ await useEvalStore.getState().refreshExperiments();+ const matchers = await revalidationMatchers();+ expect(+ matchers.some((m) =>+ m(['replica:sync', 'evalExperimentList', 1, 'anon:personal', 'all', {}]),+ ),+ ).toBe(true);+ });++ it('revalidates one detail entry by id', async () => {+ await useEvalStore.getState().refreshExperimentDetail('e1');+ const matchers = await revalidationMatchers();+ expect(+ matchers.some((m) =>+ m(['replica:sync', 'evalExperimentDetail', 1, 'anon:personal', 'e1', 'e1']),+ ),+ ).toBe(true);+ });+ });++ describe('createExperiment', () => {+ it('creates through the service, refreshes the list, and returns the created row', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.createExperiment).mockResolvedValue({+ data: { id: 'e1', name: 'Sweep' },+ success: true,+ } as any);++ const result = await useEvalStore.getState().createExperiment({+ benchmarkIds: ['b1'],+ name: 'Sweep',+ });++ expect(agentEvalService.createExperiment).toHaveBeenCalledWith({+ benchmarkIds: ['b1'],+ name: 'Sweep',+ });+ expect(result).toEqual({ id: 'e1', name: 'Sweep' });+ const matchers = await revalidationMatchers();+ expect(matchers.length).toBeGreaterThan(0);+ });+ });++ describe('deleteExperiment', () => {+ it('deletes through the service and drops the experiment from every copy', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.deleteExperiment).mockResolvedValue(undefined as any);+ useEvalStore.setState({+ experimentDetailMap: { e1: { id: 'e1', name: 'Sweep' } as any },+ experimentList: [{ id: 'e1', name: 'Sweep' } as any],+ experimentListInit: true,+ });++ await useEvalStore.getState().deleteExperiment('e1');++ expect(agentEvalService.deleteExperiment).toHaveBeenCalledWith('e1');+ expect(useEvalStore.getState().experimentDetailMap.e1).toBeUndefined();+ expect(useEvalStore.getState().experimentList).toEqual([]);+ // The optimistic removal keeps the list settled (init stays true).+ expect(useEvalStore.getState().experimentListInit).toBe(true);+ });++ it('restores the deleted row when the server rejects the delete', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.deleteExperiment).mockRejectedValue(new Error('boom'));+ useEvalStore.setState({+ experimentList: [{ id: 'e1', name: 'Sweep' } as any],+ experimentListInit: true,+ });++ await expect(useEvalStore.getState().deleteExperiment('e1')).rejects.toThrow('boom');+ expect(useEvalStore.getState().experimentList).toEqual([{ id: 'e1', name: 'Sweep' }]);+ });+ });++ describe('updateExperiment', () => {+ it('updates through the service then revalidates list and detail', async () => {+ const { agentEvalService } = await import('@/services/agentEval');+ vi.mocked(agentEvalService.updateExperiment).mockResolvedValue(undefined as any);++ await useEvalStore.getState().updateExperiment({ id: 'e1', name: 'New' });++ expect(agentEvalService.updateExperiment).toHaveBeenCalledWith({ id: 'e1', name: 'New' });+ const matchers = await revalidationMatchers();+ expect(+ matchers.some((m) =>+ m(['replica:sync', 'evalExperimentList', 1, 'anon:personal', 'all', {}]),+ ),+ ).toBe(true);+ expect(+ matchers.some((m) =>+ m(['replica:sync', 'evalExperimentDetail', 1, 'anon:personal', 'e1', 'e1']),+ ),+ ).toBe(true);+ });+ });+});diff --git a/src/store/eval/slices/experiment/action.ts b/src/store/eval/slices/experiment/action.tsindex f526f9d33ff..64210defc4c 100644--- a/src/store/eval/slices/experiment/action.ts+++ b/src/store/eval/slices/experiment/action.ts@@ -1,26 +1,105 @@-import { type AgentEvalExperimentDetail } 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 AgentEvalExperimentDetail, type AgentEvalExperimentListItem } from '@lobechat/types';++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 {+ EXPERIMENT_LIST_KEY,+ experimentDetailResource,+ experimentListResource,+} 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 experiment list keeps its long-standing flat field (`experimentList`) as+ * the replica view, gated by `experimentListInit` so a loaded-but-empty list+ * stays distinguishable from one that was never fetched (the sidebar's+ * skeleton gate).+ */+const experimentListLens: ReplicaLens<EvalStore, AgentEvalExperimentListItem[]> = {+ clear: () => ({ experimentList: [], experimentListInit: false }),+ get: (state) => (state.experimentListInit ? state.experimentList : undefined),+ keys: (state) => (state.experimentListInit ? [EXPERIMENT_LIST_KEY] : []),+ set: (_state, _key, data) =>+ data+ ? { experimentList: data, experimentListInit: true }+ : { experimentList: [], experimentListInit: false },+};++/** Pre-migration `useFetchExperiments` return shape, backed by the list replica. */+export interface ExperimentListSyncResult extends ReplicaSyncResult {+ /** The list once it has settled (hydrated or fetched), else `undefined`. */+ data: AgentEvalExperimentListItem[] | 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 `useFetchExperimentDetail` return shape, backed by the detail replica. */+export interface ExperimentDetailSyncResult {+ 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 createExperimentSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>new ExperimentActionImpl(set, get, _api);export class ExperimentActionImpl {+ 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(experimentListResource, {+ actionPrefix: 'experimentList',+ entity: arrayEntity<AgentEvalExperimentListItem>((experiment) => experiment.id),+ fetcher: () => agentEvalService.listExperiments(),+ get,+ merge: (response) => response.data,+ set,+ stateKey: 'experimentListReplica',+ view: experimentListLens,+ });+ this.#detail = createReplicaSlice(experimentDetailResource, {+ actionPrefix: 'experimentDetail',+ // The detail is a superset of the list row: the same experiment is+ // patched here and in the list when a mutation fans out through+ // `#entity`.+ entity: singleEntity<AgentEvalExperimentDetail, AgentEvalExperimentListItem>(+ (experiment) => experiment.id,+ ),+ fetcher: (id) => agentEvalService.getExperiment(id),+ get,+ merge: (response) => response.data,+ set,+ stateKey: 'experimentDetailReplica',+ view: recordLens<EvalStore, AgentEvalExperimentDetail>('experimentDetailMap'),+ });+ // The same experiment lives in the list and in its workspace page: an edit+ // or a delete patches both copies at once.+ this.#entity = linkReplicaEntity<AgentEvalExperimentListItem>([this.#list, this.#detail]);}createExperiment = async (params: {@@ -30,22 +109,15 @@ export class ExperimentActionImpl {name: string;}): Promise<any> => {const result = await agentEvalService.createExperiment(params);- await this.#get().refreshExperiments();+ await this.refreshExperiments();return result.data;};deleteExperiment = async (id: string): Promise<void> => {- // Optimistic: drop from the list immediately, then revalidate.- this.#set(- (state) => ({ experimentList: state.experimentList.filter((e) => e.id !== id) }),- false,- 'deleteExperiment/optimistic',- );- try {- await agentEvalService.deleteExperiment(id);- } finally {- await this.#get().refreshExperiments();- }+ // Optimistic: drop the row from the list (and the detail cache) right away,+ // rolling back if the server rejects it, then converge on the server list.+ await this.#entity.optimistic(id, 'remove', () => agentEvalService.deleteExperiment(id));+ await this.refreshExperiments();};updateExperiment = async (params: {@@ -56,70 +128,50 @@ export class ExperimentActionImpl {name?: string;}): Promise<void> => {await agentEvalService.updateExperiment(params);- await Promise.all([- this.#get().refreshExperiments(),- this.#get().refreshExperimentDetail(params.id),- ]);+ await Promise.all([this.refreshExperiments(), this.refreshExperimentDetail(params.id)]);};refreshExperimentDetail = async (id: string): Promise<void> => {- await mutate(evalKeys.experimentDetail(id));+ await this.#detail.revalidate(id);};refreshExperiments = async (): Promise<void> => {- await mutate(evalKeys.experiments());+ await this.#list.revalidate();};- useFetchExperimentDetail = (id?: string): SWRResponse =>- useClientDataSWR(- id ? evalKeys.experimentDetail(id) : null,- () => agentEvalService.getExperiment(id!),- {- onSuccess: (data: any) => {- this.#get().internal_setExperimentDetail(id!, data.data);- this.#get().internal_updateExperimentDetailLoading(id!, false);- },- },- );-- useFetchExperiments = (): SWRResponse =>- useClientDataSWR(evalKeys.experiments(), () => agentEvalService.listExperiments(), {- onSuccess: (data: any) => {- this.#set(- {- experimentList: data.data,- experimentListInit: true,- },- false,- 'useFetchExperiments/success',- );- },- });-- internal_setExperimentDetail = (id: string, value: AgentEvalExperimentDetail): void => {- const currentMap = this.#get().experimentDetailMap;- if (isEqual(currentMap[id], value)) return;-- this.#set(- { experimentDetailMap: { ...currentMap, [id]: value } },- false,- 'setExperimentDetail',- );+ /**+ * Fetch orchestration only (the page is read from `experimentDetailMap`).+ * Keeps the pre-migration `{ error, isLoading, mutate }` shape.+ */+ useFetchExperimentDetail = (id?: string): ExperimentDetailSyncResult => {+ const sync = this.#detail.useSync(id || null);+ return {+ error: sync.error,+ // A failed first load is neither loading nor settled: gate on the error+ // so the page can fall through to its error state instead of a skeleton.+ isLoading: !sync.error && (!sync.isHydrated || sync.isValidating),+ mutate: sync.revalidate,+ };};- internal_updateExperimentDetailLoading = (id: string, loading: boolean): void => {- this.#set(- (state) => {- if (loading) {- return { loadingExperimentDetailIds: [...state.loadingExperimentDetailIds, id] };- }- return {- loadingExperimentDetailIds: state.loadingExperimentDetailIds.filter((i) => i !== id),- };- },- false,- 'updateExperimentDetailLoading',- );+ /**+ * Fetch orchestration only (the list is read from the store). Keeps the+ * pre-migration `{ data, isLoading, error, mutate }` shape so the overview's+ * `AsyncBoundary` and the sidebar's skeleton/error gates keep working+ * unchanged.+ */+ useFetchExperiments = (): ExperimentListSyncResult => {+ // 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.experimentListInit);+ const sync = this.#list.useSync(LIST_PARAMS);+ const { experimentList, experimentListInit } = this.#get();+ return {+ ...sync,+ data: experimentListInit ? experimentList : undefined,+ isLoading: !sync.error && !experimentListInit,+ mutate: sync.revalidate,+ };};}diff --git a/src/store/eval/slices/experiment/initialState.ts b/src/store/eval/slices/experiment/initialState.tsindex 8374964097a..7286169c4db 100644--- a/src/store/eval/slices/experiment/initialState.ts+++ b/src/store/eval/slices/experiment/initialState.ts@@ -1,15 +1,28 @@import type { AgentEvalExperimentDetail, AgentEvalExperimentListItem } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+export interface ExperimentSliceState {+ /** Replica view of the experiment details, one entry per experiment id. */experimentDetailMap: Record<string, AgentEvalExperimentDetail>;+ /** Replica bookkeeping of `experimentDetailMap`. */+ experimentDetailReplica: ReplicaState<AgentEvalExperimentDetail>;+ /** Replica view of the experiment list (one entry per cache scope). */experimentList: AgentEvalExperimentListItem[];+ /**+ * 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.+ */experimentListInit: boolean;- loadingExperimentDetailIds: string[];+ /** Replica bookkeeping of `experimentList`. */+ experimentListReplica: ReplicaState<AgentEvalExperimentListItem[]>;}export const experimentInitialState: ExperimentSliceState = {experimentDetailMap: {},+ experimentDetailReplica: createReplicaState(),experimentList: [],experimentListInit: false,- loadingExperimentDetailIds: [],+ experimentListReplica: createReplicaState(),};diff --git a/src/store/eval/slices/experiment/projection.ts b/src/store/eval/slices/experiment/projection.tsnew file mode 100644index 00000000000..35ae96e6931--- /dev/null+++ b/src/store/eval/slices/experiment/projection.ts@@ -0,0 +1,38 @@+import type { AgentEvalExperimentDetail, AgentEvalExperimentListItem } from '@lobechat/types';++import { defineReplica } from '@/libs/replica';+import type { agentEvalService } from '@/services/agentEval';++/** The server wraps both experiment payloads in `{ data, success }`. */+type ExperimentListResponse = Awaited<ReturnType<typeof agentEvalService.listExperiments>>;+type ExperimentDetailResponse = Awaited<ReturnType<typeof agentEvalService.getExperiment>>;++/**+ * The experiment list has one entry per cache scope: it takes no query params,+ * so the overview, the sidebar and the header switcher all read the same list.+ */+export const EXPERIMENT_LIST_KEY = 'all';++/** Every experiment of the active scope (the flat `experimentList` view). */+export const experimentListResource = defineReplica<+ Record<string, never>,+ AgentEvalExperimentListItem[],+ ExperimentListResponse+>({+ key: () => EXPERIMENT_LIST_KEY,+ name: 'evalExperimentList',+ storage: 'indexedDB',+ version: 1,+});++/** One experiment page, keyed by the route param (`experimentDetailMap[id]`). */+export const experimentDetailResource = defineReplica<+ string,+ AgentEvalExperimentDetail,+ ExperimentDetailResponse+>({+ key: (id) => id,+ name: 'evalExperimentDetail',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/eval/slices/experiment/replica.test.ts b/src/store/eval/slices/experiment/replica.test.tsnew file mode 100644index 00000000000..f761eecb8cb--- /dev/null+++ b/src/store/eval/slices/experiment/replica.test.ts@@ -0,0 +1,166 @@+/**+ * @vitest-environment happy-dom+ *+ * The experiment list and detail are `@lobechat/replica` resources whose views+ * are the eval store's flat `experimentList` / `experimentDetailMap` 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 surfaces a failed load instead of hanging on a skeleton),+ * 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 { experimentDetailResource, experimentListResource } 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 = experimentListResource.storageKey(LIST_PARAMS);+const DETAIL_STORAGE_KEY = experimentDetailResource.storageKey('e1');++const listRow = (id: string, name: string) =>+ ({ createdAt: new Date('2026-01-01T00:00:00.000Z'), id, name }) as any;+const detailPage = (id: string, name: string) => ({ datasets: [], id, name, runs: [] }) as any;+const listResponse = (rows: any[]) => ({ data: rows, success: true }) as any;+const detailResponse = (page: any) => ({ data: page, success: true }) 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().useFetchExperiments(), { wrapper });+const renderDetailSync = (id?: string) =>+ renderHook(() => useEvalStore.getState().useFetchExperimentDetail(id), { wrapper });++describe('experiment 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) =>+ experimentListResource.storage!.remove({ queryKey: LIST_STORAGE_KEY, scope: value }),+ ),+ );+ await Promise.all(+ [...scopes].map((value) =>+ experimentDetailResource.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 experimentListResource.storage!.set(+ { queryKey: LIST_STORAGE_KEY, scope },+ { data: [listRow('e1', 'Cached')], updatedAt: 1 },+ );+ vi.spyOn(agentEvalService, 'listExperiments').mockImplementation(pending);++ renderListSync();++ await waitFor(() => expect(useEvalStore.getState().experimentListInit).toBe(true));+ expect(useEvalStore.getState().experimentList[0].name).toBe('Cached');+ });++ it('settles the list (and marks it init) from the server', async () => {+ vi.spyOn(agentEvalService, 'listExperiments').mockResolvedValue(+ listResponse([listRow('e1', 'Sweep')]),+ );++ renderListSync();++ await waitFor(() => expect(useEvalStore.getState().experimentListInit).toBe(true));+ expect(useEvalStore.getState().experimentList).toHaveLength(1);+ expect(useEvalStore.getState().experimentList[0].name).toBe('Sweep');+ });++ it('drops the previous scope’s list on a cache-scope switch', async () => {+ vi.spyOn(agentEvalService, 'listExperiments').mockResolvedValue(+ listResponse([listRow('e1', 'Personal')]),+ );+ const { rerender } = renderListSync();+ await waitFor(() => expect(useEvalStore.getState().experimentList).toHaveLength(1));++ // Switch identity: the new scope's rows are still in flight.+ useScope(`${scope.split(':')[0]}:ws-1`);+ vi.mocked(agentEvalService.listExperiments).mockImplementation(pending);+ rerender();++ expect(useEvalStore.getState().experimentList).toEqual([]);+ expect(useEvalStore.getState().experimentListInit).toBe(false);+ });++ it('fills the detail map from the server', async () => {+ vi.spyOn(agentEvalService, 'getExperiment').mockResolvedValue(+ detailResponse(detailPage('e1', 'Sweep')),+ );++ renderDetailSync('e1');++ await waitFor(() => expect(useEvalStore.getState().experimentDetailMap.e1).toBeDefined());+ expect(useEvalStore.getState().experimentDetailMap.e1.name).toBe('Sweep');+ });++ it('surfaces a failed detail load instead of holding the loading state', async () => {+ vi.spyOn(agentEvalService, 'getExperiment').mockRejectedValue(new Error('offline'));++ const { result } = renderDetailSync('e1');++ await waitFor(() => expect(result.current.error).toBeTruthy());+ expect(result.current.isLoading).toBe(false);+ expect(useEvalStore.getState().experimentDetailMap.e1).toBeUndefined();+ });++ it('repaints the refreshed list after a mutation', async () => {+ const listExperiments = vi+ .spyOn(agentEvalService, 'listExperiments')+ .mockResolvedValue(listResponse([listRow('e1', 'Before')]));+ renderListSync();+ await waitFor(() => expect(useEvalStore.getState().experimentList).toHaveLength(1));++ listExperiments.mockResolvedValue(listResponse([listRow('e1', 'After')]));+ await act(() => useEvalStore.getState().refreshExperiments());++ await waitFor(() => expect(useEvalStore.getState().experimentList[0].name).toBe('After'));+ });+});