π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(eval): + resume agent run (#13412)
Rylan Cai9264a9c66d22
diff --git a/packages/database/src/models/agentEval/runTopic.ts b/packages/database/src/models/agentEval/runTopic.tsindex a18a01ede07..abc28609c5f 100644--- a/packages/database/src/models/agentEval/runTopic.ts+++ b/packages/database/src/models/agentEval/runTopic.ts@@ -195,7 +195,10 @@ export class AgentEvalRunTopicModel {updateByRunAndTopic = async (runId: string,topicId: string,- value: Pick<Partial<AgentEvalRunTopicItem>, 'evalResult' | 'passed' | 'score' | 'status'>,+ value: Pick<+ Partial<AgentEvalRunTopicItem>,+ 'createdAt' | 'evalResult' | 'passed' | 'score' | 'status'+ >,) => {const [result] = await this.db.update(agentEvalRunTopics)diff --git a/src/app/(backend)/api/workflows/agent-eval-run/resume-agent-trajectory/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/resume-agent-trajectory/route.tsnew file mode 100644index 00000000000..97c0faacc46--- /dev/null+++ b/src/app/(backend)/api/workflows/agent-eval-run/resume-agent-trajectory/route.ts@@ -0,0 +1,53 @@+import { serve } from '@upstash/workflow/nextjs';+import debug from 'debug';++import { getServerDB } from '@/database/server';+import { qstashClient } from '@/libs/qstash';+import { AgentEvalRunService } from '@/server/services/agentEvalRun';+import type { ResumeAgentTrajectoryPayload } from '@/server/workflows/agentEvalRun';++const log = debug('lobe-server:workflows:resume-agent-trajectory');++export const { POST } = serve<ResumeAgentTrajectoryPayload>(+ async (context) => {+ const payload = context.requestPayload ?? {};+ const { runId, testCaseId, topicId, userId } = payload;++ log('Starting: runId=%s testCaseId=%s', runId, testCaseId);++ if (+ !runId ||+ !testCaseId ||+ !topicId ||+ !userId ||+ !payload.parentMessageId ||+ !payload.appContext?.topicId+ ) {+ return { error: 'Missing required parameters', success: false };+ }++ const db = await getServerDB();+ const service = new AgentEvalRunService(db, userId);++ await context.run('resume-agent-trajectory:exec-agent', () =>+ service.executeResumedTrajectory(payload),+ );++ log(+ 'Resumed agent started (async): runId=%s testCaseId=%s topicId=%s',+ runId,+ testCaseId,+ topicId,+ );++ return { success: true, testCaseId, topicId };+ },+ {+ flowControl: {+ key: 'agent-eval-run.resume-agent-trajectory',+ parallelism: 500,+ ratePerSecond: 20,+ },+ qstashClient,+ },+);diff --git a/src/app/(backend)/api/workflows/agent-eval-run/resume-thread-trajectory/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/resume-thread-trajectory/route.tsnew file mode 100644index 00000000000..f66b5b17ca5--- /dev/null+++ b/src/app/(backend)/api/workflows/agent-eval-run/resume-thread-trajectory/route.ts@@ -0,0 +1,55 @@+import { serve } from '@upstash/workflow/nextjs';+import debug from 'debug';++import { getServerDB } from '@/database/server';+import { qstashClient } from '@/libs/qstash';+import { AgentEvalRunService } from '@/server/services/agentEvalRun';+import type { ResumeThreadTrajectoryPayload } from '@/server/workflows/agentEvalRun';++const log = debug('lobe-server:workflows:resume-thread-trajectory');++export const { POST } = serve<ResumeThreadTrajectoryPayload>(+ async (context) => {+ const payload = context.requestPayload ?? {};+ const { runId, testCaseId, threadId, topicId, userId } = payload;++ log('Starting: runId=%s testCaseId=%s threadId=%s', runId, testCaseId, threadId);++ if (+ !runId ||+ !testCaseId ||+ !threadId ||+ !topicId ||+ !userId ||+ !payload.parentMessageId ||+ !payload.appContext?.topicId ||+ !payload.appContext?.threadId+ ) {+ return { error: 'Missing required parameters', success: false };+ }++ const db = await getServerDB();+ const service = new AgentEvalRunService(db, userId);++ await context.run('resume-thread-trajectory:exec-agent', () =>+ service.executeResumedThreadTrajectory(payload),+ );++ log(+ 'Resumed thread agent started: runId=%s testCaseId=%s threadId=%s',+ runId,+ testCaseId,+ threadId,+ );++ return { success: true, testCaseId, threadId, topicId };+ },+ {+ flowControl: {+ key: 'agent-eval-run.resume-thread-trajectory',+ parallelism: 500,+ ratePerSecond: 20,+ },+ qstashClient,+ },+);diff --git a/src/locales/default/eval.ts b/src/locales/default/eval.tsindex 99823eb2c6d..02af840e9ba 100644--- a/src/locales/default/eval.ts+++ b/src/locales/default/eval.ts@@ -199,9 +199,15 @@ export default {'run.actions.delete': 'Delete','run.actions.delete.confirm': 'Are you sure you want to delete this evaluation?','run.actions.retryCase': 'Retry',+ 'run.actions.resumeCase': 'Resume','run.actions.retryErrors': 'Retry Errors','run.actions.retryErrors.confirm':'This will re-run all error and timeout cases. Passed and failed cases will not be affected.',+ 'run.actions.batchResume': 'Batch Resume',+ 'run.actions.batchResume.modal.title': 'Batch Resume Cases',+ 'run.actions.batchResume.modal.confirm': 'Resume Selected',+ 'run.actions.batchResume.modal.selectAll': 'Select All',+ 'run.actions.batchResume.modal.selected': '{{count}} selected','run.actions.run': 'Run','run.edit.error': 'Failed to update evaluation','run.edit.success': 'Evaluation updated successfully',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 8a676225120..d41630dce83 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@@ -12,6 +12,8 @@ import CaseHeader from './features/CaseBanner';import ChatArea from './features/ChatArea';import InfoSidebar from './features/InfoSidebar';+const POLLING_INTERVAL = 3000;+const CaseDetail = memo(() => {const { benchmarkId, runId, caseId } = useParams<{benchmarkId: string;@@ -22,10 +24,12 @@ const CaseDetail = memo(() => {const navigate = useNavigate();const useFetchRunDetail = useEvalStore((s) => s.useFetchRunDetail);const useFetchRunResults = useEvalStore((s) => s.useFetchRunResults);+ const isActive = useEvalStore(runSelectors.isRunActive(runId!));// Ensure data is loaded even when navigating directly to this URL- useFetchRunDetail(runId!);- useFetchRunResults(runId!);+ const pollingConfig = { refreshInterval: isActive ? POLLING_INTERVAL : 0 };+ useFetchRunDetail(runId!, pollingConfig);+ useFetchRunResults(runId!, pollingConfig);const runDetail = useEvalStore(runSelectors.getRunDetailById(runId!));const runResults = useEvalStore(runSelectors.getRunResultsById(runId!));diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/index.tsxnew file mode 100644index 00000000000..f4aeb11a799--- /dev/null+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/index.tsx@@ -0,0 +1,192 @@+'use client';++import { Badge, Button, Checkbox, Modal, Skeleton, Table, Tag, Tooltip, Typography } from 'antd';+import type { ColumnsType } from 'antd/es/table';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { agentEvalService } from '@/services/agentEval';++type ResumableCase = Awaited<ReturnType<typeof agentEvalService.getResumableCases>>[number];++interface BatchResumeModalProps {+ onClose: () => void;+ onConfirm: (targets: Array<{ testCaseId: string; threadId?: string }>) => Promise<void>;+ open: boolean;+ runId: string;+}++const StatusLabel = memo<{ status: string | null | undefined }>(({ status }) => {+ const { t } = useTranslation('eval');+ if (status === 'error') return <Badge color="orange" text={t('table.filter.error')} />;+ if (status === 'timeout') return <Badge color="orange" text={t('run.status.timeout')} />;+ return <Tag>{status}</Tag>;+});++const BatchResumeModal = memo<BatchResumeModalProps>(({ open, onClose, onConfirm, runId }) => {+ const { t } = useTranslation('eval');+ const { t: tc } = useTranslation('common');+ const [cases, setCases] = useState<ResumableCase[]>([]);+ const [loading, setLoading] = useState(false);+ const [confirming, setConfirming] = useState(false);+ const [selectedIds, setSelectedIds] = useState<string[]>([]);+ const [pageSize, setPageSize] = useState(10);++ // Fetch when modal opens+ useEffect(() => {+ if (!open) return;+ setSelectedIds([]);+ setLoading(true);+ agentEvalService+ .getResumableCases(runId)+ .then((data) => {+ setCases(data);+ // Pre-select all resumable ones+ setSelectedIds(data.filter((c) => c.canResume).map((c) => c.testCaseId));+ })+ .finally(() => setLoading(false));+ }, [open, runId]);++ const resumableCases = useMemo(() => cases.filter((c) => c.canResume), [cases]);+ const allSelected = selectedIds.length === resumableCases.length && resumableCases.length > 0;+ const indeterminate = selectedIds.length > 0 && selectedIds.length < resumableCases.length;++ const handleToggleAll = useCallback(+ (checked: boolean) => {+ setSelectedIds(checked ? resumableCases.map((c) => c.testCaseId) : []);+ },+ [resumableCases],+ );++ const handleToggleRow = useCallback((testCaseId: string, checked: boolean) => {+ setSelectedIds((prev) =>+ checked ? [...prev, testCaseId] : prev.filter((id) => id !== testCaseId),+ );+ }, []);++ const columns: ColumnsType<ResumableCase> = useMemo(+ () => [+ {+ key: 'select',+ render: (_: any, record: ResumableCase) => (+ <Tooltip title={record.canResume ? undefined : record.reason}>+ <Checkbox+ checked={selectedIds.includes(record.testCaseId)}+ disabled={!record.canResume}+ onChange={(e) => handleToggleRow(record.testCaseId, e.target.checked)}+ />+ </Tooltip>+ ),+ title: (+ <Checkbox+ checked={allSelected}+ disabled={resumableCases.length === 0}+ indeterminate={indeterminate}+ onChange={(e) => handleToggleAll(e.target.checked)}+ />+ ),+ width: 48,+ },+ {+ key: 'index',+ render: (_: any, record: ResumableCase) => (+ <span+ style={{+ color: 'var(--ant-color-text-tertiary)',+ fontFamily: 'monospace',+ fontSize: 12,+ }}+ >+ {record.sortOrder ?? '-'}+ </span>+ ),+ title: '#',+ width: 48,+ },+ {+ key: 'input',+ render: (_: any, record: ResumableCase) => (+ <Typography.Paragraph+ ellipsis={{ expandable: true, rows: 2, symbol: '...' }}+ style={{ margin: 0 }}+ >+ {record.input}+ </Typography.Paragraph>+ ),+ title: t('table.columns.input'),+ },+ {+ key: 'status',+ render: (_: any, record: ResumableCase) => (+ <Tooltip title={record.canResume ? undefined : record.reason}>+ <StatusLabel status={record.resumeStatus} />+ </Tooltip>+ ),+ title: t('table.columns.status'),+ width: 110,+ },+ ],+ [t, selectedIds, allSelected, indeterminate, resumableCases, handleToggleRow, handleToggleAll],+ );++ const handleConfirm = async () => {+ if (selectedIds.length === 0) return;+ setConfirming(true);+ try {+ await onConfirm(+ cases+ .filter((item) => selectedIds.includes(item.testCaseId))+ .map((item) => ({ testCaseId: item.testCaseId, threadId: item.threadId })),+ );+ onClose();+ } finally {+ setConfirming(false);+ }+ };++ return (+ <Modal+ destroyOnHidden+ open={open}+ title={t('run.actions.batchResume.modal.title')}+ width={700}+ footer={[+ <Button key="cancel" onClick={onClose}>+ {tc('cancel')}+ </Button>,+ <Button+ disabled={selectedIds.length === 0}+ key="confirm"+ loading={confirming}+ type="primary"+ onClick={handleConfirm}+ >+ {t('run.actions.batchResume.modal.confirm')} ({selectedIds.length})+ </Button>,+ ]}+ onCancel={onClose}+ >+ {loading ? (+ <Skeleton active paragraph={{ rows: 4 }} />+ ) : (+ <Table+ columns={columns}+ dataSource={cases}+ rowKey="testCaseId"+ scroll={{ y: 400 }}+ size="small"+ style={{ minHeight: 300 }}+ pagination={{+ pageSize,+ showSizeChanger: true,+ size: 'small',+ onShowSizeChange: (_, size) => setPageSize(size),+ }}+ />+ )}+ </Modal>+ );+});++export { BatchResumeModal };+export default BatchResumeModal;diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsxindex bda0c9e8bee..437688c6bd0 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/CaseResultsTable/index.tsx@@ -6,11 +6,13 @@ import { ActionIcon, Flexbox, Icon, Tag } from '@lobehub/ui';import { Badge, Input, Select, Table, Tooltip } from 'antd';import type { ColumnsType } from 'antd/es/table';import { createStaticStyles, cssVar } from 'antd-style';-import { Footprints, RotateCcw } from 'lucide-react';+import { Footprints, Play, RotateCcw } from 'lucide-react';import { memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link } from 'react-router-dom';+import { getResumeTarget } from '../resumeTarget';+const styles = createStaticStyles(({ css, cssVar }) => ({caseLink: css`color: inherit;@@ -47,6 +49,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({interface CaseResultsTableProps {benchmarkId: string;k?: number;+ onResumeCase?: (testCaseId: string, threadId?: string) => Promise<void>;onRetryCase?: (testCaseId: string) => Promise<void>;results: any[];runId: string;@@ -110,7 +113,11 @@ const ThreadDots = memo<{ threads: EvalThreadResult[] }>(({ threads }) => ({threads.map((thread) => {let color: string = cssVar.colorTextTertiary;- if (thread.passed === true) {+ if (thread.status === 'running') {+ color = cssVar.colorPrimary;+ } else if (thread.status === 'error') {+ color = cssVar.colorError;+ } else if (thread.passed === true) {color = cssVar.colorSuccess;} else if (thread.passed === false) {color = cssVar.colorError;@@ -126,15 +133,19 @@ const ThreadDots = memo<{ threads: EvalThreadResult[] }>(({ threads }) => (const label = thread.error? 'error'- : thread.passed === true- ? 'passed'- : thread.passed === false && thread.status !== 'completed'- ? 'failed'- : thread.status === 'external'- ? 'Awaiting for external evaluation'- : thread.status === 'completed'- ? 'completed'- : 'pending';+ : thread.status === 'error'+ ? 'error'+ : thread.status === 'running'+ ? 'running'+ : thread.passed === true+ ? 'passed'+ : thread.passed === false && thread.status !== 'completed'+ ? 'failed'+ : thread.status === 'external'+ ? 'Awaiting for external evaluation'+ : thread.status === 'completed'+ ? 'completed'+ : 'pending';return (<Tooltip key={thread.threadId} title={label}>@@ -177,17 +188,18 @@ const RunningTimer = memo<{ startTime: string }>(({ startTime }) => {const RETRYABLE_STATUSES = new Set(['error', 'failed', 'timeout']);const FINISHED_RUN_STATUSES = new Set(['completed', 'failed', 'aborted']);-const CaseResultsTable = memo<CaseResultsTableProps>(- ({ results, benchmarkId, runId, k = 1, onRetryCase, runStatus }) => {+ ({ results, benchmarkId, runId, k = 1, onRetryCase, onResumeCase, runStatus }) => {const { t } = useTranslation('eval');const [searchText, setSearchText] = useState('');const [statusFilter, setStatusFilter] = useState<string>('all');const [pageSize, setPageSize] = useState(20);const [retryingCaseId, setRetryingCaseId] = useState<string | null>(null);+ const [resumingCaseId, setResumingCaseId] = useState<string | null>(null);const isMultiK = k > 1;- const canRetryCase = onRetryCase && runStatus && FINISHED_RUN_STATUSES.has(runStatus);+ const canRetryCase = !!onRetryCase && !!runStatus && FINISHED_RUN_STATUSES.has(runStatus);+ const canResumeCase = !!onResumeCase;const filteredResults = useMemo(() => {let filtered = results;@@ -381,37 +393,74 @@ const CaseResultsTable = memo<CaseResultsTableProps>(});}- if (canRetryCase) {+ if (canRetryCase || canResumeCase) {cols.push({key: 'actions',render: (_: any, record: any) => {- if (!RETRYABLE_STATUSES.has(record.status)) return null;+ const showRetry = canRetryCase && RETRYABLE_STATUSES.has(record.status);+ const resumeTarget = getResumeTarget(record, k);+ const showResume = canResumeCase && !!resumeTarget;+ if (!showRetry && !showResume) return null;const isRetrying = retryingCaseId === record.testCaseId;+ const isResuming = resumingCaseId === record.testCaseId;return (- <Tooltip title={t('run.actions.retryCase')}>- <ActionIcon- icon={RotateCcw}- loading={isRetrying}- size="small"- onClick={async () => {- setRetryingCaseId(record.testCaseId);- try {- await onRetryCase!(record.testCaseId);- } finally {- setRetryingCaseId(null);- }- }}- />- </Tooltip>+ <Flexbox horizontal gap={4}>+ {showRetry && (+ <Tooltip title={t('run.actions.retryCase')}>+ <ActionIcon+ icon={RotateCcw}+ loading={isRetrying}+ size="small"+ onClick={async () => {+ setRetryingCaseId(record.testCaseId);+ try {+ await onRetryCase!(record.testCaseId);+ } finally {+ setRetryingCaseId(null);+ }+ }}+ />+ </Tooltip>+ )}+ {showResume && (+ <Tooltip title={t('run.actions.resumeCase')}>+ <ActionIcon+ icon={Play}+ loading={isResuming}+ size="small"+ onClick={async () => {+ setResumingCaseId(record.testCaseId);+ try {+ await onResumeCase!(record.testCaseId, resumeTarget?.threadId);+ } finally {+ setResumingCaseId(null);+ }+ }}+ />+ </Tooltip>+ )}+ </Flexbox>);},title: '',- width: 48,+ width: 80,});}return cols;- }, [benchmarkId, runId, t, isMultiK, k, canRetryCase, retryingCaseId, onRetryCase]);+ }, [+ benchmarkId,+ runId,+ t,+ isMultiK,+ k,+ canRetryCase,+ canResumeCase,+ retryingCaseId,+ resumingCaseId,+ onRetryCase,+ onResumeCase,+ ]);return (<Flexbox gap={0}>diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/resumeTarget.ts b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/resumeTarget.tsnew file mode 100644index 00000000000..a82309cbf58--- /dev/null+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/resumeTarget.ts@@ -0,0 +1,32 @@+import type { EvalRunTopicResult } from '@lobechat/types';++const RESUMABLE_STATUSES = new Set(['error', 'timeout']);++interface RunResultRecord {+ evalResult?: EvalRunTopicResult | null;+ status?: string | null;+}++export interface ResumeTarget {+ resumeStatus?: 'error' | 'timeout';+ threadId?: string;+}++export const getResumeTarget = (result: RunResultRecord, k: number): ResumeTarget | undefined => {+ if (k <= 1) {+ if (!RESUMABLE_STATUSES.has(result.status ?? '')) return undefined;++ return { resumeStatus: result.status as 'error' | 'timeout' };+ }++ const thread = result.evalResult?.threads?.find((item) =>+ RESUMABLE_STATUSES.has(item.status ?? ''),+ );++ if (!thread?.status) return undefined;++ return {+ resumeStatus: thread.status as 'error' | 'timeout',+ threadId: thread.threadId,+ };+};diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsxindex e9842d722c9..e8e094816a4 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx@@ -2,17 +2,19 @@import { Flexbox } from '@lobehub/ui';import { App, Button, Card, Progress, Typography } from 'antd';-import { RotateCcw } from 'lucide-react';+import { Play, RotateCcw } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useParams } from 'react-router-dom';import { runSelectors, useEvalStore } from '@/store/eval';+import { BatchResumeModal } from './features/BatchResumeModal';import CaseResultsTable from './features/CaseResultsTable';import BenchmarkCharts from './features/Charts/BenchmarkCharts';import IdleState from './features/IdleState';import PendingState from './features/PendingState';+import { getResumeTarget } from './features/resumeTarget';import RunHeader from './features/RunHeader';import RunningState from './features/RunningState';import StatsCards from './features/StatsCards';@@ -27,10 +29,13 @@ const RunDetail = memo(() => {const useFetchRunResults = useEvalStore((s) => s.useFetchRunResults);const retryRunErrors = useEvalStore((s) => s.retryRunErrors);const retryRunCase = useEvalStore((s) => s.retryRunCase);+ const resumeRunCase = useEvalStore((s) => s.resumeRunCase);+ const batchResumeRunCases = useEvalStore((s) => s.batchResumeRunCases);const runDetail = useEvalStore(runSelectors.getRunDetailById(runId!));const runResults = useEvalStore(runSelectors.getRunResultsById(runId!));const isActive = useEvalStore(runSelectors.isRunActive(runId!));const [retrying, setRetrying] = useState(false);+ const [batchResumeOpen, setBatchResumeOpen] = useState(false);const pollingConfig = { refreshInterval: isActive ? POLLING_INTERVAL : 0 };@@ -53,6 +58,11 @@ const RunDetail = memo(() => {const errorCount = (metrics?.errorCases ?? 0) + (metrics?.timeoutCases ?? 0);const canRetry = isFinished && errorCount > 0;+ const k = runDetail.config?.k ?? 1;+ const canBatchResume = (runResults?.results ?? []).some(+ (result: any) => !!getResumeTarget(result, k),+ );+return (<Flexbox gap={24} padding={24} style={{ margin: '0 auto', maxWidth: 1440, width: '100%' }}><RunHeader@@ -118,44 +128,61 @@ const RunDetail = memo(() => {<Cardstyles={{ body: { padding: 0 }, header: { padding: '12px 20px' } }}extra={- showProgress ? (+ showProgress || canRetry || canBatchResume ? (<Flexbox horizontal align="center" gap={8}>- <Typography.Text style={{ fontSize: 12, whiteSpace: 'nowrap' }} type="secondary">- {completedCases}/{totalCases} {t('run.detail.progressCases')}- </Typography.Text>- <Progress- percent={progress}- showInfo={false}- size="small"- status={isActive ? 'active' : undefined}- style={{ margin: 0, width: 120 }}- />- <Typography.Text style={{ fontSize: 12 }} type="secondary">- {progress}%- </Typography.Text>+ {showProgress && (+ <>+ <Typography.Text+ style={{ fontSize: 12, whiteSpace: 'nowrap' }}+ type="secondary"+ >+ {completedCases}/{totalCases} {t('run.detail.progressCases')}+ </Typography.Text>+ <Progress+ percent={progress}+ showInfo={false}+ size="small"+ status={isActive ? 'active' : undefined}+ style={{ margin: 0, width: 120 }}+ />+ <Typography.Text style={{ fontSize: 12 }} type="secondary">+ {progress}%+ </Typography.Text>+ </>+ )}+ {canBatchResume && (+ <Button+ icon={<Play size={14} />}+ size="small"+ onClick={() => setBatchResumeOpen(true)}+ >+ {t('run.actions.batchResume')}+ </Button>+ )}+ {canRetry && (+ <Button+ icon={<RotateCcw size={14} />}+ loading={retrying}+ size="small"+ onClick={() => {+ modal.confirm({+ content: t('run.actions.retryErrors.confirm'),+ onOk: async () => {+ setRetrying(true);+ try {+ await retryRunErrors(runId!);+ } finally {+ setRetrying(false);+ }+ },+ title: t('run.actions.retryErrors'),+ });+ }}+ >+ {t('run.actions.retryErrors')}+ </Button>+ )}</Flexbox>- ) : canRetry ? (- <Button- icon={<RotateCcw size={14} />}- loading={retrying}- size="small"- onClick={() => {- modal.confirm({- content: t('run.actions.retryErrors.confirm'),- onOk: async () => {- setRetrying(true);- try {- await retryRunErrors(runId!);- } finally {- setRetrying(false);- }- },- title: t('run.actions.retryErrors'),- });- }}- >- {t('run.actions.retryErrors')}- </Button>) : undefined}title={@@ -166,14 +193,22 @@ const RunDetail = memo(() => {><CaseResultsTablebenchmarkId={benchmarkId!}- k={runDetail.config?.k ?? 1}+ k={k}results={runResults.results}runId={runId!}runStatus={runDetail.status}+ onResumeCase={(testCaseId, threadId) => resumeRunCase(runId!, testCaseId, threadId)}onRetryCase={(testCaseId) => retryRunCase(runId!, testCaseId)}/></Card>)}++ <BatchResumeModal+ open={batchResumeOpen}+ runId={runId!}+ onClose={() => setBatchResumeOpen(false)}+ onConfirm={(targets) => batchResumeRunCases(runId!, targets)}+ /></Flexbox>);});diff --git a/src/server/routers/lambda/agentEval.ts b/src/server/routers/lambda/agentEval.tsindex dbbc2ad13c4..02ee394ee5e 100644--- a/src/server/routers/lambda/agentEval.ts+++ b/src/server/routers/lambda/agentEval.ts@@ -1,5 +1,6 @@import { parseDataset } from '@lobechat/eval-dataset-parser';import { TRPCError } from '@trpc/server';+import debug from 'debug';import { z } from 'zod';import {@@ -49,6 +50,8 @@ const evalRunInputConfigSchema = z.object({.optional(),});+const log = debug('lobe-lambda-router:agent-eval');+const agentEvalProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -809,6 +812,55 @@ export const agentEvalRouter = router({return { runId: input.runId, success: true, testCaseId: input.testCaseId };}),+ resumeRunCase: agentEvalProcedure+ .input(z.object({ runId: z.string(), testCaseId: z.string(), threadId: z.string().optional() }))+ .mutation(async ({ input, ctx }) => {+ log(+ 'resumeRunCase: runId=%s testCaseId=%s threadId=%s',+ input.runId,+ input.testCaseId,+ input.threadId,+ );+ const result = await ctx.runService.resumeTrajectory({+ runId: input.runId,+ testCaseId: input.testCaseId,+ threadId: input.threadId,+ });+ log('resumeRunCase: result %O', result);+ return result;+ }),++ batchResumeRunCases: agentEvalProcedure+ .input(+ z.object({+ runId: z.string(),+ targets: z.array(z.object({ testCaseId: z.string(), threadId: z.string().optional() })),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ log('batchResumeRunCases: runId=%s count=%d', input.runId, input.targets.length);+ const results = await Promise.allSettled(+ input.targets.map((target) =>+ ctx.runService.resumeTrajectory({+ runId: input.runId,+ testCaseId: target.testCaseId,+ threadId: target.threadId,+ }),+ ),+ );+ const succeeded = results.filter((r) => r.status === 'fulfilled').length;+ const failed = results.filter((r) => r.status === 'rejected').length;+ log('batchResumeRunCases: succeeded=%d failed=%d', succeeded, failed);+ return { failed, succeeded, total: input.targets.length };+ }),++ getResumableCases: agentEvalProcedure+ .input(z.object({ runId: z.string() }))+ .query(async ({ input, ctx }) => {+ log('getResumableCases: runId=%s', input.runId);+ return ctx.runService.getResumableCases(input.runId);+ }),+/*** Get real-time progress of a running evaluation*/diff --git a/src/server/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts b/src/server/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.tsnew file mode 100644index 00000000000..d18553df1b6--- /dev/null+++ b/src/server/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts@@ -0,0 +1,656 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';+import { ThreadModel } from '@/database/models/thread';+import { messages, topics } from '@/database/schemas';+import { AgentEvalRunService } from '@/server/services/agentEvalRun';+import type * as AgentEvalRunWorkflowModule from '@/server/workflows/agentEvalRun';+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';++import { cleanupDB, serverDB, setupEvalChain, userId } from './_setup';++const mockExecAgent = vi.fn();++vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(() => ({+ execAgent: mockExecAgent,+ })),+}));++vi.mock('@/server/workflows/agentEvalRun', async (importOriginal) => {+ const actual = (await importOriginal()) as typeof AgentEvalRunWorkflowModule;++ return {+ ...actual,+ AgentEvalRunWorkflow: {+ ...actual.AgentEvalRunWorkflow,+ triggerResumeAgentTrajectory: vi.fn().mockResolvedValue({}),+ triggerResumeThreadTrajectory: vi.fn().mockResolvedValue({}),+ },+ };+});++vi.mock('@/envs/app', () => ({+ appEnv: { APP_URL: 'https://test.example.com' },+}));++vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ interruptOperation: vi.fn().mockResolvedValue(true),+ })),+}));++const markTopicTimeout = async (params: { runId: string; testCaseId: string; topicId: string }) => {+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);++ await runTopicModel.updateByRunAndTopic(params.runId, params.topicId, {+ evalResult: { completionReason: 'timeout', duration: 1000, rubricScores: [] },+ passed: false,+ score: 0,+ status: 'timeout',+ });++ return runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);+};++beforeEach(async () => {+ await cleanupDB();+ mockExecAgent.mockReset();+ vi.mocked(AgentEvalRunWorkflow.triggerResumeAgentTrajectory).mockReset();+ vi.mocked(AgentEvalRunWorkflow.triggerResumeThreadTrajectory).mockReset();+});++describe('AgentEvalRunService', () => {+ describe('canResumeTrajectory', () => {+ it.each(['running', 'failed', 'aborted'] as const)(+ 'should allow timeout trajectory resume when run status is %s',+ async (status) => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, { status });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ await expect(+ new AgentEvalRunService(serverDB, userId).canResumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ }),+ ).resolves.toEqual({ canResume: true });+ },+ );++ it('should reject completed runs', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'completed' });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ await expect(+ new AgentEvalRunService(serverDB, userId).canResumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ }),+ ).resolves.toEqual({+ canResume: false,+ reason: 'Trajectory is not resumable',+ });+ });++ it('should reject trajectories that are neither timeout nor error', async () => {+ const { run, testCase } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'failed' });++ await expect(+ new AgentEvalRunService(serverDB, userId).canResumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ }),+ ).resolves.toEqual({+ canResume: false,+ reason: 'Trajectory is not resumable',+ });+ });++ it('should require threadId for pass@k resume', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, {+ config: { k: 2 },+ status: 'failed',+ });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ await expect(+ new AgentEvalRunService(serverDB, userId).canResumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ }),+ ).resolves.toEqual({+ canResume: false,+ reason: 'Invalid resume target',+ });+ });++ it('should reject threads outside the target eval trajectory', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, {+ config: { k: 2 },+ status: 'failed',+ });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ const [{ id: otherTopicId }] = await serverDB+ .insert(topics)+ .values({ mode: 'test', title: 'Other Eval Topic', trigger: 'eval', userId })+ .returning({ id: topics.id });+ const otherThread = await new ThreadModel(serverDB, userId).create({+ topicId: otherTopicId,+ type: 'eval',+ });++ await expect(+ new AgentEvalRunService(serverDB, userId).canResumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ threadId: otherThread!.id,+ }),+ ).resolves.toEqual({+ canResume: false,+ reason: 'Invalid resume target',+ });+ });++ it('should allow pass@k resume when the case passed but a thread errored', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, {+ config: { k: 2 },+ status: 'failed',+ });++ const threadModel = new ThreadModel(serverDB, userId);+ const errorThread = await threadModel.create({ topicId: topic.id, type: 'eval' });+ const passedThread = await threadModel.create({ topicId: topic.id, type: 'eval' });++ await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {+ evalResult: {+ passAllK: false,+ passAtK: true,+ threads: [+ { status: 'error', threadId: errorThread!.id },+ { passed: true, status: 'passed', threadId: passedThread!.id },+ ],+ },+ passed: true,+ score: 1,+ status: 'passed',+ });++ await expect(+ new AgentEvalRunService(serverDB, userId).canResumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ threadId: errorThread!.id,+ }),+ ).resolves.toEqual({ canResume: true });+ });++ it('should enforce maxSteps using the target thread history for pass@k resume', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, {+ config: { k: 2, maxSteps: 5 },+ status: 'failed',+ });++ const threadModel = new ThreadModel(serverDB, userId);+ const errorThread = await threadModel.create({ topicId: topic.id, type: 'eval' });+ const passedThread = await threadModel.create({ topicId: topic.id, type: 'eval' });++ await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {+ evalResult: {+ passAllK: false,+ passAtK: true,+ steps: 3,+ threads: [+ { status: 'error', threadId: errorThread!.id },+ { passed: true, status: 'passed', threadId: passedThread!.id },+ ],+ },+ passed: true,+ score: 1,+ status: 'passed',+ });++ await threadModel.update(errorThread!.id, {+ metadata: {+ completedAt: new Date('2026-03-30T00:00:00.000Z').toISOString(),+ status: 'error',+ steps: 5,+ testCaseId: testCase.id,+ },+ } as any);++ await expect(+ new AgentEvalRunService(serverDB, userId).canResumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ threadId: errorThread!.id,+ }),+ ).resolves.toEqual({+ canResume: false,+ reason: 'Resume limit reached',+ });+ });+ });++ describe('getResumableCases', () => {+ it('should include pass@k cases that have resumable threads', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, {+ config: { k: 2 },+ status: 'failed',+ });++ const threadModel = new ThreadModel(serverDB, userId);+ const errorThread = await threadModel.create({ topicId: topic.id, type: 'eval' });+ const passedThread = await threadModel.create({ topicId: topic.id, type: 'eval' });++ await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {+ evalResult: {+ passAllK: false,+ passAtK: true,+ threads: [+ { status: 'error', threadId: errorThread!.id },+ { passed: true, status: 'passed', threadId: passedThread!.id },+ ],+ },+ passed: true,+ score: 1,+ status: 'passed',+ });++ await expect(+ new AgentEvalRunService(serverDB, userId).getResumableCases(run.id),+ ).resolves.toEqual([+ {+ canResume: true,+ caseStatus: 'passed',+ input: testCase.content.input,+ reason: undefined,+ resumeStatus: 'error',+ sortOrder: testCase.sortOrder,+ testCaseId: testCase.id,+ threadId: errorThread!.id,+ },+ ]);+ });+ });++ describe('resumeTrajectory', () => {+ it('should only trigger workflow for a timed-out pass@1 trajectory without mutating state', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ const [userMessage] = await serverDB+ .insert(messages)+ .values({+ content: 'What is 6*7?',+ role: 'user',+ topicId: topic.id,+ userId,+ })+ .returning({ id: messages.id });++ await serverDB.insert(messages).values({+ content: '...',+ parentId: userMessage.id,+ role: 'assistant',+ topicId: topic.id,+ userId,+ });++ const runModel = new AgentEvalRunModel(serverDB, userId);+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);++ await runModel.update(run.id, {+ metrics: {+ averageScore: 0,+ completedCases: 1,+ failedCases: 0,+ passRate: 0,+ passedCases: 0,+ timeoutCases: 1,+ totalCases: 1,+ },+ status: 'failed',+ });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ const service = new AgentEvalRunService(serverDB, userId);+ const result = await service.resumeTrajectory({ runId: run.id, testCaseId: testCase.id });++ expect(result).toEqual({+ mode: 'single',+ runId: run.id,+ testCaseId: testCase.id,+ threadId: undefined,+ topicId: topic.id,+ triggered: true,+ });++ expect(AgentEvalRunWorkflow.triggerResumeAgentTrajectory).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: { topicId: topic.id },+ envPrompt: undefined,+ maxSteps: undefined,+ parentMessageId: userMessage.id,+ runId: run.id,+ testCaseId: testCase.id,+ topicId: topic.id,+ userId,+ }),+ );+ expect(mockExecAgent).not.toHaveBeenCalled();++ const refreshedRun = await runModel.findById(run.id);+ expect(refreshedRun?.status).toBe('failed');+ expect(refreshedRun?.metrics).toMatchObject({+ completedCases: 1,+ timeoutCases: 1,+ });++ const refreshedRunTopic = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);+ expect(refreshedRunTopic?.status).toBe('timeout');+ expect(refreshedRunTopic?.evalResult).toEqual({+ completionReason: 'timeout',+ duration: 1000,+ rubricScores: [],+ });+ });++ it('should only trigger workflow for the target pass@k thread without mutating thread state', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, {+ config: { k: 2 },+ status: 'failed',+ });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ const threadModel = new ThreadModel(serverDB, userId);+ const thread = await threadModel.create({ topicId: topic.id, type: 'eval' });+ const otherThread = await threadModel.create({ topicId: topic.id, type: 'eval' });++ await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {+ evalResult: {+ passAllK: false,+ passAtK: true,+ threads: [+ { status: 'timeout', threadId: thread!.id },+ { passed: true, status: 'passed', threadId: otherThread!.id },+ ],+ },+ passed: true,+ score: 1,+ status: 'passed',+ });++ await threadModel.update(thread!.id, {+ metadata: {+ completedAt: new Date('2026-03-30T00:00:00.000Z').toISOString(),+ operationId: 'op-target-old',+ passed: false,+ score: 0,+ testCaseId: testCase.id,+ },+ } as any);+ await threadModel.update(otherThread!.id, {+ metadata: {+ completedAt: new Date('2026-03-30T00:00:01.000Z').toISOString(),+ operationId: 'op-other-thread',+ passed: true,+ score: 1,+ testCaseId: testCase.id,+ },+ } as any);++ const [threadUserMessage] = await serverDB+ .insert(messages)+ .values({+ content: 'thread user prompt',+ role: 'user',+ threadId: thread!.id,+ topicId: topic.id,+ userId,+ })+ .returning({ id: messages.id });++ await serverDB.insert(messages).values({+ content: '...',+ parentId: threadUserMessage.id,+ role: 'assistant',+ threadId: thread!.id,+ topicId: topic.id,+ userId,+ });++ const service = new AgentEvalRunService(serverDB, userId);+ const result = await service.resumeTrajectory({+ runId: run.id,+ testCaseId: testCase.id,+ threadId: thread!.id,+ });++ expect(result).toEqual({+ mode: 'thread',+ runId: run.id,+ testCaseId: testCase.id,+ threadId: thread!.id,+ topicId: topic.id,+ triggered: true,+ });++ expect(AgentEvalRunWorkflow.triggerResumeThreadTrajectory).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: { threadId: thread!.id, topicId: topic.id },+ envPrompt: undefined,+ maxSteps: undefined,+ parentMessageId: threadUserMessage.id,+ runId: run.id,+ testCaseId: testCase.id,+ threadId: thread!.id,+ topicId: topic.id,+ userId,+ }),+ );+ expect(mockExecAgent).not.toHaveBeenCalled();++ expect((await threadModel.findById(thread!.id))?.metadata).toMatchObject({+ operationId: 'op-target-old',+ testCaseId: testCase.id,+ });+ expect((await threadModel.findById(otherThread!.id))?.metadata).toMatchObject({+ operationId: 'op-other-thread',+ passed: true,+ score: 1,+ testCaseId: testCase.id,+ });+ });+ });++ describe('executeResumedTrajectory', () => {+ it('should claim a timeout trajectory, switch run back to running, and store operationId', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'failed' });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ mockExecAgent.mockResolvedValue({ operationId: 'op-resume-1' });++ const service = new AgentEvalRunService(serverDB, userId);+ const result = await service.executeResumedTrajectory({+ appContext: { topicId: topic.id },+ parentMessageId: 'parent-message-id',+ runId: run.id,+ testCaseId: testCase.id,+ topicId: topic.id,+ userId,+ });++ expect(result).toEqual({ status: 'started', topicId: topic.id });+ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: { topicId: topic.id },+ parentMessageId: 'parent-message-id',+ prompt: '',+ resume: true,+ }),+ );++ const refreshedRun = await new AgentEvalRunModel(serverDB, userId).findById(run.id);+ expect(refreshedRun?.status).toBe('running');+ expect(refreshedRun?.startedAt).toBeTruthy();++ const refreshedRunTopic = await new AgentEvalRunTopicModel(+ serverDB,+ userId,+ ).findByRunAndTestCase(run.id, testCase.id);+ expect(refreshedRunTopic?.status).toBe('running');+ expect(refreshedRunTopic?.evalResult).toEqual({+ operationId: 'op-resume-1',+ rubricScores: [],+ });+ });++ it('should cancel when the trajectory is not resumable', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'failed' });++ const result = await new AgentEvalRunService(serverDB, userId).executeResumedTrajectory({+ appContext: { topicId: topic.id },+ parentMessageId: 'parent-message-id',+ runId: run.id,+ testCaseId: testCase.id,+ topicId: topic.id,+ userId,+ });++ expect(result).toEqual({+ reason: 'Trajectory is not resumable',+ status: 'cancelled',+ topicId: topic.id,+ });+ expect(mockExecAgent).not.toHaveBeenCalled();+ });+ });++ describe('executeResumedThreadTrajectory', () => {+ it('should claim only the target timeout thread and store operationId on that thread', async () => {+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });++ await new AgentEvalRunModel(serverDB, userId).update(run.id, {+ config: { k: 2 },+ status: 'failed',+ });+ await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });++ const threadModel = new ThreadModel(serverDB, userId);+ const thread = await threadModel.create({ topicId: topic.id, type: 'eval' });+ const otherThread = await threadModel.create({ topicId: topic.id, type: 'eval' });++ await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {+ evalResult: {+ passAllK: false,+ passAtK: true,+ threads: [+ { status: 'timeout', threadId: thread!.id },+ { passed: true, status: 'passed', threadId: otherThread!.id },+ ],+ },+ passed: true,+ score: 1,+ status: 'passed',+ });++ await threadModel.update(thread!.id, {+ metadata: {+ completedAt: new Date('2026-03-30T00:00:00.000Z').toISOString(),+ cost: 1.2,+ llmCalls: 3,+ operationId: 'op-old-target',+ passed: false,+ score: 0,+ status: 'timeout',+ steps: 7,+ testCaseId: testCase.id,+ tokens: 123,+ toolCalls: 2,+ },+ } as any);+ await threadModel.update(otherThread!.id, {+ metadata: {+ completedAt: new Date('2026-03-30T00:00:01.000Z').toISOString(),+ operationId: 'op-other-thread',+ passed: true,+ score: 1,+ testCaseId: testCase.id,+ },+ } as any);++ mockExecAgent.mockResolvedValue({ operationId: 'op-thread-resume-1' });++ const result = await new AgentEvalRunService(serverDB, userId).executeResumedThreadTrajectory(+ {+ appContext: { threadId: thread!.id, topicId: topic.id },+ parentMessageId: 'parent-message-id',+ runId: run.id,+ testCaseId: testCase.id,+ threadId: thread!.id,+ topicId: topic.id,+ userId,+ },+ );++ expect(result).toEqual({ status: 'started', threadId: thread!.id, topicId: topic.id });+ expect(mockExecAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: { threadId: thread!.id, topicId: topic.id },+ initialStepCount: 7,+ parentMessageId: 'parent-message-id',+ prompt: '',+ resume: true,+ }),+ );++ const updatedThread = await threadModel.findById(thread!.id);+ expect(updatedThread?.metadata).toEqual({+ operationId: 'op-thread-resume-1',+ testCaseId: testCase.id,+ });++ const untouchedThread = await threadModel.findById(otherThread!.id);+ expect(untouchedThread?.metadata).toMatchObject({+ operationId: 'op-other-thread',+ passed: true,+ score: 1,+ testCaseId: testCase.id,+ });++ const refreshedRunTopic = await new AgentEvalRunTopicModel(+ serverDB,+ userId,+ ).findByRunAndTestCase(run.id, testCase.id);+ expect(refreshedRunTopic?.status).toBe('running');+ expect(refreshedRunTopic?.evalResult).toEqual({+ threads: [+ { status: 'running', threadId: thread!.id },+ { passed: true, status: 'passed', threadId: otherThread!.id },+ ],+ });+ });+ });+});diff --git a/src/server/services/agentEvalRun/index.ts b/src/server/services/agentEvalRun/index.tsindex 5ad879579ad..6b97f73d16c 100644--- a/src/server/services/agentEvalRun/index.ts+++ b/src/server/services/agentEvalRun/index.ts@@ -1,3 +1,4 @@+import { LOADING_FLAT } from '@lobechat/const';import { type LobeChatDatabase } from '@lobechat/database';import { evaluate } from '@lobechat/eval-rubric';import type {@@ -7,9 +8,11 @@ import type {EvalRunInputConfig,EvalRunMetrics,EvalRunTopicResult,+ EvalThreadResult,RubricType,} from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';+import debug from 'debug';import {AgentEvalBenchmarkModel,@@ -24,12 +27,51 @@ import { TopicModel } from '@/database/models/topic';import { AgentService } from '@/server/services/agent';import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';import { AiAgentService } from '@/server/services/aiAgent';-import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';+import {+ AgentEvalRunWorkflow,+ type ResumeAgentTrajectoryPayload,+ type ResumeThreadTrajectoryPayload,+} from '@/server/workflows/agentEvalRun';/** 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_RETRY_DELAY = '10000 * (1 + retried)';+const RESUMABLE_THREAD_STATUSES = new Set(['error', 'timeout']);++const log = debug('lobe-server:eval-run-service');++interface ResumableCaseTarget {+ caseStatus?: string | null;+ input: string;+ resumeStatus?: 'error' | 'timeout';+ sortOrder: number | null;+ testCaseId: string;+ threadId?: string;+}++interface ResumableThreadResult extends EvalThreadResult {+ status: 'error' | 'timeout';+}++const getThreadResultStatus = (+ evalResult: Record<string, unknown>,+): EvalThreadResult['status'] | undefined => {+ const { status } = evalResult;++ if (status === 'completed' || status === 'error' || status === 'external' || status === 'timeout')+ return status;++ if (evalResult.passed === true) return 'passed';+ if (evalResult.passed === false) return 'failed';++ return undefined;+};++const resetResumedThreadResult = (thread: EvalThreadResult): EvalThreadResult => ({+ threadId: thread.threadId,+ status: thread.status === 'external' ? 'external' : 'running',+});export class AgentEvalRunService {private readonly db: LobeChatDatabase;@@ -224,6 +266,651 @@ export class AgentEvalRunService {await this.runModel.update(runId, { status: 'running' });}+ async canResumeTrajectory(params: { runId: string; testCaseId: string; threadId?: string }) {+ const invalidResumeTargetReason = 'Invalid resume target';+ const trajectoryNotResumableReason = 'Trajectory is not resumable';+ const resumeLimitReachedReason = 'Resume limit reached';++ log('canResumeTrajectory: %O', params);+ const run = await this.runModel.findById(params.runId);+ if (!run) return { canResume: false, reason: invalidResumeTargetReason };++ if (!['aborted', 'failed', 'running'].includes(run.status)) {+ return { canResume: false, reason: trajectoryNotResumableReason };+ }++ const runTopic = await this.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);+ if (!runTopic) return { canResume: false, reason: invalidResumeTargetReason };++ log('canResumeTrajectory: runTopic.status=%s topicId=%s', runTopic.status, runTopic.topicId);++ const k = run.config?.k ?? 1;+ const hasInvalidThreadTarget = (k === 1 && !!params.threadId) || (k > 1 && !params.threadId);+ if (hasInvalidThreadTarget) {+ return { canResume: false, reason: invalidResumeTargetReason };+ }++ if (!runTopic.topicId) {+ return { canResume: false, reason: invalidResumeTargetReason };+ }++ if (k === 1 && !RESUMABLE_THREAD_STATUSES.has(runTopic.status ?? '')) {+ log('canResumeTrajectory: rejected β runTopic.status=%s', runTopic.status);+ return { canResume: false, reason: trajectoryNotResumableReason };+ }++ if (params.threadId) {+ const thread = await this.threadModel.findById(params.threadId);++ if (!thread || thread.topicId !== runTopic.topicId || thread.type !== 'eval') {+ return { canResume: false, reason: invalidResumeTargetReason };+ }++ const targetThread = runTopic.evalResult?.threads?.find(+ (item) => item.threadId === params.threadId,+ );++ if (!targetThread || !RESUMABLE_THREAD_STATUSES.has(targetThread.status ?? '')) {+ return { canResume: false, reason: trajectoryNotResumableReason };+ }++ const maxSteps = run.config?.maxSteps;+ const prevSteps =+ ((thread.metadata as Record<string, unknown> | null)?.steps as number | undefined) ?? 0;++ if (maxSteps && prevSteps >= maxSteps) {+ log(+ 'canResumeTrajectory: rejected thread β prevSteps=%d >= maxSteps=%d',+ prevSteps,+ maxSteps,+ );+ return { canResume: false, reason: resumeLimitReachedReason };+ }+ }++ // pass@1 resumes track steps on the runTopic; pass@k uses per-thread metadata above.+ if (k > 1) return { canResume: true as const };++ // Reject if the previous run already exhausted maxSteps+ const maxSteps = run.config?.maxSteps;+ const prevSteps = runTopic.evalResult?.steps ?? 0;+ if (maxSteps && prevSteps >= maxSteps) {+ log('canResumeTrajectory: rejected β prevSteps=%d >= maxSteps=%d', prevSteps, maxSteps);+ return { canResume: false, reason: resumeLimitReachedReason };+ }++ return { canResume: true as const };+ }++ /**+ * Batch-check which error/timeout cases in a run can be resumed.+ * Returns one entry per candidate case with canResume + optional reason.+ */+ async getResumableCases(runId: string) {+ const run = await this.runModel.findById(runId);+ if (!run) return [];++ const allTopics = await this.runTopicModel.findByRunId(runId);+ const k = run.config?.k ?? 1;+ const candidates = allTopics+ .map((topic) => this.getResumableCaseTarget(topic, k))+ .filter((topic): topic is ResumableCaseTarget => !!topic);++ const results = await Promise.all(+ candidates.map(async (candidate) => {+ const check = await this.canResumeTrajectory({+ runId,+ testCaseId: candidate.testCaseId,+ threadId: candidate.threadId,+ });+ return {+ caseStatus: candidate.caseStatus,+ canResume: check.canResume,+ input: candidate.input,+ reason: 'reason' in check ? check.reason : undefined,+ resumeStatus: candidate.resumeStatus,+ sortOrder: candidate.sortOrder,+ testCaseId: candidate.testCaseId,+ threadId: candidate.threadId,+ };+ }),+ );++ return results;+ }++ async resumeTrajectory(params: { runId: string; testCaseId: string; threadId?: string }) {+ log('resumeTrajectory: %O', params);+ const resumeCheck = await this.canResumeTrajectory(params);+ if (!resumeCheck.canResume) {+ log('resumeTrajectory: canResume=false reason=%s', resumeCheck.reason);+ throw new Error(resumeCheck.reason);+ }++ const target = await this.resolveTrajectoryResumeTarget(params);+ const { envPrompt, parentMessageId, run, thread, topicId } = target;+ log(+ 'resumeTrajectory: resolved target β topicId=%s parentMessageId=%s threadId=%s',+ topicId,+ parentMessageId,+ thread?.id,+ );++ if (thread) {+ log('resumeTrajectory: triggering resume-thread-trajectory');+ await AgentEvalRunWorkflow.triggerResumeThreadTrajectory({+ appContext: { threadId: thread.id, topicId },+ envPrompt,+ maxSteps: run.config?.maxSteps,+ parentMessageId,+ runId: run.id,+ targetAgentId: run.targetAgentId ?? undefined,+ testCaseId: params.testCaseId,+ threadId: thread.id,+ topicId,+ userId: this.userId,+ });+ } else {+ log('resumeTrajectory: triggering resume-agent-trajectory');+ await AgentEvalRunWorkflow.triggerResumeAgentTrajectory({+ appContext: { topicId },+ envPrompt,+ maxSteps: run.config?.maxSteps,+ parentMessageId,+ runId: run.id,+ targetAgentId: run.targetAgentId ?? undefined,+ testCaseId: params.testCaseId,+ topicId,+ userId: this.userId,+ });+ }++ const result = {+ mode: thread ? ('thread' as const) : ('single' as const),+ runId: run.id,+ testCaseId: params.testCaseId,+ threadId: thread?.id,+ topicId,+ triggered: true,+ };+ log('resumeTrajectory: done %O', result);+ return result;+ }++ private getResumableCaseTarget(+ runTopic: {+ evalResult?: EvalRunTopicResult | null;+ status?: string | null;+ testCase?: { content?: { input?: string } | null; sortOrder?: number | null } | null;+ testCaseId: string;+ },+ k: number,+ ): ResumableCaseTarget | undefined {+ if (k === 1) {+ if (!RESUMABLE_THREAD_STATUSES.has(runTopic.status ?? '')) return undefined;++ return {+ caseStatus: runTopic.status,+ input: runTopic.testCase?.content?.input ?? '',+ resumeStatus: runTopic.status as 'error' | 'timeout',+ sortOrder: runTopic.testCase?.sortOrder ?? null,+ testCaseId: runTopic.testCaseId,+ };+ }++ const resumableThread = this.getResumableThread(runTopic.evalResult?.threads);+ if (!resumableThread?.status) return undefined;++ return {+ caseStatus: runTopic.status,+ input: runTopic.testCase?.content?.input ?? '',+ resumeStatus: resumableThread.status,+ sortOrder: runTopic.testCase?.sortOrder ?? null,+ testCaseId: runTopic.testCaseId,+ threadId: resumableThread.threadId,+ };+ }++ private getResumableThread(threads?: EvalThreadResult[]) {+ return threads?.find((thread): thread is ResumableThreadResult =>+ RESUMABLE_THREAD_STATUSES.has(thread.status ?? ''),+ );+ }++ /**+ * Resume a timed-out single-agent trajectory (pass@1).+ * Claims the runTopic via CAS (timeout β running) for idempotency, then+ * calls execAgent with resume=true so the runtime continues from parentMessageId.+ */+ async executeResumedTrajectory(params: ResumeAgentTrajectoryPayload) {+ const {+ appContext,+ envPrompt,+ maxSteps,+ parentMessageId,+ runId,+ targetAgentId,+ testCaseId,+ topicId,+ } = params;++ const resumeCheck = await this.canResumeTrajectory({ runId, testCaseId });+ if (!resumeCheck.canResume) {+ return { reason: resumeCheck.reason, status: 'cancelled' as const, topicId };+ }++ // Look up the pre-created RunTopic and reset it for resume+ log(+ 'executeResumedTrajectory: run=%s testCase=%s topicId=%s parentMessageId=%s',+ runId,+ testCaseId,+ topicId,+ parentMessageId,+ );+ const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (!runTopic) {+ throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);+ }++ // Capture accumulated telemetry from previous runs before clearing evalResult+ const prevSteps = runTopic.evalResult?.steps ?? 0;+ const prevCost = runTopic.evalResult?.cost ?? 0;+ const prevLlmCalls = runTopic.evalResult?.llmCalls ?? 0;+ const prevToolCalls = runTopic.evalResult?.toolCalls ?? 0;+ const prevTokens = runTopic.evalResult?.tokens ?? 0;+ log('executeResumedTrajectory: prev telemetry steps=%d cost=%d', prevSteps, prevCost);+ const now = new Date();++ await this.runTopicModel.updateByRunAndTopic(runId, topicId, {+ createdAt: now, // reset for timeout tracking β resume is a fresh time window+ evalResult: null,+ passed: null,+ score: null,+ status: 'running',+ });++ await this.runModel.update(runId, { startedAt: now, status: 'running' });++ const aiAgentService = new AiAgentService(this.db, this.userId);+ const webhookUrl = '/api/workflows/agent-eval-run/on-trajectory-complete';+ const userId = this.userId;+ const db = this.db;++ try {+ const execResult = await aiAgentService.execAgent({+ agentId: targetAgentId,+ appContext,+ autoStart: true,+ hooks: [+ {+ handler: async (event) => {+ // Local mode: directly record completion+ const service = new AgentEvalRunService(db, userId);+ await service.recordTrajectoryCompletion({+ runId,+ status: event.status || event.reason || 'done',+ telemetry: {+ completionReason: event.reason,+ cost: (event.cost ?? 0) + prevCost,+ duration: event.duration,+ errorDetail: event.errorDetail,+ errorMessage: event.errorMessage,+ llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,+ steps: (event.steps ?? 0) + prevSteps,+ toolCalls: (event.toolCalls ?? 0) + prevToolCalls,+ totalTokens: (event.totalTokens ?? 0) + prevTokens,+ },+ testCaseId,+ });+ },+ id: 'eval-trajectory-complete',+ type: 'onComplete' as const,+ webhook: {+ body: { runId, testCaseId, userId },+ url: webhookUrl,+ },+ },+ ],+ ...(envPrompt && { evalContext: { envPrompt } }),+ initialStepCount: prevSteps,+ maxSteps,+ parentMessageId,+ prompt: '',+ resume: true,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ if (execResult?.operationId) {+ await this.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: { operationId: execResult.operationId, rubricScores: [] },+ });+ }++ return { status: 'started' as const, topicId };+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : 'Agent execution failed to start';+ console.error(+ `[resume-agent-trajectory] execAgent failed for run=${runId} testCase=${testCaseId}:`,+ error,+ );++ // Record error and finalize the run if all test cases are done+ const { allDone } = await this.recordTrajectoryCompletion({+ runId,+ status: 'error',+ telemetry: { completionReason: 'error', errorMessage },+ testCaseId,+ });++ if (allDone) {+ await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId: this.userId });+ }++ return { reason: errorMessage, status: 'error' as const, topicId };+ }+ }++ /**+ * Resume a timed-out thread trajectory (pass@k).+ * Claims the runTopic via CAS (timeout β running) for idempotency, then+ * calls execAgent with resume=true so the runtime continues from parentMessageId.+ */+ async executeResumedThreadTrajectory(params: ResumeThreadTrajectoryPayload) {+ const {+ appContext,+ envPrompt,+ maxSteps,+ parentMessageId,+ runId,+ targetAgentId,+ testCaseId,+ threadId,+ topicId,+ } = params;++ const resumeCheck = await this.canResumeTrajectory({ runId, testCaseId, threadId });+ if (!resumeCheck.canResume) {+ return { reason: resumeCheck.reason, status: 'cancelled' as const, threadId, topicId };+ }++ // Look up the pre-created RunTopic and reset it for resume+ const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (!runTopic) {+ throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);+ }++ const currentThread = await this.threadModel.findById(threadId);+ const currentThreadMeta = (currentThread?.metadata ?? {}) as Record<string, unknown>;+ const prevThreads = runTopic.evalResult?.threads ?? [];+ const nextThreads = prevThreads.some((thread) => thread.threadId === threadId)+ ? prevThreads.map((thread) =>+ thread.threadId === threadId ? resetResumedThreadResult(thread) : thread,+ )+ : [...prevThreads, { status: 'running' as const, threadId }];++ // Capture accumulated telemetry from the target thread only+ const prevSteps = (currentThreadMeta.steps as number | undefined) ?? 0;+ const prevCost = (currentThreadMeta.cost as number | undefined) ?? 0;+ const prevLlmCalls = (currentThreadMeta.llmCalls as number | undefined) ?? 0;+ const prevToolCalls = (currentThreadMeta.toolCalls as number | undefined) ?? 0;+ const prevTokens = (currentThreadMeta.tokens as number | undefined) ?? 0;+ const now = new Date();++ await this.runTopicModel.updateByRunAndTopic(runId, topicId, {+ createdAt: now,+ evalResult: { threads: nextThreads },+ passed: null,+ score: null,+ status: 'running',+ });++ await this.threadModel.update(threadId, {+ metadata: { testCaseId } as any,+ });++ await this.runModel.update(runId, { startedAt: now, status: 'running' });++ const aiAgentService = new AiAgentService(this.db, this.userId);+ const webhookUrl = '/api/workflows/agent-eval-run/on-thread-complete';+ const userId = this.userId;+ const db = this.db;++ try {+ const execResult = await aiAgentService.execAgent({+ agentId: targetAgentId,+ appContext,+ autoStart: true,+ hooks: [+ {+ handler: async (event) => {+ // Local mode: directly record thread completion+ const service = new AgentEvalRunService(db, userId);+ await service.recordThreadCompletion({+ runId,+ status: event.status || event.reason || 'done',+ telemetry: {+ completionReason: event.reason,+ cost: (event.cost ?? 0) + prevCost,+ duration: event.duration,+ errorMessage: event.errorMessage,+ llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,+ steps: (event.steps ?? 0) + prevSteps,+ toolCalls: (event.toolCalls ?? 0) + prevToolCalls,+ totalTokens: (event.totalTokens ?? 0) + prevTokens,+ },+ testCaseId,+ threadId,+ topicId,+ });+ },+ id: 'eval-thread-complete',+ type: 'onComplete' as const,+ webhook: {+ body: { runId, testCaseId, threadId, topicId, userId },+ url: webhookUrl,+ },+ },+ ],+ ...(envPrompt && { evalContext: { envPrompt } }),+ initialStepCount: prevSteps,+ maxSteps,+ parentMessageId,+ prompt: '',+ resume: true,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ // Write operationId to thread metadata+ if (execResult?.operationId) {+ await this.threadModel.update(threadId, {+ metadata: { operationId: execResult.operationId, testCaseId } as any,+ });+ }++ return { status: 'started' as const, threadId, topicId };+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : 'Thread execution failed to start';+ console.error(+ `[resume-thread-trajectory] execAgent failed for run=${runId} thread=${threadId}:`,+ error,+ );++ // Record error and finalize the run if all test cases are done+ const { allRunDone } = await this.recordThreadCompletion({+ runId,+ status: 'error',+ telemetry: { completionReason: 'error', errorMessage },+ testCaseId,+ threadId,+ topicId,+ });++ if (allRunDone) {+ await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId: this.userId });+ }++ return { reason: errorMessage, status: 'error' as const, threadId, topicId };+ }+ }++ private async resolveTrajectoryResumeTarget(params: {+ runId: string;+ testCaseId: string;+ threadId?: string;+ }) {+ log(+ 'resolveTrajectoryResumeTarget: run=%s testCase=%s thread=%s',+ params.runId,+ params.testCaseId,+ params.threadId,+ );+ const loaded = await this.loadTrajectoryData(params.runId, params.testCaseId);+ if ('error' in loaded) {+ throw new Error(loaded.error);+ }++ const { envPrompt, run } = loaded;+ const runTopic = await this.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);+ if (!runTopic?.topicId) throw new Error('RunTopic topicId is required');++ log(+ 'resolveTrajectoryResumeTarget: topicId=%s runTopic.status=%s',+ runTopic.topicId,+ runTopic.status,+ );++ let thread: Awaited<ReturnType<ThreadModel['findById']>> | undefined;++ if (params.threadId) {+ thread = await this.threadModel.findById(params.threadId);+ if (!thread) throw new Error('Thread not found');+ }++ const { danglingIds, parentMessageId } = await this.resolveResumeParentMessageId({+ threadId: thread?.id,+ topicId: runTopic.topicId,+ });++ log(+ 'resolveTrajectoryResumeTarget: parentMessageId=%s danglingIds=%d',+ parentMessageId,+ danglingIds.length,+ );++ // Remove dangling partial messages before resume so the context engine (which+ // re-fetches all topic messages after every tool-call batch) cannot include them.+ if (danglingIds.length > 0) {+ log(+ 'resolveTrajectoryResumeTarget: deleting %d dangling messages: %O',+ danglingIds.length,+ danglingIds,+ );+ await this.messageModel.deleteMessages(danglingIds);+ }++ return {+ appContext: thread+ ? { threadId: thread.id, topicId: runTopic.topicId }+ : { topicId: runTopic.topicId },+ envPrompt,+ parentMessageId,+ run,+ runTopic,+ thread,+ topicId: runTopic.topicId,+ };+ }++ private async resolveResumeParentMessageId(params: { threadId?: string; topicId: string }) {+ log('resolveResumeParentMessageId: topicId=%s threadId=%s', params.topicId, params.threadId);+ const messages = await this.messageModel.query({+ threadId: params.threadId,+ topicId: params.topicId,+ });++ log('resolveResumeParentMessageId: total messages=%d', messages.length);+ log(+ 'resolveResumeParentMessageId: messages (role, id, contentLen, parentId) = %O',+ messages.map((m) => ({+ role: m.role,+ id: m.id,+ contentLen: m.content?.length ?? 0,+ parentId: (m as any).parentId ?? null,+ })),+ );++ // Strategy:+ // - tool results are always complete (atomic, written after execution succeeds)+ // - assistant messages may be partial (LLM stream interrupted mid-way)+ // So: prefer the last tool result with content as the resume point.+ // Only fall back to assistant / user if no tool result exists.++ let parentMessageId: string | undefined;++ // Pass 1: find the last tool result with content+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];+ if (message.role === 'tool' && message.content) {+ log(+ 'resolveResumeParentMessageId: found via tool id=%s contentLen=%d',+ message.id,+ message.content.length,+ );+ parentMessageId = message.id;+ break;+ }+ }++ // Pass 2: no tool result β fall back to last substantive assistant, then user+ if (!parentMessageId) {+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];++ if (message.role === 'assistant') {+ if (!message.content || message.content === LOADING_FLAT) {+ log('resolveResumeParentMessageId: skip empty/loading assistant msgId=%s', message.id);+ continue;+ }+ log(+ 'resolveResumeParentMessageId: fallback via assistant id=%s contentLen=%d',+ message.id,+ message.content.length,+ );+ parentMessageId = message.id;+ break;+ }++ if (message.role === 'user') {+ log('resolveResumeParentMessageId: fallback via user id=%s', message.id);+ parentMessageId = message.id;+ break;+ }+ }+ }++ if (!parentMessageId) throw new Error('Unable to resolve a valid resume parent message');++ // Build the valid ancestor chain from parentMessageId up to root.+ // Return danglingIds for the caller to delete β keeping this method side-effect-free.+ const parentIdMap = new Map<string, string | null>();+ for (const m of messages) {+ parentIdMap.set(m.id, (m as any).parentId ?? null);+ }++ const ancestorSet = new Set<string>();+ let cursor: string | null = parentMessageId;+ while (cursor) {+ ancestorSet.add(cursor);+ cursor = parentIdMap.get(cursor) ?? null;+ }++ const danglingIds = messages.map((m) => m.id).filter((id) => !ancestorSet.has(id));++ return { danglingIds, parentMessageId };+ }+async loadTrajectoryData(runId: string, testCaseId: string) {const run = await this.runModel.findById(runId);if (!run) return { error: 'Run not found' as const };@@ -374,6 +1061,17 @@ export class AgentEvalRunService {if (thread) threadIds.push(thread.id);}+ await this.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: {+ // Persist thread ids before fan-out so pass@k UIs can render attempts immediately.+ ...(runTopic.evalResult as EvalRunTopicResult | null),+ threads: threadIds.map((threadId) => ({+ status: 'running' as const,+ threadId,+ })),+ } satisfies EvalRunTopicResult,+ });+// Trigger K run-thread-trajectory workflows in parallelawait Promise.all(threadIds.map((threadId) =>@@ -473,13 +1171,14 @@ export class AgentEvalRunService {error,);- // Write error to thread metadata so it counts as "completed" for aggregation+ // Mark the thread explicitly as error; aggregation and resume-target selection rely on metadata.status.await this.threadModel.update(threadId, {metadata: {completedAt: new Date().toISOString(),error: errorMessage,passed: false,score: 0,+ status: 'error',testCaseId,},} as any);@@ -527,6 +1226,8 @@ export class AgentEvalRunService {metadata: {...evalResult,completedAt: new Date().toISOString(),+ // Normalize status into metadata so later aggregation can reconstruct threads[] consistently.+ status: getThreadResultStatus(evalResult),testCaseId,},} as any);diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 76ed4eca752..936c9b4b4d5 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -277,6 +277,7 @@ export class AgentRuntimeService {operationSkillSet,signal,userTimezone,+ initialStepCount = 0,} = params;const operationToolSet = toolSet;@@ -338,7 +339,7 @@ export class AgentRuntimeService {operationId,operationToolSet,status: 'idle',- stepCount: 0,+ stepCount: initialStepCount,// Backward-compat: resolved tool fields read by RuntimeExecutorstoolManifestMap: operationToolSet.manifestMap,toolSourceMap: operationToolSet.sourceMap,@@ -402,7 +403,7 @@ export class AgentRuntimeService {priority: 'high',retryDelay: queueRetryDelay,retries: queueRetries,- stepIndex: 0,+ stepIndex: initialStepCount,});autoStarted = true;log('[%s] Scheduled first step (messageId: %s)', operationId, messageId);diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.tsindex 9c9d337794d..205fa20b21c 100644--- a/src/server/services/agentRuntime/types.ts+++ b/src/server/services/agentRuntime/types.ts@@ -165,6 +165,8 @@ export interface OperationCreationParams {hooks?: AgentHook[];initialContext: AgentRuntimeContext;initialMessages?: any[];+ /** Initial step count offset for resumed operations (accumulated from previous runs) */+ initialStepCount?: number;maxSteps?: number;modelRuntimeConfig?: any;operationId: string;diff --git a/src/server/services/aiAgent/__tests__/execAgent.resume.test.ts b/src/server/services/aiAgent/__tests__/execAgent.resume.test.tsnew file mode 100644index 00000000000..cdca401c4e4--- /dev/null+++ b/src/server/services/aiAgent/__tests__/execAgent.resume.test.ts@@ -0,0 +1,253 @@+import type * as ModelBankModule from 'model-bank';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++const { mockCreateOperation, mockFindById, mockMessageCreate, mockMessageQuery } = vi.hoisted(+ () => ({+ mockCreateOperation: vi.fn(),+ mockFindById: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockMessageQuery: vi.fn(),+ }),+);++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: mockMessageCreate,+ findById: mockFindById,+ query: mockMessageQuery,+ update: vi.fn().mockResolvedValue({}),+ })),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({})),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ })),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ })),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(() => ({+ getUserSettings: vi.fn().mockResolvedValue(undefined),+ })),+}));++vi.mock('@/database/models/userMemory/persona', () => ({+ UserPersonaModel: vi.fn().mockImplementation(() => ({+ getLatestPersonaDocument: vi.fn().mockResolvedValue(undefined),+ })),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ createOperation: mockCreateOperation,+ })),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(() => ({+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/klavis', () => ({+ KlavisService: vi.fn().mockImplementation(() => ({+ getKlavisManifests: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ uploadFromUrl: vi.fn(),+ })),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+}));++vi.mock('@/server/services/toolExecution/deviceProxy', () => ({+ deviceProxy: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();++ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++describe('AiAgentService.execAgent - resume mode', () => {+ let service: AiAgentService;++ beforeEach(() => {+ vi.clearAllMocks();++ mockCreateOperation.mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ });++ mockFindById.mockResolvedValue({+ id: 'parent-msg-1',+ sessionId: 'session-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ });++ mockMessageQuery.mockResolvedValue([+ { content: 'history user', id: 'history-1', role: 'user' },+ { content: 'history assistant', id: 'history-2', role: 'assistant' },+ ]);++ mockMessageCreate.mockResolvedValue({ id: 'assistant-msg-new' });++ service = new AiAgentService({} as any, 'user-1');+ });++ it('should create only a new assistant message in resume mode and use caller appContext', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: {+ sessionId: 'session-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ parentMessageId: 'parent-msg-1',+ prompt: 'caller prompt is ignored for runtime payload messages',+ resume: true,+ });++ expect(mockFindById).toHaveBeenCalledWith('parent-msg-1');+ expect(mockMessageQuery).toHaveBeenCalledWith(+ {+ sessionId: 'session-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ expect.any(Object),+ );+ expect(mockMessageCreate).toHaveBeenCalledTimes(1);+ expect(mockMessageCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ content: expect.any(String),+ parentId: 'parent-msg-1',+ role: 'assistant',+ threadId: 'thread-1',+ topicId: 'topic-1',+ }),+ );++ expect(mockCreateOperation).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: expect.objectContaining({+ threadId: 'thread-1',+ topicId: 'topic-1',+ }),+ initialContext: expect.objectContaining({+ payload: expect.objectContaining({+ message: [{ content: '' }],+ parentMessageId: 'parent-msg-1',+ }),+ phase: 'user_input',+ }),+ initialMessages: [+ { content: 'history user', id: 'history-1', role: 'user' },+ { content: 'history assistant', id: 'history-2', role: 'assistant' },+ ],+ }),+ );+ });++ it('should reject missing appContext in resume mode', async () => {+ await expect(+ service.execAgent({+ agentId: 'agent-1',+ parentMessageId: 'parent-msg-1',+ prompt: '',+ resume: true,+ }),+ ).rejects.toThrow('appContext is required when resume is true');+ });++ it('should reject appContext.topicId mismatch in resume mode', async () => {+ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: {+ sessionId: 'session-1',+ threadId: 'thread-1',+ topicId: 'topic-other',+ },+ parentMessageId: 'parent-msg-1',+ prompt: '',+ resume: true,+ }),+ ).rejects.toThrow('appContext.topicId does not match parent message');+ });++ it('should require parentMessageId when resume is true', async () => {+ await expect(+ service.execAgent({+ agentId: 'agent-1',+ prompt: '',+ resume: true,+ }),+ ).rejects.toThrow('parentMessageId is required when resume is true');+ });+});diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex d66f83ec918..3682a03e693 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -124,10 +124,16 @@ interface InternalExecAgentParams extends ExecAgentParams {functionTools?: Array<{ description?: string; name: string; parameters?: Record<string, any> }>;/** External lifecycle hooks (auto-adapt to local/production mode) */hooks?: AgentHook[];+ /** Initial step count offset for resumed operations (accumulated from previous runs) */+ initialStepCount?: number;/** Maximum steps for the agent operation */maxSteps?: number;+ /** Parent message ID to continue from. Only takes effect when resume is true */+ parentMessageId?: string;queueRetries?: number;queueRetryDelay?: string;+ /** Whether to continue execution from an existing persisted message */+ resume?: boolean;/** Abort startup before the agent runtime operation is created */signal?: AbortSignal;/** Step lifecycle callbacks for operation tracking (server-side only) */@@ -248,6 +254,7 @@ export class AiAgentService {taskId,evalContext,maxSteps,+ initialStepCount,signal,userInterventionConfig,completionWebhook,@@ -255,6 +262,8 @@ export class AiAgentService {queueRetryDelay,stepWebhook,webhookDelivery,+ parentMessageId,+ resume,} = params;// Validate that either agentId or slug is provided@@ -354,9 +363,50 @@ export class AiAgentService {log('execAgent: appended additional instructions to systemRole');}+ let resumeParentMessage;++ if (resume) {+ if (!parentMessageId) {+ throw new Error('parentMessageId is required when resume is true');+ }++ if (!appContext) {+ throw new Error('appContext is required when resume is true');+ }++ if (!appContext.topicId) {+ throw new Error('appContext.topicId is required when resume is true');+ }++ resumeParentMessage = await this.messageModel.findById(parentMessageId);++ if (!resumeParentMessage) {+ throw new Error(`Parent message not found: ${parentMessageId}`);+ }++ if (resumeParentMessage.topicId !== appContext.topicId) {+ throw new Error('appContext.topicId does not match parent message');+ }++ if (+ resumeParentMessage.threadId &&+ resumeParentMessage.threadId !== (appContext.threadId ?? undefined)+ ) {+ throw new Error('appContext.threadId does not match parent message');+ }++ if (resumeParentMessage.sessionId && resumeParentMessage.sessionId !== appContext.sessionId) {+ throw new Error('appContext.sessionId does not match parent message');+ }+ }+// 3. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existinglet topicId = appContext?.topicId;if (!topicId) {+ if (resume) {+ throw new Error('Resume mode requires the parent message to belong to a topic');+ }+// Prepare metadata with cronJobId, taskId, and botContext if providedconst metadata =cronJobId || taskId || botContext@@ -775,6 +825,7 @@ export class AiAgentService {historyMessages = await this.messageModel.query({sessionId: appContext?.sessionId,+ threadId: appContext?.threadId,topicId: appContext?.topicId ?? undefined,},{ postProcessUrl },@@ -786,7 +837,8 @@ export class AiAgentService {historyMessages = await this.messageModel.query({sessionId: appContext?.sessionId,- topicId: appContext.topicId,+ threadId: appContext?.threadId,+ topicId: appContext?.topicId,},{ postProcessUrl },);@@ -831,15 +883,19 @@ export class AiAgentService {// 13. Create user message in database// Include threadId if provided (for SubAgent task execution in isolated Thread)- const userMessageRecord = await this.messageModel.create({- agentId: resolvedAgentId,- content: prompt,- files: fileIds,- role: 'user',- threadId: appContext?.threadId ?? undefined,- topicId,- });- log('execAgent: created user message %s', userMessageRecord.id);+ const userMessageRecord = resume+ ? undefined+ : await this.messageModel.create({+ agentId: resolvedAgentId,+ content: prompt,+ files: fileIds,+ role: 'user',+ threadId: appContext?.threadId ?? undefined,+ topicId,+ });+ if (userMessageRecord) {+ log('execAgent: created user message %s', userMessageRecord.id);+ }// 14. Create assistant message placeholder in database// Include threadId if provided (for SubAgent task execution in isolated Thread)@@ -847,7 +903,7 @@ export class AiAgentService {agentId: resolvedAgentId,content: LOADING_FLAT,model,- parentId: userMessageRecord.id,+ parentId: parentMessageId ?? userMessageRecord?.id,provider,role: 'assistant',threadId: appContext?.threadId ?? undefined,@@ -860,7 +916,7 @@ export class AiAgentService {const userMessage = { content: prompt, imageList, role: 'user' as const };// Combine history messages with user message- const allMessages = [...historyMessages, userMessage];+ const allMessages = resume ? historyMessages : [...historyMessages, userMessage];log('execAgent: prepared evalContext for executor');@@ -876,9 +932,9 @@ export class AiAgentService {// Pass assistant message ID so agent runtime knows which message to updateassistantMessageId: assistantMessageRecord.id,isFirstMessage: true,- message: [{ content: prompt }],+ message: resume ? [{ content: '' }] : [{ content: prompt }],// Pass user message ID as parentMessageId for reference- parentMessageId: userMessageRecord.id,+ parentMessageId: parentMessageId ?? userMessageRecord?.id ?? '',// Include tools for initial LLM calltools,},@@ -963,6 +1019,7 @@ export class AiAgentService {evalContext,initialContext,initialMessages: allMessages,+ initialStepCount,maxSteps,modelRuntimeConfig: { model, provider },hooks,@@ -1000,7 +1057,7 @@ export class AiAgentService {success: true,timestamp: new Date().toISOString(),topicId,- userMessageId: userMessageRecord.id,+ userMessageId: userMessageRecord?.id ?? parentMessageId ?? '',};} catch (error) {if (isAbortError(error)) {@@ -1041,7 +1098,7 @@ export class AiAgentService {success: false,timestamp: new Date().toISOString(),topicId,- userMessageId: userMessageRecord.id,+ userMessageId: userMessageRecord?.id ?? parentMessageId ?? '',};}}diff --git a/src/server/workflows/agentEvalRun/index.ts b/src/server/workflows/agentEvalRun/index.tsindex 28fe492d8e2..d1575e59850 100644--- a/src/server/workflows/agentEvalRun/index.ts+++ b/src/server/workflows/agentEvalRun/index.ts@@ -13,6 +13,8 @@ const WORKFLOW_PATHS = {onThreadComplete: '/api/workflows/agent-eval-run/on-thread-complete',onTrajectoryComplete: '/api/workflows/agent-eval-run/on-trajectory-complete',paginateTestCases: '/api/workflows/agent-eval-run/paginate-test-cases',+ resumeAgentTrajectory: '/api/workflows/agent-eval-run/resume-agent-trajectory',+ resumeThreadTrajectory: '/api/workflows/agent-eval-run/resume-thread-trajectory',runAgentTrajectory: '/api/workflows/agent-eval-run/run-agent-trajectory',runBenchmark: '/api/workflows/agent-eval-run/run-benchmark',runThreadTrajectory: '/api/workflows/agent-eval-run/run-thread-trajectory',@@ -45,6 +47,18 @@ export interface RunAgentTrajectoryPayload {userId: string;}+export interface ResumeAgentTrajectoryPayload {+ appContext: { topicId: string };+ envPrompt?: string;+ maxSteps?: number;+ parentMessageId: string;+ runId: string;+ targetAgentId?: string;+ testCaseId: string;+ topicId: string;+ userId: string;+}+export interface FinalizeRunPayload {runId: string;userId: string;@@ -75,6 +89,19 @@ export interface RunThreadTrajectoryPayload {userId: string;}+export interface ResumeThreadTrajectoryPayload {+ appContext: { threadId: string; topicId: string };+ envPrompt?: string;+ maxSteps?: number;+ parentMessageId: string;+ runId: string;+ targetAgentId?: string;+ testCaseId: string;+ threadId: string;+ topicId: string;+ userId: string;+}+export interface OnThreadCompletePayload {cost?: number;duration?: number;@@ -152,6 +179,19 @@ export class AgentEvalRunWorkflow {return workflowClient.trigger({ body: payload, url });}+ /**+ * Trigger workflow to resume a single agent trajectory+ */+ static triggerResumeAgentTrajectory(payload: ResumeAgentTrajectoryPayload) {+ const url = getWorkflowUrl(WORKFLOW_PATHS.resumeAgentTrajectory);+ log(+ 'Triggering resume-agent-trajectory workflow: run=%s, testCase=%s',+ payload.runId,+ payload.testCaseId,+ );+ return workflowClient.trigger({ body: payload, url });+ }+/*** Trigger workflow to run a single thread trajectory (for pass@k)*/@@ -166,6 +206,20 @@ export class AgentEvalRunWorkflow {return workflowClient.trigger({ body: payload, url });}+ /**+ * Trigger workflow to resume a single thread trajectory (for pass@k)+ */+ static triggerResumeThreadTrajectory(payload: ResumeThreadTrajectoryPayload) {+ const url = getWorkflowUrl(WORKFLOW_PATHS.resumeThreadTrajectory);+ log(+ 'Triggering resume-thread-trajectory workflow: run=%s, testCase=%s, thread=%s',+ payload.runId,+ payload.testCaseId,+ payload.threadId,+ );+ return workflowClient.trigger({ body: payload, url });+ }+/*** Trigger workflow to finalize run*/diff --git a/src/services/agentEval.ts b/src/services/agentEval.tsindex 87223a050cb..eb7ca591a9d 100644--- a/src/services/agentEval.ts+++ b/src/services/agentEval.ts@@ -176,6 +176,21 @@ class AgentEvalService {return lambdaClient.agentEval.retryRunCase.mutate({ runId, testCaseId });}+ async resumeRunCase(runId: string, testCaseId: string, threadId?: string) {+ return lambdaClient.agentEval.resumeRunCase.mutate({ runId, testCaseId, threadId });+ }++ async batchResumeRunCases(+ runId: string,+ targets: Array<{ testCaseId: string; threadId?: string }>,+ ) {+ return lambdaClient.agentEval.batchResumeRunCases.mutate({ runId, targets });+ }++ async getResumableCases(runId: string) {+ return lambdaClient.agentEval.getResumableCases.query({ runId });+ }+async updateRun(params: {config?: EvalRunInputConfig;datasetId?: string;diff --git a/src/store/eval/slices/run/action.ts b/src/store/eval/slices/run/action.tsindex 2acfb9da810..49a6999059e 100644--- a/src/store/eval/slices/run/action.ts+++ b/src/store/eval/slices/run/action.ts@@ -111,11 +111,27 @@ export class RunActionImpl {}};+ batchResumeRunCases = async (+ runId: string,+ targets: Array<{ testCaseId: string; threadId?: string }>,+ ): Promise<void> => {+ await agentEvalService.batchResumeRunCases(runId, targets);+ await Promise.all([+ this.#get().refreshRunDetail(runId),+ mutate([FETCH_RUN_RESULTS_KEY, runId]),+ ]);+ };+retryRunCase = async (runId: string, testCaseId: string): Promise<void> => {await agentEvalService.retryRunCase(runId, testCaseId);await this.#get().refreshRunDetail(runId);};+ resumeRunCase = async (runId: string, testCaseId: string, threadId?: string): Promise<void> => {+ await agentEvalService.resumeRunCase(runId, testCaseId, threadId);+ await this.#get().refreshRunDetail(runId);+ };+retryRunErrors = async (id: string): Promise<void> => {await agentEvalService.retryRunErrors(id);await this.#get().refreshRunDetail(id);