🤯 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
✨ feat(eval): Experiment Workspace & External Worker Protocol for Agent Eval (#17391)
Rylan Caif6086dd66019
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.tsindex 8d7f0e159d9..920e239bbc5 100644--- a/apps/cli/src/commands/agent.test.ts+++ b/apps/cli/src/commands/agent.test.ts@@ -1,6 +1,6 @@import { mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import path from 'node:path';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -48,6 +48,7 @@ const { mockTrpcClient } = vi.hoisted(() => ({aiAgent: {execAgent: { mutate: vi.fn() },getOperationStatus: { query: vi.fn() },+ interruptTask: { mutate: vi.fn() },},device: {listDevices: { query: vi.fn() },@@ -157,8 +158,8 @@ describe('agent command', () => {}async function writeGraphFixture(graph: unknown) {- tempDir = await mkdtemp(join(tmpdir(), 'lh-agent-graph-'));- const graphFile = join(tempDir, 'graph.json');+ tempDir = await mkdtemp(path.join(tmpdir(), 'lh-agent-graph-'));+ const graphFile = path.join(tempDir, 'graph.json');await writeFile(graphFile, JSON.stringify(graph), 'utf8');return graphFile;@@ -1021,11 +1022,89 @@ describe('agent command', () => {await program.parseAsync(['node', 'test', 'agent', 'status', 'op-123', '--history']);expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledWith(- expect.objectContaining({ includeHistory: true }),+ expect.objectContaining({ includeHistory: true, operationId: 'op-123' }),);});});+ describe('interrupt', () => {+ it('should interrupt an operation by id', async () => {+ mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({+ operationId: 'op-123',+ success: true,+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'agent', 'interrupt', '--operation-id', 'op-123']);++ expect(mockTrpcClient.aiAgent.interruptTask.mutate).toHaveBeenCalledWith({+ operationId: 'op-123',+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Interrupted'));+ });++ it('should interrupt by thread id alone (server resolves the operation)', async () => {+ mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({+ operationId: 'op-123',+ success: true,+ threadId: 'thd-1',+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'agent', 'interrupt', '--thread-id', 'thd-1']);++ expect(mockTrpcClient.aiAgent.interruptTask.mutate).toHaveBeenCalledWith({+ threadId: 'thd-1',+ });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Interrupted'));+ });++ it('should require at least one of --operation-id or --thread-id', async () => {+ const program = createProgram();++ await expect(program.parseAsync(['node', 'test', 'agent', 'interrupt'])).rejects.toThrow(+ 'Either --thread-id or --operation-id must be provided',+ );+ expect(mockTrpcClient.aiAgent.interruptTask.mutate).not.toHaveBeenCalled();+ });++ it('should pass optional topic and thread ids through', async () => {+ mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({ success: true });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'interrupt',+ '--operation-id',+ 'op-123',+ '--topic-id',+ 'tpc-1',+ '--thread-id',+ 'thd-1',+ ]);++ expect(mockTrpcClient.aiAgent.interruptTask.mutate).toHaveBeenCalledWith({+ operationId: 'op-123',+ threadId: 'thd-1',+ topicId: 'tpc-1',+ });+ });++ it('should warn when the interrupt is not acknowledged', async () => {+ mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({+ operationId: 'op-123',+ success: false,+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'agent', 'interrupt', '--operation-id', 'op-123']);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('not acknowledged'));+ });+ });+describe('fs', () => {it('should list VFS entries from the unified agent root alias', async () => {mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex 195282f983e..6503ef04d13 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -1,7 +1,7 @@import { readFile } from 'node:fs/promises';import { ReasoningGraphSchema } from '@lobechat/types';-import type { Command } from 'commander';+import { type Command, InvalidArgumentError } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';@@ -686,6 +686,53 @@ export function registerAgentCommand(program: Command) {if (r.completedAt) console.log(` Ended: ${r.completedAt}`);},);++ // ── interrupt ──────────────────────────────────────────++ // Mirrors the server's InterruptTaskSchema: all three ids are optional, but+ // at least one of operationId / threadId must be provided.+ agent+ .command('interrupt')+ .description('Interrupt a running agent operation')+ .option('--operation-id <id>', 'Operation ID to interrupt')+ .option('--thread-id <id>', 'Thread ID (resolves the operation from thread metadata)')+ .option('--topic-id <id>', 'Topic ID (enables remote device cancellation when applicable)')+ .option('--json', 'Output JSON envelope')+ .action(+ async (options: {+ json?: boolean;+ operationId?: string;+ threadId?: string;+ topicId?: string;+ }) => {+ if (!options.operationId && !options.threadId) {+ throw new InvalidArgumentError('Either --thread-id or --operation-id must be provided');+ }++ const client = await getTrpcClient();+ const input: Record<string, any> = {};+ if (options.operationId) input.operationId = options.operationId;+ if (options.threadId) input.threadId = options.threadId;+ if (options.topicId) input.topicId = options.topicId;++ const result = await client.aiAgent.interruptTask.mutate(input as any);++ if (options.json) {+ outputJson(result);+ return;+ }++ const r = result as any;+ const label = r?.operationId ?? options.operationId ?? options.threadId;+ if (r?.success) {+ console.log(`${pc.green('OK')} Interrupted operation ${pc.bold(label)}`);+ } else {+ console.log(+ `${pc.yellow('!')} Interrupt not acknowledged for ${pc.bold(label)} (already finished?)`,+ );+ }+ },+ );}function colorStatus(status: string): string {diff --git a/apps/cli/src/commands/eval.test.ts b/apps/cli/src/commands/eval.test.tsindex 1ba9a02f313..be9e515c223 100644--- a/apps/cli/src/commands/eval.test.ts+++ b/apps/cli/src/commands/eval.test.ts@@ -1,40 +1,54 @@+import { rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { log } from '../utils/logger';import { registerEvalCommand } from './eval';-const { mockTrpcClient } = vi.hoisted(() => ({+const { mockTrpcClient, mockResolveLocalDeviceId } = vi.hoisted(() => ({+ mockResolveLocalDeviceId: vi.fn(),mockTrpcClient: {agentEval: {abortRun: { mutate: vi.fn() },createBenchmark: { mutate: vi.fn() },createDataset: { mutate: vi.fn() },+ createExperiment: { mutate: vi.fn() },createRun: { mutate: vi.fn() },createTestCase: { mutate: vi.fn() },deleteBenchmark: { mutate: vi.fn() },deleteDataset: { mutate: vi.fn() },+ deleteExperiment: { mutate: vi.fn() },deleteRun: { mutate: vi.fn() },deleteTestCase: { mutate: vi.fn() },getBenchmark: { query: vi.fn() },getDataset: { query: vi.fn() },+ getExperiment: { query: vi.fn() },getRunDetails: { query: vi.fn() },getRunProgress: { query: vi.fn() },getRunResults: { query: vi.fn() },getTestCase: { query: vi.fn() },listBenchmarks: { query: vi.fn() },listDatasets: { query: vi.fn() },+ listExperiments: { query: vi.fn() },listRuns: { query: vi.fn() },listTestCases: { query: vi.fn() },retryRunErrors: { mutate: vi.fn() },startRun: { mutate: vi.fn() },updateBenchmark: { mutate: vi.fn() },updateDataset: { mutate: vi.fn() },+ updateExperiment: { mutate: vi.fn() },updateTestCase: { mutate: vi.fn() },},agentEvalExternal: {datasetGet: { query: vi.fn() },messagesList: { query: vi.fn() },+ reportResultsBatch: { mutate: vi.fn() },+ runClaim: { mutate: vi.fn() },+ runCreate: { mutate: vi.fn() },+ runExecuteCase: { mutate: vi.fn() },runGet: { query: vi.fn() },runSetStatus: { mutate: vi.fn() },runTopicReportResult: { mutate: vi.fn() },@@ -42,9 +56,16 @@ const { mockTrpcClient } = vi.hoisted(() => ({testCasesCount: { query: vi.fn() },threadsList: { query: vi.fn() },},+ device: {+ listDevices: { query: vi.fn() },+ },},}));+vi.mock('../utils/device', () => ({+ resolveLocalDeviceId: mockResolveLocalDeviceId,+}));+const { getTrpcClientMock } = vi.hoisted(() => ({getTrpcClientMock: vi.fn(),}));@@ -69,6 +90,7 @@ describe('eval command', () => {beforeEach(() => {getTrpcClientMock.mockResolvedValue(mockTrpcClient);+ mockResolveLocalDeviceId.mockReset();exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});@@ -144,6 +166,84 @@ describe('eval command', () => {// ============================================// Dataset tests// ============================================+ describe('experiment', () => {+ it('should list experiments', async () => {+ mockTrpcClient.agentEval.listExperiments.query.mockResolvedValue({ data: [] });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'eval', 'experiment', 'list', '--json']);++ expect(mockTrpcClient.agentEval.listExperiments.query).toHaveBeenCalled();+ });++ it('should get an experiment', async () => {+ mockTrpcClient.agentEval.getExperiment.query.mockResolvedValue({ data: { id: 'e1' } });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'experiment',+ 'get',+ '--id',+ 'e1',+ '--json',+ ]);++ expect(mockTrpcClient.agentEval.getExperiment.query).toHaveBeenCalledWith({ id: 'e1' });+ });++ it('should create an experiment with benchmark ids and optional id', async () => {+ mockTrpcClient.agentEval.createExperiment.mutate.mockResolvedValue({ data: { id: 'e1' } });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'experiment',+ 'create',+ '--name',+ 'My Exp',+ '--benchmark-ids',+ 'b1, b2',+ '--id',+ 'exp_custom',+ '--json',+ ]);++ expect(mockTrpcClient.agentEval.createExperiment.mutate).toHaveBeenCalledWith({+ benchmarkIds: ['b1', 'b2'],+ id: 'exp_custom',+ name: 'My Exp',+ });+ });++ it('should update an experiment', async () => {+ mockTrpcClient.agentEval.updateExperiment.mutate.mockResolvedValue({ data: { id: 'e1' } });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'experiment',+ 'update',+ '--id',+ 'e1',+ '--name',+ 'Renamed',+ '--json',+ ]);++ expect(mockTrpcClient.agentEval.updateExperiment.mutate).toHaveBeenCalledWith({+ id: 'e1',+ name: 'Renamed',+ });+ });+ });+describe('dataset', () => {it('should list datasets', async () => {mockTrpcClient.agentEval.listDatasets.query.mockResolvedValue([{ id: 'd1', name: 'DS 1' }]);@@ -203,12 +303,23 @@ describe('eval command', () => {'ds1','-n','Dataset 1',+ '--eval-mode',+ 'external',+ '--eval-config',+ '{"schemaVersion":1,"dataset":"terminal-bench/terminal-bench-2-1"}',+ '--metadata',+ '{"taskCount":89}','--json',]);- expect(mockTrpcClient.agentEval.createDataset.mutate).toHaveBeenCalledWith(- expect.objectContaining({ benchmarkId: 'b1', identifier: 'ds1', name: 'Dataset 1' }),- );+ expect(mockTrpcClient.agentEval.createDataset.mutate).toHaveBeenCalledWith({+ benchmarkId: 'b1',+ evalConfig: { dataset: 'terminal-bench/terminal-bench-2-1', schemaVersion: 1 },+ evalMode: 'external',+ identifier: 'ds1',+ metadata: { taskCount: 89 },+ name: 'Dataset 1',+ });});});@@ -262,6 +373,32 @@ describe('eval command', () => {);});+ it('should create a test case with a dataset-native case id', async () => {+ mockTrpcClient.agentEval.createTestCase.mutate.mockResolvedValue({ id: 'tc1' });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'testcase',+ 'create',+ '--dataset-id',+ 'd1',+ '--input',+ 'Q?',+ '--case-id',+ 'case-7',+ ]);++ expect(mockTrpcClient.agentEval.createTestCase.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ datasetId: 'd1',+ metadata: { caseId: 'case-7' },+ }),+ );+ });+it('should delete a test case', async () => {mockTrpcClient.agentEval.deleteTestCase.mutate.mockResolvedValue({ success: true });@@ -446,6 +583,307 @@ describe('eval command', () => {});expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('status updated to'));});++ it('should set run status to failed via external API', async () => {+ mockTrpcClient.agentEvalExternal.runSetStatus.mutate.mockResolvedValue({+ runId: 'run-1',+ status: 'failed',+ success: true,+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run',+ 'set-status',+ '--id',+ 'run-1',+ '--status',+ 'failed',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runSetStatus.mutate).toHaveBeenCalledWith({+ runId: 'run-1',+ status: 'failed',+ });+ });++ it('should create an external run via the external API', async () => {+ mockTrpcClient.agentEvalExternal.runCreate.mutate.mockResolvedValue({+ id: 'r1',+ status: 'pending',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run',+ 'create',+ '--dataset-id',+ 'd1',+ '--external',+ '--json',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runCreate.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ datasetId: 'd1' }),+ );+ expect(mockTrpcClient.agentEval.createRun.mutate).not.toHaveBeenCalled();+ });++ it('should claim a run', async () => {+ mockTrpcClient.agentEvalExternal.runClaim.mutate.mockResolvedValue({+ run: { id: 'r1', status: 'running' },+ testCases: [],+ });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'eval', 'run', 'claim', '--id', 'r1', '--json']);++ expect(mockTrpcClient.agentEvalExternal.runClaim.mutate).toHaveBeenCalledWith({+ runId: 'r1',+ });+ });++ it('should map --include-cases to config.caseSelection', async () => {+ mockTrpcClient.agentEvalExternal.runCreate.mutate.mockResolvedValue({+ id: 'r1',+ status: 'pending',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run',+ 'create',+ '--dataset-id',+ 'd1',+ '--external',+ '--include-cases',+ 'case_1, case_2',+ '--json',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runCreate.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ config: { caseSelection: { caseIds: ['case_1', 'case_2'], mode: 'include' } },+ }),+ );+ });++ it('should reject --include-cases with --exclude-cases', async () => {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run',+ 'create',+ '--dataset-id',+ 'd1',+ '--include-cases',+ 'a',+ '--exclude-cases',+ 'b',+ ]);++ // handleCommandError logs and exits without calling the API+ expect(mockTrpcClient.agentEvalExternal.runCreate.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.agentEval.createRun.mutate).not.toHaveBeenCalled();+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should pass a caller-supplied id through run create --external --id', async () => {+ mockTrpcClient.agentEvalExternal.runCreate.mutate.mockResolvedValue({+ id: 'run_custom',+ status: 'pending',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run',+ 'create',+ '--dataset-id',+ 'd1',+ '--external',+ '--id',+ 'run_custom',+ '--json',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runCreate.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ datasetId: 'd1', id: 'run_custom' }),+ );+ });++ it('should filter run list by --experiment-id', async () => {+ mockTrpcClient.agentEval.listRuns.query.mockResolvedValue({ data: [] });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run',+ 'list',+ '--experiment-id',+ 'exp_1',+ '--json',+ ]);++ expect(mockTrpcClient.agentEval.listRuns.query).toHaveBeenCalledWith(+ expect.objectContaining({ experimentId: 'exp_1' }),+ );+ });+ });++ // ============================================+ // Eval Agent tests (external eval API)+ // ============================================+ describe('agent', () => {+ it('should execute a case via eval agent run', async () => {+ mockTrpcClient.agentEvalExternal.runExecuteCase.mutate.mockResolvedValue({+ status: 'started',+ testCaseId: 'tc1',+ topicId: 't1',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'agent',+ 'run',+ '--run-id',+ 'r1',+ '--case-id',+ 'case-1',+ '--json',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runExecuteCase.mutate).toHaveBeenCalledWith({+ caseId: 'case-1',+ deviceId: undefined,+ prompt: undefined,+ runId: 'r1',+ });+ });++ it('should resolve --device to a deviceId after online check', async () => {+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'dev-1', online: true },+ ]);+ mockTrpcClient.agentEvalExternal.runExecuteCase.mutate.mockResolvedValue({+ operationId: 'op-1',+ status: 'started',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'agent',+ 'run',+ '--run-id',+ 'r1',+ '--case-id',+ 'case-1',+ '--device',+ 'dev-1',+ '--json',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runExecuteCase.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'dev-1' }),+ );+ });++ it('should resolve --device local via the connected device', async () => {+ mockResolveLocalDeviceId.mockReturnValue('dev-local');+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'dev-local', online: true },+ ]);+ mockTrpcClient.agentEvalExternal.runExecuteCase.mutate.mockResolvedValue({+ status: 'started',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'agent',+ 'run',+ '--run-id',+ 'r1',+ '--case-id',+ 'case-1',+ '--device',+ 'local',+ '--json',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runExecuteCase.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'dev-local' }),+ );+ });++ it('should fail --device local when no local device is connected', async () => {+ mockResolveLocalDeviceId.mockReturnValue(undefined);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'agent',+ 'run',+ '--run-id',+ 'r1',+ '--case-id',+ 'case-1',+ '--device',+ 'local',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runExecuteCase.mutate).not.toHaveBeenCalled();+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should reject an offline device', async () => {+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'dev-1', online: false },+ ]);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'agent',+ 'run',+ '--run-id',+ 'r1',+ '--case-id',+ 'case-1',+ '--device',+ 'dev-1',+ ]);++ expect(mockTrpcClient.agentEvalExternal.runExecuteCase.mutate).not.toHaveBeenCalled();+ expect(exitSpy).toHaveBeenCalledWith(1);+ });});// ============================================@@ -510,6 +948,67 @@ describe('eval command', () => {topicId: 'topic-1',});});++ it('should batch report results from a JSON file', async () => {+ const items = [+ { correct: true, score: 1, topicId: 'topic-1' },+ { correct: false, result: { reason: 'wrong' }, score: 0, topicId: 'topic-2' },+ ];+ const tmpFile = path.join(os.tmpdir(), `eval-report-${process.pid}.json`);+ await writeFile(tmpFile, JSON.stringify(items));++ mockTrpcClient.agentEvalExternal.reportResultsBatch.mutate.mockResolvedValue({+ success: true,+ });++ try {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run-topic',+ 'report-results',+ '--run-id',+ 'run-1',+ '--file',+ tmpFile,+ '--json',+ ]);++ expect(mockTrpcClient.agentEvalExternal.reportResultsBatch.mutate).toHaveBeenCalledWith({+ items,+ runId: 'run-1',+ });+ } finally {+ await rm(tmpFile, { force: true });+ }+ });++ it('should reject an empty batch file without calling the API', async () => {+ const tmpFile = path.join(os.tmpdir(), `eval-report-empty-${process.pid}.json`);+ await writeFile(tmpFile, '[]');++ try {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'run-topic',+ 'report-results',+ '--run-id',+ 'run-1',+ '--file',+ tmpFile,+ ]);++ expect(mockTrpcClient.agentEvalExternal.reportResultsBatch.mutate).not.toHaveBeenCalled();+ expect(exitSpy).toHaveBeenCalledWith(1);+ } finally {+ await rm(tmpFile, { force: true });+ }+ });});// ============================================diff --git a/apps/cli/src/commands/eval.ts b/apps/cli/src/commands/eval.tsindex 7eb6790f7b4..f06daf2955a 100644--- a/apps/cli/src/commands/eval.ts+++ b/apps/cli/src/commands/eval.ts@@ -1,8 +1,11 @@+import { readFile } from 'node:fs/promises';+import type { Command } from 'commander';import { InvalidArgumentError } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';+import { resolveLocalDeviceId } from '../utils/device';import { log } from '../utils/logger';const JSON_VERSION = 'v1' as const;@@ -108,12 +111,30 @@ const parseResultJson = (value: string) => {return parsed;};-const parseRunStatus = (value: string) => {- if (value !== 'completed' && value !== 'external') {- throw new InvalidArgumentError("Only 'completed' and 'external' are supported");+const parseJsonObject = (option: string) => (value: string) => {+ let parsed: unknown;+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new InvalidArgumentError(`Invalid JSON value for ${option}`);}+ if (!isRecord(parsed) || Array.isArray(parsed)) {+ throw new InvalidArgumentError(`${option} must be a JSON object`);+ }+ return parsed;+};- return value as 'completed' | 'external';+const RUN_SET_STATUSES = ['completed', 'external', 'failed', 'aborted'] as const;+type RunSetStatus = (typeof RUN_SET_STATUSES)[number];++const parseRunStatus = (value: string): RunSetStatus => {+ if (!(RUN_SET_STATUSES as readonly string[]).includes(value)) {+ throw new InvalidArgumentError(+ `Only ${RUN_SET_STATUSES.map((s) => `'${s}'`).join(', ')} are supported`,+ );+ }++ return value as RunSetStatus;};const executeCommand = async (@@ -253,6 +274,121 @@ export function registerEvalCommand(program: Command) {),);+ // ============================================+ // Experiment Operations+ // ============================================+ const experimentCmd = evalCmd.command('experiment').description('Manage evaluation experiments');++ experimentCmd+ .command('list')+ .description('List experiments')+ .option('--json', 'Output JSON envelope')+ .action(async (options: JsonOption) =>+ executeCommand(options, async () => {+ const client = await getTrpcClient();+ return client.agentEval.listExperiments.query();+ }),+ );++ experimentCmd+ .command('get')+ .description('Get experiment details (benchmarks, datasets, runs)')+ .requiredOption('--id <id>', 'Experiment ID')+ .option('--json', 'Output JSON envelope')+ .action(async (options: JsonOption & { id: string }) =>+ executeCommand(options, async () => {+ const client = await getTrpcClient();+ return client.agentEval.getExperiment.query({ id: options.id });+ }),+ );++ experimentCmd+ .command('create')+ .description('Create an experiment')+ .requiredOption('-n, --name <name>', 'Experiment name')+ .requiredOption('--benchmark-ids <ids>', 'Comma-separated benchmark IDs')+ .option('--id <id>', 'Caller-supplied ID (idempotent cross-server create)')+ .option('-d, --description <desc>', 'Description')+ .option('--json', 'Output JSON envelope')+ .action(+ async (+ options: JsonOption & {+ benchmarkIds: string;+ description?: string;+ id?: string;+ name: string;+ },+ ) =>+ executeCommand(+ options,+ async () => {+ const client = await getTrpcClient();+ const input: Record<string, any> = {+ benchmarkIds: options.benchmarkIds+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean),+ name: options.name,+ };+ if (options.id) input.id = options.id;+ if (options.description) input.description = options.description;+ return client.agentEval.createExperiment.mutate(input as any);+ },+ `Created experiment ${pc.bold(options.name)}`,+ ),+ );++ experimentCmd+ .command('update')+ .description('Update an experiment')+ .requiredOption('--id <id>', 'Experiment ID')+ .option('-n, --name <name>', 'New name')+ .option('-d, --description <desc>', 'New description')+ .option('--benchmark-ids <ids>', 'Comma-separated benchmark IDs (replaces existing)')+ .option('--json', 'Output JSON envelope')+ .action(+ async (+ options: JsonOption & {+ benchmarkIds?: string;+ description?: string;+ id: string;+ name?: string;+ },+ ) =>+ executeCommand(+ options,+ async () => {+ const client = await getTrpcClient();+ const input: Record<string, any> = { id: options.id };+ if (options.name) input.name = options.name;+ if (options.description) input.description = options.description;+ if (options.benchmarkIds)+ input.benchmarkIds = options.benchmarkIds+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+ return client.agentEval.updateExperiment.mutate(input as any);+ },+ `Updated experiment ${pc.bold(options.id)}`,+ ),+ );++ experimentCmd+ .command('delete')+ .description('Delete an experiment (detaches runs and datasets)')+ .requiredOption('--id <id>', 'Experiment ID')+ .option('--json', 'Output JSON envelope')+ .action(async (options: JsonOption & { id: string }) =>+ executeCommand(+ options,+ async () => {+ const client = await getTrpcClient();+ return client.agentEval.deleteExperiment.mutate({ id: options.id });+ },+ `Deleted experiment ${pc.bold(options.id)}`,+ ),+ );+// ============================================// Dataset Operations// ============================================@@ -296,14 +432,22 @@ export function registerEvalCommand(program: Command) {.requiredOption('-n, --name <name>', 'Dataset name').option('-d, --description <desc>', 'Description').option('--eval-mode <mode>', 'Evaluation mode')+ .option(+ '--eval-config <json>',+ 'Evaluation config JSON object',+ parseJsonObject('--eval-config'),+ )+ .option('--metadata <json>', 'Dataset metadata JSON object', parseJsonObject('--metadata')).option('--json', 'Output JSON envelope').action(async (options: JsonOption & {benchmarkId: string;description?: string;+ evalConfig?: Record<string, unknown>;evalMode?: string;identifier: string;+ metadata?: Record<string, unknown>;name: string;},) =>@@ -318,6 +462,8 @@ export function registerEvalCommand(program: Command) {};if (options.description) input.description = options.description;if (options.evalMode) input.evalMode = options.evalMode;+ if (options.evalConfig) input.evalConfig = options.evalConfig;+ if (options.metadata) input.metadata = options.metadata;return client.agentEval.createDataset.mutate(input as any);},`Created dataset ${pc.bold(options.name)}`,@@ -413,11 +559,13 @@ export function registerEvalCommand(program: Command) {.requiredOption('--input <text>', 'Input text').option('--expected <text>', 'Expected output').option('--category <cat>', 'Category')+ .option('--case-id <id>', 'Dataset-native case ID (stored in metadata.caseId)').option('--sort-order <n>', 'Sort order').option('--json', 'Output JSON envelope').action(async (options: JsonOption & {+ caseId?: string;category?: string;datasetId: string;expected?: string;@@ -434,6 +582,7 @@ export function registerEvalCommand(program: Command) {if (options.category) content.category = options.category;const input: Record<string, any> = { content, datasetId: options.datasetId };+ if (options.caseId) input.metadata = { caseId: options.caseId };if (options.sortOrder) input.sortOrder = Number.parseInt(options.sortOrder, 10);return client.agentEval.createTestCase.mutate(input as any);},@@ -515,6 +664,7 @@ export function registerEvalCommand(program: Command) {.description('List evaluation runs').option('--benchmark-id <id>', 'Filter by benchmark ID').option('--dataset-id <id>', 'Filter by dataset ID')+ .option('--experiment-id <id>', 'Filter by experiment ID').option('--status <status>', 'Filter by status').option('-L, --limit <n>', 'Page size', '50').option('--offset <n>', 'Offset', '0')@@ -524,6 +674,7 @@ export function registerEvalCommand(program: Command) {options: JsonOption & {benchmarkId?: string;datasetId?: string;+ experimentId?: string;limit?: string;offset?: string;status?: string;@@ -534,6 +685,7 @@ export function registerEvalCommand(program: Command) {const input: Record<string, any> = {};if (options.benchmarkId) input.benchmarkId = options.benchmarkId;if (options.datasetId) input.datasetId = options.datasetId;+ if (options.experimentId) input.experimentId = options.experimentId;if (options.status) input.status = options.status;input.limit = Number.parseInt(options.limit || '50', 10);input.offset = Number.parseInt(options.offset || '0', 10);@@ -567,12 +719,22 @@ export function registerEvalCommand(program: Command) {.option('--max-concurrency <n>', 'Max concurrency (1-10)').option('--max-steps <n>', 'Max steps (1-1000)').option('--timeout <ms>', 'Timeout in ms (60000-3600000)')+ .option('--experiment-id <id>', 'Experiment ID')+ .option('--external', 'Create a claimable external run (pending, no topics, k=1)')+ .option('--id <id>', 'Caller-supplied run ID (idempotent create; 409 if params differ)')+ .option('--include-cases <ids>', 'Comma-separated dataset-native case IDs to include')+ .option('--exclude-cases <ids>', 'Comma-separated dataset-native case IDs to exclude').option('--json', 'Output JSON envelope').action(async (options: JsonOption & {agentId?: string;datasetId: string;+ excludeCases?: string;+ experimentId?: string;+ external?: boolean;+ id?: string;+ includeCases?: string;k?: string;maxConcurrency?: string;maxSteps?: string;@@ -583,23 +745,59 @@ export function registerEvalCommand(program: Command) {executeCommand(options,async () => {+ if (options.includeCases && options.excludeCases) {+ throw new InvalidArgumentError('Use only one of --include-cases or --exclude-cases');+ }+const client = await getTrpcClient();const input: Record<string, any> = { datasetId: options.datasetId };if (options.agentId) input.targetAgentId = options.agentId;if (options.name) input.name = options.name;+ if (options.experimentId) input.experimentId = options.experimentId;+ if (options.id) input.id = options.id;const config: Record<string, any> = {};if (options.k) config.k = Number.parseInt(options.k, 10);if (options.maxConcurrency)config.maxConcurrency = Number.parseInt(options.maxConcurrency, 10);if (options.maxSteps) config.maxSteps = Number.parseInt(options.maxSteps, 10);if (options.timeout) config.timeout = Number.parseInt(options.timeout, 10);+ const parseCaseIds = (csv: string) =>+ csv+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+ if (options.includeCases)+ config.caseSelection = {+ caseIds: parseCaseIds(options.includeCases),+ mode: 'include',+ };+ if (options.excludeCases)+ config.caseSelection = {+ caseIds: parseCaseIds(options.excludeCases),+ mode: 'exclude',+ };if (Object.keys(config).length > 0) input.config = config;+ if (options.external) {+ return client.agentEvalExternal.runCreate.mutate(input as any);+ }return client.agentEval.createRun.mutate(input as any);},'Created evaluation run',),);+ runCmd+ .command('claim')+ .description('Claim a pending external run (pending -> running) and fetch its workload')+ .requiredOption('--id <id>', 'Run ID')+ .option('--json', 'Output JSON envelope')+ .action(async (options: JsonOption & { id: string }) =>+ executeCommand(options, async () => {+ const client = await getTrpcClient();+ return client.agentEvalExternal.runClaim.mutate({ runId: options.id });+ }),+ );+runCmd.command('delete').description('Delete an evaluation run')@@ -691,11 +889,15 @@ export function registerEvalCommand(program: Command) {runCmd.command('set-status')- .description('Set run status (external eval API, supports completed or external)')+ .description('Set run status (external eval API: completed | external | failed | aborted)').requiredOption('--id <id>', 'Run ID')- .requiredOption('--status <status>', 'Status (completed | external)', parseRunStatus)+ .requiredOption(+ '--status <status>',+ 'Status (completed | external | failed | aborted)',+ parseRunStatus,+ ).option('--json', 'Output JSON envelope')- .action(async (options: JsonOption & { id: string; status: 'completed' | 'external' }) =>+ .action(async (options: JsonOption & { id: string; status: RunSetStatus }) =>executeCommand(options,async () => {@@ -768,6 +970,47 @@ export function registerEvalCommand(program: Command) {),);+ runTopicCmd+ .command('report-results')+ .description('Batch report evaluation results from a JSON file (or stdin with -)')+ .requiredOption('--run-id <id>', 'Run ID')+ .requiredOption(+ '--file <path>',+ 'JSON file: array of {topicId, score, correct, result?, threadId?} (use - for stdin)',+ )+ .option('--json', 'Output JSON envelope')+ .action(async (options: JsonOption & { file: string; runId: string }) =>+ executeCommand(+ options,+ async () => {+ const raw =+ options.file === '-'+ ? await new Promise<string>((resolve, reject) => {+ let data = '';+ process.stdin.on('data', (chunk) => (data += chunk));+ process.stdin.on('end', () => resolve(data));+ process.stdin.on('error', reject);+ })+ : await readFile(options.file, 'utf8');++ const parsed = JSON.parse(raw);+ const items = Array.isArray(parsed) ? parsed : parsed.items;+ if (!Array.isArray(items) || items.length === 0) {+ throw new InvalidArgumentError(+ 'Expected a JSON array of result items (or { items: [...] })',+ );+ }++ const client = await getTrpcClient();+ return client.agentEvalExternal.reportResultsBatch.mutate({+ items,+ runId: options.runId,+ } as any);+ },+ `Reported batch results for run ${pc.bold(options.runId)}`,+ ),+ );+// ============================================// Eval Thread Operations (external eval API)// ============================================@@ -785,6 +1028,68 @@ export function registerEvalCommand(program: Command) {}),);+ // ============================================+ // Eval Agent Execution (external eval API)+ // ============================================+ evalCmd+ .command('agent')+ .description('Run eval agent operations')+ .command('run')+ .description('Execute one case of a claimed run (creates topic on demand)')+ .requiredOption('--run-id <id>', 'Run ID')+ .requiredOption('--case-id <id>', 'Dataset-native case ID (or internal test case ID)')+ .option('--prompt <text>', 'Override the case input prompt')+ .option('--device <target>', 'Target device ID, or "local" for the current connected device')+ .option('--json', 'Output JSON envelope')+ .action(+ async (+ options: JsonOption & { caseId: string; device?: string; prompt?: string; runId: string },+ ) =>+ executeCommand(+ options,+ async () => {+ const client = await getTrpcClient();++ let deviceId: string | undefined;+ if (options.device !== undefined) {+ if (options.device === 'local') {+ deviceId = resolveLocalDeviceId();+ if (!deviceId) {+ throw new InvalidArgumentError(+ "No local device found. Run 'lh connect' first, then retry with --device local.",+ );+ }+ } else {+ deviceId = options.device;+ }++ const devices = await client.device.listDevices.query();+ const matched = devices.find(+ (device: { deviceId?: string; online?: boolean }) => device.deviceId === deviceId,+ );+ if (!matched) {+ throw new InvalidArgumentError(+ `Device "${deviceId}" was not found. Check 'lh device list' and try again.`,+ );+ }+ if (!matched.online) {+ throw new InvalidArgumentError(+ `Device "${deviceId}" is not online. Bring it online and try again.`,+ );+ }+ }++ return client.agentEvalExternal.runExecuteCase.mutate({+ caseId: options.caseId,+ deviceId,+ prompt: options.prompt,+ runId: options.runId,+ });+ },+ `Started case ${pc.bold(options.caseId)} for run ${pc.bold(options.runId)}`,+ ),+ );+// ============================================// Eval Message Operations (external eval API)// ============================================diff --git a/apps/server/src/routers/lambda/__tests__/agentEvalExternal.status.test.ts b/apps/server/src/routers/lambda/__tests__/agentEvalExternal.status.test.tsnew file mode 100644index 00000000000..a0b8c1cdf05--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentEvalExternal.status.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { resolveExpectedTotalCases, resolveRunStatus } from '../agentEvalExternal';++describe('resolveRunStatus', () => {+ it('returns external when any topic still awaits external eval', () => {+ expect(+ resolveRunStatus({ completedCases: 9, errorCases: 0, timeoutCases: 0, totalCases: 9 }, true),+ ).toBe('external');+ });++ it('returns running while cases are still outstanding (partial execution)', () => {+ // Regression: a partially executed external run must not flip to+ // completed/failed just because the executed cases are all evaluated.+ expect(+ resolveRunStatus({ completedCases: 3, errorCases: 0, timeoutCases: 0, totalCases: 9 }, false),+ ).toBe('running');+ });++ it('returns failed when every case errored or timed out', () => {+ expect(+ resolveRunStatus({ completedCases: 4, errorCases: 3, timeoutCases: 1, totalCases: 4 }, false),+ ).toBe('failed');+ });++ it('returns completed when all cases are done and at least one succeeded', () => {+ expect(+ resolveRunStatus({ completedCases: 4, errorCases: 1, timeoutCases: 0, totalCases: 4 }, false),+ ).toBe('completed');+ });++ it('prefers external over the other states', () => {+ expect(+ resolveRunStatus({ completedCases: 2, errorCases: 2, timeoutCases: 0, totalCases: 9 }, true),+ ).toBe('external');+ });+});++describe('resolveExpectedTotalCases', () => {+ it('uses the full dataset count when caseSelection is omitted (canonical all)', () => {+ expect(resolveExpectedTotalCases(undefined, 10)).toBe(10);+ expect(resolveExpectedTotalCases({ mode: 'all' }, 10)).toBe(10);+ });++ it('uses the selection size for include', () => {+ expect(resolveExpectedTotalCases({ caseIds: ['c1'], mode: 'include' }, 10)).toBe(1);+ expect(resolveExpectedTotalCases({ caseIds: ['c1', 'c2', 'c3'], mode: 'include' }, 10)).toBe(3);+ });++ it('subtracts the excluded ids for exclude', () => {+ expect(resolveExpectedTotalCases({ caseIds: ['c1', 'c2'], mode: 'exclude' }, 10)).toBe(8);+ });++ it('clamps exclude to zero when more ids are excluded than exist', () => {+ expect(resolveExpectedTotalCases({ caseIds: ['c1', 'c2'], mode: 'exclude' }, 1)).toBe(0);+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/evalRunConfig.schema.test.ts b/apps/server/src/routers/lambda/__tests__/evalRunConfig.schema.test.tsnew file mode 100644index 00000000000..e1a9647e100--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/evalRunConfig.schema.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest';++import { evalCaseSelectionSchema } from '../evalRunConfig.schema';++describe('evalCaseSelectionSchema', () => {+ describe('canonical "all" — normalizes to omission', () => {+ it('omitted caseSelection parses to undefined (= all cases)', () => {+ const result = evalCaseSelectionSchema.optional().safeParse(undefined);+ expect(result.success).toBe(true);+ expect(result.data).toBeUndefined();+ });++ it('explicit {mode:all} with absent caseIds normalizes to undefined', () => {+ const result = evalCaseSelectionSchema.safeParse({ mode: 'all' });+ expect(result.success).toBe(true);+ expect(result.data).toBeUndefined();+ });++ it('explicit {mode:all} with empty caseIds normalizes to undefined', () => {+ const result = evalCaseSelectionSchema.safeParse({ caseIds: [], mode: 'all' });+ expect(result.success).toBe(true);+ expect(result.data).toBeUndefined();+ });++ it('rejects {mode:all} with non-empty caseIds', () => {+ expect(evalCaseSelectionSchema.safeParse({ caseIds: ['c1'], mode: 'all' }).success).toBe(+ false,+ );+ });++ it('exclude with empty caseIds normalizes to undefined (= all)', () => {+ const result = evalCaseSelectionSchema.safeParse({ caseIds: [], mode: 'exclude' });+ expect(result.success).toBe(true);+ expect(result.data).toBeUndefined();+ });++ it('exclude with missing caseIds normalizes to undefined (= all)', () => {+ const result = evalCaseSelectionSchema.safeParse({ mode: 'exclude' });+ expect(result.success).toBe(true);+ expect(result.data).toBeUndefined();+ });+ });++ describe('include/exclude — validated and persisted unchanged', () => {+ it('accepts include with unique non-blank caseIds, unchanged', () => {+ const input = { caseIds: ['case_1', 'case_2'], mode: 'include' } as const;+ const result = evalCaseSelectionSchema.safeParse(input);+ expect(result.success).toBe(true);+ expect(result.data).toEqual(input);+ });++ it('accepts exclude with unique non-blank caseIds, unchanged', () => {+ const input = { caseIds: ['case_9'], mode: 'exclude' } as const;+ const result = evalCaseSelectionSchema.safeParse(input);+ expect(result.success).toBe(true);+ expect(result.data).toEqual(input);+ });++ it('rejects include without caseIds', () => {+ expect(evalCaseSelectionSchema.safeParse({ mode: 'include' }).success).toBe(false);+ });++ it('rejects include with empty caseIds', () => {+ expect(evalCaseSelectionSchema.safeParse({ caseIds: [], mode: 'include' }).success).toBe(+ false,+ );+ });++ it('rejects blank caseIds', () => {+ expect(+ evalCaseSelectionSchema.safeParse({ caseIds: ['ok', ' '], mode: 'include' }).success,+ ).toBe(false);+ });++ it('rejects duplicate caseIds', () => {+ expect(+ evalCaseSelectionSchema.safeParse({ caseIds: ['c1', 'c1'], mode: 'exclude' }).success,+ ).toBe(false);+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.tsindex 1c0f845d75d..fc148f34b95 100644--- a/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts@@ -876,7 +876,12 @@ describe('Agent Eval Router Integration Tests', () => {});expect(result.name).toBe('Test Run');- expect(result.config).toEqual({ maxConcurrency: 5, timeout: 300000 });+ // createRun stamps an immutable executionMode snapshot into the config+ expect(result.config).toEqual({+ executionMode: 'internal',+ maxConcurrency: 5,+ timeout: 300000,+ });});it('should default status to idle', async () => {diff --git a/apps/server/src/routers/lambda/agentEval.ts b/apps/server/src/routers/lambda/agentEval.tsindex f2883746dfe..cfb381edb3b 100644--- a/apps/server/src/routers/lambda/agentEval.ts+++ b/apps/server/src/routers/lambda/agentEval.ts@@ -8,6 +8,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport {AgentEvalBenchmarkModel,AgentEvalDatasetModel,+ AgentEvalExperimentModel,AgentEvalRunModel,AgentEvalRunTopicModel,AgentEvalTestCaseModel,@@ -18,6 +19,8 @@ import { AgentEvalRunService } from '@/server/services/agentEvalRun';import { FileService } from '@/server/services/file';import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';+import { evalRunInputConfigSchema } from './evalRunConfig.schema';+const rubricTypeSchema = z.enum(['equals','contains',@@ -41,17 +44,6 @@ const rubricTypeSchema = z.enum([const evalConfigSchema = z.object({ judgePrompt: z.string().optional() }).passthrough();-const evalRunInputConfigSchema = z.object({- k: z.number().min(1).max(10).optional(),- maxConcurrency: z.number().min(1).max(20).optional(),- maxSteps: z.number().min(1).max(1000).optional(),- timeout: z- .number()- .min(60_000)- .max(6 * 3_600_000)- .optional(),-});-const log = debug('lobe-lambda-router:agent-eval');const agentEvalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {@@ -62,6 +54,7 @@ const agentEvalProcedure = wsCompatProcedure.use(serverDatabase).use(async (optsctx: {benchmarkModel: new AgentEvalBenchmarkModel(ctx.serverDB, ctx.userId, wsId),datasetModel: new AgentEvalDatasetModel(ctx.serverDB, ctx.userId, wsId),+ experimentModel: new AgentEvalExperimentModel(ctx.serverDB, ctx.userId, wsId),runModel: new AgentEvalRunModel(ctx.serverDB, ctx.userId, wsId),runService: new AgentEvalRunService(ctx.serverDB, ctx.userId, wsId),runTopicModel: new AgentEvalRunTopicModel(ctx.serverDB, ctx.userId, wsId),@@ -177,6 +170,94 @@ export const agentEvalRouter = router({}}),+ // ============================================+ // Experiment Operations+ // ============================================+ createExperiment: agentEvalProcedureWrite+ .input(+ z.object({+ // Optional caller-supplied id for cross-server idempotent creation.+ id: z.string().optional(),+ name: z.string(),+ description: z.string().optional(),+ metadata: z.record(z.string(), z.unknown()).optional(),+ benchmarkIds: z.array(z.string()).min(1),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const data = await ctx.experimentModel.create(input);+ return { data, success: true };+ }),++ listExperiments: agentEvalProcedure.query(async ({ ctx }) => {+ const data = await ctx.experimentModel.query();+ return { data, success: true };+ }),++ getExperiment: agentEvalProcedure+ .input(z.object({ id: z.string() }))+ .query(async ({ input, ctx }) => {+ const experiment = await ctx.experimentModel.findById(input.id);+ if (!experiment) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Experiment not found' });+ }++ // Enrich runs with target agent display info (batched) and dataset name+ // (mapped from the datasets already fetched — no extra queries).+ const agentIds = [+ ...new Set(experiment.runs.map((run) => run.targetAgentId).filter(Boolean)),+ ] as string[];+ const agents = await Promise.all(+ agentIds.map((id) => ctx.runService.getAgentDisplayInfo(id)),+ );+ const agentMap = Object.fromEntries(agents.filter(Boolean).map((a) => [a!.id, a!]));+ const datasetNameMap = new Map(experiment.datasets.map((d) => [d.id, d.name]));++ const runs = experiment.runs.map((run) => ({+ ...run,+ datasetName: datasetNameMap.get(run.datasetId) || undefined,+ targetAgent: run.targetAgentId ? agentMap[run.targetAgentId] : undefined,+ }));++ return { data: { ...experiment, runs }, success: true };+ }),++ updateExperiment: agentEvalProcedureWrite+ .input(+ z.object({+ id: z.string(),+ name: z.string().optional(),+ description: z.string().optional(),+ metadata: z.record(z.string(), z.unknown()).optional(),+ benchmarkIds: z.array(z.string()).optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const { id, ...data } = input;+ const result = await ctx.experimentModel.update(id, data);+ if (!result) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Experiment not found' });+ }+ return { data: result, success: true };+ }),++ deleteExperiment: agentEvalProcedureWrite+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ try {+ const result = await ctx.experimentModel.delete(input.id);+ if (result.rowCount === 0) {+ return { success: false, error: 'Experiment not found' };+ }+ return { success: true };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Failed to delete experiment',+ };+ }+ }),+// ============================================// Dataset Operations// ============================================@@ -190,6 +271,7 @@ export const agentEvalRouter = router({evalMode: rubricTypeSchema.optional(),evalConfig: evalConfigSchema.optional(),metadata: z.record(z.string(), z.unknown()).optional(),+ sourceExperimentId: z.string().optional(),}),).mutation(async ({ input, ctx }) => {@@ -227,7 +309,7 @@ export const agentEvalRouter = router({listDatasets: agentEvalProcedure.input(z.object({ benchmarkId: z.string().optional() }).optional()).query(async ({ ctx, input }) => {- return ctx.datasetModel.query(input?.benchmarkId);+ return ctx.datasetModel.query({ benchmarkId: input?.benchmarkId });}),getDataset: agentEvalProcedure@@ -606,6 +688,10 @@ export const agentEvalRouter = router({targetAgentId: z.string().optional(),name: z.string().optional(),config: evalRunInputConfigSchema.optional(),+ experimentId: z.string().optional(),+ parentRunId: z.string().optional(),+ // 'external': create claimable (pending) run with no pre-created topics.+ mode: z.enum(['internal', 'external']).optional(),}),).mutation(async ({ input, ctx }) => {@@ -621,6 +707,13 @@ export const agentEvalRouter = router({} catch (error: any) {const pgError = error?.cause || error;+ if (pgError?.message === 'Experiment not found') {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Experiment not found' });+ }+ if (pgError?.message === 'Parent run not found') {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Parent run not found' });+ }+// Check for foreign key violation (dataset not found)if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {throw new TRPCError({@@ -637,6 +730,7 @@ export const agentEvalRouter = router({z.object({benchmarkId: z.string().optional(),datasetId: z.string().optional(),+ experimentId: z.string().optional(),status: z.enum(['idle', 'pending', 'running', 'completed', 'failed', 'aborted', 'external']).optional(),@@ -648,6 +742,7 @@ export const agentEvalRouter = router({const data = await ctx.runModel.query({benchmarkId: input.benchmarkId,datasetId: input.datasetId,+ experimentId: input.experimentId,status: input.status,limit: input.limit,offset: input.offset,@@ -813,7 +908,18 @@ export const agentEvalRouter = router({});}- await ctx.runService.retrySingleCase(input.runId, input.testCaseId);+ try {+ await ctx.runService.retrySingleCase(input.runId, input.testCaseId);+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Cannot retry case';+ if (message.startsWith('Cannot retry: case is')) {+ throw new TRPCError({ code: 'CONFLICT', message });+ }+ if (message === 'RunTopic not found') {+ throw new TRPCError({ code: 'NOT_FOUND', message });+ }+ throw error;+ }await AgentEvalRunWorkflow.triggerExecuteTestCase({runId: input.runId,diff --git a/apps/server/src/routers/lambda/agentEvalExternal.test.ts b/apps/server/src/routers/lambda/agentEvalExternal.test.tsnew file mode 100644index 00000000000..3d24a73b65e--- /dev/null+++ b/apps/server/src/routers/lambda/agentEvalExternal.test.ts@@ -0,0 +1,140 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { agentEvalExternalRouter } from './agentEvalExternal';++const mocks = vi.hoisted(() => ({+ countByDatasetId: vi.fn(),+ evaluateAndFinalizeRun: vi.fn(),+ findRunById: vi.fn(),+ findRunTopics: vi.fn(),+ updateRun: vi.fn(),+ updateRunTopic: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));++vi.mock('@/database/models/agentEval', () => ({+ AgentEvalDatasetModel: vi.fn().mockImplementation(() => ({})),+ AgentEvalRunModel: vi.fn().mockImplementation(() => ({+ findById: mocks.findRunById,+ update: mocks.updateRun,+ })),+ AgentEvalRunTopicModel: vi.fn().mockImplementation(() => ({+ findByRunId: mocks.findRunTopics,+ updateByRunAndTopic: mocks.updateRunTopic,+ })),+ AgentEvalTestCaseModel: vi.fn().mockImplementation(() => ({+ countByDatasetId: mocks.countByDatasetId,+ })),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({})),+}));++vi.mock('@/server/services/agentEvalRun', () => ({+ AgentEvalRunService: vi.fn().mockImplementation(() => ({+ evaluateAndFinalizeRun: mocks.evaluateAndFinalizeRun,+ })),+ RUN_CREATE_ID_CONFLICT: 'RUN_CREATE_ID_CONFLICT',+}));++const caller = () => agentEvalExternalRouter.createCaller({ userId: 'user-1' } as never);++beforeEach(() => {+ vi.clearAllMocks();+});++describe('agentEvalExternalRouter.reportResult', () => {+ it('keeps a partially executed multi-case run running', async () => {+ const run = {+ config: { k: 1 },+ datasetId: 'dataset-1',+ id: 'run-1',+ metrics: null,+ startedAt: new Date(),+ };+ const awaitingTopic = {+ evalResult: { awaitingExternalEval: true },+ status: 'external',+ topicId: 'topic-1',+ };+ const completedTopic = {+ evalResult: { awaitingExternalEval: false },+ passed: true,+ score: 1,+ status: 'passed',+ topicId: 'topic-1',+ };++ mocks.findRunById.mockResolvedValue(run);+ mocks.findRunTopics+ .mockResolvedValueOnce([awaitingTopic])+ .mockResolvedValueOnce([completedTopic]);+ mocks.countByDatasetId.mockResolvedValue(10);+ mocks.evaluateAndFinalizeRun.mockResolvedValue({+ completedCases: 1,+ errorCases: 0,+ timeoutCases: 0,+ totalCases: 10,+ });+ mocks.updateRun.mockResolvedValue({ ...run, status: 'running' });++ const result = await caller().reportResult({+ correct: true,+ runId: run.id,+ score: 1,+ topicId: awaitingTopic.topicId,+ });++ expect(result.runStatus).toBe('running');+ expect(mocks.updateRun).toHaveBeenCalledWith(+ run.id,+ expect.objectContaining({ status: 'running' }),+ );+ });++ it('uses the caseSelection subset as the total-cases denominator', async () => {+ const run = {+ config: { caseSelection: { caseIds: ['c1'], mode: 'include' }, k: 1 },+ datasetId: 'dataset-1',+ id: 'run-1',+ metrics: null,+ startedAt: new Date(),+ };+ const passedTopic = {+ evalResult: { awaitingExternalEval: false },+ passed: true,+ score: 1,+ status: 'passed',+ topicId: 'topic-1',+ };++ mocks.findRunById.mockResolvedValue(run);+ mocks.findRunTopics.mockResolvedValueOnce([passedTopic]).mockResolvedValueOnce([passedTopic]);+ mocks.countByDatasetId.mockResolvedValue(10);+ mocks.evaluateAndFinalizeRun.mockResolvedValue({+ completedCases: 1,+ errorCases: 0,+ timeoutCases: 0,+ totalCases: 1,+ });+ mocks.updateRun.mockResolvedValue({ ...run, status: 'completed' });++ const result = await caller().reportResult({+ correct: true,+ runId: run.id,+ score: 1,+ topicId: passedTopic.topicId,+ });++ // The denominator comes from the selection (1 selected case), not the+ // full dataset count (10) — so reporting the only selected case completes+ // the run instead of leaving it running forever.+ expect(mocks.evaluateAndFinalizeRun).toHaveBeenCalledWith(+ expect.objectContaining({ expectedTotalCases: 1 }),+ );+ expect(result.runStatus).toBe('completed');+ });+});diff --git a/apps/server/src/routers/lambda/agentEvalExternal.ts b/apps/server/src/routers/lambda/agentEvalExternal.tsindex c9ee1e6435a..135545a356b 100644--- a/apps/server/src/routers/lambda/agentEvalExternal.ts+++ b/apps/server/src/routers/lambda/agentEvalExternal.ts@@ -1,6 +1,12 @@-import type { EvalRunTopicResult, EvalThreadResult } from '@lobechat/types';+import type {+ EvalCaseSelection,+ EvalRunMetrics,+ EvalRunTopicResult,+ EvalThreadResult,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import { and, asc, eq, isNull } from 'drizzle-orm';+import isEqual from 'fast-deep-equal';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';@@ -16,7 +22,9 @@ import { messages } from '@/database/schemas';import { buildWorkspaceWhere } from '@/database/utils/workspace';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { AgentEvalRunService } from '@/server/services/agentEvalRun';+import { AgentEvalRunService, RUN_CREATE_ID_CONFLICT } from '@/server/services/agentEvalRun';++import { evalRunInputConfigSchema } from './evalRunConfig.schema';const runStatusSchema = z.enum(['idle',@@ -28,6 +36,17 @@ const runStatusSchema = z.enum(['external',]);+const runCreateInputSchema = z.object({+ config: evalRunInputConfigSchema.optional(),+ datasetId: z.string(),+ experimentId: z.string().optional(),+ // Caller-supplied id for idempotent cross-server creation.+ id: z.string().optional(),+ name: z.string().optional(),+ parentRunId: z.string().optional(),+ targetAgentId: z.string().optional(),+});+const reportResultItemSchema = z.object({correct: z.boolean(),result: z.record(z.string(), z.unknown()).optional(),@@ -59,11 +78,50 @@ const agentEvalExternalWriteProcedure = agentEvalExternalProcedure.use(type ReportResultInput = z.infer<typeof reportResultItemSchema> & { runId: string };+/**+ * Decide the run status from aggregated metrics. Priority: external (still+ * awaiting external eval) > running (cases outstanding) > failed (every case+ * errored/timed out) > completed. Exported for unit tests.+ */+export const resolveRunStatus = (+ metrics: Pick<EvalRunMetrics, 'completedCases' | 'errorCases' | 'timeoutCases' | 'totalCases'>,+ hasAwaitingExternal: boolean,+): 'completed' | 'external' | 'failed' | 'running' => {+ if (hasAwaitingExternal) return 'external';+ const totalCases = metrics.totalCases ?? 0;+ if ((metrics.completedCases ?? 0) < totalCases) return 'running';+ return (metrics.errorCases ?? 0) + (metrics.timeoutCases ?? 0) >= totalCases+ ? 'failed'+ : 'completed';+};++/**+ * Denominator for external-run totals. External runs create topics on demand,+ * so the dataset case count is the baseline; a persisted caseSelection narrows+ * it to the selected subset (include → selection size, exclude → dataset minus+ * excluded). Omitted selection means all cases (canonical).+ *+ * caseIds are shape-validated only (existence is the worker's contract); a+ * worker executing fewer cases than the selection is treated the same as one+ * executing fewer than the full dataset — no extra clamping query. Exported+ * for unit tests.+ */+export const resolveExpectedTotalCases = (+ caseSelection: EvalCaseSelection | undefined,+ datasetCaseCount: number,+): number => {+ if (!caseSelection || caseSelection.mode === 'all') return datasetCaseCount;+ const selectedIds = caseSelection.caseIds ?? [];+ if (caseSelection.mode === 'include') return selectedIds.length;+ return Math.max(datasetCaseCount - selectedIds.length, 0);+};+const recomputeRunAggregation = async (ctx: {runModel: AgentEvalRunModel;runService: AgentEvalRunService;runTopicModel: AgentEvalRunTopicModel;+ testCaseModel: AgentEvalTestCaseModel;},runId: string,) => {@@ -72,6 +130,10 @@ const recomputeRunAggregation = async (const refreshedTopics = await ctx.runTopicModel.findByRunId(runId);const metrics = await ctx.runService.evaluateAndFinalizeRun({+ expectedTotalCases: resolveExpectedTotalCases(+ refreshedRun.config?.caseSelection,+ await ctx.testCaseModel.countByDatasetId(refreshedRun.datasetId),+ ),run: {config: refreshedRun.config,id: refreshedRun.id,@@ -86,12 +148,7 @@ const recomputeRunAggregation = async (topic.status === 'external' ||(topic.evalResult as Record<string, unknown> | null)?.awaitingExternalEval === true,);- const nonSuccessCases = (metrics.errorCases || 0) + (metrics.timeoutCases || 0);- const status = hasAwaitingExternal- ? 'external'- : nonSuccessCases >= metrics.totalCases- ? 'failed'- : 'completed';+ const status = resolveRunStatus(metrics, hasAwaitingExternal);await ctx.runModel.update(runId, { metrics, status });@@ -103,6 +160,7 @@ const applyReportResult = async (runModel: AgentEvalRunModel;runTopicModel: AgentEvalRunTopicModel;runService: AgentEvalRunService;+ testCaseModel: AgentEvalTestCaseModel;threadModel: ThreadModel;},input: ReportResultInput,@@ -176,7 +234,13 @@ const applyReportResult = async (const alreadyReported =targetThread.status === 'completed' &&targetThread.score === input.score &&- targetThread.passed === input.correct;+ targetThread.passed === input.correct &&+ isEqual(+ (existingEvalResult.externalThreadResults as Record<string, unknown> | undefined)?.[+ input.threadId+ ],+ externalResult,+ );if (alreadyReported) {idempotent = true;} else {@@ -248,7 +312,8 @@ const applyReportResult = async (const alreadyReported =runTopic.status === (input.correct ? 'passed' : 'failed') &&runTopic.score === input.score &&- runTopic.passed === input.correct;+ runTopic.passed === input.correct &&+ isEqual(existingEvalResult.externalResult, externalResult);if (alreadyReported) {idempotent = true;} else {@@ -291,6 +356,75 @@ const applyReportResult = async (};export const agentEvalExternalRouter = router({+ /**+ * Create an external run: immediately claimable (`pending`), no pre-created+ * Topics/RunTopics, no workflow triggered. k=1 only.+ */+ runCreate: agentEvalExternalWriteProcedure+ .input(runCreateInputSchema)+ .mutation(async ({ ctx, input }) => {+ try {+ const run = await ctx.runService.createRun({ ...input, mode: 'external' });+ return {+ datasetId: run.datasetId,+ experimentId: run.experimentId ?? undefined,+ id: run.id,+ status: run.status,+ success: true,+ targetAgentId: run.targetAgentId ?? undefined,+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Failed to create run';+ if (message === RUN_CREATE_ID_CONFLICT) {+ throw new TRPCError({ code: 'CONFLICT', message });+ }+ throw new TRPCError({ code: 'BAD_REQUEST', message });+ }+ }),++ /**+ * Atomically claim a pending run (pending -> running) and return everything+ * the worker needs: run, dataset, all test cases, and the agent snapshot.+ */+ runClaim: agentEvalExternalWriteProcedure+ .input(z.object({ runId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ try {+ const payload = await ctx.runService.claimRun(input.runId);+ return { ...payload, success: true };+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Run is not claimable';+ throw new TRPCError({ code: 'CONFLICT', message });+ }+ }),++ /**+ * Execute a single case of a claimed run by dataset-native caseId. Creates+ * the Topic/RunTopic on demand, then starts the agent trajectory.+ */+ runExecuteCase: agentEvalExternalWriteProcedure+ .input(+ z.object({+ caseId: z.string(),+ /** Route execution to an enrolled device (native AgentRuntime). */+ deviceId: z.string().optional(),+ prompt: z.string().optional(),+ runId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const result = await ctx.runService.executeTrajectoryOnDemand(input);+ if ('error' in result && result.error) {+ return { status: 'error' as const, success: false, ...result };+ }+ return { status: 'started' as const, success: true, ...result };+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Failed to execute case';+ throw new TRPCError({ code: 'BAD_REQUEST', message });+ }+ }),+datasetGet: agentEvalExternalProcedure.input(z.object({ datasetId: z.string() })).query(async ({ ctx, input }) => {@@ -303,6 +437,8 @@ export const agentEvalExternalRouter = router({return {benchmarkId: dataset.benchmarkId,+ evalConfig: dataset.evalConfig,+ evalMode: dataset.evalMode,id: dataset.id,identifier: dataset.identifier,metadata,@@ -408,10 +544,46 @@ export const agentEvalExternalRouter = router({throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });}+ // Worker-driven terminal failure/abort: allowed from any non-terminal+ // state. Marks remaining non-terminal RunTopics aborted and finalizes.+ if (input.status === 'failed' || input.status === 'aborted') {+ if (['completed', 'failed', 'aborted'].includes(run.status)) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Run is already in a terminal state: ${run.status}`,+ });+ }++ await ctx.runTopicModel.batchMarkAborted(input.runId);++ if (input.status === 'failed') {+ const runTopics = await ctx.runTopicModel.findByRunId(input.runId);+ const metrics = await ctx.runService.evaluateAndFinalizeRun({+ expectedTotalCases: resolveExpectedTotalCases(+ run.config?.caseSelection,+ await ctx.testCaseModel.countByDatasetId(run.datasetId),+ ),+ run: { config: run.config, id: run.id, metrics: run.metrics, startedAt: run.startedAt },+ runTopics,+ });+ const updated = await ctx.runModel.update(input.runId, { metrics, status: 'failed' });+ return {+ metrics,+ runId: input.runId,+ status: updated?.status ?? 'failed',+ success: true,+ };+ }++ const updated = await ctx.runModel.update(input.runId, { status: 'aborted' });+ return { runId: input.runId, status: updated?.status ?? 'aborted', success: true };+ }+if (input.status !== 'completed' && input.status !== 'external') {throw new TRPCError({code: 'BAD_REQUEST',- message: 'External endpoint only supports setting status to completed or external',+ message:+ 'External endpoint only supports setting status to completed, external, failed, or aborted',});}@@ -437,6 +609,10 @@ export const agentEvalExternalRouter = router({}const metrics = await ctx.runService.evaluateAndFinalizeRun({+ expectedTotalCases: resolveExpectedTotalCases(+ run.config?.caseSelection,+ await ctx.testCaseModel.countByDatasetId(run.datasetId),+ ),run: { config: run.config, id: run.id, metrics: run.metrics, startedAt: run.startedAt },runTopics,});diff --git a/apps/server/src/routers/lambda/evalRunConfig.schema.ts b/apps/server/src/routers/lambda/evalRunConfig.schema.tsnew file mode 100644index 00000000000..c8bb923bd8f--- /dev/null+++ b/apps/server/src/routers/lambda/evalRunConfig.schema.ts@@ -0,0 +1,72 @@+import { z } from 'zod';++/**+ * Case selection for scoping a run to a subset of dataset cases.+ * Stored verbatim in the run config (Exp Proposal ↔ Run Config consistency+ * checks). Canonical form: "all cases" is represented by OMITTING+ * caseSelection — never persist a second "all" representation.+ *+ * Boundary acceptance + normalization:+ * - {mode:'all'} with absent or empty caseIds → accepted, normalized to omitted+ * - {mode:'all'} with non-empty caseIds → rejected+ * - {mode:'exclude'} with missing/empty caseIds → accepted, normalized to omitted+ * - {mode:'include'} with missing/empty caseIds → rejected+ * - valid include/exclude → persisted unchanged (unique, non-blank ids)+ */+export const evalCaseSelectionSchema = z+ .object({+ mode: z.enum(['all', 'include', 'exclude']),+ caseIds: z.array(z.string()).optional(),+ })+ .superRefine((val, ctx) => {+ if (val.mode === 'all') {+ if (val.caseIds && val.caseIds.length > 0) {+ ctx.addIssue({+ code: 'custom',+ message: 'caseIds must be absent or empty when mode is "all"',+ });+ }+ return;+ }++ const ids = val.caseIds ?? [];+ if (ids.length === 0) {+ if (val.mode === 'include') {+ ctx.addIssue({+ code: 'custom',+ message: 'caseIds must be non-empty when mode is "include"',+ });+ }+ // exclude with missing/empty caseIds normalizes to all — allowed+ return;+ }++ if (ids.some((id) => id.trim().length === 0)) {+ ctx.addIssue({ code: 'custom', message: 'caseIds must not contain blank values' });+ }+ if (new Set(ids).size !== ids.length) {+ ctx.addIssue({ code: 'custom', message: 'caseIds must be unique' });+ }+ })+ .transform((val) => {+ // Canonicalize "all cases" to omission.+ if (val.mode === 'all') return undefined;+ if (val.mode === 'exclude' && (!val.caseIds || val.caseIds.length === 0)) return undefined;+ return val;+ });++/**+ * User-facing config for creating an eval run. Shared by the internal+ * (agentEval) and external (agentEvalExternal) routers.+ */+export const evalRunInputConfigSchema = z.object({+ caseSelection: evalCaseSelectionSchema.optional(),+ k: z.number().min(1).max(10).optional(),+ maxConcurrency: z.number().min(1).max(20).optional(),+ maxSteps: z.number().min(1).max(1000).optional(),+ timeout: z+ .number()+ .min(60_000)+ .max(6 * 3_600_000)+ .optional(),+});diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.tsindex 737bcfbc058..2ecc3590697 100644--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts@@ -77,6 +77,47 @@ describe('AgentEvalRunService', () => {}});+ it('should store caseSelection without changing internal topic pre-creation', async () => {+ const benchmarkModel = new AgentEvalBenchmarkModel(serverDB, userId);+ const benchmark = await benchmarkModel.create({+ identifier: 'test-benchmark',+ isSystem: false,+ name: 'Test Benchmark',+ rubrics: [],+ });++ const [dataset] = await serverDB+ .insert(agentEvalDatasets)+ .values({+ benchmarkId: benchmark.id,+ identifier: 'test-dataset',+ name: 'Test Dataset',+ userId,+ })+ .returning();++ for (let i = 0; i < 2; i++) {+ await serverDB.insert(agentEvalTestCases).values({+ userId,+ content: { input: `Question ${i + 1}` },+ datasetId: dataset.id,+ metadata: { caseId: `case_${i + 1}` },+ sortOrder: i + 1,+ });+ }++ const service = new AgentEvalRunService(serverDB, userId);+ const caseSelection = { caseIds: ['case_1'], mode: 'include' as const };+ const run = await service.createRun({ config: { caseSelection }, datasetId: dataset.id });++ // Stored verbatim+ expect((run.config as any).caseSelection).toEqual(caseSelection);++ // Storage-only scope: internal pre-creation is unaffected (all cases)+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ expect(await runTopicModel.findByRunId(run.id)).toHaveLength(2);+ });+it('should handle dataset with no test cases', async () => {const benchmarkModel = new AgentEvalBenchmarkModel(serverDB, userId);const benchmark = await benchmarkModel.create({diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.external.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.external.test.tsnew file mode 100644index 00000000000..5e25e031c74--- /dev/null+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.external.test.ts@@ -0,0 +1,481 @@+import { eq } from 'drizzle-orm';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ AgentEvalBenchmarkModel,+ AgentEvalRunModel,+ AgentEvalRunTopicModel,+} from '@/database/models/agentEval';+import { agentEvalDatasets, agentEvalTestCases, topics } from '@/database/schemas';+import { AgentEvalRunService } from '@/server/services/agentEvalRun';++import { cleanupDB, serverDB, userId } from './_setup';++// Mock AiAgentService — created inside executeTrajectoryCore+const mockExecAgent = vi.fn();+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(() => ({+ execAgent: mockExecAgent,+ })),+}));++vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ interruptOperation: vi.fn().mockResolvedValue(true),+ })),+}));++beforeEach(async () => {+ await cleanupDB();+ mockExecAgent.mockReset();+ mockExecAgent.mockResolvedValue({ operationId: 'op-1' });+});++const setupDataset = async (cases: Array<{ caseId?: string; input: string }>) => {+ const benchmarkModel = new AgentEvalBenchmarkModel(serverDB, userId);+ const benchmark = await benchmarkModel.create({+ identifier: 'ext-benchmark',+ isSystem: false,+ name: 'External Benchmark',+ rubrics: [],+ });++ const [dataset] = await serverDB+ .insert(agentEvalDatasets)+ .values({+ benchmarkId: benchmark.id,+ identifier: 'ext-dataset',+ name: 'External Dataset',+ userId,+ })+ .returning();++ const testCases = [];+ for (const [i, c] of cases.entries()) {+ const [tc] = await serverDB+ .insert(agentEvalTestCases)+ .values({+ userId,+ content: { input: c.input },+ datasetId: dataset.id,+ metadata: c.caseId ? { caseId: c.caseId } : undefined,+ sortOrder: i + 1,+ })+ .returning();+ testCases.push(tc);+ }++ return { dataset, testCases };+};++describe('AgentEvalRunService external protocol', () => {+ describe('createRun mode=external', () => {+ it('should create a pending run with no topics or run topics', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }, { input: 'Q2' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });++ expect(run.status).toBe('pending');+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ expect(await runTopicModel.findByRunId(run.id)).toHaveLength(0);+ });++ it('should default to internal mode (idle + pre-created topics)', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const run = await service.createRun({ datasetId: dataset.id });++ expect(run.status).toBe('idle');+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ expect(await runTopicModel.findByRunId(run.id)).toHaveLength(1);+ });++ it('should reject external runs with k > 1', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ await expect(+ service.createRun({ config: { k: 3 }, datasetId: dataset.id, mode: 'external' }),+ ).rejects.toThrow('k=1');+ });++ it('should persist caseSelection verbatim in the run config', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const caseSelection = { caseIds: ['case_1', 'case_2'], mode: 'include' as const };+ const run = await service.createRun({+ config: { caseSelection },+ datasetId: dataset.id,+ mode: 'external',+ });++ expect((run.config as any).caseSelection).toEqual(caseSelection);+ });++ it('should store no caseSelection key when omitted (canonical all)', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });++ expect((run.config as any)?.caseSelection).toBeUndefined();+ expect('caseSelection' in ((run.config ?? {}) as object)).toBe(false);+ });+ });++ describe('createRun idempotency (caller-supplied id)', () => {+ it('should create with a caller-supplied id', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const run = await service.createRun({+ datasetId: dataset.id,+ id: 'run_custom_1',+ mode: 'external',+ });++ expect(run.id).toBe('run_custom_1');+ });++ it('should return the existing run when id and immutable params are equivalent', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const first = await service.createRun({+ config: { maxSteps: 5 },+ datasetId: dataset.id,+ id: 'run_idem_1',+ mode: 'external',+ name: 'Original',+ });+ const second = await service.createRun({+ config: { maxSteps: 5 },+ datasetId: dataset.id,+ id: 'run_idem_1',+ mode: 'external',+ name: 'Retry name differs (mutable)',+ });++ expect(second.id).toBe(first.id);+ expect(second.name).toBe('Original');+ });++ it('should throw a conflict when the same id has non-equivalent params', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ await service.createRun({+ config: { maxSteps: 5 },+ datasetId: dataset.id,+ id: 'run_idem_2',+ mode: 'external',+ });++ await expect(+ service.createRun({+ config: { maxSteps: 9 },+ datasetId: dataset.id,+ id: 'run_idem_2',+ mode: 'external',+ }),+ ).rejects.toThrow('different create parameters');+ });++ it('should treat config key order and undefined as equivalent', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ await service.createRun({+ config: { k: 1, maxSteps: 5 },+ datasetId: dataset.id,+ id: 'run_idem_3',+ mode: 'external',+ });+ const retry = await service.createRun({+ config: { maxSteps: 5, k: 1 },+ datasetId: dataset.id,+ id: 'run_idem_3',+ mode: 'external',+ });++ expect(retry.id).toBe('run_idem_3');+ });++ it('should persist executionMode in the run config', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const external = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ expect((external.config as any).executionMode).toBe('external');++ const internal = await service.createRun({ datasetId: dataset.id });+ expect((internal.config as any).executionMode).toBe('internal');+ });++ it('should conflict when the same id is reused external after internal', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ await service.createRun({ datasetId: dataset.id, id: 'run_mode_1' }); // internal (idle)++ await expect(+ service.createRun({ datasetId: dataset.id, id: 'run_mode_1', mode: 'external' }),+ ).rejects.toThrow('different create parameters');+ });++ it('should conflict when the same id is reused internal after external', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ await service.createRun({ datasetId: dataset.id, id: 'run_mode_2', mode: 'external' });++ await expect(service.createRun({ datasetId: dataset.id, id: 'run_mode_2' })).rejects.toThrow(+ 'different create parameters',+ );+ });++ it('should not infer mode from status: terminal external run still conflicts with internal reuse', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);++ const run = await service.createRun({+ datasetId: dataset.id,+ id: 'run_mode_3',+ mode: 'external',+ });+ // Drive to a terminal state — status alone can no longer reveal the mode.+ const runModel = new AgentEvalRunModel(serverDB, userId);+ await runModel.update(run.id, { status: 'completed' });++ await expect(service.createRun({ datasetId: dataset.id, id: 'run_mode_3' })).rejects.toThrow(+ 'different create parameters',+ );+ // ...but an equivalent external retry still returns it idempotently+ const retry = await service.createRun({+ datasetId: dataset.id,+ id: 'run_mode_3',+ mode: 'external',+ });+ expect(retry.id).toBe('run_mode_3');+ expect(retry.status).toBe('completed');+ });+ });++ describe('claimRun', () => {+ it('should claim a pending external run and return the workload', async () => {+ const { dataset } = await setupDataset([+ { caseId: 'case-a', input: 'Q1' },+ { caseId: 'case-b', input: 'Q2' },+ ]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });++ const payload = await service.claimRun(run.id);++ expect(payload.run.status).toBe('running');+ expect(payload.run.startedAt).toBeDefined();+ expect(payload.dataset?.id).toBe(dataset.id);+ expect(payload.testCases).toHaveLength(2);+ expect(payload.testCases.map((t) => (t.metadata as any)?.caseId)).toEqual([+ 'case-a',+ 'case-b',+ ]);+ });++ it('should throw when the run is not pending (double claim)', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });++ await service.claimRun(run.id);+ await expect(service.claimRun(run.id)).rejects.toThrow('not pending');+ });++ it('should return caseSelection unchanged in the claim payload', async () => {+ const { dataset } = await setupDataset([{ caseId: 'case-a', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const caseSelection = { caseIds: ['case-a'], mode: 'include' as const };+ const run = await service.createRun({+ config: { caseSelection },+ datasetId: dataset.id,+ mode: 'external',+ });++ const payload = await service.claimRun(run.id);++ expect((payload.run.config as any).caseSelection).toEqual(caseSelection);+ });+ });++ describe('executeTrajectoryOnDemand', () => {+ it('should resolve metadata.caseId, create topic/runTopic on demand, and start the agent', async () => {+ const { dataset, testCases } = await setupDataset([{ caseId: 'case-x', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ const result = await service.executeTrajectoryOnDemand({ caseId: 'case-x', runId: run.id });++ expect(result.testCaseId).toBe(testCases[0].id);+ expect(result.topicId).toBeTruthy();+ expect(mockExecAgent).toHaveBeenCalledOnce();++ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ const runTopics = await runTopicModel.findByRunId(run.id);+ expect(runTopics).toHaveLength(1);+ expect(runTopics[0].status).toBe('running');++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, result.topicId!));+ expect(topic.trigger).toBe('eval');+ });++ it('should return the execAgent operationId', async () => {+ const { dataset } = await setupDataset([{ caseId: 'case-op', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ const result = await service.executeTrajectoryOnDemand({ caseId: 'case-op', runId: run.id });++ expect(result.operationId).toBe('op-1');+ expect(mockExecAgent).toHaveBeenCalledWith(expect.objectContaining({ queueRetries: 5 }));+ });++ it('should pass deviceId through to execAgent', async () => {+ const { dataset } = await setupDataset([{ caseId: 'case-dev', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ await service.executeTrajectoryOnDemand({+ caseId: 'case-dev',+ deviceId: 'device-123',+ runId: run.id,+ });++ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'device-123' }),+ );+ });++ it('should not pass deviceId when omitted', async () => {+ const { dataset } = await setupDataset([{ caseId: 'case-nodev', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ await service.executeTrajectoryOnDemand({ caseId: 'case-nodev', runId: run.id });++ const callArgs = mockExecAgent.mock.calls[0][0];+ expect('deviceId' in callArgs).toBe(false);+ });++ it('should fall back to the internal test case id', async () => {+ const { dataset, testCases } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ const result = await service.executeTrajectoryOnDemand({+ caseId: testCases[0].id,+ runId: run.id,+ });+ expect(result.testCaseId).toBe(testCases[0].id);+ });++ it('should throw when the run has not been claimed', async () => {+ const { dataset } = await setupDataset([{ caseId: 'c1', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });++ await expect(+ service.executeTrajectoryOnDemand({ caseId: 'c1', runId: run.id }),+ ).rejects.toThrow('not running');+ });++ it('should throw for an unknown caseId', async () => {+ const { dataset } = await setupDataset([{ caseId: 'c1', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ await expect(+ service.executeTrajectoryOnDemand({ caseId: 'nope', runId: run.id }),+ ).rejects.toThrow('Test case not found');+ });++ it('should reject re-executing an active case', async () => {+ const { dataset } = await setupDataset([{ caseId: 'c1', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);+ await service.executeTrajectoryOnDemand({ caseId: 'c1', runId: run.id });++ await expect(+ service.executeTrajectoryOnDemand({ caseId: 'c1', runId: run.id }),+ ).rejects.toThrow('already active');+ });++ it('should idempotently re-link a terminal case to a fresh topic (old topic preserved)', async () => {+ const { dataset, testCases } = await setupDataset([{ caseId: 'c1', input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ const first = await service.executeTrajectoryOnDemand({ caseId: 'c1', runId: run.id });++ // Mark terminal+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ await runTopicModel.updateByRunAndTopic(run.id, first.topicId!, { status: 'passed' });++ const second = await service.executeTrajectoryOnDemand({ caseId: 'c1', runId: run.id });++ expect(second.topicId).not.toBe(first.topicId);+ expect(second.testCaseId).toBe(testCases[0].id);++ // Still exactly one RunTopic for this (run, testCase)+ const runTopics = await runTopicModel.findByRunId(run.id);+ expect(runTopics).toHaveLength(1);++ // Old topic preserved+ const [oldTopic] = await serverDB.select().from(topics).where(eq(topics.id, first.topicId!));+ expect(oldTopic).toBeDefined();+ });+ });++ describe('abortRun', () => {+ it('should abort an external run with no run topics', async () => {+ const { dataset } = await setupDataset([{ input: 'Q1' }]);+ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });+ await service.claimRun(run.id);++ await service.abortRun(run.id);++ const updated = await service['runModel'].findById(run.id);+ expect(updated?.status).toBe('aborted');+ });+ });++ describe('evaluateAndFinalizeRun expectedTotalCases', () => {+ it('should use expectedTotalCases as the denominator for external runs', async () => {+ const service = new AgentEvalRunService(serverDB, userId);++ const metrics = await service.evaluateAndFinalizeRun({+ expectedTotalCases: 10,+ run: { config: null, id: 'r1' },+ runTopics: [+ { runId: 'r1', score: 1, status: 'passed', topicId: 't1' },+ { runId: 'r1', score: 0, status: 'failed', topicId: 't2' },+ ],+ });++ expect(metrics.totalCases).toBe(10);+ expect(metrics.completedCases).toBe(2);+ expect(metrics.passRate).toBeCloseTo(0.1);+ });+ });+});diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.tsindex 57a2d0a663f..d42c97e8076 100644--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.ts+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.ts@@ -18,7 +18,7 @@ beforeEach(cleanupDB);describe('AgentEvalRunService', () => {describe('retryErrorCases', () => {- it('should delete error/timeout RunTopics and orphan topics, set run to pending', async () => {+ it('should delete error/timeout RunTopics but preserve old topics, set run to pending', async () => {const { run, cases } = await setupMultiCaseRun([{ assistantOutput: '42', expected: '42' },@@ -78,11 +78,11 @@ describe('AgentEvalRunService', () => {expect(passedTopics).toHaveLength(1);expect(pendingTopics).toHaveLength(2);- // Old orphan topics for error/timeout cases should be deleted+ // Old topics for error/timeout cases should be PRESERVED (audit/history)const [topic2] = await serverDB.select().from(topics).where(eq(topics.id, cases[1].topic.id));const [topic3] = await serverDB.select().from(topics).where(eq(topics.id, cases[2].topic.id));- expect(topic2).toBeUndefined();- expect(topic3).toBeUndefined();+ expect(topic2).toBeDefined();+ expect(topic3).toBeDefined();// New pending RunTopics should have new topic IDs (not the old ones)const newTopicIds = pendingTopics.map((t) => t.topicId);@@ -125,6 +125,57 @@ describe('AgentEvalRunService', () => {});});+ describe('retrySingleCase', () => {+ it('should preserve the old topic and re-link a fresh RunTopic', async () => {+ const { run, cases } = await setupMultiCaseRun([{ assistantOutput: '42', expected: '42' }], {+ datasetEvalMode: 'contains',+ });++ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ const service = new AgentEvalRunService(serverDB, userId);++ // Complete the case as passed+ await service.recordTrajectoryCompletion({+ runId: run.id,+ telemetry: { completionReason: 'stop', duration: 1000 },+ testCaseId: cases[0].testCase.id,+ });++ const oldTopicId = cases[0].topic.id;+ await service.retrySingleCase(run.id, cases[0].testCase.id);++ // Old topic preserved+ const [oldTopic] = await serverDB.select().from(topics).where(eq(topics.id, oldTopicId));+ expect(oldTopic).toBeDefined();++ // Exactly one RunTopic, pointing at a new topic, back to pending+ const runTopics = await runTopicModel.findByRunId(run.id);+ expect(runTopics).toHaveLength(1);+ expect(runTopics[0].topicId).not.toBe(oldTopicId);+ expect(runTopics[0].status).toBe('pending');+ });++ it('should reject retrying an active (running) case', async () => {+ const { run, cases } = await setupMultiCaseRun([{ assistantOutput: null }], {+ datasetEvalMode: 'contains',+ });++ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ const service = new AgentEvalRunService(serverDB, userId);++ const rt = await runTopicModel.findByRunAndTestCase(run.id, cases[0].testCase.id);+ await runTopicModel.updateByRunAndTopic(rt!.runId, rt!.topicId, { status: 'running' });++ await expect(service.retrySingleCase(run.id, cases[0].testCase.id)).rejects.toThrow(+ 'Cannot retry: case is running',+ );++ // RunTopic untouched+ const still = await runTopicModel.findByRunAndTestCase(run.id, cases[0].testCase.id);+ expect(still?.topicId).toBe(rt!.topicId);+ });+ });+describe('deleteErrorRunTopics', () => {it('should only delete error and timeout RunTopics, not passed or failed', async () => {const { run, cases } = await setupMultiCaseRun([diff --git a/apps/server/src/services/agentEvalRun/index.ts b/apps/server/src/services/agentEvalRun/index.tsindex 97c40dc9361..0fb09e7ee7c 100644--- a/apps/server/src/services/agentEvalRun/index.ts+++ b/apps/server/src/services/agentEvalRun/index.ts@@ -17,6 +17,7 @@ import debug from 'debug';import {AgentEvalBenchmarkModel,AgentEvalDatasetModel,+ AgentEvalExperimentModel,AgentEvalRunModel,AgentEvalRunTopicModel,AgentEvalTestCaseModel,@@ -35,10 +36,25 @@ import {/** Round cost to at most 6 decimal places to avoid floating-point noise */const roundCost = (v: number): number => Math.round(v * 1e6) / 1e6;-const EVAL_AGENT_RUNTIME_QSTASH_RETRIES = 10;+const EVAL_AGENT_RUNTIME_QSTASH_RETRIES = 5;const EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY = '10000 * (1 + retried)';const RESUMABLE_THREAD_STATUSES = new Set(['error', 'timeout']);+/** Thrown when a caller-supplied run id exists with non-equivalent create params. */+export const RUN_CREATE_ID_CONFLICT = 'Run id already exists with different create parameters';++/** Stable JSON stringify: sorts object keys recursively, drops undefined. */+const stableStringify = (value: unknown): string => {+ if (value === undefined) return '';+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? '';+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;+ const entries = Object.entries(value as Record<string, unknown>)+ .filter(([, v]) => v !== undefined)+ .sort(([a], [b]) => (a < b ? -1 : 1))+ .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`);+ return `{${entries.join(',')}}`;+};+const log = debug('lobe-server:eval-run-service');interface ResumableCaseTarget {@@ -79,6 +95,7 @@ export class AgentEvalRunService {private readonly runModel: AgentEvalRunModel;private readonly benchmarkModel: AgentEvalBenchmarkModel;private readonly datasetModel: AgentEvalDatasetModel;+ private readonly experimentModel: AgentEvalExperimentModel;private readonly runTopicModel: AgentEvalRunTopicModel;private readonly testCaseModel: AgentEvalTestCaseModel;private readonly messageModel: MessageModel;@@ -95,6 +112,7 @@ export class AgentEvalRunService {this.runModel = new AgentEvalRunModel(db, userId, workspaceId);this.benchmarkModel = new AgentEvalBenchmarkModel(db, userId, workspaceId);this.datasetModel = new AgentEvalDatasetModel(db, userId, workspaceId);+ this.experimentModel = new AgentEvalExperimentModel(db, userId, workspaceId);this.runTopicModel = new AgentEvalRunTopicModel(db, userId, workspaceId);this.testCaseModel = new AgentEvalTestCaseModel(db, userId, workspaceId);this.messageModel = new MessageModel(db, userId, workspaceId);@@ -106,24 +124,142 @@ export class AgentEvalRunService {async createRun(params: {config?: EvalRunInputConfig;datasetId: string;+ experimentId?: string;+ /**+ * Caller-supplied run id for idempotent cross-server creation. When a run+ * with this id already exists: equivalent immutable create params → the+ * existing run is returned; otherwise a conflict error is thrown.+ */+ id?: string;+ /**+ * 'internal' (default): pre-create Topics/RunTopics for every test case and+ * leave the run `idle` until `startRun` triggers the QStash workflow.+ * 'external': create no Topics/RunTopics and set the run `pending` so an+ * external worker can claim it; no workflow is triggered.+ */+ mode?: 'external' | 'internal';name?: string;+ parentRunId?: string;targetAgentId?: string;}) {- const agentSnapshot = params.targetAgentId- ? await this.snapshotAgentConfig(params.targetAgentId)- : undefined;+ let { datasetId, targetAgentId } = params;+ let inputConfig = params.config;+ const isExternal = params.mode === 'external';++ // Fork: inherit target agent / dataset / config from the parent run.+ // These are immutable on a fork — reject any override attempt.+ if (params.parentRunId) {+ const parent = await this.runModel.findById(params.parentRunId);+ if (!parent) throw new Error('Parent run not found');++ if (+ (params.targetAgentId && params.targetAgentId !== parent.targetAgentId) ||+ (params.config && Object.keys(params.config).length > 0) ||+ (params.datasetId && params.datasetId !== parent.datasetId)+ ) {+ throw new Error('Cannot override target agent, config, or dataset when forking a run');+ }++ targetAgentId = parent.targetAgentId ?? undefined;+ datasetId = parent.datasetId;+ inputConfig = (parent.config as EvalRunInputConfig | undefined) ?? undefined;+ }++ // External execution is driven case-by-case through `runExecuteCase`, which+ // only supports single-thread (k=1) runs today. Check after fork resolution+ // so inherited configs are covered too.+ if (isExternal && ((inputConfig as { k?: number } | undefined)?.k ?? 1) > 1) {+ throw new Error('External runs only support k=1 (pass@k is not supported yet)');+ }++ // Validate the experiment scope (and bump its recency once the run exists).+ if (params.experimentId) {+ const experiment = await this.experimentModel.findById(params.experimentId);+ if (!experiment) throw new Error('Experiment not found');+ }++ // Re-snapshot the current agent config (forks capture the *current* state).+ const agentSnapshot = targetAgentId ? await this.snapshotAgentConfig(targetAgentId) : undefined;++ // Persist the execution mode as an immutable snapshot: a run's mode cannot+ // be inferred from status once the run reaches a terminal state, and the+ // idempotency check below must compare it.+ const executionMode = isExternal ? ('external' as const) : ('internal' as const);+ const config = { ...inputConfig, agentSnapshot, executionMode };++ // Idempotent create: a caller-supplied id that already exists returns the+ // existing run when the immutable create params are equivalent (datasetId /+ // experimentId / parentRunId / targetAgentId / executionMode / input config+ // — the agent snapshot is excluded since it is re-captured server-side on+ // every create).+ const matchesExisting = (existing: {+ config?: unknown;+ datasetId: string;+ experimentId?: string | null;+ parentRunId?: string | null;+ targetAgentId?: string | null;+ }) => {+ const {+ agentSnapshot: _existingSnapshot,+ executionMode: existingMode,+ ...existingConfig+ } = (existing.config ?? {}) as Record<string, unknown>;+ return (+ existing.datasetId === datasetId &&+ (existing.experimentId ?? null) === (params.experimentId ?? null) &&+ (existing.parentRunId ?? null) === (params.parentRunId ?? null) &&+ (existing.targetAgentId ?? null) === (targetAgentId ?? null) &&+ existingMode === executionMode &&+ stableStringify(existingConfig) === stableStringify(inputConfig ?? {})+ );+ };++ if (params.id) {+ const existing = await this.runModel.findById(params.id);+ if (existing) {+ if (!matchesExisting(existing)) throw new Error(RUN_CREATE_ID_CONFLICT);+ return existing;+ }+ }++ const { mode: _mode, ...restParams } = params;+ let run;+ try {+ run = await this.runModel.create({+ ...restParams,+ datasetId,+ targetAgentId,+ config,+ // External runs start claimable; internal runs wait for `startRun`.+ status: isExternal ? 'pending' : 'idle',+ });+ } catch (error) {+ // Race-safe idempotency: a concurrent create with the same caller id won+ // — return the winner when params are equivalent, else conflict.+ if (params.id && (error as { code?: string })?.code === '23505') {+ const existing = await this.runModel.findById(params.id);+ if (existing) {+ if (!matchesExisting(existing)) throw new Error(RUN_CREATE_ID_CONFLICT, { cause: error });+ return existing;+ }+ }+ throw error;+ }- const config = { ...params.config, agentSnapshot };+ if (params.experimentId) {+ await this.experimentModel.touch(params.experimentId);+ }- const run = await this.runModel.create({ ...params, config });+ // External runs create Topics/RunTopics on demand (per executed case).+ if (isExternal) return run;// Pre-create Topics and RunTopics for all test cases (status='pending')- const testCases = await this.testCaseModel.findByDatasetId(params.datasetId);+ const testCases = await this.testCaseModel.findByDatasetId(datasetId);if (testCases.length > 0) {const createdTopics = await this.topicModel.batchCreate(testCases.map((tc) => ({- agentId: params.targetAgentId ?? undefined,+ agentId: targetAgentId ?? undefined,title: `[Eval Case #${(tc.sortOrder ?? 0) + 1}] ${tc.content?.input?.slice(0, 50) || 'Test Case'}...`,trigger: RequestTrigger.Eval,})),@@ -200,13 +336,12 @@ export class AgentEvalRunService {sortOrder: t.testCase?.sortOrder,}));- // 1. Delete error/timeout RunTopics+ // 1. Delete error/terminal RunTopics (the filter above excludes active+ // running/pending cases, so only terminal rows are ever removed).await this.runTopicModel.deleteErrorRunTopics(runId);- // 2. Delete orphan Topics (old conversations)- const topicIds = errorTopics.map((t) => t.topicId).filter(Boolean);- if (topicIds.length > 0) await this.topicModel.batchDelete(topicIds);-+ // 2. Preserve old Topics (old conversations are kept for audit/history);+ // only the RunTopic association is replaced.// 3. Create new Topics and pending RunTopics for the error test casesconst createdTopics = await this.topicModel.batchCreate(errorTestCases.map((tc) => ({@@ -238,14 +373,15 @@ export class AgentEvalRunService {const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);if (!runTopic) throw new Error('RunTopic not found');- // 1. Delete old RunTopic- await this.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);-- // 2. Delete old Topic- if (runTopic.topicId) {- await this.topicModel.batchDelete([runTopic.topicId]);+ // Active associations must not be replaced — surface a conflict.+ if (runTopic.status === 'running' || runTopic.status === 'pending') {+ throw new Error(`Cannot retry: case is ${runTopic.status}`);}+ // 1. Delete old RunTopic association+ await this.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);++ // 2. Preserve the old Topic (conversation history); only re-link.// 3. Create new Topicconst [newTopic] = await this.topicModel.batchCreate([{@@ -949,7 +1085,7 @@ export class AgentEvalRunService {testCase: { content: { input?: string }; sortOrder?: number | null };testCaseId: string;}) {- const { envPrompt, run, runId, testCaseId } = params;+ const { runId, testCaseId } = params;// Look up the pre-created RunTopic (created during createRun)const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);@@ -957,7 +1093,28 @@ export class AgentEvalRunService {throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);}- const topicId = runTopic.topicId;+ return this.executeTrajectoryCore({ ...params, topicId: runTopic.topicId });+ }++ /**+ * Shared trajectory execution once the target topic is known. Marks the+ * RunTopic running and starts the agent via execAgent.+ */+ private async executeTrajectoryCore(params: {+ /** Route execution to an enrolled device (native AgentRuntime). */+ deviceId?: string;+ envPrompt?: string;+ run: {+ config?: EvalRunConfig | null;+ datasetId: string;+ targetAgentId?: string | null;+ };+ runId: string;+ testCase: { content: { input?: string }; sortOrder?: number | null };+ testCaseId: string;+ topicId: string;+ }) {+ const { envPrompt, run, runId, testCaseId, topicId } = params;// Update status from 'pending' to 'running'await this.runTopicModel.updateByRunAndTopic(runId, topicId, { status: 'running' });@@ -974,6 +1131,7 @@ export class AgentEvalRunService {agentId: run.targetAgentId ?? undefined,appContext: { topicId },autoStart: true,+ ...(params.deviceId && { deviceId: params.deviceId }),trigger: RequestTrigger.Eval,hooks: [{@@ -1020,7 +1178,7 @@ export class AgentEvalRunService {});}- return { topicId };+ return { operationId: execResult?.operationId, topicId };} catch (error) {const errorMessage =error instanceof Error ? error.message : 'Agent execution failed to start';@@ -1040,6 +1198,117 @@ export class AgentEvalRunService {}}+ /**+ * Atomically claim a pending external run (pending -> running) and return+ * everything a worker needs: the run, its dataset, all test cases (each+ * exposing the dataset-native `metadata.caseId`), and the agent snapshot.+ * Throws when the run is not owned or not currently pending.+ */+ async claimRun(runId: string) {+ const run = await this.runModel.claim(runId);+ if (!run) throw new Error('Run is not pending or already claimed');++ const [dataset, testCases] = await Promise.all([+ this.datasetModel.findById(run.datasetId),+ this.testCaseModel.findByDatasetId(run.datasetId),+ ]);++ return {+ agentSnapshot: (run.config as EvalRunConfig | null)?.agentSnapshot,+ dataset: dataset+ ? {+ evalConfig: dataset.evalConfig,+ id: dataset.id,+ identifier: dataset.identifier,+ metadata: dataset.metadata,+ name: dataset.name,+ }+ : undefined,+ run,+ testCases: testCases.map((tc) => ({+ content: tc.content,+ id: tc.id,+ metadata: tc.metadata,+ sortOrder: tc.sortOrder,+ })),+ };+ }++ /**+ * External worker entry point: execute a single case of a claimed run by its+ * dataset-native `metadata.caseId` (falling back to the internal test case+ * id). Creates the Topic/RunTopic on demand (external runs pre-create none),+ * then runs the trajectory. Idempotent for terminal cases — the old RunTopic+ * association is replaced with a fresh Topic; an active case is rejected.+ */+ async executeTrajectoryOnDemand(params: {+ caseId: string;+ /** Route execution to an enrolled device (native AgentRuntime). */+ deviceId?: string;+ prompt?: string;+ runId: string;+ }) {+ const { runId, caseId } = params;++ const run = await this.runModel.findById(runId);+ if (!run) throw new Error('Run not found');+ if (run.status !== 'running') {+ throw new Error(`Run is not running (status=${run.status}); claim it first`);+ }+ if (((run.config as EvalRunConfig | null)?.k ?? 1) > 1) {+ throw new Error('External execution only supports k=1');+ }++ // Resolve the dataset-native caseId to an internal test case.+ let testCase = await this.testCaseModel.findByDatasetIdAndCaseId(run.datasetId, caseId);+ if (!testCase) {+ const byId = await this.testCaseModel.findById(caseId);+ if (byId && byId.datasetId === run.datasetId) testCase = byId;+ }+ if (!testCase) throw new Error(`Test case not found for caseId=${caseId}`);++ const testCaseId = testCase.id;+ const dataset = await this.datasetModel.findById(run.datasetId);+ const envPrompt = dataset?.evalConfig?.envPrompt;++ // Idempotent re-run of a terminal case: drop only the old RunTopic+ // association (the old Topic is preserved) and link a fresh one.+ const existing = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (existing) {+ if (existing.status === 'running' || existing.status === 'pending') {+ throw new Error(`Case ${caseId} is already active for this run`);+ }+ await this.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);+ }++ const [topic] = await this.topicModel.batchCreate([+ {+ agentId: run.targetAgentId ?? undefined,+ title: `[Eval Case #${(testCase.sortOrder ?? 0) + 1}] ${(testCase.content?.input ?? '').slice(0, 50)}...`,+ trigger: RequestTrigger.Eval,+ },+ ]);++ await this.runTopicModel.batchCreate([+ { runId, status: 'pending' as const, testCaseId, topicId: topic.id },+ ]);++ const result = await this.executeTrajectoryCore({+ deviceId: params.deviceId,+ envPrompt,+ run: { config: run.config, datasetId: run.datasetId, targetAgentId: run.targetAgentId },+ runId,+ testCase: {+ content: { ...testCase.content, input: params.prompt ?? testCase.content.input },+ sortOrder: testCase.sortOrder,+ },+ testCaseId,+ topicId: topic.id,+ });++ return { ...result, testCaseId };+ }+/*** Execute a test case with K threads (for pass@k).* Creates K threads in the pre-existing topic, then triggers K run-thread-trajectory workflows.@@ -1839,6 +2108,12 @@ export class AgentEvalRunService {}async evaluateAndFinalizeRun(params: {+ /**+ * Dataset case count. For external runs (Topics created on demand) this is+ * the denominator for totalCases/passRate; internal runs omit it and keep+ * `runTopics.length` (all cases are pre-created).+ */+ expectedTotalCases?: number;run: {config?: EvalRunConfig | null;id: string;@@ -1942,7 +2217,7 @@ export class AgentEvalRunService {}}- const totalCases = runTopics.length;+ const totalCases = params.expectedTotalCases ?? runTopics.length;const evaluatedCases = passedCases + failedCases;const rubricScores: Record<string, number> = {};for (const [rubricId, acc] of Object.entries(rubricScoreAcc)) {@@ -1955,7 +2230,9 @@ export class AgentEvalRunService {const metrics: EvalRunMetrics = {averageScore: evaluatedCases > 0 ? totalScore / evaluatedCases : 0,- completedCases: totalCases,+ // Cases with a RunTopic (executed). Equals totalCases for internal runs,+ // where every case gets a pre-created topic.+ completedCases: runTopics.length,cost: sumCost ? roundCost(sumCost) : undefined,duration: wallClockDuration || undefined,errorCases,diff --git a/locales/en-US/eval.json b/locales/en-US/eval.jsonindex 93bbfb9b351..9845767ddaf 100644--- a/locales/en-US/eval.json+++ b/locales/en-US/eval.json@@ -178,8 +178,55 @@"evalMode.prompt.placeholder": "Enter the evaluation criteria or prompt for LLM judge","evalMode.rubric": "Rubric Scoring","evalMode.rubric.desc": "Score output using benchmark rubrics with weighted criteria",+ "experiment.actions.create": "Create Experiment",+ "experiment.actions.delete": "Delete Experiment",+ "experiment.actions.delete.confirm": "Are you sure you want to delete this experiment? Its runs and scoped datasets will no longer be grouped here.",+ "experiment.card.benchmarkCount": "{{count}} benchmarks",+ "experiment.card.empty": "No runs yet",+ "experiment.card.emptyHint": "Open the experiment to start the first run.",+ "experiment.card.lastRun": "Last Run",+ "experiment.card.open": "Open Experiment",+ "experiment.card.runCount": "{{count}} runs",+ "experiment.create.benchmarks.label": "Benchmarks",+ "experiment.create.benchmarks.placeholder": "Select one or more benchmarks",+ "experiment.create.benchmarksRequired": "Please select at least one benchmark",+ "experiment.create.description.label": "Description",+ "experiment.create.description.placeholder": "Experiment description (optional)",+ "experiment.create.error": "Failed to create experiment",+ "experiment.create.name.label": "Name",+ "experiment.create.name.placeholder": "Enter experiment name",+ "experiment.create.nameRequired": "Please enter an experiment name",+ "experiment.create.title": "Create Experiment",+ "experiment.delete.error": "Failed to delete experiment",+ "experiment.detail.backToList": "Back to Experiments",+ "experiment.detail.benchmarks": "Benchmarks",+ "experiment.detail.benchmarksEmpty": "No benchmark datasets available yet.",+ "experiment.detail.datasetActions.create": "Create Dataset",+ "experiment.detail.datasetActions.createSubset": "Create Subset",+ "experiment.detail.datasets": "Datasets",+ "experiment.detail.datasetsBaseline": "Benchmark Datasets",+ "experiment.detail.datasetsScoped": "Scoped Datasets",+ "experiment.detail.datasetsScopedEmpty": "No scoped datasets yet.",+ "experiment.detail.lastAccessed": "Last accessed {{time}}",+ "experiment.detail.runs": "Runs",+ "experiment.detail.stats.benchmarks": "Benchmarks",+ "experiment.detail.stats.branches": "Branches",+ "experiment.detail.stats.runs": "Runs",+ "experiment.edit.error": "Failed to update experiment",+ "experiment.edit.success": "Experiment updated successfully",+ "experiment.edit.title": "Edit Experiment",+ "experiment.empty": "No experiments yet",+ "experiment.list.error": "Failed to load experiments",+ "experiment.list.subtitle": "Track optimization contexts, scoped datasets, and run iterations.",+ "experiment.list.title": "Experiments",+ "experiment.overview.emptyHint": "Run activity and scoped datasets will appear here.",+ "experiment.run.parent": "Forked from {{name}}","overview.createBenchmark": "Create Benchmark",+ "overview.createExperiment": "Create Experiment","overview.importDataset": "Import Dataset",+ "overview.sections.experiments.subtitle": "Optimization workspaces for scoped datasets, baselines, and forked iterations.",+ "overview.sections.experiments.title": "Experiments",+ "overview.sections.experiments.viewAll": "View all experiments","overview.subtitle": "Benchmark and evaluate your AI agents across datasets","overview.title": "Evaluation Lab","run.actions.abort": "Abort",@@ -229,6 +276,7 @@"run.create.dataset": "Dataset","run.create.dataset.placeholder": "Select a dataset","run.create.dataset.required": "Please select a dataset",+ "run.create.error": "Failed to create run","run.create.name": "Run Name","run.create.name.placeholder": "Enter a name for this run","run.create.name.required": "Please enter a run name",@@ -287,6 +335,7 @@"sidebar.benchmarks": "Benchmarks","sidebar.dashboard": "Dashboard","sidebar.datasets": "Datasets",+ "sidebar.experiments": "Experiments","sidebar.runs": "Runs","table.columns.avgCost": "Avg Cost","table.columns.category": "Category",diff --git a/locales/zh-CN/eval.json b/locales/zh-CN/eval.jsonindex 1fc539216b0..720fb0dcbfc 100644--- a/locales/zh-CN/eval.json+++ b/locales/zh-CN/eval.json@@ -178,8 +178,55 @@"evalMode.prompt.placeholder": "输入 LLM 评判的评估标准或提示词","evalMode.rubric": "混合指标评分","evalMode.rubric.desc": "使用基准的加权指标进行混合评分",+ "experiment.actions.create": "创建实验",+ "experiment.actions.delete": "删除实验",+ "experiment.actions.delete.confirm": "确定要删除此实验吗?其运行和作用域数据集将不再归组于此。",+ "experiment.card.benchmarkCount": "{{count}} 个基准",+ "experiment.card.empty": "还没有运行",+ "experiment.card.emptyHint": "打开实验以开始第一次运行。",+ "experiment.card.lastRun": "最近运行",+ "experiment.card.open": "打开实验",+ "experiment.card.runCount": "{{count}} 次运行",+ "experiment.create.benchmarks.label": "基准",+ "experiment.create.benchmarks.placeholder": "选择一个或多个基准",+ "experiment.create.benchmarksRequired": "请至少选择一个基准",+ "experiment.create.description.label": "描述",+ "experiment.create.description.placeholder": "实验描述(可选)",+ "experiment.create.error": "创建实验失败",+ "experiment.create.name.label": "名称",+ "experiment.create.name.placeholder": "输入实验名称",+ "experiment.create.nameRequired": "请输入实验名称",+ "experiment.create.title": "创建实验",+ "experiment.delete.error": "删除实验失败",+ "experiment.detail.backToList": "返回实验列表",+ "experiment.detail.benchmarks": "基准",+ "experiment.detail.benchmarksEmpty": "暂无基准数据集。",+ "experiment.detail.datasetActions.create": "创建数据集",+ "experiment.detail.datasetActions.createSubset": "创建子集",+ "experiment.detail.datasets": "数据集",+ "experiment.detail.datasetsBaseline": "基准数据集",+ "experiment.detail.datasetsScoped": "作用域数据集",+ "experiment.detail.datasetsScopedEmpty": "暂无作用域数据集。",+ "experiment.detail.lastAccessed": "最近访问 {{time}}",+ "experiment.detail.runs": "运行",+ "experiment.detail.stats.benchmarks": "基准",+ "experiment.detail.stats.branches": "分支",+ "experiment.detail.stats.runs": "运行",+ "experiment.edit.error": "更新实验失败",+ "experiment.edit.success": "实验更新成功",+ "experiment.edit.title": "编辑实验",+ "experiment.empty": "还没有实验",+ "experiment.list.error": "加载实验列表失败",+ "experiment.list.subtitle": "跟踪优化上下文、作用域数据集与运行迭代。",+ "experiment.list.title": "实验",+ "experiment.overview.emptyHint": "运行活动与作用域数据集将显示在这里。",+ "experiment.run.parent": "派生自 {{name}}","overview.createBenchmark": "创建基准",+ "overview.createExperiment": "创建实验","overview.importDataset": "导入数据集",+ "overview.sections.experiments.subtitle": "跟踪优化上下文与运行迭代。",+ "overview.sections.experiments.title": "实验",+ "overview.sections.experiments.viewAll": "查看全部实验","overview.subtitle": "对你的 AI 助手进行跨数据集的基准测试与评估","overview.title": "评测实验室","run.actions.abort": "终止",@@ -229,6 +276,7 @@"run.create.dataset": "数据集","run.create.dataset.placeholder": "选择数据集","run.create.dataset.required": "请选择数据集",+ "run.create.error": "创建运行失败","run.create.name": "评测名称","run.create.name.placeholder": "输入评测名称","run.create.name.required": "请输入评测名称",@@ -287,6 +335,7 @@"sidebar.benchmarks": "基准","sidebar.dashboard": "总览","sidebar.datasets": "数据集",+ "sidebar.experiments": "实验","sidebar.runs": "评测","table.columns.avgCost": "平均成本","table.columns.category": "分类",diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 48ce0bb1c11..2facd206333 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -2644,6 +2644,39 @@ describe('AgentModel', () => {});});+ it('should replace an explicitly supplied reasoning graph', async () => {+ const oldGraph = {+ edges: [],+ entry: 'legacy',+ fields: {},+ name: 'legacy-graph',+ nodes: {},+ states: { legacy: {} },+ terminal: 'legacy',+ };+ const graph = {+ edges: [{ from: '__root__', instruction: 'Complete the task.', to: 'work' }],+ fields: {},+ name: 'compiled-graph',+ nodes: { work: { type: 'agent' } },+ terminal: 'work',+ };+ const [agent] = await serverDB+ .insert(agents)+ .values({+ chatConfig: { enableGraphMode: true, graph: oldGraph },+ title: 'Graph Agent',+ userId,+ } as NewAgent)+ .returning();++ await agentModel.updateConfig(agent.id, { chatConfig: { graph } } as any);++ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });++ expect(result?.chatConfig).toEqual({ enableGraphMode: true, graph });+ });+it('should delete params field when value is undefined', async () => {const [agent] = await serverDB.insert(agents)diff --git a/packages/database/src/models/__tests__/agentEval.workspace.test.ts b/packages/database/src/models/__tests__/agentEval.workspace.test.tsindex f078cf37656..53fb736ab67 100644--- a/packages/database/src/models/__tests__/agentEval.workspace.test.ts+++ b/packages/database/src/models/__tests__/agentEval.workspace.test.ts@@ -92,12 +92,12 @@ describe('Agent eval workspace scope', () => {name: 'Workspace dataset',});- await expect(personalDatasetModel.query(personalBenchmark.id)).resolves.toEqual([- expect.objectContaining({ id: personalDataset.id }),- ]);- await expect(workspaceDatasetModel.query(workspaceBenchmark.id)).resolves.toEqual([- expect.objectContaining({ id: workspaceDataset.id }),- ]);+ await expect(+ personalDatasetModel.query({ benchmarkId: personalBenchmark.id }),+ ).resolves.toEqual([expect.objectContaining({ id: personalDataset.id })]);+ await expect(+ workspaceDatasetModel.query({ benchmarkId: workspaceBenchmark.id }),+ ).resolves.toEqual([expect.objectContaining({ id: workspaceDataset.id })]);await expect(personalDatasetModel.findById(personalDataset.id)).resolves.toMatchObject({id: personalDataset.id,workspaceId: null,diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex c7b404741af..962a551250c 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -1145,6 +1145,14 @@ export class AgentModel {}}+ // A ReasoningGraph is a complete executable document, not a partial chatConfig patch.+ if (data.chatConfig && Object.hasOwn(data.chatConfig, 'graph')) {+ mergedValue.chatConfig = {+ ...mergedValue.chatConfig,+ graph: data.chatConfig.graph,+ } as AgentItem['chatConfig'];+ }+// Apply the processed parametersmergedValue.params = Object.keys(updatedParams).length > 0 ? updatedParams : undefined;diff --git a/packages/database/src/models/agentEval/__tests__/dataset.test.ts b/packages/database/src/models/agentEval/__tests__/dataset.test.tsindex 184aacab4af..865e635b359 100644--- a/packages/database/src/models/agentEval/__tests__/dataset.test.ts+++ b/packages/database/src/models/agentEval/__tests__/dataset.test.ts@@ -5,6 +5,7 @@ import { getTestDB } from '../../../core/getTestDB';import {agentEvalBenchmarks,agentEvalDatasets,+ agentEvalExperiments,agentEvalTestCases,users,} from '../../../schemas';@@ -186,12 +187,54 @@ describe('AgentEvalDatasetModel', () => {});it('should query datasets by benchmarkId', async () => {- const results = await datasetModel.query(benchmarkId);+ const results = await datasetModel.query({ benchmarkId });expect(results).toHaveLength(2); // user-dataset-1, system-datasetexpect(results.every((r) => r.benchmarkId === benchmarkId)).toBe(true);});+ it('should query datasets across multiple benchmarks via benchmarkIds', async () => {+ const [benchmark2] = await serverDB+ .select()+ .from(agentEvalBenchmarks)+ .where(eq(agentEvalBenchmarks.identifier, 'benchmark-2'));++ const results = await datasetModel.query({ benchmarkIds: [benchmarkId, benchmark2.id] });++ // user-dataset-1, user-dataset-2, system-dataset (other-user-dataset excluded)+ expect(results).toHaveLength(3);+ expect(results.map((r) => r.identifier)).toEqual(+ expect.arrayContaining(['user-dataset-1', 'user-dataset-2', 'system-dataset']),+ );+ });++ it('should query an experiment-scoped subset and exclude system rows', async () => {+ const [experiment] = await serverDB+ .insert(agentEvalExperiments)+ .values({ name: 'Experiment 1', userId })+ .returning();+ await serverDB.insert(agentEvalDatasets).values([+ {+ benchmarkId,+ identifier: 'scoped-dataset',+ name: 'Scoped Dataset',+ sourceExperimentId: experiment.id,+ userId,+ },+ {+ benchmarkId,+ identifier: 'scoped-system-dataset',+ name: 'Scoped System Dataset',+ sourceExperimentId: experiment.id,+ userId: null, // system row inside the scope must be excluded+ },+ ]);++ const results = await datasetModel.query({ sourceExperimentId: experiment.id });++ expect(results.map((r) => r.identifier)).toEqual(['scoped-dataset']);+ });+it('should order by createdAt descending', async () => {const results = await datasetModel.query();diff --git a/packages/database/src/models/agentEval/__tests__/experiment.test.ts b/packages/database/src/models/agentEval/__tests__/experiment.test.tsnew file mode 100644index 00000000000..212e79233de--- /dev/null+++ b/packages/database/src/models/agentEval/__tests__/experiment.test.ts@@ -0,0 +1,364 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import {+ agentEvalBenchmarks,+ agentEvalDatasets,+ agentEvalExperimentBenchmarks,+ agentEvalExperiments,+ agentEvalRuns,+ users,+} from '../../../schemas';+import { AgentEvalExperimentModel } from '../experiment';++const serverDB = await getTestDB();++const userId = 'experiment-test-user';+const userId2 = 'experiment-test-user-2';+const experimentModel = new AgentEvalExperimentModel(serverDB, userId);+const experimentModel2 = new AgentEvalExperimentModel(serverDB, userId2);++const createBenchmark = async (+ overrides: Partial<typeof agentEvalBenchmarks.$inferInsert> = {},+) => {+ const [benchmark] = await serverDB+ .insert(agentEvalBenchmarks)+ .values({+ identifier: `bench-${Math.random().toString(36).slice(2, 8)}`,+ isSystem: false,+ name: 'Benchmark',+ rubrics: [],+ userId,+ ...overrides,+ })+ .returning();+ return benchmark;+};++const createDataset = async (overrides: Partial<typeof agentEvalDatasets.$inferInsert> = {}) => {+ const [dataset] = await serverDB+ .insert(agentEvalDatasets)+ .values({+ benchmarkId: overrides.benchmarkId!,+ identifier: `ds-${Math.random().toString(36).slice(2, 8)}`,+ name: 'Dataset',+ userId,+ ...overrides,+ })+ .returning();+ return dataset;+};++beforeEach(async () => {+ await serverDB.delete(agentEvalRuns);+ await serverDB.delete(agentEvalDatasets);+ await serverDB.delete(agentEvalExperimentBenchmarks);+ await serverDB.delete(agentEvalExperiments);+ await serverDB.delete(agentEvalBenchmarks);+ await serverDB.delete(users);++ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);+});++afterEach(async () => {+ await serverDB.delete(agentEvalRuns);+ await serverDB.delete(agentEvalDatasets);+ await serverDB.delete(agentEvalExperimentBenchmarks);+ await serverDB.delete(agentEvalExperiments);+ await serverDB.delete(agentEvalBenchmarks);+ await serverDB.delete(users);+});++describe('AgentEvalExperimentModel', () => {+ describe('create', () => {+ it('should create an experiment with benchmark junction rows', async () => {+ const bench1 = await createBenchmark();+ const bench2 = await createBenchmark();++ const result = await experimentModel.create({+ benchmarkIds: [bench1.id, bench2.id],+ name: 'My Experiment',+ });++ expect(result.id).toBeDefined();+ expect(result.userId).toBe(userId);++ const junctions = await serverDB.query.agentEvalExperimentBenchmarks.findMany({+ where: eq(agentEvalExperimentBenchmarks.experimentId, result.id),+ });+ expect(junctions).toHaveLength(2);+ });++ it('should dedupe benchmark ids', async () => {+ const bench1 = await createBenchmark();++ const result = await experimentModel.create({+ benchmarkIds: [bench1.id, bench1.id],+ name: 'Deduped',+ });++ const junctions = await serverDB.query.agentEvalExperimentBenchmarks.findMany({+ where: eq(agentEvalExperimentBenchmarks.experimentId, result.id),+ });+ expect(junctions).toHaveLength(1);+ });++ it('should create with a caller-supplied id', async () => {+ const bench1 = await createBenchmark();++ const result = await experimentModel.create({+ benchmarkIds: [bench1.id],+ id: 'exp_custom_id',+ name: 'Custom ID',+ });++ expect(result.id).toBe('exp_custom_id');+ });++ it('should be idempotent: creating twice with the same id returns the existing experiment', async () => {+ const bench1 = await createBenchmark();++ const first = await experimentModel.create({+ benchmarkIds: [bench1.id],+ id: 'exp_idempotent',+ name: 'First',+ });+ const second = await experimentModel.create({+ benchmarkIds: [bench1.id],+ id: 'exp_idempotent',+ name: 'Second (ignored)',+ });++ expect(second.id).toBe(first.id);+ expect(second.name).toBe('First');++ // No duplicate junction rows+ const junctions = await serverDB.query.agentEvalExperimentBenchmarks.findMany({+ where: eq(agentEvalExperimentBenchmarks.experimentId, first.id),+ });+ expect(junctions).toHaveLength(1);+ });++ it('should reject an inaccessible benchmark id without creating anything', async () => {+ const otherBench = await createBenchmark({ userId: userId2 });++ await expect(+ experimentModel.create({ benchmarkIds: [otherBench.id], name: 'Nope' }),+ ).rejects.toThrow('Benchmarks not found or inaccessible');++ const all = await serverDB.query.agentEvalExperiments.findMany();+ expect(all).toHaveLength(0);+ });+ });++ describe('findById', () => {+ it('should return the single payload with benchmarks, datasets and runs', async () => {+ const bench = await createBenchmark();+ const baseline = await createDataset({ benchmarkId: bench.id });+ const experiment = await experimentModel.create({+ benchmarkIds: [bench.id],+ name: 'Detail',+ });+ const scoped = await createDataset({+ benchmarkId: bench.id,+ sourceExperimentId: experiment.id,+ });+ await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId: scoped.id, experimentId: experiment.id, status: 'idle', userId });++ const detail = await experimentModel.findById(experiment.id);++ expect(detail).toBeDefined();+ expect(detail!.benchmarks.map((b) => b.id)).toEqual([bench.id]);+ // Both baseline and scoped datasets come back in one payload+ const datasetIds = detail!.datasets.map((d) => d.id);+ expect(datasetIds).toContain(baseline.id);+ expect(datasetIds).toContain(scoped.id);+ expect(detail!.runs).toHaveLength(1);+ expect(detail!.runs[0].experimentId).toBe(experiment.id);+ });++ it("should not find another user's experiment", async () => {+ const bench = await createBenchmark();+ const experiment = await experimentModel.create({ benchmarkIds: [bench.id], name: 'Mine' });++ const result = await experimentModel2.findById(experiment.id);+ expect(result).toBeUndefined();+ });++ it('should return undefined when not found', async () => {+ expect(await experimentModel.findById('non-existent')).toBeUndefined();+ });+ });++ describe('query', () => {+ it('should return aggregate counts and a recent-runs preview', async () => {+ const bench = await createBenchmark();+ const experiment = await experimentModel.create({+ benchmarkIds: [bench.id],+ name: 'Agg',+ });+ const scoped = await createDataset({+ benchmarkId: bench.id,+ sourceExperimentId: experiment.id,+ });+ const [run] = await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId: scoped.id, experimentId: experiment.id, status: 'idle', userId })+ .returning();++ const results = await experimentModel.query();+ const row = results.find((r) => r.id === experiment.id)!;++ expect(row.benchmarkCount).toBe(1);+ expect(row.datasetCount).toBe(1);+ expect(row.runCount).toBe(1);+ expect(row.benchmarks.map((b) => b.id)).toEqual([bench.id]);++ // recent runs preview (batched, no N+1) with dataset + benchmark context+ expect(row.recentRuns).toHaveLength(1);+ expect(row.recentRuns![0].id).toBe(run.id);+ expect(row.recentRuns![0].datasetName).toBe(scoped.name);+ expect(row.recentRuns![0].benchmarkId).toBe(bench.id);+ });++ it('should cap recent runs at 5 per experiment without N+1', async () => {+ const bench = await createBenchmark();+ const experiment = await experimentModel.create({+ benchmarkIds: [bench.id],+ name: 'Capped',+ });+ const scoped = await createDataset({+ benchmarkId: bench.id,+ sourceExperimentId: experiment.id,+ });+ await serverDB.insert(agentEvalRuns).values(+ Array.from({ length: 8 }, (_, i) => ({+ datasetId: scoped.id,+ experimentId: experiment.id,+ name: `Run ${i}`,+ status: 'idle' as const,+ userId,+ })),+ );++ const results = await experimentModel.query();+ const row = results.find((r) => r.id === experiment.id)!;++ expect(row.runCount).toBe(8);+ expect(row.recentRuns).toHaveLength(5);+ });++ it("should not return another user's experiments", async () => {+ const bench = await createBenchmark();+ await experimentModel.create({ benchmarkIds: [bench.id], name: 'Mine' });++ const results = await experimentModel2.query();+ expect(results).toHaveLength(0);+ });+ });++ describe('update', () => {+ it('should update fields and replace benchmark junctions', async () => {+ const bench1 = await createBenchmark();+ const bench2 = await createBenchmark();+ const experiment = await experimentModel.create({+ benchmarkIds: [bench1.id],+ name: 'Original',+ });++ const updated = await experimentModel.update(experiment.id, {+ benchmarkIds: [bench2.id],+ name: 'Updated',+ });++ expect(updated?.name).toBe('Updated');+ const junctions = await serverDB.query.agentEvalExperimentBenchmarks.findMany({+ where: eq(agentEvalExperimentBenchmarks.experimentId, experiment.id),+ });+ expect(junctions.map((j) => j.benchmarkId)).toEqual([bench2.id]);+ });++ it('should reject invalid benchmark ids and preserve existing junctions', async () => {+ const bench1 = await createBenchmark();+ const otherBench = await createBenchmark({ userId: userId2 });+ const experiment = await experimentModel.create({+ benchmarkIds: [bench1.id],+ name: 'Keep',+ });++ await expect(+ experimentModel.update(experiment.id, { benchmarkIds: [otherBench.id] }),+ ).rejects.toThrow('Benchmarks not found or inaccessible');++ const junctions = await serverDB.query.agentEvalExperimentBenchmarks.findMany({+ where: eq(agentEvalExperimentBenchmarks.experimentId, experiment.id),+ });+ expect(junctions.map((j) => j.benchmarkId)).toEqual([bench1.id]);+ });+ });++ describe('delete', () => {+ it('should detach runs and datasets before deleting the experiment', async () => {+ const bench = await createBenchmark();+ const experiment = await experimentModel.create({+ benchmarkIds: [bench.id],+ name: 'ToDelete',+ });+ const scoped = await createDataset({+ benchmarkId: bench.id,+ sourceExperimentId: experiment.id,+ });+ const [run] = await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId: scoped.id, experimentId: experiment.id, status: 'idle', userId })+ .returning();++ await experimentModel.delete(experiment.id);++ // Experiment + junctions gone+ expect(+ await serverDB.query.agentEvalExperiments.findFirst({+ where: eq(agentEvalExperiments.id, experiment.id),+ }),+ ).toBeUndefined();+ expect(+ await serverDB.query.agentEvalExperimentBenchmarks.findMany({+ where: eq(agentEvalExperimentBenchmarks.experimentId, experiment.id),+ }),+ ).toHaveLength(0);++ // Run + dataset preserved but detached+ const runAfter = await serverDB.query.agentEvalRuns.findFirst({+ where: eq(agentEvalRuns.id, run.id),+ });+ expect(runAfter).toBeDefined();+ expect(runAfter!.experimentId).toBeNull();++ const datasetAfter = await serverDB.query.agentEvalDatasets.findFirst({+ where: eq(agentEvalDatasets.id, scoped.id),+ });+ expect(datasetAfter).toBeDefined();+ expect(datasetAfter!.sourceExperimentId).toBeNull();+ });+ });++ describe('touch', () => {+ it('should bump accessedAt', async () => {+ const bench = await createBenchmark();+ const experiment = await experimentModel.create({ benchmarkIds: [bench.id], name: 'Touch' });++ const before = experiment.accessedAt;+ // Ensure a measurable difference+ await new Promise((resolve) => setTimeout(resolve, 5));+ const touched = await experimentModel.touch(experiment.id);++ expect(touched).toBeDefined();+ expect(new Date(touched!.accessedAt).getTime()).toBeGreaterThanOrEqual(+ new Date(before).getTime(),+ );+ });+ });+});diff --git a/packages/database/src/models/agentEval/__tests__/run.test.ts b/packages/database/src/models/agentEval/__tests__/run.test.tsindex 76a30157d75..d947261f20b 100644--- a/packages/database/src/models/agentEval/__tests__/run.test.ts+++ b/packages/database/src/models/agentEval/__tests__/run.test.ts@@ -483,6 +483,59 @@ describe('AgentEvalRunModel', () => {});});+ describe('claim', () => {+ it('should transition a pending run to running and set startedAt', async () => {+ const [run] = await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId, userId, status: 'pending' })+ .returning();++ const result = await runModel.claim(run.id);++ expect(result).toBeDefined();+ expect(result?.status).toBe('running');+ expect(result?.startedAt).toBeDefined();+ });++ it('should return undefined for a non-pending run (double claim)', async () => {+ const [run] = await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId, userId, status: 'pending' })+ .returning();++ const first = await runModel.claim(run.id);+ expect(first?.status).toBe('running');++ const second = await runModel.claim(run.id);+ expect(second).toBeUndefined();+ });++ it('should not claim a run owned by another user', async () => {+ const [run] = await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId, userId: userId2, status: 'pending' })+ .returning();++ const result = await runModel.claim(run.id);+ expect(result).toBeUndefined();++ const unchanged = await serverDB.query.agentEvalRuns.findFirst({+ where: eq(agentEvalRuns.id, run.id),+ });+ expect(unchanged?.status).toBe('pending');+ });++ it('should not claim an idle run', async () => {+ const [run] = await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId, userId, status: 'idle' })+ .returning();++ const result = await runModel.claim(run.id);+ expect(result).toBeUndefined();+ });+ });+describe('countByDatasetId', () => {beforeEach(async () => {// Create another datasetdiff --git a/packages/database/src/models/agentEval/__tests__/testCase.test.ts b/packages/database/src/models/agentEval/__tests__/testCase.test.tsindex ca8f280e5e4..5e0c3cf90a9 100644--- a/packages/database/src/models/agentEval/__tests__/testCase.test.ts+++ b/packages/database/src/models/agentEval/__tests__/testCase.test.ts@@ -419,6 +419,52 @@ describe('AgentEvalTestCaseModel', () => {});});+ describe('findByDatasetIdAndCaseId', () => {+ it('should find a test case by metadata.caseId', async () => {+ const created = await testCaseModel.create({+ datasetId,+ content: { input: 'External case' },+ metadata: { caseId: 'case-42' },+ });++ const result = await testCaseModel.findByDatasetIdAndCaseId(datasetId, 'case-42');++ expect(result).toBeDefined();+ expect(result?.id).toBe(created.id);+ });++ it('should return undefined when no case carries that caseId', async () => {+ await testCaseModel.create({+ datasetId,+ content: { input: 'Some case' },+ metadata: { caseId: 'case-1' },+ });++ const result = await testCaseModel.findByDatasetIdAndCaseId(datasetId, 'missing');+ expect(result).toBeUndefined();+ });++ it('should not match a case from another dataset with the same caseId', async () => {+ const [benchmark2] = await serverDB+ .insert(agentEvalBenchmarks)+ .values({ identifier: 'benchmark-2', isSystem: false, name: 'Benchmark 2', rubrics: [] })+ .returning();+ const [dataset2] = await serverDB+ .insert(agentEvalDatasets)+ .values({ benchmarkId: benchmark2.id, identifier: 'ds-2', name: 'DS 2', userId })+ .returning();++ await testCaseModel.create({+ datasetId: dataset2.id,+ content: { input: 'Other dataset case' },+ metadata: { caseId: 'shared-id' },+ });++ const result = await testCaseModel.findByDatasetIdAndCaseId(datasetId, 'shared-id');+ expect(result).toBeUndefined();+ });+ });+describe('countByDatasetId', () => {it('should count test cases by dataset id', async () => {await serverDB.insert(agentEvalTestCases).values([diff --git a/packages/database/src/models/agentEval/dataset.ts b/packages/database/src/models/agentEval/dataset.tsindex a2c105776c6..8882b9ada94 100644--- a/packages/database/src/models/agentEval/dataset.ts+++ b/packages/database/src/models/agentEval/dataset.ts@@ -1,9 +1,15 @@-import { and, asc, count, desc, eq, isNull, or } from 'drizzle-orm';+import { and, asc, count, desc, eq, inArray, isNull, or } from 'drizzle-orm';import { agentEvalDatasets, agentEvalTestCases, type NewAgentEvalDataset } from '../../schemas';import { type LobeChatDatabase } from '../../type';import { buildWorkspaceWhere } from '../../utils/workspace';+interface QueryDatasetsFilters {+ benchmarkId?: string;+ benchmarkIds?: string[];+ sourceExperimentId?: string;+}+export class AgentEvalDatasetModel {private userId: string;private db: LobeChatDatabase;@@ -51,15 +57,26 @@ export class AgentEvalDatasetModel {/*** Query datasets (system + user/workspace-owned) with test case counts- * @param benchmarkId - Optional benchmark filter+ * @param filters - Optional benchmark / experiment filters*/- query = async (benchmarkId?: string) => {+ query = async (filters?: QueryDatasetsFilters) => {+ const { benchmarkId, benchmarkIds, sourceExperimentId } = filters || {};const conditions = [this.ownership()];if (benchmarkId) {conditions.push(eq(agentEvalDatasets.benchmarkId, benchmarkId));}+ if (benchmarkIds && benchmarkIds.length > 0) {+ conditions.push(inArray(agentEvalDatasets.benchmarkId, benchmarkIds));+ }++ if (sourceExperimentId) {+ conditions.push(eq(agentEvalDatasets.sourceExperimentId, sourceExperimentId));+ // Scoped subsets are experiment-owned; exclude system rows from this scope.+ conditions.push(this.mutableOwnership());+ }+return this.db.select({benchmarkId: agentEvalDatasets.benchmarkId,@@ -71,6 +88,7 @@ export class AgentEvalDatasetModel {identifier: agentEvalDatasets.identifier,metadata: agentEvalDatasets.metadata,name: agentEvalDatasets.name,+ sourceExperimentId: agentEvalDatasets.sourceExperimentId,testCaseCount: count(agentEvalTestCases.id).as('testCaseCount'),updatedAt: agentEvalDatasets.updatedAt,userId: agentEvalDatasets.userId,diff --git a/packages/database/src/models/agentEval/experiment.ts b/packages/database/src/models/agentEval/experiment.tsnew file mode 100644index 00000000000..fa3e4df5958--- /dev/null+++ b/packages/database/src/models/agentEval/experiment.ts@@ -0,0 +1,449 @@+import type {+ AgentEvalExperimentBenchmark,+ AgentEvalExperimentDetail,+ AgentEvalExperimentListItem,+ AgentEvalRunListItem,+} from '@lobechat/types';+import { and, count, desc, eq, getTableColumns, inArray, isNull, or, sql } from 'drizzle-orm';++import {+ agentEvalBenchmarks,+ agentEvalDatasets,+ agentEvalExperimentBenchmarks,+ agentEvalExperiments,+ agentEvalRuns,+ type NewAgentEvalExperiment,+} from '../../schemas';+import { type LobeChatDatabase } from '../../type';+import { buildWorkspaceWhere } from '../../utils/workspace';+import { AgentEvalDatasetModel } from './dataset';+import { AgentEvalRunModel } from './run';++const RECENT_RUNS_PER_EXPERIMENT = 5;++export class AgentEvalExperimentModel {+ private userId: string;+ private db: LobeChatDatabase;+ private workspaceId?: string;+ private datasetModel: AgentEvalDatasetModel;+ private runModel: AgentEvalRunModel;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ this.datasetModel = new AgentEvalDatasetModel(db, userId, workspaceId);+ this.runModel = new AgentEvalRunModel(db, userId, workspaceId);+ }++ private experimentOwnership = () =>+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ agentEvalExperiments,+ );++ private junctionOwnership = () =>+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ agentEvalExperimentBenchmarks,+ );++ private datasetOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentEvalDatasets);++ private runOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentEvalRuns);++ /** Read predicate for benchmarks: workspace/personal rows + system rows. */+ private benchmarkReadable = () =>+ or(+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ agentEvalBenchmarks,+ ),+ isNull(agentEvalBenchmarks.userId),+ );++ private normalizeBenchmarkIds = (benchmarkIds: string[]) => [...new Set(benchmarkIds)];++ private ensureVisibleBenchmarks = async (benchmarkIds: string[]) => {+ if (benchmarkIds.length === 0) return;++ const rows = await this.db+ .select({ id: agentEvalBenchmarks.id })+ .from(agentEvalBenchmarks)+ .where(and(inArray(agentEvalBenchmarks.id, benchmarkIds), this.benchmarkReadable()));++ if (rows.length !== benchmarkIds.length) {+ throw new Error('Benchmarks not found or inaccessible');+ }+ };++ create = async (+ params: Omit<NewAgentEvalExperiment, 'userId' | 'workspaceId'> & {+ benchmarkIds: string[];+ },+ ) => {+ const { benchmarkIds, ...experiment } = params;+ const normalizedBenchmarkIds = this.normalizeBenchmarkIds(benchmarkIds);++ await this.ensureVisibleBenchmarks(normalizedBenchmarkIds);++ // Idempotent create: when the caller supplies an `id` (cross-server machine+ // creation), return the existing experiment instead of failing on conflict.+ if (experiment.id) {+ const [existing] = await this.db+ .select()+ .from(agentEvalExperiments)+ .where(and(eq(agentEvalExperiments.id, experiment.id), this.experimentOwnership()))+ .limit(1);+ if (existing) return existing;+ }++ const insert = async () =>+ this.db.transaction(async (trx) => {+ const [created] = await trx+ .insert(agentEvalExperiments)+ .values({+ ...experiment,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })+ .returning();++ if (normalizedBenchmarkIds.length > 0) {+ await trx.insert(agentEvalExperimentBenchmarks).values(+ normalizedBenchmarkIds.map((benchmarkId) => ({+ benchmarkId,+ experimentId: created.id,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })),+ );+ }++ return created;+ });++ try {+ return await insert();+ } catch (error) {+ // Race-safe idempotency: a concurrent insert with the same id lost the+ // race — return the winner's row.+ if (experiment.id && (error as { code?: string })?.code === '23505') {+ const [existing] = await this.db+ .select()+ .from(agentEvalExperiments)+ .where(and(eq(agentEvalExperiments.id, experiment.id), this.experimentOwnership()))+ .limit(1);+ if (existing) return existing;+ }+ throw error;+ }+ };++ /**+ * Delete an experiment, detaching (not deleting) its runs and scoped+ * datasets first so their history is preserved.+ */+ delete = async (id: string) => {+ return this.db.transaction(async (trx) => {+ await trx+ .update(agentEvalRuns)+ .set({ experimentId: null, updatedAt: new Date() })+ .where(and(eq(agentEvalRuns.experimentId, id), this.runOwnership()));++ await trx+ .update(agentEvalDatasets)+ .set({ sourceExperimentId: null, updatedAt: new Date() })+ .where(and(eq(agentEvalDatasets.sourceExperimentId, id), this.datasetOwnership()));++ return trx+ .delete(agentEvalExperiments)+ .where(and(eq(agentEvalExperiments.id, id), this.experimentOwnership()));+ });+ };++ /** Experiment row + its linked benchmarks. */+ private findWithBenchmarks = async (id: string) => {+ const [experiment] = await this.db+ .select()+ .from(agentEvalExperiments)+ .where(and(eq(agentEvalExperiments.id, id), this.experimentOwnership()))+ .limit(1);++ if (!experiment) return undefined;++ const benchmarks = await this.db+ .select({+ id: agentEvalBenchmarks.id,+ description: agentEvalBenchmarks.description,+ identifier: agentEvalBenchmarks.identifier,+ isSystem: agentEvalBenchmarks.isSystem,+ name: agentEvalBenchmarks.name,+ })+ .from(agentEvalExperimentBenchmarks)+ .innerJoin(+ agentEvalBenchmarks,+ eq(agentEvalExperimentBenchmarks.benchmarkId, agentEvalBenchmarks.id),+ )+ .where(+ and(+ eq(agentEvalExperimentBenchmarks.experimentId, id),+ this.junctionOwnership(),+ this.benchmarkReadable(),+ ),+ )+ .orderBy(agentEvalBenchmarks.name);++ return { ...experiment, benchmarks: benchmarks as AgentEvalExperimentBenchmark[] };+ };++ /**+ * Single-payload detail: experiment + linked benchmarks + ALL datasets+ * across those benchmarks (baseline + scoped) + experiment runs.+ * Flat queries only — no N+1.+ */+ findById = async (id: string): Promise<AgentEvalExperimentDetail | undefined> => {+ const base = await this.findWithBenchmarks(id);+ if (!base) return undefined;++ const benchmarkIds = base.benchmarks.map((benchmark) => benchmark.id);++ const [datasets, runs] = await Promise.all([+ benchmarkIds.length > 0 ? this.datasetModel.query({ benchmarkIds }) : [],+ this.runModel.query({ experimentId: id }),+ ]);++ return { ...base, datasets, runs } as AgentEvalExperimentDetail;+ };++ /**+ * List experiments with aggregate counts and a recent-runs preview.+ * Recent runs are fetched for ALL experiments in a single window-function+ * query (ROW_NUMBER per experiment), then grouped in JS — no per-experiment+ * N+1.+ */+ query = async (): Promise<AgentEvalExperimentListItem[]> => {+ const datasetCountSq = this.db+ .select({+ count: count().as('dataset_count'),+ experimentId: agentEvalDatasets.sourceExperimentId,+ })+ .from(agentEvalDatasets)+ .where(this.datasetOwnership())+ .groupBy(agentEvalDatasets.sourceExperimentId)+ .as('dc');++ const runCountSq = this.db+ .select({+ count: count().as('run_count'),+ experimentId: agentEvalRuns.experimentId,+ })+ .from(agentEvalRuns)+ .where(this.runOwnership())+ .groupBy(agentEvalRuns.experimentId)+ .as('rc');++ const benchmarkCountSq = this.db+ .select({+ count: count().as('benchmark_count'),+ experimentId: agentEvalExperimentBenchmarks.experimentId,+ })+ .from(agentEvalExperimentBenchmarks)+ .where(this.junctionOwnership())+ .groupBy(agentEvalExperimentBenchmarks.experimentId)+ .as('bc');++ const rows = await this.db+ .select({+ accessedAt: agentEvalExperiments.accessedAt,+ benchmarkCount: benchmarkCountSq.count,+ createdAt: agentEvalExperiments.createdAt,+ datasetCount: datasetCountSq.count,+ description: agentEvalExperiments.description,+ id: agentEvalExperiments.id,+ metadata: agentEvalExperiments.metadata,+ name: agentEvalExperiments.name,+ runCount: runCountSq.count,+ updatedAt: agentEvalExperiments.updatedAt,+ userId: agentEvalExperiments.userId,+ })+ .from(agentEvalExperiments)+ .leftJoin(datasetCountSq, eq(agentEvalExperiments.id, datasetCountSq.experimentId))+ .leftJoin(runCountSq, eq(agentEvalExperiments.id, runCountSq.experimentId))+ .leftJoin(benchmarkCountSq, eq(agentEvalExperiments.id, benchmarkCountSq.experimentId))+ .where(this.experimentOwnership())+ .orderBy(desc(agentEvalExperiments.accessedAt), desc(agentEvalExperiments.updatedAt));++ const experimentIds = rows.map((row) => row.id);++ const benchmarkRows =+ experimentIds.length === 0+ ? []+ : await this.db+ .select({+ benchmarkId: agentEvalBenchmarks.id,+ benchmarkName: agentEvalBenchmarks.name,+ experimentId: agentEvalExperimentBenchmarks.experimentId,+ })+ .from(agentEvalExperimentBenchmarks)+ .innerJoin(+ agentEvalBenchmarks,+ eq(agentEvalExperimentBenchmarks.benchmarkId, agentEvalBenchmarks.id),+ )+ .where(+ and(+ this.junctionOwnership(),+ inArray(agentEvalExperimentBenchmarks.experimentId, experimentIds),+ this.benchmarkReadable(),+ ),+ )+ .orderBy(agentEvalBenchmarks.name);++ const benchmarkMap = new Map<string, AgentEvalExperimentBenchmark[]>();++ for (const row of benchmarkRows) {+ const list = benchmarkMap.get(row.experimentId) || [];+ list.push({ id: row.benchmarkId, name: row.benchmarkName });+ benchmarkMap.set(row.experimentId, list);+ }++ // Recent runs (≤5 per experiment) in ONE window-function query, then a+ // single batched dataset lookup for names — no N+1, no join collision.+ const recentRunsMap = new Map<string, AgentEvalRunListItem[]>();++ if (experimentIds.length > 0) {+ const rankedRuns = this.db+ .select({+ ...getTableColumns(agentEvalRuns),+ rn: sql<number>`row_number() over (partition by ${agentEvalRuns.experimentId} order by ${agentEvalRuns.createdAt} desc)`.as(+ 'rn',+ ),+ })+ .from(agentEvalRuns)+ .where(and(this.runOwnership(), inArray(agentEvalRuns.experimentId, experimentIds)))+ .as('ranked_runs');++ const recentRunRows = await this.db+ .select()+ .from(rankedRuns)+ .where(sql`${rankedRuns.rn} <= ${RECENT_RUNS_PER_EXPERIMENT}`);++ const datasetIds = [...new Set(recentRunRows.map((row) => row.datasetId))];+ const datasetRows =+ datasetIds.length === 0+ ? []+ : await this.db+ .select({+ benchmarkId: agentEvalDatasets.benchmarkId,+ id: agentEvalDatasets.id,+ name: agentEvalDatasets.name,+ })+ .from(agentEvalDatasets)+ .where(inArray(agentEvalDatasets.id, datasetIds));+ const datasetMap = new Map(datasetRows.map((dataset) => [dataset.id, dataset]));++ for (const row of recentRunRows) {+ if (!row.experimentId) continue;+ const { rn: _rn, ...run } = row;+ const dataset = datasetMap.get(row.datasetId);+ const list = recentRunsMap.get(row.experimentId) || [];+ list.push({+ ...(run as unknown as AgentEvalRunListItem),+ benchmarkId: dataset?.benchmarkId,+ datasetName: dataset?.name,+ });+ recentRunsMap.set(row.experimentId, list);+ }+ }++ return rows.map((row) => ({+ ...row,+ benchmarkCount: Number(row.benchmarkCount) || 0,+ benchmarks: benchmarkMap.get(row.id) || [],+ datasetCount: Number(row.datasetCount) || 0,+ recentRuns: recentRunsMap.get(row.id) || [],+ runCount: Number(row.runCount) || 0,+ })) as AgentEvalExperimentListItem[];+ };++ /** Reverse lookup: which experiments are linked to the given benchmarks. */+ findByBenchmarkIds = async (benchmarkIds: string[]) => {+ if (benchmarkIds.length === 0) return [];++ return this.db+ .select({+ benchmarkId: agentEvalExperimentBenchmarks.benchmarkId,+ experimentId: agentEvalExperiments.id,+ experimentName: agentEvalExperiments.name,+ })+ .from(agentEvalExperimentBenchmarks)+ .innerJoin(+ agentEvalExperiments,+ eq(agentEvalExperimentBenchmarks.experimentId, agentEvalExperiments.id),+ )+ .where(+ and(+ this.junctionOwnership(),+ inArray(agentEvalExperimentBenchmarks.benchmarkId, benchmarkIds),+ ),+ )+ .orderBy(desc(agentEvalExperiments.updatedAt));+ };++ touch = async (id: string) => {+ const [result] = await this.db+ .update(agentEvalExperiments)+ .set({ accessedAt: new Date(), updatedAt: new Date() })+ .where(and(eq(agentEvalExperiments.id, id), this.experimentOwnership()))+ .returning();++ return result;+ };++ update = async (+ id: string,+ params: Partial<Omit<NewAgentEvalExperiment, 'id' | 'userId' | 'workspaceId'>> & {+ benchmarkIds?: string[];+ },+ ) => {+ const { benchmarkIds, ...value } = params;+ const normalizedBenchmarkIds = benchmarkIds+ ? this.normalizeBenchmarkIds(benchmarkIds)+ : undefined;++ if (normalizedBenchmarkIds) {+ await this.ensureVisibleBenchmarks(normalizedBenchmarkIds);+ }++ return this.db.transaction(async (trx) => {+ const [updated] = await trx+ .update(agentEvalExperiments)+ .set({ ...value, updatedAt: new Date() })+ .where(and(eq(agentEvalExperiments.id, id), this.experimentOwnership()))+ .returning();++ if (!updated) return undefined;++ if (normalizedBenchmarkIds) {+ await trx+ .delete(agentEvalExperimentBenchmarks)+ .where(and(eq(agentEvalExperimentBenchmarks.experimentId, id), this.junctionOwnership()));++ if (normalizedBenchmarkIds.length > 0) {+ await trx.insert(agentEvalExperimentBenchmarks).values(+ normalizedBenchmarkIds.map((benchmarkId) => ({+ benchmarkId,+ experimentId: id,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })),+ );+ }+ }++ return updated;+ });+ };+}diff --git a/packages/database/src/models/agentEval/index.ts b/packages/database/src/models/agentEval/index.tsindex 3d0796da242..1b3fa080ec5 100644--- a/packages/database/src/models/agentEval/index.ts+++ b/packages/database/src/models/agentEval/index.ts@@ -1,5 +1,6 @@export * from './benchmark';export * from './dataset';+export * from './experiment';export * from './run';export * from './runTopic';export * from './testCase';diff --git a/packages/database/src/models/agentEval/run.ts b/packages/database/src/models/agentEval/run.tsindex 39d6de09cb2..87c49a4865a 100644--- a/packages/database/src/models/agentEval/run.ts+++ b/packages/database/src/models/agentEval/run.ts@@ -35,6 +35,7 @@ export class AgentEvalRunModel {query = async (filter?: {benchmarkId?: string;datasetId?: string;+ experimentId?: string;limit?: number;offset?: number;status?: 'idle' | 'pending' | 'running' | 'completed' | 'failed' | 'aborted' | 'external';@@ -45,6 +46,10 @@ export class AgentEvalRunModel {conditions.push(eq(agentEvalRuns.datasetId, filter.datasetId));}+ if (filter?.experimentId) {+ conditions.push(eq(agentEvalRuns.experimentId, filter.experimentId));+ }+if (filter?.benchmarkId) {const datasetIds = this.db.select({ id: agentEvalDatasets.id })@@ -100,6 +105,20 @@ export class AgentEvalRunModel {return result;};+ /**+ * Atomically claim a pending run (pending -> running) via a single+ * conditional update. Returns the updated run, or undefined when the run is+ * not owned / not currently pending (already claimed or terminal).+ */+ claim = async (id: string) => {+ const [result] = await this.db+ .update(agentEvalRuns)+ .set({ startedAt: new Date(), status: 'running', updatedAt: new Date() })+ .where(and(eq(agentEvalRuns.id, id), eq(agentEvalRuns.status, 'pending'), this.ownership()))+ .returning();+ return result;+ };+/*** Delete run (only user-created runs)*/diff --git a/packages/database/src/models/agentEval/testCase.ts b/packages/database/src/models/agentEval/testCase.tsindex 4de89f6657d..d84e0837689 100644--- a/packages/database/src/models/agentEval/testCase.ts+++ b/packages/database/src/models/agentEval/testCase.ts@@ -94,6 +94,25 @@ export class AgentEvalTestCaseModel {return query;};+ /**+ * Find a test case by the dataset-native case id stored in `metadata.caseId`.+ * Returns undefined when no case carries that external id.+ */+ findByDatasetIdAndCaseId = async (datasetId: string, caseId: string) => {+ const [result] = await this.db+ .select()+ .from(agentEvalTestCases)+ .where(+ and(+ eq(agentEvalTestCases.datasetId, datasetId),+ sql`${agentEvalTestCases.metadata} ->> 'caseId' = ${caseId}`,+ this.ownership(),+ ),+ )+ .limit(1);+ return result;+ };+/*** Count test cases by dataset id*/diff --git a/packages/locales/src/default/eval.ts b/packages/locales/src/default/eval.tsindex 41b4bdec78c..217f56ba999 100644--- a/packages/locales/src/default/eval.ts+++ b/packages/locales/src/default/eval.ts@@ -60,11 +60,13 @@ export default {'benchmark.detail.stats.needSetup': 'Setup Required','benchmark.detail.stats.noEvalRecord': 'No evaluation records yet','benchmark.detail.stats.perRun': '/ Run',+ 'benchmark.detail.stats.p99Duration': 'P99: {{duration}}','benchmark.detail.stats.topAgents': 'Top Agents','benchmark.detail.stats.totalCases': 'Total Cases','benchmark.detail.stats.waiting': 'Waiting...','benchmark.detail.tabs.data': 'Data','benchmark.detail.tabs.datasets': 'Datasets',+ 'benchmark.detail.tabs.experiments': 'Experiments','benchmark.detail.tabs.runs': 'Runs','benchmark.empty': 'No benchmarks yet. Create one to get started.',@@ -74,6 +76,7 @@ export default {'common.edit': 'Edit','common.later': 'Later','common.next': 'Next',+ 'common.unknown': 'Unknown','common.update': 'Update','caseDetail.actual': 'Actual Output',@@ -88,6 +91,7 @@ export default {'caseDetail.resources': 'Resources','caseDetail.score': 'Score','caseDetail.completionReason': 'Status',+ 'caseDetail.section.externalResult': 'External Result','caseDetail.section.runtime': 'Runtime','caseDetail.section.scoring': 'Scoring Details','caseDetail.section.testCase': 'Test Case',@@ -104,15 +108,34 @@ export default {'dataset.delete.success': 'Dataset deleted successfully','dataset.create.description.label': 'Description','dataset.create.description.placeholder': 'Dataset description (optional)',+ 'dataset.create.benchmark.label': 'Benchmark Container',+ 'dataset.create.benchmark.placeholder': 'Select a benchmark',+ 'dataset.create.benchmarkRequired': 'Please select a benchmark','dataset.create.error': 'Failed to create dataset',+ 'dataset.create.fork.filter.hint':+ 'Leave empty to include all categories from the source dataset.',+ 'dataset.create.fork.filter.label': 'Filter',+ 'dataset.create.fork.filter.placeholder': 'Select categories',+ 'dataset.create.fork.inherit': 'Preset: {{preset}} · Eval mode: {{evalMode}}',+ 'dataset.create.fork.sampling.hint':+ 'Sample up to {{count}} test case{{count, plural, one {} other {s}}} from the filtered source set.',+ 'dataset.create.fork.sampling.label': 'Sampling','dataset.create.identifier.label': 'Identifier','dataset.create.identifier.placeholder': 'dataset-identifier','dataset.create.identifierRequired': 'Please enter an identifier','dataset.create.importNow': 'Would you like to import data now?',+ 'dataset.create.mode.empty': 'Create Empty',+ 'dataset.create.mode.fork': 'From Existing','dataset.create.name.label': 'Dataset Name','dataset.create.name.placeholder': 'Enter dataset name','dataset.create.nameRequired': 'Please enter a dataset name','dataset.create.preset.label': 'Dataset Preset',+ 'dataset.create.preset.optional': 'Optional:',+ 'dataset.create.preset.placeholder': 'Select a preset',+ 'dataset.create.preset.required': 'Required:',+ 'dataset.create.sourceDataset.label': 'Source Dataset',+ 'dataset.create.sourceDataset.placeholder': 'Select a benchmark dataset',+ 'dataset.create.sourceDataset.required': 'Please select a source dataset','dataset.create.success': 'Dataset created successfully','dataset.create.successTitle': 'Dataset Created','dataset.create.title': 'Create Dataset',@@ -170,6 +193,51 @@ export default {'dataset.evalMode.hint':'Default eval mode for the dataset, can be overridden at test case level',+ 'experiment.actions.create': 'Create Experiment',+ 'experiment.empty': 'No experiments yet',+ 'experiment.actions.delete': 'Delete Experiment',+ 'experiment.actions.delete.confirm':+ 'Are you sure you want to delete this experiment? Its runs and scoped datasets will no longer be grouped here.',+ 'experiment.card.benchmarkCount': '{{count}} benchmarks',+ 'experiment.card.empty': 'No runs yet',+ 'experiment.card.emptyHint': 'Open the experiment to start the first run.',+ 'experiment.card.lastRun': 'Last Run',+ 'experiment.card.open': 'Open Experiment',+ 'experiment.card.runCount': '{{count}} runs',+ 'experiment.overview.emptyHint': 'Run activity and scoped datasets will appear here.',+ 'experiment.create.benchmarks.label': 'Benchmarks',+ 'experiment.create.benchmarks.placeholder': 'Select one or more benchmarks',+ 'experiment.create.benchmarksRequired': 'Please select at least one benchmark',+ 'experiment.create.description.label': 'Description',+ 'experiment.create.description.placeholder': 'Experiment description (optional)',+ 'experiment.create.error': 'Failed to create experiment',+ 'experiment.create.name.label': 'Name',+ 'experiment.create.name.placeholder': 'Enter experiment name',+ 'experiment.create.nameRequired': 'Please enter an experiment name',+ 'experiment.create.title': 'Create Experiment',+ 'experiment.delete.error': 'Failed to delete experiment',+ 'experiment.edit.error': 'Failed to update experiment',+ 'experiment.edit.success': 'Experiment updated successfully',+ 'experiment.edit.title': 'Edit Experiment',+ 'experiment.detail.backToList': 'Back to Experiments',+ 'experiment.detail.benchmarksEmpty': 'No benchmark datasets available yet.',+ 'experiment.detail.benchmarks': 'Benchmarks',+ 'experiment.detail.datasetActions.create': 'Create Dataset',+ 'experiment.detail.datasetActions.createSubset': 'Create Subset',+ 'experiment.detail.datasets': 'Datasets',+ 'experiment.detail.datasetsBaseline': 'Benchmark Datasets',+ 'experiment.detail.datasetsScopedEmpty': 'No scoped datasets yet.',+ 'experiment.detail.datasetsScoped': 'Scoped Datasets',+ 'experiment.detail.lastAccessed': 'Last accessed {{time}}',+ 'experiment.detail.runs': 'Runs',+ 'experiment.detail.stats.benchmarks': 'Benchmarks',+ 'experiment.detail.stats.branches': 'Branches',+ 'experiment.detail.stats.runs': 'Runs',+ 'experiment.list.subtitle': 'Track optimization contexts, scoped datasets, and run iterations.',+ 'experiment.list.error': 'Failed to load experiments',+ 'experiment.list.title': 'Experiments',+ 'experiment.run.parent': 'Forked from {{name}}',+'difficulty.easy': 'Easy','difficulty.hard': 'Hard','difficulty.medium': 'Medium',@@ -193,8 +261,16 @@ export default {'evalMode.rubric.desc': 'Score output using benchmark rubrics with weighted criteria','overview.createBenchmark': 'Create Benchmark',+ 'overview.createExperiment': 'Create Experiment','overview.importDataset': 'Import Dataset',- 'overview.subtitle': 'Benchmark and evaluate your AI agents across datasets',+ 'overview.sections.benchmarks.subtitle': 'Shared evaluation assets and benchmark baselines.',+ 'overview.sections.benchmarks.title': 'Benchmarks',+ 'overview.sections.count': '{{count}} total',+ 'overview.sections.experiments.subtitle':+ 'Optimization workspaces for scoped datasets, baselines, and forked iterations.',+ 'overview.sections.experiments.title': 'Experiments',+ 'overview.sections.experiments.viewAll': 'View all experiments',+ 'overview.subtitle': 'Manage benchmark baselines and experiment iterations in one workspace','overview.title': 'Evaluation Lab','run.actions.abort': 'Abort',@@ -213,6 +289,7 @@ export default {'run.actions.batchResume.modal.confirm': 'Resume Selected','run.actions.batchResume.modal.selectAll': 'Select All','run.actions.batchResume.modal.selected': '{{count}} selected',+ 'run.actions.fork': 'Fork Run','run.actions.run': 'Run','run.edit.error': 'Failed to update evaluation','run.edit.success': 'Evaluation updated successfully',@@ -225,6 +302,8 @@ export default {'run.filter.active': 'Active','run.filter.empty': 'No runs match the current filter.',+ 'run.lineage.forkedFrom': 'Forked from {{parent}}',+ 'run.lineage.forks': '{{count}} forks','run.empty.description': 'Start your first evaluation run on this dataset','run.empty.descriptionBenchmark': 'Start your first evaluation run on this benchmark',@@ -250,6 +329,13 @@ export default {'run.create.dataset': 'Dataset','run.create.dataset.placeholder': 'Select a dataset','run.create.dataset.required': 'Please select a dataset',+ 'run.create.error': 'Failed to create run',+ 'run.create.forkTitle': 'Fork Run from "{{run}}"',+ 'run.create.forkSummary.agent': 'Agent: {{agent}}',+ 'run.create.forkSummary.dataset': 'Dataset: {{dataset}}',+ 'run.create.forkSummary.snapshot':+ 'A fresh snapshot will be generated from the current agent configuration.',+ 'run.create.forkSummary.title': 'Inherited from parent run','run.create.name': 'Run Name','run.create.openAgent': 'Open agent in new window','run.create.name.placeholder': 'Enter a name for this run',@@ -271,10 +357,12 @@ export default {'run.detail.copyRunIdFailed': 'Failed to copy Run ID','run.detail.copyRunIdSuccess': 'Run ID copied','run.detail.dataset': 'Dataset',+ 'run.detail.experiment': 'Experiment','run.detail.model': 'Model','run.detail.overview': 'Overview','run.detail.progress': 'Progress','run.detail.progressCases': 'cases',+ 'run.error.start': 'Failed to start run','run.chart.duration': 'Duration (s)','run.chart.error': 'Error','run.chart.fail': 'Fail',@@ -289,6 +377,7 @@ export default {'run.metrics.errorCases': 'Error','run.metrics.evaluated': '{{count}} evaluated','run.metrics.passRate': 'Pass Rate',+ 'run.metrics.passRate.short': 'pass rate','run.metrics.perCase': '/ case','run.metrics.tokens': 'Tokens','run.metrics.totalDuration': 'Cumulative',@@ -296,6 +385,7 @@ export default {'sidebar.benchmarks': 'Benchmarks','sidebar.dashboard': 'Dashboard','sidebar.datasets': 'Datasets',+ 'sidebar.experiments': 'Experiments','sidebar.runs': 'Runs','run.status.aborted': 'Aborted',diff --git a/packages/types/src/eval/agentEval.ts b/packages/types/src/eval/agentEval.tsindex 6cf994bcc45..41be53385eb 100644--- a/packages/types/src/eval/agentEval.ts+++ b/packages/types/src/eval/agentEval.ts@@ -52,9 +52,34 @@ export interface EvalRunAgentSnapshot {title?: string | null;}+/**+ * Case selection for scoping a run to a subset of dataset cases.+ * Stored verbatim in the run config for Exp Proposal ↔ Run Config consistency+ * checks; dispatch filtering is owned by the external worker.+ */+export interface EvalCaseSelection {+ /**+ * Dataset-native `metadata.caseId` values (NOT internal TestCase primary+ * keys). Required (non-empty, unique, non-blank) for include/exclude;+ * must be absent for 'all'.+ */+ caseIds?: string[];+ /**+ * all (default): every case; include: only caseIds; exclude: all except caseIds+ */+ mode: 'all' | 'exclude' | 'include';+}+export interface EvalRunConfig {[key: string]: unknown;agentSnapshot?: EvalRunAgentSnapshot;+ caseSelection?: EvalCaseSelection;+ /**+ * Immutable snapshot of how the run executes: 'internal' (QStash workflow,+ * topics pre-created) or 'external' (worker-driven, on-demand). Written at+ * creation; never inferred from status.+ */+ executionMode?: 'external' | 'internal';judgeModel?: string;judgeProvider?: string;/**@@ -82,7 +107,7 @@ export interface EvalRunConfig {*/export type EvalRunInputConfig = Pick<EvalRunConfig,- 'k' | 'maxConcurrency' | 'maxSteps' | 'timeout'+ 'caseSelection' | 'k' | 'maxConcurrency' | 'maxSteps' | 'timeout'>;/**@@ -180,6 +205,10 @@ export interface EvalRunTopicResult {error?: string;errorDetail?: unknown;+ /** Opaque evidence reported by an external evaluator. */+ externalResult?: Record<string, unknown>;+ /** Per-thread external evidence for K > 1 runs. */+ externalThreadResults?: Record<string, unknown>;extractedAnswer?: string;completionReason?: string;operationId?: string;diff --git a/packages/types/src/eval/agentEvalDataset.ts b/packages/types/src/eval/agentEvalDataset.tsindex 1176aac2885..a7111ee3655 100644--- a/packages/types/src/eval/agentEvalDataset.ts+++ b/packages/types/src/eval/agentEvalDataset.ts@@ -34,7 +34,13 @@ export interface AgentEvalDatasetListItem {evalMode?: EvalMode | null;id: string;identifier: string;+ metadata?: Record<string, unknown> | null;name: string;+ /**+ * Set when this dataset is an experiment-scoped subset/fork.+ * Null/undefined = baseline benchmark dataset.+ */+ sourceExperimentId?: string | null;// Computed statistics for UItestCaseCount?: number;updatedAt: Date;diff --git a/packages/types/src/eval/agentEvalExperiment.ts b/packages/types/src/eval/agentEvalExperiment.tsnew file mode 100644index 00000000000..28ee5057731--- /dev/null+++ b/packages/types/src/eval/agentEvalExperiment.ts@@ -0,0 +1,57 @@+import type { AgentEvalDatasetListItem } from './agentEvalDataset';+import type { AgentEvalRunListItem } from './agentEvalRun';++// ============================================+// Experiment Entity Types+// ============================================++/**+ * Lightweight benchmark reference embedded in an experiment+ */+export interface AgentEvalExperimentBenchmark {+ description?: string | null;+ id: string;+ identifier?: string;+ isSystem?: boolean;+ name: string;+}++/**+ * Full experiment entity.+ * An experiment groups several benchmarks into one workspace; it owns+ * scoped datasets (subsets/forks) and runs.+ */+export interface AgentEvalExperiment {+ accessedAt: Date;+ benchmarks: AgentEvalExperimentBenchmark[];+ createdAt: Date;+ description?: string | null;+ id: string;+ metadata?: Record<string, unknown> | null;+ name: string;+ updatedAt: Date;+ userId: string;+}++/**+ * Lightweight experiment item (for list / overview display)+ * Adds aggregate counts and a small recent-runs preview.+ */+export interface AgentEvalExperimentListItem extends AgentEvalExperiment {+ benchmarkCount: number;+ datasetCount: number;+ recentRuns?: AgentEvalRunListItem[];+ runCount: number;+}++/**+ * Single-payload experiment detail: everything the workspace page needs in+ * one query. `datasets` contains ALL datasets across the linked benchmarks —+ * baseline datasets (`sourceExperimentId` null / different) and experiment+ * scoped subsets (`sourceExperimentId === id`) — so the client can group and+ * split without a second fetch. `runs` are the experiment-scoped runs.+ */+export interface AgentEvalExperimentDetail extends AgentEvalExperiment {+ datasets: AgentEvalDatasetListItem[];+ runs: AgentEvalRunListItem[];+}diff --git a/packages/types/src/eval/agentEvalRun.ts b/packages/types/src/eval/agentEvalRun.tsindex 24506c6ed19..25d1a11a634 100644--- a/packages/types/src/eval/agentEvalRun.ts+++ b/packages/types/src/eval/agentEvalRun.ts@@ -6,13 +6,7 @@ import type { AgentEvalDataset } from './agentEvalDataset';// ============================================export type AgentEvalRunStatus =- | 'aborted'- | 'completed'- | 'failed'- | 'idle'- | 'pending'- | 'external'- | 'running';+ 'aborted' | 'completed' | 'failed' | 'idle' | 'pending' | 'external' | 'running';export interface AgentEvalRunTargetAgent {avatar?: string;@@ -45,16 +39,20 @@ export interface AgentEvalRun {*/export interface AgentEvalRunListItem {averageScore?: number;+ benchmarkId?: string;completedCases?: number;config?: EvalRunConfig | null;createdAt: Date;datasetId: string;datasetName?: string;errorCount?: number;+ experimentId?: string | null;+ experimentName?: string;failCount?: number;id: string;metrics?: EvalRunMetrics | null;name?: string | null;+ parentRunId?: string | null;passCount?: number;passRate?: number;status: AgentEvalRunStatus;diff --git a/packages/types/src/eval/index.ts b/packages/types/src/eval/index.tsindex f87faa63e1d..65c8e3f83f3 100644--- a/packages/types/src/eval/index.ts+++ b/packages/types/src/eval/index.ts@@ -1,5 +1,6 @@export * from './agentEval';export * from './agentEvalDataset';+export * from './agentEvalExperiment';export * from './agentEvalRun';export * from './benchmark';export * from './dataset';diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 3740c05eab7..0f1a8feeaf9 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -508,6 +508,8 @@ export const evalKeys = {datasetDetail: def('eval:datasetDetail', (id: string) => ['eval:datasetDetail', id]),datasetRuns: def('eval:datasetRuns', (datasetId: string) => ['eval:datasetRuns', datasetId]),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/routes/(main)/eval/_layout/Sidebar/Body/ExperimentList.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/ExperimentList.tsxnew file mode 100644index 00000000000..eabaea96862--- /dev/null+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/ExperimentList.tsx@@ -0,0 +1,101 @@+'use client';++import { AccordionItem, Flexbox, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { Beaker, RotateCw } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import NavItem from '@/features/NavPanel/components/NavItem';+import SkeletonList from '@/features/NavPanel/components/SkeletonList';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';+import { useEvalStore } from '@/store/eval';+import { isModifierClick } from '@/utils/navigation';++interface ExperimentListProps {+ activeKey: string;+ itemKey: string;+}++const ExperimentList = memo<ExperimentListProps>(({ activeKey, itemKey }) => {+ const { t } = useTranslation('eval');+ const { t: tCommon } = useTranslation('common');+ const navigate = useWorkspaceAwareNavigate();+ const experimentList = useEvalStore((s) => s.experimentList);+ const isInit = useEvalStore((s) => s.experimentListInit);+ const useFetchExperiments = useEvalStore((s) => s.useFetchExperiments);+ const { error, mutate } = useFetchExperiments();++ // Error gates before the skeleton: a failed fetch never settles `isInit`, so+ // without this branch the list would hang on SkeletonList forever (ux Feedback).+ const body = (() => {+ if (error && !isInit) {+ return (+ <Flexbox gap={4} padding={'8px 12px'}>+ <Text fontSize={12} type={'secondary'}>+ {t('experiment.list.error')}+ </Text>+ <Button icon={RotateCw} size={'small'} type={'text'} onClick={() => mutate()}>+ {tCommon('retry')}+ </Button>+ </Flexbox>+ );+ }++ if (!isInit) return <SkeletonList rows={3} />;++ if (experimentList.length === 0) {+ return (+ <Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">+ {t('experiment.empty')}+ </Text>+ );+ }++ return experimentList.map((experiment) => (+ <WorkspaceLink+ key={experiment.id}+ to={`/eval/experiments/${experiment.id}`}+ onClick={(e) => {+ if (isModifierClick(e)) return;+ e.preventDefault();+ navigate(`/eval/experiments/${experiment.id}`);+ }}+ >+ <NavItem+ active={activeKey === `experiment-${experiment.id}`}+ icon={Beaker}+ iconSize={16}+ title={experiment.name}+ />+ </WorkspaceLink>+ ));+ })();++ return (+ <AccordionItem+ itemKey={itemKey}+ paddingBlock={4}+ paddingInline={'8px 4px'}+ title={+ <Flexbox horizontal align="center" gap={4}>+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>+ {t('sidebar.experiments')}+ </Text>+ {experimentList.length > 0 && (+ <Text fontSize={12} type="secondary">+ {experimentList.length}+ </Text>+ )}+ </Flexbox>+ }+ >+ <Flexbox gap={1} paddingBlock={1}>+ {body}+ </Flexbox>+ </AccordionItem>+ );+});++export default ExperimentList;diff --git a/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsxindex 5af8300a7b2..3c07d167687 100644--- a/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx@@ -12,13 +12,17 @@ import { usePathname } from '@/libs/router/navigation';import { useEvalStore } from '@/store/eval';import BenchmarkList from './BenchmarkList';+import ExperimentList from './ExperimentList';const useActiveKey = () => {const pathname = usePathname();if (pathname === '/eval') return 'dashboard';- const match = pathname.match(/\/eval\/bench\/([^/]+)/);- if (match) return `bench-${match[1]}`;+ const benchMatch = pathname.match(/\/eval\/bench\/([^/]+)/);+ if (benchMatch) return `bench-${benchMatch[1]}`;++ const experimentMatch = pathname.match(/\/eval\/experiments\/([^/]+)/);+ if (experimentMatch) return `experiment-${experimentMatch[1]}`;return 'dashboard';};@@ -28,7 +32,9 @@ const Body = memo(() => {const navigate = useWorkspaceAwareNavigate();const { t } = useTranslation('eval');const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);+ const useFetchExperiments = useEvalStore((s) => s.useFetchExperiments);useFetchBenchmarks();+ useFetchExperiments();return (<Flexbox gap={8} paddingInline={4}>@@ -47,7 +53,8 @@ const Body = memo(() => {/></WorkspaceLink></Flexbox>- <Accordion defaultExpandedKeys={['benchmarks']} gap={8}>+ <Accordion defaultExpandedKeys={['benchmarks', 'experiments']} gap={8}>+ <ExperimentList activeKey={activeKey} itemKey="experiments" /><BenchmarkList activeKey={activeKey} itemKey="benchmarks" /></Accordion></Flexbox>diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsxindex 516a6b3c2ea..ea73ceb7c57 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx@@ -3,7 +3,7 @@import { AGENT_PROFILE_URL, DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';import { Accordion, AccordionItem, ActionIcon, Avatar, Flexbox, Text } from '@lobehub/ui';import { Select, useModalContext } from '@lobehub/ui/base-ui';-import { Form, Input, InputNumber, Space } from 'antd';+import { App, Form, Input, InputNumber, Space } from 'antd';import { createStaticStyles, cssVar } from 'antd-style';import { SquareArrowOutUpRight } from 'lucide-react';import { type FC, useCallback, useEffect, useMemo, useState } from 'react';@@ -64,6 +64,9 @@ export interface RunCreateContentProps {benchmarkId: string;datasetId?: string;datasetName?: string;+ /** When set, the created run is tagged to this experiment (and the+ * experiment detail payload is revalidated instead of the benchmark runs). */+ experimentId?: string;onLoadingChange?: (loading: boolean) => void;onSubmitReady: (submit: (shouldStart: boolean) => Promise<void>) => void;}@@ -72,11 +75,13 @@ const RunCreateContent: FC<RunCreateContentProps> = ({benchmarkId,datasetId,datasetName,+ experimentId,onLoadingChange,onSubmitReady,}) => {const { t } = useTranslation('eval');const { t: tChat } = useTranslation('chat');+ const { message } = App.useApp();const { close } = useModalContext();const navigate = useWorkspaceAwareNavigate();const activeWorkspaceSlug = useActiveWorkspaceSlug();@@ -169,16 +174,28 @@ const RunCreateContent: FC<RunCreateContentProps> = ({timeout: timeoutMinutes * 60_000,},datasetId: isDatasetMode ? datasetId : values.datasetId,+ experimentId,name: values.name,targetAgentId: values.targetAgentId,});if (run?.id) {- if (shouldStart) {- await startRun(run.id);+ try {+ if (shouldStart) {+ await startRun(run.id);+ }+ } catch {+ // Run was created — surface the start failure (ux Act) but keep+ // going to the run page so the user can retry there.+ message.error(t('run.error.start'));}navigate(`/eval/bench/${benchmarkId}/runs/${run.id}`);}close();+ } catch (error) {+ // createRun failure: toast and keep the modal open for retry (ux Act).+ message.error(+ error instanceof Error && error.message ? error.message : t('run.create.error'),+ );} finally {onLoadingChange?.(false);}@@ -188,11 +205,14 @@ const RunCreateContent: FC<RunCreateContentProps> = ({close,createRun,datasetId,+ experimentId,form,isDatasetMode,+ message,navigate,onLoadingChange,startRun,+ t,],);diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/CaseBanner/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/CaseBanner/index.tsxindex 1869fff0f66..af2412f214f 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/CaseBanner/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/CaseBanner/index.tsx@@ -2,29 +2,28 @@import type { EvalRunTopicResult } from '@lobechat/types';import { formatCost, formatShortenNumber } from '@lobechat/utils';-import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import {ArrowLeft,- CheckCircle2,ChevronLeft,ChevronRight,Clock,DollarSign,Footprints,Hash,- TriangleAlert,- XCircle,} from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';const styles = createStaticStyles(({ css }) => ({backLink: css`+ cursor: pointer;+align-self: flex-start;- cursor: pointer;border-radius: ${cssVar.borderRadiusSM};+color: ${cssVar.colorTextTertiary};transition: color 0.15s ease;@@ -42,13 +41,6 @@ const styles = createStaticStyles(({ css }) => ({transition: none;}`,- // Tonal outcome hero band — leads with the case result.- hero: css`- padding: 16px;- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorFillQuaternary};- `,header: css`padding-block: 16px;padding-inline: 16px;@@ -90,30 +82,6 @@ const styles = createStaticStyles(({ css }) => ({line-height: 1.4;color: ${cssVar.colorText};`,- // Large mono score in the hero.- scoreValue: css`- font-family: ${cssVar.fontFamilyCode};- font-size: ${cssVar.fontSizeHeading2};- font-weight: 600;- line-height: 1;- color: ${cssVar.colorText};- `,- // The result word, color-coded — always paired with an icon.- statusLabel: css`- font-size: ${cssVar.fontSizeLG};- font-weight: 600;- line-height: 1;- `,- statusTile: css`- display: flex;- flex-shrink: 0;- align-items: center;- justify-content: center;-- width: 44px;- height: 44px;- border-radius: ${cssVar.borderRadius};- `,}));interface CaseHeaderProps {@@ -122,43 +90,13 @@ interface CaseHeaderProps {onBack: () => void;onNext?: () => void;onPrev?: () => void;- passed?: boolean | null;runName: string;- score?: number | null;}const CaseHeader = memo<CaseHeaderProps>(- ({ passed, caseNumber, runName, evalResult, onBack, onPrev, onNext, score }) => {+ ({ caseNumber, runName, evalResult, onBack, onPrev, onNext }) => {const { t } = useTranslation('eval');- // Resolve the outcome: error (run threw) > failed > passed > unknown.- // Color is always paired with an icon + label, never used alone.- const hasError = !!evalResult?.error;- const outcome = hasError- ? {- bg: cssVar.colorErrorBg,- color: cssVar.colorError,- icon: TriangleAlert,- label: t('table.filter.error'),- }- : passed === true- ? {- bg: cssVar.colorSuccessBg,- color: cssVar.colorSuccess,- icon: CheckCircle2,- label: t('table.filter.passed'),- }- : passed === false- ? {- bg: cssVar.colorErrorBg,- color: cssVar.colorError,- icon: XCircle,- label: t('table.filter.failed'),- }- : null;-- const hasScore = score !== undefined && score !== null;-const metrics = [{icon: Clock,@@ -216,30 +154,6 @@ const CaseHeader = memo<CaseHeaderProps>(</Flexbox></Flexbox>- {/* Outcome hero — the result is the centerpiece */}- {(outcome || hasScore) && (- <Flexbox horizontal align="center" className={styles.hero} gap={16}>- {outcome && (- <Flexbox horizontal align="center" flex={1} gap={12}>- <div className={styles.statusTile} style={{ background: outcome.bg }}>- <Icon icon={outcome.icon} size={24} style={{ color: outcome.color }} />- </div>- <span className={styles.statusLabel} style={{ color: outcome.color }}>- {outcome.label}- </span>- </Flexbox>- )}-- {hasScore && (- <Flexbox align="flex-end" gap={2}>- <span className={styles.scoreValue}>{score.toFixed(2)}</span>- <span className={styles.metricLabel}>{t('caseDetail.score')}</span>- </Flexbox>- )}- </Flexbox>- )}-- {/* Runtime metric pills */}{metrics.length > 0 && (<Flexbox horizontal align="center" gap={8} wrap="wrap">{metrics.map((m) => (diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsxindex 41862ee7b4d..407f992116b 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/features/InfoSidebar/index.tsx@@ -2,7 +2,7 @@import type { EvalRubricScore } from '@lobechat/types';import { formatCost, formatShortenNumber } from '@lobechat/utils';-import { Flexbox, Tag, Text } from '@lobehub/ui';+import { Flexbox, Highlighter, Tag, Text } from '@lobehub/ui';import { Collapse } from 'antd';import { createStaticStyles, cssVar } from 'antd-style';import { memo, type ReactNode } from 'react';@@ -42,7 +42,6 @@ const styles = createStaticStyles(({ css }) => ({scoreCard: css`padding: 12px;border-radius: ${cssVar.borderRadius};-background: ${cssVar.colorFillQuaternary};`,scoreValue: css`@@ -82,6 +81,7 @@ export interface EvalResultDisplayData {cost?: number;duration?: number;error?: string;+ externalResult?: Record<string, unknown>;rubricScores?: EvalRubricScore[];steps?: number;tokens?: number;@@ -292,6 +292,21 @@ const InfoSidebar = memo<InfoSidebarProps>(({ testCase, evalResult, passed, scor</div>)}</Flexbox>++ {evalResult?.externalResult && (+ <Flexbox gap={8}>+ <SectionTitle>{t('caseDetail.section.externalResult')}</SectionTitle>+ <Highlighter+ wrap+ actionIconSize="small"+ language="json"+ style={{ fontSize: 12, maxHeight: 360, overflow: 'auto' }}+ variant="filled"+ >+ {JSON.stringify(evalResult.externalResult, null, 2)}+ </Highlighter>+ </Flexbox>+ )}</Flexbox>);});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 c6745e6630f..f491fa095f8 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@@ -108,9 +108,7 @@ const CaseDetail = memo(() => {<CaseHeadercaseNumber={(caseResult.testCase?.sortOrder ?? 0) + 1}evalResult={displayEvalResult}- passed={displayPassed}runName={runDetail?.name || runId!.slice(0, 8)}- score={displayScore}onBack={() => navigate(`/eval/bench/${benchmarkId}/runs/${runId}`)}onNext={nextCaseId ? () => navigate(`${basePath}/${nextCaseId}`) : undefined}onPrev={prevCaseId ? () => navigate(`${basePath}/${prevCaseId}`) : undefined}diff --git a/src/routes/(main)/eval/experiments/[experimentId]/index.tsx b/src/routes/(main)/eval/experiments/[experimentId]/index.tsxnew file mode 100644index 00000000000..65e51cd2427--- /dev/null+++ b/src/routes/(main)/eval/experiments/[experimentId]/index.tsx@@ -0,0 +1,5 @@+'use client';++import { ExperimentDetailPage } from '../../features/Experiments';++export default ExperimentDetailPage;diff --git a/src/routes/(main)/eval/features/Experiments/BenchmarksSection.tsx b/src/routes/(main)/eval/features/Experiments/BenchmarksSection.tsxnew file mode 100644index 00000000000..8b5a4c14438--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/BenchmarksSection.tsx@@ -0,0 +1,79 @@+'use client';++import type { AgentEvalExperimentDetail } from '@lobechat/types';+import { ActionIcon, Empty, Flexbox } from '@lobehub/ui';+import { Card } from 'antd';+import { createStaticStyles } from 'antd-style';+import { ChevronRight, Database } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import WorkspaceLink from '@/features/Workspace/WorkspaceLink';++import DatasetRow from './DatasetRow';+import type { useExperimentActions } from './useExperimentActions';++const styles = createStaticStyles(({ css }) => ({+ listCard: css`+ .ant-card-body {+ padding-block: 4px;+ padding-inline: 8px;+ }+ `,+ sectionTitle: css`+ margin: 0;+ font-size: 16px;+ font-weight: 600;+ `,+}));++interface BenchmarksSectionProps {+ actions: ReturnType<typeof useExperimentActions>;+ experiment: AgentEvalExperimentDetail;+}++/** Baseline datasets, grouped per linked benchmark. Each row offers "Add Run". */+const BenchmarksSection = memo<BenchmarksSectionProps>(({ actions, experiment }) => {+ const { t } = useTranslation('eval');++ const groups = useMemo(+ () =>+ experiment.benchmarks.map((benchmark) => ({+ benchmark,+ datasets: actions.baselineDatasets.filter(+ (dataset) => dataset.benchmarkId === benchmark.id,+ ),+ })),+ [experiment.benchmarks, actions.baselineDatasets],+ );++ return (+ <Flexbox gap={12}>+ <h3 className={styles.sectionTitle}>{t('experiment.detail.benchmarks')}</h3>+ {groups.map(({ benchmark, datasets }) => (+ <Card+ className={styles.listCard}+ key={benchmark.id}+ title={benchmark.name}+ extra={+ <WorkspaceLink to={`/eval/bench/${benchmark.id}`}>+ <ActionIcon icon={ChevronRight} size={'small'} />+ </WorkspaceLink>+ }+ >+ {datasets.length === 0 ? (+ <Empty description={t('experiment.detail.benchmarksEmpty')} icon={Database} />+ ) : (+ <Flexbox gap={0}>+ {datasets.map((dataset) => (+ <DatasetRow dataset={dataset} key={dataset.id} onAddRun={actions.addRun} />+ ))}+ </Flexbox>+ )}+ </Card>+ ))}+ </Flexbox>+ );+});++export default BenchmarksSection;diff --git a/src/routes/(main)/eval/features/Experiments/DatasetRow.tsx b/src/routes/(main)/eval/features/Experiments/DatasetRow.tsxnew file mode 100644index 00000000000..1fee156e87d--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/DatasetRow.tsx@@ -0,0 +1,82 @@+'use client';++import type { AgentEvalDatasetListItem } from '@lobechat/types';+import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ChevronRight, Database, Play } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import WorkspaceLink from '@/features/Workspace/WorkspaceLink';++const styles = createStaticStyles(({ css }) => ({+ iconBox: css`+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;++ width: 32px;+ height: 32px;+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorPrimary};++ background: ${cssVar.colorPrimaryBg};+ `,+ row: css`+ padding-block: 10px;+ padding-inline: 4px;+ border-radius: ${cssVar.borderRadius};+ transition: background 0.15s ease;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+}));++interface DatasetRowProps {+ dataset: AgentEvalDatasetListItem;+ onAddRun: (dataset: AgentEvalDatasetListItem) => void;+}++/**+ * Compact dataset row for the experiment workspace: identity + test-case+ * count, an "Add Run" action, and a chevron to the full dataset detail page.+ */+const DatasetRow = memo<DatasetRowProps>(({ dataset, onAddRun }) => {+ const { t } = useTranslation('eval');++ return (+ <Flexbox horizontal align="center" className={styles.row} gap={12}>+ <div className={styles.iconBox}>+ <Icon icon={Database} size={16} />+ </div>+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis weight={500}>+ {dataset.name}+ </Text>+ {typeof dataset.testCaseCount === 'number' && (+ <Text fontSize={12} type="secondary">+ {t('run.create.caseCount', { count: dataset.testCaseCount })}+ </Text>+ )}+ </Flexbox>++ <Button icon={Play} size={'small'} type={'text'} onClick={() => onAddRun(dataset)}>+ {t('dataset.detail.addRun')}+ </Button>+ <WorkspaceLink to={`/eval/bench/${dataset.benchmarkId}/datasets/${dataset.id}`}>+ <ActionIcon icon={ChevronRight} size={'small'} />+ </WorkspaceLink>+ </Flexbox>+ );+});++export default DatasetRow;diff --git a/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx b/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsxnew file mode 100644index 00000000000..fedd4295268--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx@@ -0,0 +1,154 @@+'use client';++import type { AgentEvalExperiment } from '@lobechat/types';+import {+ Button,+ ModalFooter,+ type ModalInstance,+ Select,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { App, Form, Input } from 'antd';+import { t } from 'i18next';+import { memo, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import { benchmarkSelectors, useEvalStore } from '@/store/eval';+import { createFormModal } from '@/utils/createFormModal';++interface ExperimentModalProps {+ experiment?: AgentEvalExperiment;+ onSuccess?: (id: string) => void;+}++interface ExperimentModalContentProps extends ExperimentModalProps {+ formId: string;+ onLoadingChange: (loading: boolean) => void;+}++const ExperimentModalContent = memo<ExperimentModalContentProps>(+ ({ experiment, formId, onLoadingChange, onSuccess }) => {+ const { t } = useTranslation('eval');+ const { message } = App.useApp();+ const { close } = useModalContext();+ const [form] = Form.useForm();+ const createExperiment = useEvalStore((s) => s.createExperiment);+ const updateExperiment = useEvalStore((s) => s.updateExperiment);+ const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);+ const benchmarkList = useEvalStore(benchmarkSelectors.benchmarkList);++ useFetchBenchmarks();++ useEffect(() => {+ if (experiment) {+ form.setFieldsValue({+ benchmarkIds: experiment.benchmarks.map((benchmark) => benchmark.id),+ description: experiment.description || undefined,+ name: experiment.name,+ });+ }+ }, [experiment, form]);++ const handleSubmit = async (values: {+ benchmarkIds: string[];+ description?: string;+ name: string;+ }) => {+ onLoadingChange(true);+ try {+ const result = experiment+ ? await updateExperiment({ ...values, id: experiment.id })+ : await createExperiment(values);++ message.success(experiment ? t('experiment.edit.success') : t('experiment.create.title'));+ close();+ onSuccess?.(result.id);+ } catch (error) {+ message.error(+ error instanceof Error+ ? error.message+ : experiment+ ? t('experiment.edit.error')+ : t('experiment.create.error'),+ );+ } finally {+ onLoadingChange(false);+ }+ };++ return (+ <Form form={form} id={formId} layout="vertical" onFinish={handleSubmit}>+ <Form.Item+ label={t('experiment.create.name.label')}+ name="name"+ rules={[{ message: t('experiment.create.nameRequired'), required: true }]}+ >+ <Input placeholder={t('experiment.create.name.placeholder')} />+ </Form.Item>++ <Form.Item label={t('experiment.create.description.label')} name="description">+ <Input.TextArea placeholder={t('experiment.create.description.placeholder')} rows={3} />+ </Form.Item>++ <Form.Item+ label={t('experiment.create.benchmarks.label')}+ name="benchmarkIds"+ rules={[{ message: t('experiment.create.benchmarksRequired'), required: true }]}+ >+ <Select+ mode="multiple"+ placeholder={t('experiment.create.benchmarks.placeholder')}+ options={benchmarkList.map((benchmark) => ({+ label: benchmark.name,+ value: benchmark.id,+ }))}+ />+ </Form.Item>+ </Form>+ );+ },+);++const ExperimentModalFooter = memo<{+ formId: string;+ loading: boolean;+ submitText: string;+}>(({ formId, loading, submitText }) => {+ const { t } = useTranslation('eval');+ const { close } = useModalContext();++ return (+ <ModalFooter>+ <Button disabled={loading} onClick={close}>+ {t('common.cancel')}+ </Button>+ <Button form={formId} htmlType="submit" loading={loading} type="primary">+ {submitText}+ </Button>+ </ModalFooter>+ );+});++export const createExperimentModal = ({+ experiment,+ onSuccess,+}: ExperimentModalProps = {}): ModalInstance =>+ createFormModal({+ renderContent: ({ formId, setLoading }) => (+ <ExperimentModalContent+ experiment={experiment}+ formId={formId}+ onLoadingChange={setLoading}+ onSuccess={onSuccess}+ />+ ),+ renderFooter: ({ formId, loading }) => (+ <ExperimentModalFooter+ formId={formId}+ loading={loading}+ submitText={t(experiment ? 'common.update' : 'common.create', { ns: 'eval' })}+ />+ ),+ title: t(experiment ? 'experiment.edit.title' : 'experiment.create.title', { ns: 'eval' }),+ width: 520,+ });diff --git a/src/routes/(main)/eval/features/Experiments/ExperimentDetailPage.tsx b/src/routes/(main)/eval/features/Experiments/ExperimentDetailPage.tsxnew file mode 100644index 00000000000..4f99c5c07da--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/ExperimentDetailPage.tsx@@ -0,0 +1,71 @@+'use client';++import { Flexbox, Skeleton } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';+import { useParams } from 'react-router';++import AsyncBoundary from '@/components/AsyncBoundary';+import { experimentSelectors, useEvalStore } from '@/store/eval';++import BenchmarksSection from './BenchmarksSection';+import ExperimentHeader from './ExperimentHeader';+import ExperimentStats from './ExperimentStats';+import RunsSection from './RunsSection';+import ScopedDatasetsSection from './ScopedDatasetsSection';+import { useExperimentActions } from './useExperimentActions';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ overflow-y: auto;+ padding-block: 24px;+ padding-inline: 32px;+ `,+}));++/**+ * Experiment workspace page. Thin orchestrator: one fetch populates the single+ * experiment-detail payload (benchmarks + datasets + runs); every section is a+ * focused component fed by the shared useExperimentActions.+ */+const ExperimentDetailPage = memo(() => {+ const { experimentId } = useParams<{ experimentId: string }>();+ const useFetchExperimentDetail = useEvalStore((s) => s.useFetchExperimentDetail);+ const experiment = useEvalStore(experimentSelectors.getExperimentDetailById(experimentId || ''));++ const { error, isLoading, mutate } = useFetchExperimentDetail(experimentId);++ const actions = useExperimentActions(experiment);++ // Error (including a deleted / unknown experiment) must gate before the+ // skeleton — otherwise a failed first load hangs on it forever (ux Feedback).+ return (+ <Flexbox className={styles.container} gap={24} height="100%" width="100%">+ <AsyncBoundary+ data={experiment}+ error={error}+ errorVariant={'block'}+ isLoading={isLoading && !experiment}+ loading={+ <>+ <Skeleton active paragraph={{ rows: 2 }} title={{ width: 240 }} />+ <Skeleton active paragraph={{ rows: 6 }} title={false} />+ </>+ }+ onRetry={() => mutate()}+ >+ {experiment && (+ <>+ <ExperimentHeader experiment={experiment} />+ <ExperimentStats datasetCount={experiment.datasets.length} experiment={experiment} />+ <BenchmarksSection actions={actions} experiment={experiment} />+ <ScopedDatasetsSection actions={actions} />+ <RunsSection actions={actions} experiment={experiment} />+ </>+ )}+ </AsyncBoundary>+ </Flexbox>+ );+});++export default ExperimentDetailPage;diff --git a/src/routes/(main)/eval/features/Experiments/ExperimentHeader.tsx b/src/routes/(main)/eval/features/Experiments/ExperimentHeader.tsxnew file mode 100644index 00000000000..e4b3cec6abd--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/ExperimentHeader.tsx@@ -0,0 +1,85 @@+'use client';++import type { AgentEvalExperimentDetail } from '@lobechat/types';+import { Flexbox, Text } from '@lobehub/ui';+import { Button, type DropdownItem, DropdownMenu } from '@lobehub/ui/base-ui';+import { App } from 'antd';+import { createStaticStyles, cssVar } from 'antd-style';+import { Ellipsis, Pencil, Trash2 } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useEvalStore } from '@/store/eval';++import { createExperimentModal } from './ExperimentCreateModal';++const styles = createStaticStyles(({ css }) => ({+ meta: css`+ font-size: 13px;+ color: ${cssVar.colorTextTertiary};+ `,+}));++interface ExperimentHeaderProps {+ experiment: AgentEvalExperimentDetail;+}++const ExperimentHeader = memo<ExperimentHeaderProps>(({ experiment }) => {+ const { t } = useTranslation('eval');+ const { message, modal } = App.useApp();+ const navigate = useWorkspaceAwareNavigate();+ const deleteExperiment = useEvalStore((s) => s.deleteExperiment);++ const menuItems: DropdownItem[] = [+ {+ danger: true,+ icon: <Trash2 size={16} />,+ key: 'delete',+ label: t('common.delete'),+ onClick: () =>+ modal.confirm({+ content: t('experiment.actions.delete.confirm'),+ okButtonProps: { danger: true },+ okText: t('experiment.actions.delete'),+ onOk: async () => {+ try {+ await deleteExperiment(experiment.id);+ navigate('/eval');+ } catch {+ // Optimistic removal surfaces its failure here (ux Act) — stay+ // on the page and let the user retry instead of navigating away.+ message.error(t('experiment.delete.error'));+ }+ },+ title: t('experiment.actions.delete'),+ }),+ },+ ];++ return (+ <Flexbox horizontal align="start" justify="space-between">+ <Flexbox gap={6} style={{ minWidth: 0 }}>+ <Text as="h3" style={{ fontSize: 24, fontWeight: 600, margin: 0 }}>+ {experiment.name}+ </Text>+ {experiment.description && <Text type="secondary">{experiment.description}</Text>}+ <span className={styles.meta}>+ {t('experiment.detail.lastAccessed', {+ time: new Date(experiment.accessedAt).toLocaleString(),+ })}+ </span>+ </Flexbox>+ <Flexbox horizontal gap={8}>+ <Button icon={Pencil} onClick={() => createExperimentModal({ experiment })}>+ {t('common.edit')}+ </Button>+ <DropdownMenu items={menuItems} trigger={['click']}>+ <Button icon={Ellipsis} />+ </DropdownMenu>+ </Flexbox>+ </Flexbox>+ );+});++export default ExperimentHeader;diff --git a/src/routes/(main)/eval/features/Experiments/ExperimentStats.tsx b/src/routes/(main)/eval/features/Experiments/ExperimentStats.tsxnew file mode 100644index 00000000000..8d94bc93c05--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/ExperimentStats.tsx@@ -0,0 +1,54 @@+'use client';++import type { AgentEvalExperimentDetail } from '@lobechat/types';+import { Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++const styles = createStaticStyles(({ css }) => ({+ statDivider: css`+ width: 1px;+ height: 28px;+ background: ${cssVar.colorBorderSecondary};+ `,+ statValue: css`+ font-family: ${cssVar.fontFamilyCode};+ font-weight: 600;+ color: ${cssVar.colorText};+ `,+}));++// One labeled figure in the strip (big mono number over a quiet label) — the+// same pattern as BenchmarkCard's stat strip.+const Stat = memo<{ label: string; value: number | string }>(({ value, label }) => (+ <Flexbox gap={2}>+ <Text className={styles.statValue} fontSize={20}>+ {value}+ </Text>+ <Text color={cssVar.colorTextTertiary} fontSize={12}>+ {label}+ </Text>+ </Flexbox>+));++interface ExperimentStatsProps {+ datasetCount: number;+ experiment: AgentEvalExperimentDetail;+}++const ExperimentStats = memo<ExperimentStatsProps>(({ experiment, datasetCount }) => {+ const { t } = useTranslation('eval');++ return (+ <Flexbox horizontal align="center" gap={24}>+ <Stat label={t('experiment.detail.stats.benchmarks')} value={experiment.benchmarks.length} />+ <span className={styles.statDivider} />+ <Stat label={t('sidebar.datasets')} value={datasetCount} />+ <span className={styles.statDivider} />+ <Stat label={t('experiment.detail.stats.runs')} value={experiment.runs.length} />+ </Flexbox>+ );+});++export default ExperimentStats;diff --git a/src/routes/(main)/eval/features/Experiments/RunRow.tsx b/src/routes/(main)/eval/features/Experiments/RunRow.tsxnew file mode 100644index 00000000000..33c8d3f02f7--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/RunRow.tsx@@ -0,0 +1,93 @@+'use client';++import type { AgentEvalRunListItem } from '@lobechat/types';+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ChevronRight } from 'lucide-react';+import { memo } from 'react';++import WorkspaceLink from '@/features/Workspace/WorkspaceLink';++import SegmentBar from '../SegmentBar';+import StatusBadge from '../StatusBadge';++const styles = createStaticStyles(({ css }) => ({+ passRate: css`+ font-family: ${cssVar.fontFamilyCode};+ font-weight: 600;+ color: ${cssVar.colorText};+ `,+ row: css`+ padding-block: 10px;+ padding-inline: 4px;+ border-radius: ${cssVar.borderRadius};+ transition: background 0.15s ease;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+}));++interface RunRowProps {+ benchmarkId: string;+ run: AgentEvalRunListItem;+}++/**+ * Compact read-only run row for the experiment workspace: name + status ++ * pass/fail/error breakdown + pass rate, linking out to the full run page.+ */+const RunRow = memo<RunRowProps>(({ run, benchmarkId }) => {+ const passCount = run.passCount ?? run.metrics?.passedCases ?? 0;+ const failCount = run.failCount ?? run.metrics?.failedCases ?? 0;+ const errorCount = run.errorCount ?? run.metrics?.errorCases ?? 0;+ const passRate = run.passRate ?? run.metrics?.passRate;++ return (+ <Flexbox horizontal align="center" className={styles.row} gap={12}>+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Flexbox horizontal align="center" gap={8}>+ <Text ellipsis weight={500}>+ {run.name || run.id}+ </Text>+ <StatusBadge status={run.status} />+ </Flexbox>+ <Flexbox horizontal align="center" gap={8}>+ {run.datasetName && (+ <Text fontSize={12} type="secondary">+ {run.datasetName}+ </Text>+ )}+ <Text fontSize={12} type="secondary">+ {new Date(run.createdAt).toLocaleDateString()}+ </Text>+ </Flexbox>+ </Flexbox>++ <Flexbox align="flex-end" gap={4} style={{ width: 140 }}>+ {typeof passRate === 'number' && (+ <span className={styles.passRate}>{(passRate * 100).toFixed(0)}%</span>+ )}+ <SegmentBar+ height={6}+ segments={[+ { color: cssVar.colorSuccess, value: passCount },+ { color: cssVar.colorError, value: failCount },+ { color: cssVar.colorWarning, value: errorCount },+ ]}+ />+ </Flexbox>++ <WorkspaceLink to={`/eval/bench/${benchmarkId}/runs/${run.id}`}>+ <ActionIcon icon={ChevronRight} size={'small'} />+ </WorkspaceLink>+ </Flexbox>+ );+});++export default RunRow;diff --git a/src/routes/(main)/eval/features/Experiments/RunsSection.tsx b/src/routes/(main)/eval/features/Experiments/RunsSection.tsxnew file mode 100644index 00000000000..8bd39fca59f--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/RunsSection.tsx@@ -0,0 +1,56 @@+'use client';++import type { AgentEvalExperimentDetail } from '@lobechat/types';+import { Empty, Flexbox } from '@lobehub/ui';+import { Card } from 'antd';+import { createStaticStyles } from 'antd-style';+import { FlaskConical } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import RunRow from './RunRow';+import type { useExperimentActions } from './useExperimentActions';++const styles = createStaticStyles(({ css }) => ({+ listCard: css`+ .ant-card-body {+ padding-block: 4px;+ padding-inline: 8px;+ }+ `,+ sectionTitle: css`+ margin: 0;+ font-size: 16px;+ font-weight: 600;+ `,+}));++interface RunsSectionProps {+ actions: ReturnType<typeof useExperimentActions>;+ experiment: AgentEvalExperimentDetail;+}++/** Experiment runs — compact read-only rows linking out to the full run page. */+const RunsSection = memo<RunsSectionProps>(({ actions, experiment }) => {+ const { t } = useTranslation('eval');+ const runs = experiment.runs || [];++ return (+ <Flexbox gap={12}>+ <h3 className={styles.sectionTitle}>{t('experiment.detail.runs')}</h3>+ <Card className={styles.listCard}>+ {runs.length === 0 ? (+ <Empty description={t('run.empty.title')} icon={FlaskConical} />+ ) : (+ <Flexbox gap={0}>+ {runs.map((run) => (+ <RunRow benchmarkId={actions.resolveRunBenchmarkId(run)} key={run.id} run={run} />+ ))}+ </Flexbox>+ )}+ </Card>+ </Flexbox>+ );+});++export default RunsSection;diff --git a/src/routes/(main)/eval/features/Experiments/ScopedDatasetsSection.tsx b/src/routes/(main)/eval/features/Experiments/ScopedDatasetsSection.tsxnew file mode 100644index 00000000000..3aba95cec90--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/ScopedDatasetsSection.tsx@@ -0,0 +1,54 @@+'use client';++import { Empty, Flexbox } from '@lobehub/ui';+import { Card } from 'antd';+import { createStaticStyles } from 'antd-style';+import { Database } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import DatasetRow from './DatasetRow';+import type { useExperimentActions } from './useExperimentActions';++const styles = createStaticStyles(({ css }) => ({+ listCard: css`+ .ant-card-body {+ padding-block: 4px;+ padding-inline: 8px;+ }+ `,+ sectionTitle: css`+ margin: 0;+ font-size: 16px;+ font-weight: 600;+ `,+}));++interface ScopedDatasetsSectionProps {+ actions: ReturnType<typeof useExperimentActions>;+}++/** Experiment-scoped subsets / forks — read-only display with "Add Run". */+const ScopedDatasetsSection = memo<ScopedDatasetsSectionProps>(({ actions }) => {+ const { t } = useTranslation('eval');+ const { scopedDatasets } = actions;++ return (+ <Flexbox gap={12}>+ <h3 className={styles.sectionTitle}>{t('experiment.detail.datasetsScoped')}</h3>+ <Card className={styles.listCard}>+ {scopedDatasets.length === 0 ? (+ <Empty description={t('experiment.detail.datasetsScopedEmpty')} icon={Database} />+ ) : (+ <Flexbox gap={0}>+ {scopedDatasets.map((dataset) => (+ <DatasetRow dataset={dataset} key={dataset.id} onAddRun={actions.addRun} />+ ))}+ </Flexbox>+ )}+ </Card>+ </Flexbox>+ );+});++export default ScopedDatasetsSection;diff --git a/src/routes/(main)/eval/features/Experiments/SummaryCard.tsx b/src/routes/(main)/eval/features/Experiments/SummaryCard.tsxnew file mode 100644index 00000000000..507edd7eaf0--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/SummaryCard.tsx@@ -0,0 +1,119 @@+'use client';++import type { AgentEvalExperimentListItem } from '@lobechat/types';+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowRight, Beaker } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import WorkspaceLink from '@/features/Workspace/WorkspaceLink';++import RunRow from './RunRow';++const styles = createStaticStyles(({ css }) => ({+ card: css`+ height: 100%;+ padding: 20px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgContainer};++ transition: border-color 0.15s ease;++ &:hover {+ border-color: ${cssVar.colorBorder};+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ detailLink: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;+ border-radius: ${cssVar.borderRadiusSM};++ color: ${cssVar.colorTextTertiary};++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ iconBox: css`+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;++ width: 40px;+ height: 40px;+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorInfo};++ background: ${cssVar.colorInfoBg};+ `,+ name: css`+ font-size: ${cssVar.fontSizeLG};+ font-weight: 600;+ color: ${cssVar.colorText};++ &:hover {+ color: ${cssVar.colorPrimary};+ }+ `,+}));++interface SummaryCardProps {+ experiment: AgentEvalExperimentListItem;+}++/** Home overview card for an experiment: identity + counts + recent-runs preview. */+const SummaryCard = memo<SummaryCardProps>(({ experiment }) => {+ const { t } = useTranslation('eval');+ const recentRuns = experiment.recentRuns?.slice(0, 3) || [];+ const fallbackBenchmarkId = experiment.benchmarks[0]?.id || '';++ return (+ <Flexbox className={styles.card} gap={16}>+ <Flexbox horizontal align="flex-start" gap={12} justify="space-between">+ <Flexbox horizontal align="center" gap={12} style={{ minWidth: 0 }}>+ <div className={styles.iconBox}>+ <Icon icon={Beaker} size={22} />+ </div>+ <Flexbox gap={2} style={{ minWidth: 0 }}>+ <WorkspaceLink className={styles.name} to={`/eval/experiments/${experiment.id}`}>+ {experiment.name}+ </WorkspaceLink>+ <Text color={cssVar.colorTextTertiary} fontSize={12}>+ {t('experiment.card.benchmarkCount', { count: experiment.benchmarkCount })}+ {' · '}+ {t('experiment.card.runCount', { count: experiment.runCount })}+ </Text>+ </Flexbox>+ </Flexbox>+ <WorkspaceLink className={styles.detailLink} to={`/eval/experiments/${experiment.id}`}>+ <Icon icon={ArrowRight} size={16} />+ </WorkspaceLink>+ </Flexbox>++ {recentRuns.length > 0 && (+ <Flexbox gap={0}>+ {recentRuns.map((run) => (+ <RunRow benchmarkId={run.benchmarkId || fallbackBenchmarkId} key={run.id} run={run} />+ ))}+ </Flexbox>+ )}+ </Flexbox>+ );+});++export default SummaryCard;diff --git a/src/routes/(main)/eval/features/Experiments/index.ts b/src/routes/(main)/eval/features/Experiments/index.tsnew file mode 100644index 00000000000..b9be4b32965--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/index.ts@@ -0,0 +1,3 @@+export { createExperimentModal } from './ExperimentCreateModal';+export { default as ExperimentDetailPage } from './ExperimentDetailPage';+export { default as ExperimentSummaryCard } from './SummaryCard';diff --git a/src/routes/(main)/eval/features/Experiments/useExperimentActions.ts b/src/routes/(main)/eval/features/Experiments/useExperimentActions.tsnew file mode 100644index 00000000000..aebcf52b4f2--- /dev/null+++ b/src/routes/(main)/eval/features/Experiments/useExperimentActions.ts@@ -0,0 +1,51 @@+'use client';++import type { AgentEvalDatasetListItem, AgentEvalExperimentDetail } from '@lobechat/types';+import { useMemo } from 'react';++import { createRunCreateModal } from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal';++/**+ * Shared derivations + mutations for the experiment workspace. The single+ * experiment-detail payload is split into baseline vs scoped datasets here,+ * and "Add Run" opens the shared RunCreateModal (which revalidates the+ * experiment detail itself via the experimentId passthrough).+ */+export const useExperimentActions = (experiment?: AgentEvalExperimentDetail) => {+ const experimentId = experiment?.id;++ /** Baseline (non-scoped) datasets across the linked benchmarks. */+ const baselineDatasets = useMemo<AgentEvalDatasetListItem[]>(+ () =>+ (experiment?.datasets || []).filter((dataset) => dataset.sourceExperimentId !== experimentId),+ [experiment, experimentId],+ );++ /** Experiment-scoped subsets / forks. */+ const scopedDatasets = useMemo<AgentEvalDatasetListItem[]>(+ () =>+ (experiment?.datasets || []).filter((dataset) => dataset.sourceExperimentId === experimentId),+ [experiment, experimentId],+ );++ const datasetBenchmarkMap = useMemo(+ () => new Map((experiment?.datasets || []).map((dataset) => [dataset.id, dataset.benchmarkId])),+ [experiment],+ );++ const addRun = (dataset: AgentEvalDatasetListItem) => {+ if (!experimentId) return;+ createRunCreateModal({+ benchmarkId: dataset.benchmarkId,+ datasetId: dataset.id,+ datasetName: dataset.name,+ experimentId,+ });+ };++ /** Resolve the benchmark a run belongs to (experiments span benchmarks). */+ const resolveRunBenchmarkId = (run: { datasetId: string }) =>+ datasetBenchmarkMap.get(run.datasetId) || experiment?.benchmarks[0]?.id || '';++ return { addRun, baselineDatasets, resolveRunBenchmarkId, scopedDatasets };+};diff --git a/src/routes/(main)/eval/index.tsx b/src/routes/(main)/eval/index.tsxindex 97df1e6f10d..36855068e02 100644--- a/src/routes/(main)/eval/index.tsx+++ b/src/routes/(main)/eval/index.tsx@@ -12,6 +12,7 @@ import { useEvalStore } from '@/store/eval';import BenchmarkCard from './features/BenchmarkCard';import { createCreateBenchmarkModal } from './features/CreateBenchmarkModal';+import { createExperimentModal, ExperimentSummaryCard } from './features/Experiments';const styles = createStaticStyles(({ css }) => ({container: css`@@ -61,6 +62,15 @@ const EvalOverview = memo(() => {const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);const { data, isLoading, error, mutate } = useFetchBenchmarks();+ const experimentList = useEvalStore((s) => s.experimentList);+ const useFetchExperiments = useEvalStore((s) => s.useFetchExperiments);+ const {+ data: experimentData,+ isLoading: isLoadingExperiments,+ error: experimentError,+ mutate: mutateExperiments,+ } = useFetchExperiments();+// Purpose-built onboarding empty — only reached when the fetch succeeded with// zero benchmarks. A *failed* fetch is gated ahead of this by AsyncBoundary so// we never invite the user to re-create benchmarks they already own (ux Read@@ -80,6 +90,23 @@ const EvalOverview = memo(() => {</Flexbox>);+ // Same contract for the experiments grid (ux Read: empty is a real page with+ // a CTA, not a blank grid).+ const experimentsEmptyState = (+ <Flexbox align={'center'} flex={1} justify={'center'}>+ <Empty description={t('experiment.empty')} icon={FlaskConical}>+ <Button+ icon={Plus}+ style={{ marginTop: 16 }}+ type={'primary'}+ onClick={() => createExperimentModal()}+ >+ {t('overview.createExperiment')}+ </Button>+ </Empty>+ </Flexbox>+ );+return (<Flexbox className={styles.container} gap={32} height={'100%'} width={'100%'}>{/* Header */}@@ -97,35 +124,69 @@ const EvalOverview = memo(() => {)}</Flexbox>- {/* Body: error / loading / empty / grid (error gated before empty) */}- <AsyncBoundary- data={data}- empty={emptyState}- error={error}- errorVariant={'block'}- isEmpty={benchmarkList.length === 0}- isLoading={isLoading}- loading={<SkeletonGrid />}- onRetry={() => mutate()}- >- <div className={styles.grid}>- {benchmarkList.map((benchmark: any) => (- <BenchmarkCard- bestScore={benchmark.bestScore}- datasetCount={benchmark.datasetCount}- description={benchmark.description}- id={benchmark.id}- key={benchmark.id}- name={benchmark.name}- recentRuns={benchmark.recentRuns}- runCount={benchmark.runCount}- source={benchmark.source}- tags={benchmark.tags}- testCaseCount={benchmark.testCaseCount}- />- ))}- </div>- </AsyncBoundary>+ {/* Experiments */}+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Text as={'h2'} style={{ fontSize: 18, fontWeight: 600, margin: 0 }}>+ {t('overview.sections.experiments.title')}+ </Text>+ <Button icon={Plus} size={'small'} onClick={() => createExperimentModal()}>+ {t('overview.createExperiment')}+ </Button>+ </Flexbox>+ <AsyncBoundary+ data={experimentData}+ empty={experimentsEmptyState}+ error={experimentError}+ errorVariant={'block'}+ isEmpty={experimentList.length === 0}+ isLoading={isLoadingExperiments}+ loading={<SkeletonGrid />}+ onRetry={() => mutateExperiments()}+ >+ <div className={styles.grid}>+ {experimentList.map((experiment) => (+ <ExperimentSummaryCard experiment={experiment} key={experiment.id} />+ ))}+ </div>+ </AsyncBoundary>+ </Flexbox>++ {/* Benchmarks */}+ <Flexbox gap={16}>+ <Text as={'h2'} style={{ fontSize: 18, fontWeight: 600, margin: 0 }}>+ {t('overview.sections.benchmarks.title')}+ </Text>+ {/* Body: error / loading / empty / grid (error gated before empty) */}+ <AsyncBoundary+ data={data}+ empty={emptyState}+ error={error}+ errorVariant={'block'}+ isEmpty={benchmarkList.length === 0}+ isLoading={isLoading}+ loading={<SkeletonGrid />}+ onRetry={() => mutate()}+ >+ <div className={styles.grid}>+ {benchmarkList.map((benchmark: any) => (+ <BenchmarkCard+ bestScore={benchmark.bestScore}+ datasetCount={benchmark.datasetCount}+ description={benchmark.description}+ id={benchmark.id}+ key={benchmark.id}+ name={benchmark.name}+ recentRuns={benchmark.recentRuns}+ runCount={benchmark.runCount}+ source={benchmark.source}+ tags={benchmark.tags}+ testCaseCount={benchmark.testCaseCount}+ />+ ))}+ </div>+ </AsyncBoundary>+ </Flexbox></Flexbox>);});diff --git a/src/services/agentEval.ts b/src/services/agentEval.tsindex eb7ca591a9d..9dc5309f361 100644--- a/src/services/agentEval.ts+++ b/src/services/agentEval.ts@@ -3,6 +3,38 @@ import type { EvalRunInputConfig, RubricType } from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';class AgentEvalService {+ // ============ Experiment ============+ async listExperiments() {+ return lambdaClient.agentEval.listExperiments.query();+ }++ async getExperiment(id: string) {+ return lambdaClient.agentEval.getExperiment.query({ id });+ }++ async createExperiment(params: {+ benchmarkIds: string[];+ description?: string;+ metadata?: Record<string, unknown>;+ name: string;+ }) {+ return lambdaClient.agentEval.createExperiment.mutate(params);+ }++ async updateExperiment(params: {+ benchmarkIds?: string[];+ description?: string;+ id: string;+ metadata?: Record<string, unknown>;+ name?: string;+ }) {+ return lambdaClient.agentEval.updateExperiment.mutate(params);+ }++ async deleteExperiment(id: string) {+ return lambdaClient.agentEval.deleteExperiment.mutate({ id });+ }+// ============ Benchmark ============async listBenchmarks() {return lambdaClient.agentEval.listBenchmarks.query();@@ -55,6 +87,7 @@ class AgentEvalService {identifier: string;metadata?: Record<string, unknown>;name: string;+ sourceExperimentId?: string;}) {return lambdaClient.agentEval.createDataset.mutate(params);}@@ -139,7 +172,7 @@ class AgentEvalService {}// ============ Run ============- async listRuns(params: { benchmarkId?: string; datasetId?: string }) {+ async listRuns(params: { benchmarkId?: string; datasetId?: string; experimentId?: string }) {return lambdaClient.agentEval.listRuns.query(params);}@@ -154,7 +187,9 @@ class AgentEvalService {async createRun(params: {config?: EvalRunInputConfig;datasetId: string;+ experimentId?: string;name?: string;+ parentRunId?: string;targetAgentId?: string;}) {return lambdaClient.agentEval.createRun.mutate(params);diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsxindex 32f3b53776c..f435d017c13 100644--- a/src/spa/router/desktopRouter.config.desktop.tsx+++ b/src/spa/router/desktopRouter.config.desktop.tsx@@ -107,6 +107,7 @@ import EvalBenchLayout from '@/routes/(main)/eval/bench/[benchmarkId]/_layout';import EvalDatasetDetailPage from '@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]';import EvalRunDetailPage from '@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]';import EvalCaseDetailPage from '@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]';+import EvalExperimentDetailPage from '@/routes/(main)/eval/experiments/[experimentId]';import GroupPage from '@/routes/(main)/group';import DesktopGroupLayout from '@/routes/(main)/group/_layout';import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';@@ -529,6 +530,10 @@ export const sharedMainAreaChildren: RouteObject[] = [element: <EvalOverviewPage />,index: true,},+ {+ element: <EvalExperimentDetailPage />,+ path: 'experiments/:experimentId',+ },],element: <EvalHomeLayout />,},diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex 291ba3148b7..c2e497545a0 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -587,6 +587,13 @@ export const sharedMainAreaChildren: RouteObject[] = [),index: true,},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/eval/experiments/[experimentId]'),+ 'Desktop > Eval > Experiment Detail',+ ),+ path: 'experiments/:experimentId',+ },],element: dynamicElement(() => import('@/routes/(main)/eval/(home)/_layout'),diff --git a/src/store/eval/initialState.ts b/src/store/eval/initialState.tsindex d54fbcbca8c..c11cab4a93a 100644--- a/src/store/eval/initialState.ts+++ b/src/store/eval/initialState.ts@@ -1,14 +1,24 @@import { benchmarkInitialState, type BenchmarkSliceState } from './slices/benchmark/initialState';import { datasetInitialState, type DatasetSliceState } from './slices/dataset/initialState';+import {+ experimentInitialState,+ type ExperimentSliceState,+} from './slices/experiment/initialState';import { runInitialState, type RunSliceState } from './slices/run/initialState';import { testCaseInitialState, type TestCaseSliceState } from './slices/testCase/initialState';export interface EvalStoreState- extends BenchmarkSliceState, DatasetSliceState, RunSliceState, TestCaseSliceState {}+ extends+ BenchmarkSliceState,+ DatasetSliceState,+ ExperimentSliceState,+ RunSliceState,+ TestCaseSliceState {}export const initialState: EvalStoreState = {...benchmarkInitialState,...datasetInitialState,+ ...experimentInitialState,...runInitialState,...testCaseInitialState,};diff --git a/src/store/eval/selectors.ts b/src/store/eval/selectors.tsindex d462ba7e3f4..6c51e2ea999 100644--- a/src/store/eval/selectors.ts+++ b/src/store/eval/selectors.ts@@ -1,2 +1,3 @@export { benchmarkSelectors } from './slices/benchmark/selectors';+export { experimentSelectors } from './slices/experiment/selectors';export { runSelectors } from './slices/run/selectors';diff --git a/src/store/eval/slices/experiment/action.ts b/src/store/eval/slices/experiment/action.tsnew file mode 100644index 00000000000..f526f9d33ff--- /dev/null+++ b/src/store/eval/slices/experiment/action.ts@@ -0,0 +1,126 @@+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 { agentEvalService } from '@/services/agentEval';+import { type EvalStore } from '@/store/eval/store';+import { type StoreSetter } from '@/store/types';++type Setter = StoreSetter<EvalStore>;++export const createExperimentSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>+ new ExperimentActionImpl(set, get, _api);++export class ExperimentActionImpl {+ readonly #get: () => EvalStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => EvalStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ createExperiment = async (params: {+ benchmarkIds: string[];+ description?: string;+ metadata?: Record<string, unknown>;+ name: string;+ }): Promise<any> => {+ const result = await agentEvalService.createExperiment(params);+ await this.#get().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();+ }+ };++ updateExperiment = async (params: {+ benchmarkIds?: string[];+ description?: string;+ id: string;+ metadata?: Record<string, unknown>;+ name?: string;+ }): Promise<void> => {+ await agentEvalService.updateExperiment(params);+ await Promise.all([+ this.#get().refreshExperiments(),+ this.#get().refreshExperimentDetail(params.id),+ ]);+ };++ refreshExperimentDetail = async (id: string): Promise<void> => {+ await mutate(evalKeys.experimentDetail(id));+ };++ refreshExperiments = async (): Promise<void> => {+ await mutate(evalKeys.experiments());+ };++ 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',+ );+ };++ 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',+ );+ };+}++export type ExperimentAction = Pick<ExperimentActionImpl, keyof ExperimentActionImpl>;diff --git a/src/store/eval/slices/experiment/initialState.ts b/src/store/eval/slices/experiment/initialState.tsnew file mode 100644index 00000000000..8374964097a--- /dev/null+++ b/src/store/eval/slices/experiment/initialState.ts@@ -0,0 +1,15 @@+import type { AgentEvalExperimentDetail, AgentEvalExperimentListItem } from '@lobechat/types';++export interface ExperimentSliceState {+ experimentDetailMap: Record<string, AgentEvalExperimentDetail>;+ experimentList: AgentEvalExperimentListItem[];+ experimentListInit: boolean;+ loadingExperimentDetailIds: string[];+}++export const experimentInitialState: ExperimentSliceState = {+ experimentDetailMap: {},+ experimentList: [],+ experimentListInit: false,+ loadingExperimentDetailIds: [],+};diff --git a/src/store/eval/slices/experiment/selectors.ts b/src/store/eval/slices/experiment/selectors.tsnew file mode 100644index 00000000000..886428a2d01--- /dev/null+++ b/src/store/eval/slices/experiment/selectors.ts@@ -0,0 +1,11 @@+import type { EvalStore } from '@/store/eval/store';++const experimentList = (s: EvalStore) => s.experimentList;+const isExperimentListInit = (s: EvalStore) => s.experimentListInit;+const getExperimentDetailById = (id: string) => (s: EvalStore) => s.experimentDetailMap[id];++export const experimentSelectors = {+ experimentList,+ getExperimentDetailById,+ isExperimentListInit,+};diff --git a/src/store/eval/slices/run/action.ts b/src/store/eval/slices/run/action.tsindex ee63869cb04..64337bc3789 100644--- a/src/store/eval/slices/run/action.ts+++ b/src/store/eval/slices/run/action.ts@@ -33,13 +33,21 @@ export class RunActionImpl {createRun = async (params: {config?: EvalRunInputConfig;datasetId: string;+ experimentId?: string;name?: string;+ parentRunId?: string;targetAgentId?: string;}): Promise<any> => {this.#set({ isCreatingRun: true }, false, 'createRun/start');try {const result = await agentEvalService.createRun(params);- await this.#get().refreshRuns();+ // Experiment-scoped runs are served by the experiment detail payload;+ // benchmark-scoped runs by the benchmark run list.+ if (params.experimentId) {+ await this.#get().refreshExperimentDetail(params.experimentId);+ } else {+ await this.#get().refreshRuns();+ }return result;} finally {this.#set({ isCreatingRun: false }, false, 'createRun/end');diff --git a/src/store/eval/store.ts b/src/store/eval/store.tsindex 10b471b6e80..7bf176e9559 100644--- a/src/store/eval/store.ts+++ b/src/store/eval/store.ts@@ -9,11 +9,13 @@ import { type ResetableStore, ResetableStoreAction } from '../utils/resetableStoimport { type EvalStoreState, initialState } from './initialState';import { type BenchmarkAction, createBenchmarkSlice } from './slices/benchmark/action';import { createDatasetSlice, type DatasetAction } from './slices/dataset/action';+import { createExperimentSlice, type ExperimentAction } from './slices/experiment/action';import { createRunSlice, type RunAction } from './slices/run/action';import { createTestCaseSlice, type TestCaseAction } from './slices/testCase/action';type EvalStoreAction = BenchmarkAction &DatasetAction &+ ExperimentAction &RunAction &TestCaseAction &ResetableStore;@@ -31,6 +33,7 @@ const createStore: StateCreator<EvalStore, [['zustand/devtools', never]]> = (...flattenActions<EvalStoreAction>([createBenchmarkSlice(...parameters),createDatasetSlice(...parameters),+ createExperimentSlice(...parameters),createRunSlice(...parameters),createTestCaseSlice(...parameters),new EvalStoreResetAction(...parameters),