π€― 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): restore test case history into run topics (#18604)
Rylan Cai3c64a7edb712
diff --git a/apps/cli/src/commands/eval.test.ts b/apps/cli/src/commands/eval.test.tsindex 5d2f94e3d48..13f8e1644f5 100644--- a/apps/cli/src/commands/eval.test.ts+++ b/apps/cli/src/commands/eval.test.ts@@ -163,6 +163,99 @@ describe('eval command', () => {});});+ describe('testcase', () => {+ it('should create a test case with messages from a JSON file', async () => {+ const tmpFile = path.join(os.tmpdir(), `eval-messages-${process.pid}.json`);+ await writeFile(tmpFile, JSON.stringify([{ content: 'Earlier turn', role: 'user' }]));+ mockTrpcClient.agentEval.createTestCase.mutate.mockResolvedValue({ id: 'case-1' });++ try {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'testcase',+ 'create',+ '--dataset-id',+ 'dataset-1',+ '--input',+ 'Continue',+ '--messages-file',+ tmpFile,+ ]);++ expect(mockTrpcClient.agentEval.createTestCase.mutate).toHaveBeenCalledWith({+ content: {+ input: 'Continue',+ messages: [{ content: 'Earlier turn', role: 'user' }],+ },+ datasetId: 'dataset-1',+ });+ } finally {+ await rm(tmpFile, { force: true });+ }+ });++ it('should omit an empty messages file when creating a test case', async () => {+ const tmpFile = path.join(os.tmpdir(), `eval-empty-messages-${process.pid}.json`);+ await writeFile(tmpFile, '[]');+ mockTrpcClient.agentEval.createTestCase.mutate.mockResolvedValue({ id: 'case-1' });++ try {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'testcase',+ 'create',+ '--dataset-id',+ 'dataset-1',+ '--input',+ 'Fresh conversation',+ '--messages-file',+ tmpFile,+ ]);++ expect(mockTrpcClient.agentEval.createTestCase.mutate).toHaveBeenCalledWith({+ content: { input: 'Fresh conversation' },+ datasetId: 'dataset-1',+ });+ } finally {+ await rm(tmpFile, { force: true });+ }+ });++ it('should pass an empty messages file when updating a test case', async () => {+ const tmpFile = path.join(os.tmpdir(), `eval-empty-messages-${process.pid}.json`);+ await writeFile(tmpFile, '[]');+ mockTrpcClient.agentEval.updateTestCase.mutate.mockResolvedValue({ id: 'case-1' });++ try {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'eval',+ 'testcase',+ 'update',+ '--id',+ 'case-1',+ '--messages-file',+ tmpFile,+ ]);++ expect(mockTrpcClient.agentEval.updateTestCase.mutate).toHaveBeenCalledWith({+ content: { messages: [] },+ id: 'case-1',+ });+ } finally {+ await rm(tmpFile, { force: true });+ }+ });+ });+// ============================================// Dataset tests// ============================================diff --git a/apps/cli/src/commands/eval.ts b/apps/cli/src/commands/eval.tsindex a66cecc0e23..2546543434d 100644--- a/apps/cli/src/commands/eval.ts+++ b/apps/cli/src/commands/eval.ts@@ -559,6 +559,7 @@ export function registerEvalCommand(program: Command) {.requiredOption('--input <text>', 'Input text').option('--expected <text>', 'Expected output').option('--category <cat>', 'Category')+ .option('--messages-file <path>', 'JSON file containing the prior message sequence').option('--case-id <id>', 'Dataset-native case ID (stored in metadata.caseId)').option('--environment <json>',@@ -576,6 +577,7 @@ export function registerEvalCommand(program: Command) {environment?: Record<string, unknown>;expected?: string;input: string;+ messagesFile?: string;sortOrder?: string;},) =>@@ -587,6 +589,10 @@ export function registerEvalCommand(program: Command) {if (options.expected) content.expected = options.expected;if (options.category) content.category = options.category;if (options.environment) content.environment = options.environment;+ if (options.messagesFile) {+ const messages = JSON.parse(await readFile(options.messagesFile, 'utf8'));+ if (!Array.isArray(messages) || messages.length > 0) content.messages = messages;+ }const input: Record<string, any> = { content, datasetId: options.datasetId };if (options.caseId) input.metadata = { caseId: options.caseId };@@ -604,6 +610,7 @@ export function registerEvalCommand(program: Command) {.option('--input <text>', 'New input text').option('--expected <text>', 'New expected output').option('--category <cat>', 'New category')+ .option('--messages-file <path>', 'JSON file containing the prior message sequence').option('--environment <json>','Test case environment JSON object',@@ -619,6 +626,7 @@ export function registerEvalCommand(program: Command) {environment?: Record<string, unknown>;id: string;input?: string;+ messagesFile?: string;sortOrder?: string;},) =>@@ -632,6 +640,9 @@ export function registerEvalCommand(program: Command) {if (options.expected) content.expected = options.expected;if (options.category) content.category = options.category;if (options.environment) content.environment = options.environment;+ if (options.messagesFile) {+ content.messages = JSON.parse(await readFile(options.messagesFile, 'utf8'));+ }if (Object.keys(content).length > 0) input.content = content;if (options.sortOrder) input.sortOrder = Number.parseInt(options.sortOrder, 10);return client.agentEval.updateTestCase.mutate(input as any);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 fc148f34b95..4661f8e94cd 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@@ -711,6 +711,24 @@ describe('Agent Eval Router Integration Tests', () => {expect(result.metadata).toEqual({ reviewed: true });expect(result.sortOrder).toBe(5);});++ it('should clear a test case message history', async () => {+ const caller = agentEvalRouter.createCaller(createTestContext(userId));+ const created = await caller.createTestCase({+ content: {+ input: 'Original',+ messages: [{ content: 'Old turn', role: 'user' }],+ },+ datasetId,+ });++ const result = await caller.updateTestCase({+ content: { input: 'Original', messages: [] },+ id: created.id,+ });++ expect(result.content.messages).toEqual([]);+ });});describe('deleteTestCase', () => {diff --git a/apps/server/src/routers/lambda/agentEval.ts b/apps/server/src/routers/lambda/agentEval.tsindex f3845da519a..6ed0aef129c 100644--- a/apps/server/src/routers/lambda/agentEval.ts+++ b/apps/server/src/routers/lambda/agentEval.ts@@ -46,6 +46,7 @@ const evalConfigSchema = z.object({ judgePrompt: z.string().optional() }).passthconst evalCaseEnvironmentSchema = z.object({+ envPrompt: z.string().optional(),toolForwarding: z.record(z.string().trim().min(1),@@ -60,12 +61,72 @@ const evalCaseEnvironmentSchema = z}).strict();+const dateValueSchema = z.union([+ z.number().finite(),+ z.string().refine((value) => !Number.isNaN(Date.parse(value)), 'Invalid timestamp'),+]);++const recordSchema = z.record(z.string(), z.unknown());++const evalTestCaseMessagesSchema = z+ .array(+ z+ .object({+ content: z.string(),+ createdAt: dateValueSchema.optional(),+ error: recordSchema.optional(),+ id: z.string().min(1).optional(),+ metadata: recordSchema.optional(),+ model: z.string().optional(),+ parentId: z.string().min(1).nullable().optional(),+ plugin: recordSchema.optional(),+ pluginError: recordSchema.optional(),+ pluginIntervention: recordSchema.optional(),+ pluginState: recordSchema.optional(),+ provider: z.string().optional(),+ reasoning: recordSchema.optional(),+ role: z.enum(['user', 'assistant', 'system', 'tool']),+ search: recordSchema.optional(),+ tool_call_id: z.string().optional(),+ tools: z.array(recordSchema).optional(),+ traceId: z.string().optional(),+ updatedAt: dateValueSchema.optional(),+ })+ .strict(),+ )+ .superRefine((messages, ctx) => {+ const ids = new Set<string>();++ for (const [index, message] of messages.entries()) {+ if (!message.id) continue;+ if (ids.has(message.id)) {+ ctx.addIssue({+ code: 'custom',+ message: 'Message ids must be unique',+ path: [index, 'id'],+ });+ }+ ids.add(message.id);+ }++ for (const [index, message] of messages.entries()) {+ if (message.parentId && !ids.has(message.parentId)) {+ ctx.addIssue({+ code: 'custom',+ message: 'Message parentId must reference a message in the same sequence',+ path: [index, 'parentId'],+ });+ }+ }+ });+const evalTestCaseContentSchema = z.object({category: z.string().optional(),choices: z.array(z.string()).optional(),environment: evalCaseEnvironmentSchema.optional(),expected: z.string().optional(),input: z.string(),+ messages: evalTestCaseMessagesSchema.optional(),});const log = debug('lobe-lambda-router:agent-eval');@@ -627,6 +688,7 @@ export const agentEvalRouter = router({choices: z.array(z.string()).optional(),category: z.string().optional(),environment: evalCaseEnvironmentSchema.optional(),+ messages: evalTestCaseMessagesSchema.optional(),}).optional(),evalMode: rubricTypeSchema.nullish(),diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.tsindex 2ecc3590697..3a2080b3996 100644--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts@@ -2,7 +2,14 @@ import { eq } from 'drizzle-orm';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AgentEvalBenchmarkModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';-import { agentEvalDatasets, agentEvalTestCases, topics } from '@/database/schemas';+import {+ agentEvalDatasets,+ agentEvalTestCases,+ messagePlugins,+ messages,+ threads,+ topics,+} from '@/database/schemas';import { AgentEvalRunService } from '@/server/services/agentEvalRun';import { cleanupDB, serverDB, userId } from './_setup';@@ -13,6 +20,12 @@ vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({})),}));+vi.mock('@/server/workflows/agentEvalRun', () => ({+ AgentEvalRunWorkflow: {+ triggerRunThreadTrajectory: vi.fn(),+ },+}));+beforeEach(cleanupDB);describe('AgentEvalRunService', () => {@@ -118,6 +131,159 @@ describe('AgentEvalRunService', () => {expect(await runTopicModel.findByRunId(run.id)).toHaveLength(2);});+ it('should restore case messages and use their tail as the eval-thread source', async () => {+ const benchmarkModel = new AgentEvalBenchmarkModel(serverDB, userId);+ const benchmark = await benchmarkModel.create({+ identifier: 'history-benchmark',+ isSystem: false,+ name: 'History Benchmark',+ rubrics: [],+ });+ const [dataset] = await serverDB+ .insert(agentEvalDatasets)+ .values({+ benchmarkId: benchmark.id,+ identifier: 'history-dataset',+ name: 'History Dataset',+ userId,+ })+ .returning();+ const [testCase] = await serverDB+ .insert(agentEvalTestCases)+ .values({+ content: {+ input: 'Continue from the prior answer',+ messages: [+ { content: 'Prior question', id: 'history-user', role: 'user' },+ {+ content: 'Prior answer',+ id: 'history-assistant',+ parentId: 'history-user',+ role: 'assistant',+ },+ ],+ },+ datasetId: dataset.id,+ sortOrder: 1,+ userId,+ })+ .returning();++ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ config: { k: 2 }, datasetId: dataset.id });+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ const runTopic = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);+ const restored = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, runTopic!.topicId))+ .orderBy(messages.createdAt);++ expect(restored.map((message) => message.content)).toEqual([+ 'Prior question',+ 'Prior answer',+ ]);+ expect(restored.map((message) => message.agentId)).toEqual([null, null]);++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, runTopic!.topicId));+ expect(topic.metadata?.evalHistoryTailMessageId).toBe(restored[1].id);++ await service.executeMultiThreadTrajectory({+ k: 2,+ run: { config: run.config, datasetId: run.datasetId, targetAgentId: run.targetAgentId },+ runId: run.id,+ testCaseId: testCase.id,+ });++ const attempts = await serverDB+ .select()+ .from(threads)+ .where(eq(threads.topicId, runTopic!.topicId));++ expect(attempts).toHaveLength(2);+ expect(attempts.map((thread) => thread.sourceMessageId)).toEqual([+ restored[1].id,+ restored[1].id,+ ]);+ });++ it('should restore large histories in input order and preserve interventions', async () => {+ const benchmarkModel = new AgentEvalBenchmarkModel(serverDB, userId);+ const benchmark = await benchmarkModel.create({+ identifier: 'large-history-benchmark',+ isSystem: false,+ name: 'Large History Benchmark',+ rubrics: [],+ });+ const [dataset] = await serverDB+ .insert(agentEvalDatasets)+ .values({+ benchmarkId: benchmark.id,+ identifier: 'large-history-dataset',+ name: 'Large History Dataset',+ userId,+ })+ .returning();+ const history: Array<{+ content: string;+ createdAt: number;+ pluginIntervention?: { status: 'pending' };+ role: 'assistant' | 'tool' | 'user';+ }> = Array.from({ length: 500 }, (_, index) => ({+ content: `History message ${index}`,+ createdAt: index % 3,+ role: index % 2 === 0 ? 'user' : 'assistant',+ }));+ history.push({+ content: 'Awaiting approval',+ createdAt: 0,+ pluginIntervention: { status: 'pending' },+ role: 'tool',+ });++ const [testCase] = await serverDB+ .insert(agentEvalTestCases)+ .values({+ content: { input: 'Continue the conversation', messages: history },+ datasetId: dataset.id,+ sortOrder: 1,+ userId,+ })+ .returning();++ const service = new AgentEvalRunService(serverDB, userId);+ const run = await service.createRun({ datasetId: dataset.id });+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);+ const runTopic = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);+ const restored = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, runTopic!.topicId))+ .orderBy(messages.createdAt);++ expect(restored.map((message) => message.content)).toEqual(+ history.map((message) => message.content),+ );+ expect(restored[0].parentId).toBeNull();+ expect(+ restored.slice(1).every((message, index) => message.parentId === restored[index].id),+ ).toBe(true);+ expect(+ restored.every(+ (message, index) => index === 0 || message.createdAt > restored[index - 1].createdAt,+ ),+ ).toBe(true);++ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, restored.at(-1)!.id));+ expect(plugin.intervention).toEqual({ status: 'pending' });++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, runTopic!.topicId));+ expect(topic.metadata?.evalHistoryTailMessageId).toBe(restored.at(-1)?.id);+ });+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__/trajectoryMethods.test.ts b/apps/server/src/services/agentEvalRun/__tests__/trajectoryMethods.test.tsindex e65680ed4d9..689c5439163 100644--- a/apps/server/src/services/agentEvalRun/__tests__/trajectoryMethods.test.ts+++ b/apps/server/src/services/agentEvalRun/__tests__/trajectoryMethods.test.ts@@ -1,4 +1,5 @@-import type { EvalCaseEnvironment } from '@lobechat/types';+import type { EvalCaseEnvironment, ImportedMessage } from '@lobechat/types';+import { eq } from 'drizzle-orm';import { beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';@@ -59,6 +60,7 @@ beforeEach(async () => {async function setupTrajectoryChain(opts?: {envPrompt?: string;input?: string;+ messages?: ImportedMessage[];sortOrder?: number;targetAgentId?: string | null;environment?: EvalCaseEnvironment;@@ -89,6 +91,7 @@ async function setupTrajectoryChain(opts?: {...(opts?.environment && { environment: opts.environment }),expected: '42',input: opts?.input ?? 'What is 6*7?',+ ...(opts?.messages && { messages: opts.messages }),},datasetId: dataset.id,sortOrder: opts?.sortOrder ?? 1,@@ -107,6 +110,32 @@ async function setupTrajectoryChain(opts?: {}describe('AgentEvalRunService', () => {+ describe('createRun restored history', () => {+ it('should link a child to a parent in a later message batch', async () => {+ const history: ImportedMessage[] = Array.from({ length: 501 }, (_, index) => ({+ content: `history-${index}`,+ id: `source-${index}`,+ role: 'user' as const,+ }));+ history[0]!.parentId = 'source-500';++ const { run, testCase } = await setupTrajectoryChain({ messages: history });+ const [runTopic] = await serverDB+ .select()+ .from(agentEvalRunTopics)+ .where(eq(agentEvalRunTopics.runId, run.id));+ const restored = await serverDB+ .select({ content: messages.content, id: messages.id, parentId: messages.parentId })+ .from(messages)+ .where(eq(messages.topicId, runTopic.topicId));+ const byContent = new Map(restored.map((message) => [message.content, message]));++ expect(restored).toHaveLength(history.length);+ expect(byContent.get('history-0')?.parentId).toBe(byContent.get('history-500')?.id);+ expect(runTopic.testCaseId).toBe(testCase.id);+ });+ });+// βββ loadTrajectoryData βββββββββββββββββββββββββββββββββββββββββββββdescribe('loadTrajectoryData', () => {it('should return run, testCase, and envPrompt when all exist', async () => {@@ -271,12 +300,12 @@ describe('AgentEvalRunService', () => {expect(mockExecAgent).toHaveBeenCalledWith(expect.objectContaining({- evalContext: { envPrompt: undefined, toolForwarding: environment.toolForwarding },+ evalRuntime: { toolForwarding: environment.toolForwarding },}),);});- it('should pass the dataset case id through evalContext', async () => {+ it('should pass the dataset case id through evalRuntime', async () => {const { run, testCase } = await setupTrajectoryChain();mockExecAgent.mockResolvedValue({ operationId: 'op-case-id' });@@ -294,7 +323,7 @@ describe('AgentEvalRunService', () => {});expect(mockExecAgent).toHaveBeenCalledWith(- expect.objectContaining({ evalContext: { caseId: 'case-42' } }),+ expect.objectContaining({ evalRuntime: { caseId: 'case-42' } }),);});diff --git a/apps/server/src/services/agentEvalRun/index.ts b/apps/server/src/services/agentEvalRun/index.tsindex 168bf799eb7..ac476fed634 100644--- a/apps/server/src/services/agentEvalRun/index.ts+++ b/apps/server/src/services/agentEvalRun/index.ts@@ -1,5 +1,6 @@import { LOADING_FLAT } from '@lobechat/const';-import { type LobeChatDatabase } from '@lobechat/database';+import type { LobeChatDatabase } from '@lobechat/database';+import { idGenerator } from '@lobechat/database';import { evaluate } from '@lobechat/eval-rubric';import type {EvalBenchmarkRubric,@@ -11,10 +12,13 @@ import type {EvalRunTopicResult,EvalTestCaseMetadata,EvalThreadResult,+ ImportedMessage,RubricType,+ ToolIntervention,} from '@lobechat/types';import { getActivePluginIds, RequestTrigger } from '@lobechat/types';import debug from 'debug';+import { eq, inArray, sql } from 'drizzle-orm';import {AgentEvalBenchmarkModel,@@ -27,8 +31,10 @@ import {import { MessageModel } from '@/database/models/message';import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';+import { agentEvalRunTopics, messagePlugins, messages, topics } from '@/database/schemas';import { AgentService } from '@/server/services/agent';import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';+import type { EvalRuntimeContext } from '@/server/services/agentRuntime/types';import { AiAgentService } from '@/server/services/aiAgent';import {AgentEvalRunWorkflow,@@ -40,22 +46,27 @@ import {const roundCost = (v: number): number => Math.round(v * 1e6) / 1e6;const EVAL_AGENT_RUNTIME_QSTASH_RETRIES = 5;const EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY = '10000 * (1 + retried)';+const EVAL_HISTORY_MESSAGE_BATCH_SIZE = 500;+const EVAL_HISTORY_TAIL_METADATA_KEY = 'evalHistoryTailMessageId';const RESUMABLE_THREAD_STATUSES = new Set(['error', 'timeout']);const getEvalContextParams = (envPrompt?: string,environment?: EvalCaseEnvironment,caseId?: string,-) =>- envPrompt || environment || caseId- ? {- evalContext: {- ...(caseId && { caseId }),- envPrompt,- toolForwarding: environment?.toolForwarding,- },- }- : {};+) => {+ const mergedEnvPrompt =+ [envPrompt, environment?.envPrompt].filter(Boolean).join('\n\n') || undefined;+ const evalRuntime: EvalRuntimeContext | undefined =+ caseId || environment?.toolForwarding+ ? { ...(caseId && { caseId }), toolForwarding: environment?.toolForwarding }+ : undefined;++ return {+ ...(mergedEnvPrompt && { evalContext: { envPrompt: mergedEnvPrompt } }),+ ...(evalRuntime && { evalRuntime }),+ };+};const getCaseId = (metadata?: EvalTestCaseMetadata | null) => metadata?.caseId;@@ -276,25 +287,187 @@ export class AgentEvalRunService {const testCases = await this.testCaseModel.findByDatasetId(datasetId);if (testCases.length > 0) {- const createdTopics = await this.topicModel.batchCreate(- testCases.map((tc) => ({- agentId: targetAgentId ?? undefined,- title: `[Eval Case #${(tc.sortOrder ?? 0) + 1}] ${tc.content?.input?.slice(0, 50) || 'Test Case'}...`,- trigger: RequestTrigger.Eval,+ await this.createRunTopics(run.id, targetAgentId, testCases);+ }++ return run;+ }++ private createRunTopics(+ runId: string,+ targetAgentId: string | null | undefined,+ testCases: Array<{+ content: { input: string; messages?: ImportedMessage[] };+ id: string;+ sortOrder: number | null;+ }>,+ ) {+ return this.db.transaction(async (tx) => {+ const preparedCases = testCases.map((testCase) => ({+ testCase,+ topicId: idGenerator('topics'),+ }));++ await tx.insert(topics).values(+ preparedCases.map(({ testCase, topicId }) => ({+ agentId: targetAgentId ?? null,+ id: topicId,+ title: `[Eval Case #${(testCase.sortOrder ?? 0) + 1}] ${testCase.content.input.slice(0, 50) || 'Test Case'}...`,+ trigger: 'eval' as const,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,})),);- await this.runTopicModel.batchCreate(- createdTopics.map((topic, index) => ({- runId: run.id,+ for (const { testCase, topicId } of preparedCases) {+ const history = testCase.content.messages?.filter((message) => message.role !== 'system');+ if (!history?.length) continue;++ const idMapping = new Map<string, string>();+ const hasParentInfo = history.some((message) => message.parentId != null);+ const now = Date.now();+ let previousCreatedAt = Number.NEGATIVE_INFINITY;+ const preparedMessages = history.map((message, index) => {+ const id = idGenerator('messages');+ if (message.id) idMapping.set(message.id, id);++ const timestamp =+ message.createdAt === undefined+ ? now + index+ : typeof message.createdAt === 'number'+ ? message.createdAt+ : Date.parse(message.createdAt);+ const createdAt = Math.max(+ Number.isNaN(timestamp) ? now + index : timestamp,+ previousCreatedAt + 1,+ );+ previousCreatedAt = createdAt;++ const updatedTimestamp =+ message.updatedAt === undefined+ ? createdAt+ : typeof message.updatedAt === 'number'+ ? message.updatedAt+ : Date.parse(message.updatedAt);++ return {+ createdAt,+ id,+ message,+ updatedAt: Math.max(+ Number.isNaN(updatedTimestamp) ? createdAt : updatedTimestamp,+ createdAt,+ ),+ };+ });++ const messageRows = preparedMessages.map(+ ({ createdAt, id, message, updatedAt }, index) => ({+ agentId: null,+ content: message.content,+ createdAt: new Date(createdAt),+ error: message.error ?? null,+ id,+ metadata: message.metadata ?? null,+ model: message.model ?? null,+ parentId: null,+ provider: message.provider ?? null,+ reasoning: message.reasoning ?? null,+ role: message.role,+ search: message.search ?? null,+ tools: message.tools ?? null,+ topicId,+ traceId: message.traceId ?? null,+ updatedAt: new Date(updatedAt),+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ }),+ );+ const pluginRows = preparedMessages.flatMap(({ id, message }) => {+ if (+ !message.plugin &&+ !message.pluginError &&+ !message.pluginIntervention &&+ !message.pluginState &&+ !message.tool_call_id+ ) {+ return [];+ }++ return [+ {+ apiName: message.plugin?.apiName ?? null,+ arguments: message.plugin?.arguments ?? null,+ error: message.pluginError ?? null,+ id,+ identifier: message.plugin?.identifier ?? null,+ intervention: message.pluginIntervention as ToolIntervention | undefined,+ state: message.pluginState ?? null,+ toolCallId: message.tool_call_id ?? null,+ type: message.plugin?.type ?? null,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ },+ ];+ });++ for (let index = 0; index < messageRows.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {+ await tx+ .insert(messages)+ .values(messageRows.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE));+ }+ const parentLinks = preparedMessages+ .map(({ id, message }, index) => ({+ id,+ parentId: hasParentInfo+ ? message.parentId+ ? (idMapping.get(message.parentId) ?? null)+ : null+ : (preparedMessages[index - 1]?.id ?? null),+ }))+ .filter((link): link is { id: string; parentId: string } => link.parentId !== null);+ for (let index = 0; index < parentLinks.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {+ const chunk = parentLinks.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE);+ await tx+ .update(messages)+ .set({+ parentId: sql`case ${messages.id} ${sql.join(+ chunk.map(({ id, parentId }) => sql`when ${id} then ${parentId}`),+ sql` `,+ )} end`,+ })+ .where(+ inArray(+ messages.id,+ chunk.map(({ id }) => id),+ ),+ );+ }+ for (let index = 0; index < pluginRows.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {+ await tx+ .insert(messagePlugins)+ .values(pluginRows.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE));+ }++ await tx+ .update(topics)+ .set({ metadata: { [EVAL_HISTORY_TAIL_METADATA_KEY]: preparedMessages.at(-1)!.id } })+ .where(eq(topics.id, topicId));+ }++ await tx.insert(agentEvalRunTopics).values(+ preparedCases.map(({ testCase, topicId }) => ({+ runId,status: 'pending' as const,- testCaseId: testCases[index].id,- topicId: topic.id,+ testCaseId: testCase.id,+ topicId,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,})),);- }- return run;+ return preparedCases.map(({ topicId }) => topicId);+ });}async deleteRun(id: string) {@@ -350,9 +523,9 @@ export class AgentEvalRunService {// Collect test case IDs and info for recreationconst errorTestCases = errorTopics.map((t) => ({+ content: t.testCase?.content ?? { input: '' },id: t.testCaseId,- input: t.testCase?.content?.input,- sortOrder: t.testCase?.sortOrder,+ sortOrder: t.testCase?.sortOrder ?? null,}));// 1. Delete error/terminal RunTopics (the filter above excludes active@@ -361,23 +534,8 @@ export class AgentEvalRunService {// 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 cases- const createdTopics = await this.topicModel.batchCreate(- errorTestCases.map((tc) => ({- agentId: run.targetAgentId ?? undefined,- title: `[Eval Case #${(tc.sortOrder ?? 0) + 1}] ${tc.input?.slice(0, 50) || 'Test Case'}...`,- trigger: RequestTrigger.Eval,- })),- );-- await this.runTopicModel.batchCreate(- createdTopics.map((topic, index) => ({- runId,- status: 'pending' as const,- testCaseId: errorTestCases[index].id,- topicId: topic.id,- })),- );+ // 3. Create fresh Topics, histories, and pending RunTopics together.+ await this.createRunTopics(runId, run.targetAgentId, errorTestCases);// 4. Set run status to pendingawait this.runModel.update(runId, { status: 'pending' });@@ -401,22 +559,12 @@ export class AgentEvalRunService {await this.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);// 2. Preserve the old Topic (conversation history); only re-link.- // 3. Create new Topic- const [newTopic] = await this.topicModel.batchCreate([+ // 3. Create a fresh Topic, its history, and its RunTopic together.+ await this.createRunTopics(runId, run.targetAgentId, [{- agentId: run.targetAgentId ?? undefined,- title: `[Eval Case #${(runTopic.testCase?.sortOrder ?? 0) + 1}] ${runTopic.testCase?.content?.input?.slice(0, 50) || 'Test Case'}...`,- trigger: RequestTrigger.Eval,- },- ]);-- // 4. Create new RunTopic with pending status- await this.runTopicModel.batchCreate([- {- runId,- status: 'pending' as const,- testCaseId,- topicId: newTopic.id,+ content: runTopic.testCase?.content ?? { input: '' },+ id: testCaseId,+ sortOrder: runTopic.testCase?.sortOrder ?? null,},]);@@ -1323,17 +1471,11 @@ export class AgentEvalRunService {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 topicId = (+ await this.createRunTopics(runId, run.targetAgentId, [+ { content: testCase.content, id: testCaseId, sortOrder: testCase.sortOrder },+ ])+ )[0]!;const result = await this.executeTrajectoryCore({deviceId: params.deviceId,@@ -1346,7 +1488,7 @@ export class AgentEvalRunService {sortOrder: testCase.sortOrder,},testCaseId,- topicId: topic.id,+ topicId,environment,});@@ -1375,6 +1517,10 @@ export class AgentEvalRunService {}const topicId = runTopic.topicId;+ const topic = await this.topicModel.findById(topicId);+ const historyTailMessageId = topic?.metadata?.[EVAL_HISTORY_TAIL_METADATA_KEY];+ const sourceMessageId =+ typeof historyTailMessageId === 'string' ? historyTailMessageId : undefined;// Update status from 'pending' to 'running'await this.runTopicModel.updateByRunAndTopic(runId, topicId, { status: 'running' });@@ -1383,6 +1529,7 @@ export class AgentEvalRunService {const threadIds: string[] = [];for (let i = 0; i < k; i++) {const thread = await this.threadModel.create({+ sourceMessageId,topicId,type: 'eval',});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex a20c35012b0..4b16b55c42e 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -563,6 +563,7 @@ export class AgentRuntimeService {deviceAccessPolicy,discordContext,evalContext,+ evalRuntime,enableExpertise,expertise,executionPlan,@@ -664,6 +665,7 @@ export class AgentRuntimeService {deviceSystemInfo,discordContext,evalContext,+ evalRuntime,executionPlan,// need be removedmodelRuntimeConfig,@@ -3033,13 +3035,13 @@ export class AgentRuntimeService {if (metadata?.trigger === RequestTrigger.Eval &&- metadata.evalContext?.toolForwarding &&+ metadata.evalRuntime?.toolForwarding &&!hookDispatcher.hasHook(operationId, EVAL_TOOL_FORWARDING_HOOK_ID)) {hookDispatcher.register(operationId, [createEvalToolForwardingHook(- metadata.evalContext.toolForwarding,- metadata.evalContext.caseId,+ metadata.evalRuntime.toolForwarding,+ metadata.evalRuntime.caseId,),]);}diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 7b920e3f9de..11fb0104dfc 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -9,13 +9,17 @@ import type {} from '@lobechat/context-engine';import type {ChatTopicBotContext,+ EvalToolForwardingConfig,ExpertiseContextSnapshot,UserInterventionConfig,} from '@lobechat/types';import type { SearchDecision } from 'model-bank';import type { ExecutionPlan } from '@/helpers/executionTarget';-import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';+import type {+ EvalContext,+ ServerUserMemoryConfig,+} from '@/server/modules/Mecha/ContextEngineering/types';import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/operationMarker';import type { DeviceAccessReason } from '@/server/services/aiAgent/deviceAccessPolicy';@@ -427,7 +431,10 @@ export interface OperationCreationParams {discordContext?: any;/** Whether ContextEngine may inject the operation expertise snapshot. */enableExpertise?: boolean;- evalContext?: any;+ /** Evaluation prompt data consumed by Context Engine. */+ evalContext?: EvalContext;+ /** Evaluation execution controls consumed by Agent Runtime. */+ evalRuntime?: EvalRuntimeContext;/*** Resolved execution plan for the run (see `resolveExecutionPlan`).* Forwarded into `state.metadata.executionPlan` so step-level layers (the@@ -558,3 +565,7 @@ export interface StartExecutionResult {scheduled: boolean;success: boolean;}+export interface EvalRuntimeContext {+ caseId?: string;+ toolForwarding?: EvalToolForwardingConfig;+}diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 2b8c3605bf6..ce841a3d98d 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -144,6 +144,7 @@ import type {AgentExecutionParams,AgentExecutionResult,AgentRuntimeServiceOptions,+ EvalRuntimeContext,SubAgentBridgeParams,} from '@/server/services/agentRuntime';import { AgentRuntimeService } from '@/server/services/agentRuntime';@@ -413,6 +414,8 @@ interface InternalExecAgentParams extends ExecAgentParams {ephemeralUserMessage?: string;/** Eval context for injecting environment prompts into system message */evalContext?: EvalContext;+ /** Eval execution controls, such as fixture tool forwarding. */+ evalRuntime?: EvalRuntimeContext;/*** Restrict this orchestration turn to exactly these plugins. Unlike* `additionalPluginIds`, this excludes the agent's pinned and default tools@@ -1401,6 +1404,7 @@ export class AiAgentService {cronJobId,taskId,evalContext,+ evalRuntime,maxSteps,disableLocalSystem,initialStepCount,@@ -4824,6 +4828,7 @@ export class AiAgentService {deviceAccessPolicy: { canUseDevice, reason: deviceAccessReason },discordContext,evalContext,+ evalRuntime,enableExpertise,expertise,initialContext,diff --git a/packages/context-engine/src/providers/EvalContextSystemInjector.ts b/packages/context-engine/src/providers/EvalContextSystemInjector.tsindex 3d38d976bd8..5bc0b997acc 100644--- a/packages/context-engine/src/providers/EvalContextSystemInjector.ts+++ b/packages/context-engine/src/providers/EvalContextSystemInjector.ts@@ -1,4 +1,3 @@-import type { EvalToolForwardingConfig } from '@lobechat/types';import debug from 'debug';import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';@@ -13,9 +12,7 @@ declare module '../types' {const log = debug('context-engine:provider:EvalContextSystemInjector');export interface EvalContext {- caseId?: string;envPrompt?: string;- toolForwarding?: EvalToolForwardingConfig;}export interface EvalContextSystemInjectorConfig {diff --git a/packages/types/src/eval/agentEval.ts b/packages/types/src/eval/agentEval.tsindex 32f853ec687..5fb57e19ab7 100644--- a/packages/types/src/eval/agentEval.ts+++ b/packages/types/src/eval/agentEval.ts@@ -3,6 +3,8 @@* Defines test cases, run configurations, and metadata for agent evaluation*/+import type { ImportedMessage } from '../export';+export type { RubricType as EvalMode } from './rubric';export interface EvalConfig {@@ -22,6 +24,8 @@ export interface EvalToolForwardingTarget {/** Per-test-case runtime configuration used only by eval trajectories. */export interface EvalCaseEnvironment {+ /** Case-specific system context appended after the dataset eval prompt. */+ envPrompt?: string;toolForwarding?: EvalToolForwardingConfig;}@@ -34,6 +38,8 @@ export interface EvalTestCaseContent {environment?: EvalCaseEnvironment;expected?: string;input: string;+ /** Conversation history restored into the eval topic before `input` is sent. */+ messages?: ImportedMessage[];}/**diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex cb66c3b014e..312f90ce24b 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -118,6 +118,8 @@ export interface ChatTopicMetadata {summarizedAt: string;version: number;};+ /** Restored-history tail used as the source message for eval attempt threads. */+ evalHistoryTailMessageId?: string;bot?: ChatTopicBotContext;boundDeviceId?: string;cronJobId?: string;