Skip to content

🤯 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.

♻️ refactor: migrate modals to @lobehub/ui/base-ui (LOBE-9711 + eval batch) (#15416)

Innei13ce3c52ecdf
diff --git a/src/features/Electron/AuthRequiredModal/index.tsx b/src/features/Electron/AuthRequiredModal/index.tsx
index 697cfefb2c7..0b6247e61c0 100644
--- a/src/features/Electron/AuthRequiredModal/index.tsx
+++ b/src/features/Electron/AuthRequiredModal/index.tsx
@@ -1,8 +1,14 @@
'use client';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
-import { type ModalInstance } from '@lobehub/ui';
-import { Button, createModal, Flexbox, Icon } from '@lobehub/ui';
+import { Button, Flexbox, Icon } from '@lobehub/ui';
+import {
+ createModal,
+ type ImperativeModalProps,
+ ModalFooter,
+ type ModalInstance,
+} from '@lobehub/ui/base-ui';
+import { t as i18nt } from 'i18next';
import { AlertCircle, LogIn } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,12 +16,13 @@ import { useTranslation } from 'react-i18next';
import { useElectronStore } from '@/store/electron';
interface AuthRequiredModalContentProps {
+ onActionReady: (api: { signIn: () => Promise<void> }) => void;
onClose: () => void;
onSigningInChange?: (isSigningIn: boolean) => void;
}
const AuthRequiredModalContent = memo<AuthRequiredModalContentProps>(
- ({ onClose, onSigningInChange }) => {
+ ({ onActionReady, onClose, onSigningInChange }) => {
const { t } = useTranslation('auth');
const [isSigningIn, setIsSigningIn] = useState(false);
const isClosingRef = useRef(false);
@@ -32,7 +39,6 @@ const AuthRequiredModalContent = memo<AuthRequiredModalContentProps>(
onSigningInChange?.(isSigningIn);
}, [isSigningIn, onSigningInChange]);
- // Listen for successful authorization to close the modal
useWatchBroadcast('authorizationSuccessful', async () => {
if (isClosingRef.current) return;
isClosingRef.current = true;
@@ -41,12 +47,11 @@ const AuthRequiredModalContent = memo<AuthRequiredModalContentProps>(
await refreshServerConfig();
});
- // Listen for authorization failure
useWatchBroadcast('authorizationFailed', () => {
setIsSigningIn(false);
});
- const handleSignIn = useCallback(async () => {
+ const signIn = useCallback(async () => {
setIsSigningIn(true);
clearRemoteServerSyncError();
@@ -56,81 +61,93 @@ const AuthRequiredModalContent = memo<AuthRequiredModalContentProps>(
});
}, [clearRemoteServerSyncError, connectRemoteServer, dataSyncConfig]);
- const handleLater = useCallback(() => {
- if (isClosingRef.current) return;
- isClosingRef.current = true;
- onClose();
- }, [onClose]);
-
- return (
- <Flexbox gap={16} style={{ padding: 16 }}>
- <p style={{ margin: 0 }}>{t('authModal.description')}</p>
- <Flexbox horizontal gap={8} justify="flex-end">
- <Button disabled={isSigningIn} onClick={handleLater}>
- {t('authModal.later')}
- </Button>
- <Button
- icon={<Icon icon={LogIn} />}
- loading={isSigningIn}
- type="primary"
- onClick={handleSignIn}
- >
- {isSigningIn ? t('authModal.signingIn') : t('authModal.signIn')}
- </Button>
- </Flexbox>
- </Flexbox>
- );
+ useEffect(() => {
+ onActionReady({ signIn });
+ }, [onActionReady, signIn]);
+
+ return <p style={{ margin: 0 }}>{t('authModal.description')}</p>;
},
);
AuthRequiredModalContent.displayName = 'AuthRequiredModalContent';
-/**
- * Hook to create and manage the auth required modal
- */
-export const useAuthRequiredModal = () => {
+interface FooterProps {
+ isSigningIn: boolean;
+ onLater: () => void;
+ onSignIn: () => void;
+}
+
+const AuthRequiredFooter = memo<FooterProps>(({ isSigningIn, onLater, onSignIn }) => {
const { t } = useTranslation('auth');
+ return (
+ <ModalFooter>
+ <Button disabled={isSigningIn} onClick={onLater}>
+ {t('authModal.later')}
+ </Button>
+ <Button icon={<Icon icon={LogIn} />} loading={isSigningIn} type="primary" onClick={onSignIn}>
+ {isSigningIn ? t('authModal.signingIn') : t('authModal.signIn')}
+ </Button>
+ </ModalFooter>
+ );
+});
+AuthRequiredFooter.displayName = 'AuthRequiredFooter';
+
+export const useAuthRequiredModal = () => {
const instanceRef = useRef<ModalInstance | null>(null);
const open = useCallback(() => {
if (instanceRef.current) return;
+ let isSigningIn = false;
+ const isClosingRef = { current: false };
+ let signIn: () => Promise<void> = async () => {};
+
const handleClose = () => {
+ if (isClosingRef.current) return;
+ isClosingRef.current = true;
instanceRef.current?.close();
instanceRef.current = null;
};
- const handleSigningInChange = (isSigningIn: boolean) => {
- instanceRef.current?.update?.({
- closable: !isSigningIn,
- keyboard: !isSigningIn,
- maskClosable: !isSigningIn,
- });
- };
+ const renderFooter = () => (
+ <AuthRequiredFooter
+ isSigningIn={isSigningIn}
+ onLater={handleClose}
+ onSignIn={() => signIn()}
+ />
+ );
instanceRef.current = createModal({
- children: (
- <AuthRequiredModalContent onClose={handleClose} onSigningInChange={handleSigningInChange} />
+ content: (
+ <AuthRequiredModalContent
+ onClose={handleClose}
+ onActionReady={(api) => {
+ signIn = api.signIn;
+ }}
+ onSigningInChange={(next) => {
+ if (isSigningIn === next) return;
+ isSigningIn = next;
+ instanceRef.current?.update?.({
+ footer: renderFooter(),
+ maskClosable: !next,
+ } as Partial<ImperativeModalProps>);
+ }}
+ />
),
- closable: false,
- footer: null,
- keyboard: false,
+ footer: renderFooter(),
maskClosable: false,
title: (
<Flexbox horizontal align="center" gap={8}>
<Icon icon={AlertCircle} />
- {t('authModal.title')}
+ {i18nt('authModal.title', { ns: 'auth' })}
</Flexbox>
),
});
- }, [t]);
+ }, []);
return { open };
};
-/**
- * Component that listens for authorizationRequired IPC events and opens the modal
- */
const AuthRequiredModal = memo(() => {
const { open } = useAuthRequiredModal();
diff --git a/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx b/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx
deleted file mode 100644
index e31cf7ea536..00000000000
--- a/src/features/LibraryModal/AddFilesToKnowledgeBase/SelectForm.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import { Block, Button, Flexbox, Form, MaterialFileTypeIcon, Select } from '@lobehub/ui';
-import { App } from 'antd';
-import { memo, useState } from 'react';
-import { Trans, useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
-
-import RepoIcon from '@/components/LibIcon';
-import { useKnowledgeBaseStore } from '@/store/library';
-
-interface CreateFormProps {
- fileIds: string[];
- knowledgeBaseId?: string;
- onClose?: () => void;
- resolveFileIds?: () => Promise<string[]>;
- selectedCount?: number;
-}
-
-const SelectForm = memo<CreateFormProps>(
- ({ onClose, knowledgeBaseId, fileIds, resolveFileIds, selectedCount }) => {
- const { t } = useTranslation('knowledgeBase');
- const [loading, setLoading] = useState(false);
-
- const { message } = App.useApp();
- const [useFetchKnowledgeBaseList, addFilesToKnowledgeBase] = useKnowledgeBaseStore((s) => [
- s.useFetchKnowledgeBaseList,
- s.addFilesToKnowledgeBase,
- ]);
- const { data, isLoading } = useFetchKnowledgeBaseList();
- const onFinish = async (values: { id: string }) => {
- setLoading(true);
-
- try {
- const effectiveFileIds = resolveFileIds ? await resolveFileIds() : fileIds;
- await addFilesToKnowledgeBase(values.id, effectiveFileIds);
- setLoading(false);
- message.success({
- content: (
- <Trans
- i18nKey={'addToKnowledgeBase.addSuccess'}
- ns={'knowledgeBase'}
- components={[
- <span key="0" />,
- <Link key="1" to={`/knowledge/library/${values.id}`} />,
- ]}
- />
- ),
- });
-
- onClose?.();
- } catch (e) {
- console.error(e);
- setLoading(false);
- }
- };
-
- return (
- <Form
- gap={16}
- itemsType={'flat'}
- layout={'vertical'}
- footer={
- <Button block htmlType={'submit'} loading={loading} type={'primary'}>
- {t('addToKnowledgeBase.confirm')}
- </Button>
- }
- items={[
- {
- children: (
- <Block horizontal align={'center'} gap={8} padding={16} variant={'filled'}>
- <MaterialFileTypeIcon filename={''} size={32} />
- {t('addToKnowledgeBase.totalFiles', { count: selectedCount ?? fileIds.length })}
- </Block>
- ),
- noStyle: true,
- },
- {
- children: (
- <Select
- autoFocus
- loading={isLoading}
- placeholder={t('addToKnowledgeBase.id.placeholder')}
- options={(data || [])
- .filter((item) => item.id !== knowledgeBaseId)
- .map((item) => ({
- label: (
- <Flexbox horizontal gap={8}>
- <RepoIcon />
- {item.name}
- </Flexbox>
- ),
- value: item.id,
- }))}
- />
- ),
- label: t('addToKnowledgeBase.id.title'),
- name: 'id',
- rules: [{ message: t('addToKnowledgeBase.id.required'), required: true }],
- },
- ]}
- onFinish={onFinish}
- />
- );
- },
-);
-
-export default SelectForm;
diff --git a/src/features/LibraryModal/AddFilesToKnowledgeBase/index.test.tsx b/src/features/LibraryModal/AddFilesToKnowledgeBase/index.test.tsx
deleted file mode 100644
index 45caec883ff..00000000000
--- a/src/features/LibraryModal/AddFilesToKnowledgeBase/index.test.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import type * as LobehubUiModule from '@lobehub/ui';
-import { renderHook } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { useAddFilesToKnowledgeBaseModal } from './index';
-
-const mockCreateModal = vi.hoisted(() => vi.fn());
-
-vi.mock('@lobehub/ui', async (importOriginal) => {
- const actual = await importOriginal<typeof LobehubUiModule>();
-
- return {
- ...actual,
- Flexbox: () => null,
- Icon: () => null,
- createModal: mockCreateModal,
- useModalContext: () => ({ close: vi.fn() }),
- };
-});
-
-describe('useAddFilesToKnowledgeBaseModal', () => {
- it('should forward onClose to createModal afterClose', () => {
- const onClose = vi.fn();
- const { result } = renderHook(() => useAddFilesToKnowledgeBaseModal());
-
- result.current.open({ fileIds: ['file-1'], onClose });
-
- expect(mockCreateModal).toHaveBeenCalledWith(expect.objectContaining({ afterClose: onClose }));
- });
-});
diff --git a/src/features/LibraryModal/AddFilesToKnowledgeBase/index.tsx b/src/features/LibraryModal/AddFilesToKnowledgeBase/index.tsx
deleted file mode 100644
index c1f3114ca26..00000000000
--- a/src/features/LibraryModal/AddFilesToKnowledgeBase/index.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { createModal, Flexbox, Icon, useModalContext } from '@lobehub/ui';
-import { BookUp2Icon } from 'lucide-react';
-import { memo, Suspense, useCallback } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import SelectForm from './SelectForm';
-
-interface AddFilesToKnowledgeBaseModalProps {
- fileIds: string[];
- knowledgeBaseId?: string;
- onClose?: () => void;
- resolveFileIds?: () => Promise<string[]>;
- selectedCount?: number;
-}
-
-interface ModalContentProps {
- fileIds: string[];
- knowledgeBaseId?: string;
- resolveFileIds?: () => Promise<string[]>;
- selectedCount?: number;
-}
-
-const ModalContent = memo<ModalContentProps>(
- ({ fileIds, knowledgeBaseId, resolveFileIds, selectedCount }) => {
- const { t } = useTranslation('knowledgeBase');
- const { close } = useModalContext();
- return (
- <>
- <Flexbox
- horizontal
- gap={8}
- paddingBlock={16}
- paddingInline={16}
- style={{ paddingBottom: 0 }}
- >
- <Icon icon={BookUp2Icon} />
- {t('addToKnowledgeBase.title')}
- </Flexbox>
- <Flexbox padding={16} style={{ paddingTop: 0 }}>
- <SelectForm
- fileIds={fileIds}
- knowledgeBaseId={knowledgeBaseId}
- resolveFileIds={resolveFileIds}
- selectedCount={selectedCount}
- onClose={close}
- />
- </Flexbox>
- </>
- );
- },
-);
-
-ModalContent.displayName = 'AddFilesToKnowledgeBaseModalContent';
-
-export const useAddFilesToKnowledgeBaseModal = () => {
- const open = useCallback((params?: AddFilesToKnowledgeBaseModalProps) => {
- createModal({
- afterClose: params?.onClose,
- children: (
- <Suspense fallback={<div style={{ minHeight: 200 }} />}>
- <ModalContent
- fileIds={params?.fileIds || []}
- knowledgeBaseId={params?.knowledgeBaseId}
- resolveFileIds={params?.resolveFileIds}
- selectedCount={params?.selectedCount}
- />
- </Suspense>
- ),
- footer: null,
- title: null,
- });
- }, []);
-
- return { open };
-};
diff --git a/src/features/LibraryModal/CreateNew/index.tsx b/src/features/LibraryModal/CreateNew/index.tsx
index ea6a8cdd27c..74538521cbe 100644
--- a/src/features/LibraryModal/CreateNew/index.tsx
+++ b/src/features/LibraryModal/CreateNew/index.tsx
@@ -1,4 +1,4 @@
-import { createModal, Flexbox, useModalContext } from '@lobehub/ui';
+import { createModal, useModalContext } from '@lobehub/ui/base-ui';
import { memo, Suspense, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,11 +13,7 @@ interface ModalContentProps {
const ModalContent = memo<ModalContentProps>(({ id, initialValues, onSuccess }) => {
const { close } = useModalContext();
- return (
- <Flexbox paddingInline={8} style={{ paddingBottom: 8 }}>
- <CreateForm id={id} initialValues={initialValues} onClose={close} onSuccess={onSuccess} />
- </Flexbox>
- );
+ return <CreateForm id={id} initialValues={initialValues} onClose={close} onSuccess={onSuccess} />;
});
ModalContent.displayName = 'KnowledgeBaseCreateModalContent';
@@ -36,7 +32,7 @@ export const useCreateNewModal = () => {
const isEditMode = !!props?.id;
createModal({
- children: (
+ content: (
<Suspense fallback={<div style={{ minHeight: 200 }} />}>
<ModalContent
id={props?.id}
@@ -45,10 +41,9 @@ export const useCreateNewModal = () => {
/>
</Suspense>
),
- width: 420,
- focusTriggerAfterClose: true,
footer: null,
title: isEditMode ? t('createNew.edit.title') : t('createNew.title'),
+ width: 420,
});
},
[t],
diff --git a/src/features/LibraryModal/index.ts b/src/features/LibraryModal/index.ts
index a865e1b3b9d..4aa226de76e 100644
--- a/src/features/LibraryModal/index.ts
+++ b/src/features/LibraryModal/index.ts
@@ -1,3 +1,2 @@
-export * from './AddFilesToKnowledgeBase';
export * from './AssignKnowledgeBase';
export * from './CreateNew';
diff --git a/src/features/SkillStore/SkillDetail/index.tsx b/src/features/SkillStore/SkillDetail/index.tsx
index 405443896b6..0116af2480b 100644
--- a/src/features/SkillStore/SkillDetail/index.tsx
+++ b/src/features/SkillStore/SkillDetail/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import { createModal } from '@lobehub/ui';
+import { createModal } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
import { type Klavis } from 'klavis';
@@ -17,8 +17,7 @@ export const createBuiltinAgentSkillDetailModal = ({
identifier,
}: CreateBuiltinAgentSkillDetailModalOptions) =>
createModal({
- children: <BuiltinAgentSkillDetailContent identifier={identifier} />,
- destroyOnHidden: true,
+ content: <BuiltinAgentSkillDetailContent identifier={identifier} />,
footer: null,
title: t('dev.title.skillDetails', { ns: 'plugin' }),
width: 800,
@@ -32,8 +31,7 @@ export const createBuiltinSkillDetailModal = ({
identifier,
}: CreateBuiltinSkillDetailModalOptions) =>
createModal({
- children: <BuiltinSkillDetailContent identifier={identifier} />,
- destroyOnHidden: true,
+ content: <BuiltinSkillDetailContent identifier={identifier} />,
footer: null,
title: t('dev.title.skillDetails', { ns: 'plugin' }),
width: 800,
@@ -49,8 +47,7 @@ export const createKlavisSkillDetailModal = ({
serverName,
}: CreateKlavisSkillDetailModalOptions) =>
createModal({
- children: <KlavisSkillDetailContent identifier={identifier} serverName={serverName} />,
- destroyOnHidden: true,
+ content: <KlavisSkillDetailContent identifier={identifier} serverName={serverName} />,
footer: null,
title: t('dev.title.skillDetails', { ns: 'plugin' }),
width: 800,
@@ -64,8 +61,7 @@ export const createLobehubSkillDetailModal = ({
identifier,
}: CreateLobehubSkillDetailModalOptions) =>
createModal({
- children: <LobehubSkillDetailContent identifier={identifier} />,
- destroyOnHidden: true,
+ content: <LobehubSkillDetailContent identifier={identifier} />,
footer: null,
title: t('dev.title.skillDetails', { ns: 'plugin' }),
width: 800,
diff --git a/src/features/SkillStore/SkillStoreContent.tsx b/src/features/SkillStore/SkillStoreContent.tsx
index dd1c11dd503..0a4bbaac683 100644
--- a/src/features/SkillStore/SkillStoreContent.tsx
+++ b/src/features/SkillStore/SkillStoreContent.tsx
@@ -39,7 +39,7 @@ export const SkillStoreContent = () => {
return (
<Flexbox gap={8} style={{ maxHeight: '75vh' }} width={'100%'}>
- <Flexbox gap={8} paddingInline={16}>
+ <Flexbox gap={8}>
<Flexbox horizontal align={'center'} gap={8}>
<Segmented
block
@@ -57,7 +57,7 @@ export const SkillStoreContent = () => {
onSkillSearch={setSkillKeywords}
/>
</Flexbox>
- <Flexbox height={496}>
+ <Flexbox height={496} style={{ marginBlockEnd: -12, marginInline: -16 }}>
<Flexbox flex={1} style={{ display: isLobeHub ? 'flex' : 'none', overflow: 'auto' }}>
<LobeHubList keywords={lobehubKeywords} />
</Flexbox>
diff --git a/src/features/SkillStore/index.tsx b/src/features/SkillStore/index.tsx
index 1c60563ac54..8d9d8ee9f6d 100644
--- a/src/features/SkillStore/index.tsx
+++ b/src/features/SkillStore/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import { createModal, LOBE_THEME_APP_ID } from '@lobehub/ui';
+import { createModal } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
import { isDesktop } from '@/const/version';
@@ -10,20 +10,12 @@ import { SkillStoreContent } from './SkillStoreContent';
export const createSkillStoreModal = () =>
createModal({
- allowFullscreen: true,
- children: (
+ content: (
<MarketAuthProvider isDesktop={isDesktop}>
<SkillStoreContent />
</MarketAuthProvider>
),
- destroyOnHidden: false,
footer: null,
- // Render the antd Modal inside appElement instead of document.body,
- // so the modal and DropdownMenu portals share the same stacking context
- getContainer: () => document.getElementById(LOBE_THEME_APP_ID) || document.body,
- styles: {
- body: { overflow: 'hidden', padding: 0 },
- },
title: t('skillStore.title', { ns: 'setting' }),
width: 'min(80%, 800px)',
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
index 310b742314d..472e187c357 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
@@ -11,13 +11,13 @@ import { Link, useNavigate, useParams } from 'react-router-dom';
import { agentEvalService } from '@/services/agentEval';
import { runSelectors, useEvalStore } from '@/store/eval';
-import DatasetEditModal from '../../../../features/DatasetEditModal';
-import DatasetImportModal from '../../../../features/DatasetImportModal';
-import TestCaseCreateModal from '../../../../features/TestCaseCreateModal';
-import TestCaseEditModal from '../../../../features/TestCaseEditModal';
+import { createDatasetEditModal } from '../../../../features/DatasetEditModal';
+import { createDatasetImportModal } from '../../../../features/DatasetImportModal';
+import { createTestCaseCreateModal } from '../../../../features/TestCaseCreateModal';
+import { createTestCaseEditModal } from '../../../../features/TestCaseEditModal';
import TestCasePreviewPanel from '../../features/DatasetsTab/TestCasePreviewPanel';
import TestCaseTable from '../../features/DatasetsTab/TestCaseTable';
-import RunCreateModal from '../../features/RunCreateModal';
+import { createRunCreateModal } from '../../features/RunCreateModal';
import EmptyState from '../../features/RunsTab/EmptyState';
import RunCard from '../../features/RunsTab/RunCard';
@@ -31,11 +31,6 @@ const DatasetDetail = memo(() => {
const [search, setSearch] = useState('');
const [diffFilter, setDiffFilter] = useState<'all' | 'easy' | 'medium' | 'hard'>('all');
const [previewCase, setPreviewCase] = useState<any | null>(null);
- const [editOpen, setEditOpen] = useState(false);
- const [editingCase, setEditingCase] = useState<any | null>(null);
- const [importOpen, setImportOpen] = useState(false);
- const [addCaseOpen, setAddCaseOpen] = useState(false);
- const [createRunOpen, setCreateRunOpen] = useState(false);
const useFetchDatasetDetail = useEvalStore((s) => s.useFetchDatasetDetail);
const useFetchTestCases = useEvalStore((s) => s.useFetchTestCases);
@@ -182,7 +177,7 @@ const DatasetDetail = memo(() => {
icon={Pencil}
size="small"
variant="outlined"
- onClick={() => setEditOpen(true)}
+ onClick={() => createDatasetEditModal({ dataset, onSuccess: handleRefresh })}
>
{t('common.edit')}
</Button>
@@ -216,16 +211,22 @@ const DatasetDetail = memo(() => {
selectedId={previewCase?.id}
testCases={filteredCases}
total={total}
- onAddCase={() => setAddCaseOpen(true)}
onDelete={handleDeleteCase}
- onEdit={setEditingCase}
- onImport={() => setImportOpen(true)}
onPageChange={(page, pageSize) => setPagination({ current: page, pageSize })}
onPreview={setPreviewCase}
+ onAddCase={() =>
+ createTestCaseCreateModal({ datasetId: datasetId!, onSuccess: handleRefresh })
+ }
onDiffFilterChange={(f) => {
setDiffFilter(f);
setPagination((prev) => ({ ...prev, current: 1 }));
}}
+ onEdit={(testCase) =>
+ createTestCaseEditModal({ onSuccess: handleRefresh, testCase })
+ }
+ onImport={() =>
+ createDatasetImportModal({ datasetId: datasetId!, onSuccess: handleRefresh })
+ }
onSearchChange={(v) => {
setSearch(v);
setPagination((prev) => ({ ...prev, current: 1 }));
@@ -240,7 +241,17 @@ const DatasetDetail = memo(() => {
<Typography.Text strong>
{t('dataset.detail.relatedRuns', { count: sortedRuns.length })}
</Typography.Text>
- <Button icon={Plus} size="small" onClick={() => setCreateRunOpen(true)}>
+ <Button
+ icon={Plus}
+ size="small"
+ onClick={() =>
+ createRunCreateModal({
+ benchmarkId: benchmarkId!,
+ datasetId: datasetId!,
+ datasetName: dataset.name,
+ })
+ }
+ >
{t('dataset.detail.addRun')}
</Button>
</Flexbox>
@@ -251,7 +262,15 @@ const DatasetDetail = memo(() => {
))}
</Flexbox>
) : (
- <EmptyState onCreate={() => setCreateRunOpen(true)} />
+ <EmptyState
+ onCreate={() =>
+ createRunCreateModal({
+ benchmarkId: benchmarkId!,
+ datasetId: datasetId!,
+ datasetName: dataset.name,
+ })
+ }
+ />
)}
</Flexbox>
</Flexbox>
@@ -260,46 +279,6 @@ const DatasetDetail = memo(() => {
<TestCasePreviewPanel testCase={previewCase} onClose={() => setPreviewCase(null)} />
)}
</Flexbox>
-
- {editOpen && (
- <DatasetEditModal
- dataset={dataset}
- open={editOpen}
- onCancel={() => setEditOpen(false)}
- onSuccess={handleRefresh}
- />
- )}
-
- <DatasetImportModal
- datasetId={datasetId!}
- open={importOpen}
- onClose={() => setImportOpen(false)}
- onSuccess={handleRefresh}
- />
-
- <TestCaseCreateModal
- datasetId={datasetId!}
- open={addCaseOpen}
- onClose={() => setAddCaseOpen(false)}
- onSuccess={handleRefresh}
- />
-
- {editingCase && (
- <TestCaseEditModal
- open={!!editingCase}
- testCase={editingCase}
- onClose={() => setEditingCase(null)}
- onSuccess={handleRefresh}
- />
- )}
-
- <RunCreateModal
- benchmarkId={benchmarkId!}
- datasetId={datasetId!}
- datasetName={dataset.name}
- open={createRunOpen}
- onClose={() => setCreateRunOpen(false)}
- />
</>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
index 4a70625f55b..881df16b809 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/BenchmarkHeader/index.tsx
@@ -18,13 +18,13 @@ import {
User,
} from 'lucide-react';
import { type LucideIcon } from 'lucide-react';
-import { memo, useMemo, useState } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useEvalStore } from '@/store/eval';
-import BenchmarkEditModal from '../../../../features/BenchmarkEditModal';
+import { createBenchmarkEditModal } from '../../../../features/BenchmarkEditModal';
import { formatDuration, formatDurationMinutes } from '../../../../utils';
const RANK_COLORS = [cssVar.colorPrimary, cssVar.colorSuccess, cssVar.colorTextQuaternary];
@@ -101,13 +101,14 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
const navigate = useNavigate();
const deleteBenchmark = useEvalStore((s) => s.deleteBenchmark);
const refreshBenchmarkDetail = useEvalStore((s) => s.refreshBenchmarkDetail);
- const [editOpen, setEditOpen] = useState(false);
const handleEditSuccess = async () => {
await refreshBenchmarkDetail(benchmark.id);
onBenchmarkUpdate?.(benchmark);
};
+ const handleEdit = () => createBenchmarkEditModal({ benchmark, onSuccess: handleEditSuccess });
+
const handleDelete = () => {
confirmModal({
content: t('benchmark.actions.delete.confirm'),
@@ -222,7 +223,7 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
</Flexbox>
<Flexbox horizontal gap={8}>
- <Button icon={Edit} size="small" variant="outlined" onClick={() => setEditOpen(true)}>
+ <Button icon={Edit} size="small" variant="outlined" onClick={handleEdit}>
{t('common.edit')}
</Button>
<Dropdown menu={{ items: menuItems }} placement="bottomRight" trigger={['click']}>
@@ -495,13 +496,6 @@ const BenchmarkHeader = memo<BenchmarkHeaderProps>(
</Flexbox>
</div>
</Flexbox>
-
- <BenchmarkEditModal
- benchmark={benchmark}
- open={editOpen}
- onCancel={() => setEditOpen(false)}
- onSuccess={handleEditSuccess}
- />
</>
);
},
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetRunCreateModal/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetRunCreateModal/index.tsx
deleted file mode 100644
index c4c145bb092..00000000000
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetRunCreateModal/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from '../RunCreateModal';
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewModal.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewModal.tsx
deleted file mode 100644
index 4d370fa8b6d..00000000000
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewModal.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import { Flexbox } from '@lobehub/ui';
-import { Badge, Modal } from 'antd';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-interface TestCasePreviewModalProps {
- onClose: () => void;
- open: boolean;
- testCase: any | null;
-}
-
-const getDifficultyBadge = (difficulty: string) => {
- const config: Record<string, { bg: string; color: string }> = {
- easy: {
- bg: 'var(--ant-color-success-bg)',
- color: 'var(--ant-color-success)',
- },
- hard: {
- bg: 'var(--ant-color-error-bg)',
- color: 'var(--ant-color-error)',
- },
- medium: {
- bg: 'var(--ant-color-warning-bg)',
- color: 'var(--ant-color-warning)',
- },
- };
-
- const c = config[difficulty] || config.easy;
- return (
- <Badge
- style={{
- backgroundColor: c.bg,
- borderColor: c.color + '30',
- color: c.color,
- fontSize: 11,
- textTransform: 'capitalize',
- }}
- >
- {difficulty}
- </Badge>
- );
-};
-
-const TestCasePreviewModal = memo<TestCasePreviewModalProps>(({ open, testCase, onClose }) => {
- const { t } = useTranslation('eval');
-
- return (
- <Modal footer={null} open={open} title={t('testCase.preview.title')} width={600} onCancel={onClose}>
- {testCase && (
- <Flexbox gap={16}>
- <Flexbox gap={4}>
- <p
- style={{
- color: 'var(--ant-color-text-tertiary)',
- fontSize: 12,
- fontWeight: 500,
- margin: 0,
- textTransform: 'uppercase',
- }}
- >
- {t('testCase.preview.input')}
- </p>
- <div
- style={{
- background: 'var(--ant-color-fill-secondary)',
- borderRadius: 8,
- color: 'var(--ant-color-text)',
- fontSize: 14,
- lineHeight: 1.6,
- padding: 12,
- }}
- >
- {testCase.content?.input}
- </div>
- </Flexbox>
- <Flexbox gap={4}>
- <p
- style={{
- color: 'var(--ant-color-text-tertiary)',
- fontSize: 12,
- fontWeight: 500,
- margin: 0,
- textTransform: 'uppercase',
- }}
- >
- {t('testCase.preview.expected')}
- </p>
- <div
- style={{
- background: 'var(--ant-color-fill-secondary)',
- borderRadius: 8,
- color: 'var(--ant-color-text)',
- fontSize: 14,
- lineHeight: 1.6,
- padding: 12,
- }}
- >
- {testCase.content?.expectedOutput || '-'}
- </div>
- </Flexbox>
- <Flexbox horizontal align="center" gap={8}>
- {testCase.metadata?.difficulty && getDifficultyBadge(testCase.metadata.difficulty)}
- {testCase.metadata?.tags?.map((tag: string) => (
- <Badge
- key={tag}
- style={{
- backgroundColor: 'transparent',
- borderColor: 'var(--ant-color-border)',
- color: 'var(--ant-color-text-tertiary)',
- fontSize: 12,
- }}
- >
- {tag}
- </Badge>
- ))}
- </Flexbox>
- </Flexbox>
- )}
- </Modal>
- );
-});
-
-export default TestCasePreviewModal;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
index f2139139af6..c0d3e0fb749 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/index.tsx
@@ -11,11 +11,11 @@ import { useTranslation } from 'react-i18next';
import { agentEvalService } from '@/services/agentEval';
import { useEvalStore } from '@/store/eval';
-import DatasetCreateModal from '../../../../features/DatasetCreateModal';
-import DatasetEditModal from '../../../../features/DatasetEditModal';
-import DatasetImportModal from '../../../../features/DatasetImportModal';
-import TestCaseCreateModal from '../../../../features/TestCaseCreateModal';
-import RunCreateModal from '../RunCreateModal';
+import { createDatasetCreateModal } from '../../../../features/DatasetCreateModal';
+import { createDatasetEditModal } from '../../../../features/DatasetEditModal';
+import { createDatasetImportModal } from '../../../../features/DatasetImportModal';
+import { createTestCaseCreateModal } from '../../../../features/TestCaseCreateModal';
+import { createRunCreateModal } from '../RunCreateModal';
import DatasetCard from './DatasetCard';
import EmptyState from './EmptyState';
@@ -59,13 +59,6 @@ const DatasetsTab = memo<DatasetsTabProps>(
const [search, setSearch] = useState('');
const [diffFilter, setDiffFilter] = useState<'all' | 'easy' | 'medium' | 'hard'>('all');
- // Create, Edit, and Import modals
- const [createOpen, setCreateOpen] = useState(false);
- const [editDataset, setEditDataset] = useState<any | null>(null);
- const [importDatasetId, setImportDatasetId] = useState<string | null>(null);
- const [addCaseDatasetId, setAddCaseDatasetId] = useState<string | null>(null);
- const [runDatasetId, setRunDatasetId] = useState<string | null>(null);
-
const useFetchTestCases = useEvalStore((s) => s.useFetchTestCases);
const refreshTestCases = useEvalStore((s) => s.refreshTestCases);
@@ -114,6 +107,50 @@ const DatasetsTab = memo<DatasetsTabProps>(
setPagination((prev) => ({ ...prev, current: 1 }));
}, []);
+ const handleCreateDataset = useCallback(() => {
+ createDatasetCreateModal({
+ benchmarkId,
+ onSuccess: (dataset) => {
+ onRefresh();
+ confirmModal({
+ cancelText: t('common.later'),
+ content: t('dataset.create.importNow'),
+ okText: t('dataset.actions.import'),
+ onOk: () => {
+ createDatasetImportModal({
+ datasetId: dataset.id,
+ onSuccess: handleRefreshTestCases,
+ presetId: dataset.preset,
+ });
+ },
+ title: t('dataset.create.successTitle'),
+ });
+ },
+ });
+ }, [benchmarkId, handleRefreshTestCases, onRefresh, t]);
+
+ const handleImportDataset = useCallback(
+ (ds: any) => {
+ createDatasetImportModal({
+ datasetId: ds.id,
+ onSuccess: handleRefreshTestCases,
+ presetId: ds.metadata?.preset,
+ });
+ },
+ [handleRefreshTestCases],
+ );
+
+ const handleRunDataset = useCallback(
+ (ds: any) => {
+ createRunCreateModal({
+ benchmarkId,
+ datasetId: ds.id,
+ datasetName: ds.name,
+ });
+ },
+ [benchmarkId],
+ );
+
const handleDeleteCase = useCallback(
(testCase: any) => {
confirmModal({
@@ -144,7 +181,7 @@ const DatasetsTab = memo<DatasetsTabProps>(
<p style={{ color: 'var(--ant-color-text-tertiary)', fontSize: 14, margin: 0 }}>
{t('benchmark.detail.datasetCount', { count: datasets.length })}
</p>
- <Button icon={Plus} size="small" type="primary" onClick={() => setCreateOpen(true)}>
+ <Button icon={Plus} size="small" type="primary" onClick={handleCreateDataset}>
{t('dataset.actions.addDataset')}
</Button>
</Flexbox>
@@ -167,7 +204,7 @@ const DatasetsTab = memo<DatasetsTabProps>(
))}
</Flexbox>
) : datasets.length === 0 ? (
- <EmptyState onAddDataset={() => setCreateOpen(true)} />
+ <EmptyState onAddDataset={handleCreateDataset} />
) : (
<Flexbox gap={12}>
{datasets.map((ds) => {
@@ -184,78 +221,27 @@ const DatasetsTab = memo<DatasetsTabProps>(
pagination={pagination}
search={search}
total={isExpanded ? total : 0}
- onAddCase={() => setAddCaseDatasetId(ds.id)}
onDeleteCase={handleDeleteCase}
onDiffFilterChange={handleDiffFilterChange}
- onEdit={setEditDataset}
onExpand={() => handleExpand(ds.id)}
- onImport={() => setImportDatasetId(ds.id)}
+ onImport={() => handleImportDataset(ds)}
onPageChange={(page, pageSize) => setPagination({ current: page, pageSize })}
onRefresh={onRefresh}
- onRun={() => setRunDatasetId(ds.id)}
+ onRun={() => handleRunDataset(ds)}
onSearchChange={handleSearchChange}
+ onAddCase={() =>
+ createTestCaseCreateModal({
+ datasetId: ds.id,
+ onSuccess: handleRefreshTestCases,
+ })
+ }
+ onEdit={(dataset) => createDatasetEditModal({ dataset, onSuccess: onRefresh })}
/>
);
})}
</Flexbox>
)}
</Flexbox>
-
- {/* Edit Dataset Modal */}
- {editDataset && (
- <DatasetEditModal
- dataset={editDataset}
- open={!!editDataset}
- onCancel={() => setEditDataset(null)}
- onSuccess={onRefresh}
- />
- )}
-
- {/* Create Dataset Modal */}
- <DatasetCreateModal
- benchmarkId={benchmarkId}
- open={createOpen}
- onClose={() => setCreateOpen(false)}
- onSuccess={(dataset) => {
- onRefresh();
- // Ask if user wants to import data immediately
- confirmModal({
- cancelText: t('common.later'),
- content: t('dataset.create.importNow'),
- okText: t('dataset.actions.import'),
- onOk: () => {
- setImportDatasetId(dataset.id);
- },
- title: t('dataset.create.successTitle'),
- });
- }}
- />
-
- {/* Import Dataset Modal */}
- <DatasetImportModal
- datasetId={importDatasetId!}
- open={!!importDatasetId}
- presetId={datasets.find((ds) => ds.id === importDatasetId)?.metadata?.preset}
- onClose={() => setImportDatasetId(null)}
- onSuccess={handleRefreshTestCases}
- />
-
- {/* Add Test Case Modal */}
- <TestCaseCreateModal
- datasetId={addCaseDatasetId!}
- open={!!addCaseDatasetId}
- onClose={() => setAddCaseDatasetId(null)}
- onSuccess={handleRefreshTestCases}
- />
-
- {/* Create Run Modal */}
- <RunCreateModal
- benchmarkId={benchmarkId}
- datasetId={runDatasetId!}
- datasetName={datasets.find((ds) => ds.id === runDatasetId)?.name || ''}
- open={!!runDatasetId}
- onClose={() => setRunDatasetId(null)}
- />
</>
);
},
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
new file mode 100644
index 00000000000..2fdd3a5ec18
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
@@ -0,0 +1,327 @@
+'use client';
+
+import { AGENT_PROFILE_URL, DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
+import { Accordion, AccordionItem, ActionIcon, Avatar, Flexbox, Text } from '@lobehub/ui';
+import { useModalContext } from '@lobehub/ui/base-ui';
+import { Form, Input, InputNumber, Select, Space } from 'antd';
+import { createStaticStyles } from 'antd-style';
+import { SquareArrowOutUpRight } from 'lucide-react';
+import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { agentService } from '@/services/agent';
+import { useEvalStore } from '@/store/eval';
+
+const DEFAULT_MAX_STEPS = 100;
+const DEFAULT_TIMEOUT_MINUTES = 30;
+const MAX_TIMEOUT_MINUTES = 240;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ agentSelect: css`
+ .ant-select-content-value {
+ height: 22px !important;
+ }
+ `,
+ hint: css`
+ display: inline-block;
+ margin-block-start: 4px;
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ timestampLink: css`
+ cursor: pointer;
+
+ display: inline-block;
+
+ margin-block-start: 4px;
+
+ font-size: 12px;
+
+ transition: color 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+}));
+
+interface AgentOption {
+ avatar?: string | null;
+ backgroundColor?: string | null;
+ description?: string | null;
+ id: string;
+ title?: string | null;
+}
+
+export interface RunCreateContentProps {
+ benchmarkId: string;
+ datasetId?: string;
+ datasetName?: string;
+ onLoadingChange?: (loading: boolean) => void;
+ onSubmitReady: (submit: (shouldStart: boolean) => Promise<void>) => void;
+}
+
+const RunCreateContent: FC<RunCreateContentProps> = ({
+ benchmarkId,
+ datasetId,
+ datasetName,
+ onLoadingChange,
+ onSubmitReady,
+}) => {
+ const { t } = useTranslation('eval');
+ const { t: tChat } = useTranslation('chat');
+ const { close } = useModalContext();
+ const navigate = useNavigate();
+ const createRun = useEvalStore((s) => s.createRun);
+ const startRun = useEvalStore((s) => s.startRun);
+ const datasetList = useEvalStore((s) => s.datasetList);
+ const [form] = Form.useForm();
+ const kValue = Form.useWatch('k', form) ?? 1;
+
+ const isDatasetMode = !!datasetId && !!datasetName;
+
+ const [agents, setAgents] = useState<AgentOption[]>([]);
+ const [loadingAgents, setLoadingAgents] = useState(false);
+
+ useEffect(() => {
+ setLoadingAgents(true);
+ agentService
+ .queryAgents()
+ .then((list) => setAgents(list as AgentOption[]))
+ .finally(() => setLoadingAgents(false));
+ }, []);
+
+ useEffect(() => {
+ if (datasetId && !isDatasetMode) {
+ form.setFieldsValue({ datasetId });
+ }
+ }, [datasetId, isDatasetMode, form]);
+
+ const inboxAgent: AgentOption = useMemo(
+ () => ({
+ avatar: DEFAULT_INBOX_AVATAR,
+ id: INBOX_SESSION_ID,
+ title: tChat('inbox.title'),
+ }),
+ [tChat],
+ );
+
+ const allAgents = useMemo(() => [inboxAgent, ...agents], [inboxAgent, agents]);
+
+ const agentOptions = useMemo(
+ () =>
+ allAgents.map((agent) => ({
+ label: (
+ <span style={{ alignItems: 'center', display: 'inline-flex', gap: 8 }}>
+ <Avatar
+ avatar={agent.avatar || undefined}
+ background={agent.backgroundColor || undefined}
+ size={20}
+ title={agent.title || ''}
+ />
+ <span>{agent.title}</span>
+ </span>
+ ),
+ searchLabel: agent.title || '',
+ value: agent.id,
+ })),
+ [allAgents],
+ );
+
+ const handleOpenAgent = useCallback((agentId: string, e: React.MouseEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+ window.open(AGENT_PROFILE_URL(agentId), `agent_${agentId}`, 'noopener,noreferrer');
+ }, []);
+
+ const submit = useCallback(
+ async (shouldStart: boolean) => {
+ let values;
+ try {
+ values = await form.validateFields();
+ } catch {
+ return;
+ }
+ onLoadingChange?.(true);
+ try {
+ const maxSteps = values.maxSteps ?? DEFAULT_MAX_STEPS;
+ const timeoutMinutes = values.timeoutMinutes ?? DEFAULT_TIMEOUT_MINUTES;
+ const k = values.k ?? 1;
+ const run = await createRun({
+ config: {
+ k,
+ maxSteps,
+ timeout: timeoutMinutes * 60_000,
+ },
+ datasetId: isDatasetMode ? datasetId : values.datasetId,
+ name: values.name,
+ targetAgentId: values.targetAgentId,
+ });
+ if (run?.id) {
+ if (shouldStart) {
+ await startRun(run.id);
+ }
+ navigate(`/eval/bench/${benchmarkId}/runs/${run.id}`);
+ }
+ close();
+ } finally {
+ onLoadingChange?.(false);
+ }
+ },
+ [
+ benchmarkId,
+ close,
+ createRun,
+ datasetId,
+ form,
+ isDatasetMode,
+ navigate,
+ onLoadingChange,
+ startRun,
+ ],
+ );
+
+ useEffect(() => {
+ onSubmitReady(submit);
+ }, [onSubmitReady, submit]);
+
+ return (
+ <Form form={form} layout="vertical">
+ <Form.Item
+ label={t('run.create.name')}
+ name="name"
+ rules={[{ message: t('run.create.name.required'), required: true }]}
+ extra={
+ <Text
+ className={styles.timestampLink}
+ type="secondary"
+ onClick={() => {
+ const now = new Date();
+ const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
+ form.setFieldsValue({ name: ts });
+ }}
+ >
+ {t('run.create.name.useTimestamp')}
+ </Text>
+ }
+ >
+ <Input placeholder={t('run.create.name.placeholder')} variant="filled" />
+ </Form.Item>
+
+ <Form.Item
+ label={t('run.create.agent')}
+ name="targetAgentId"
+ rules={[{ message: t('run.create.agent.required'), required: true }]}
+ >
+ <Select
+ allowClear
+ showSearch
+ className={styles.agentSelect}
+ loading={loadingAgents}
+ options={agentOptions}
+ placeholder={t('run.create.agent.placeholder')}
+ variant="filled"
+ filterOption={(input, option) =>
+ (option?.searchLabel as string)?.toLowerCase().includes(input.toLowerCase())
+ }
+ optionRender={(option) => (
+ <span
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ gap: 8,
+ justifyContent: 'space-between',
+ }}
+ >
+ {option.label}
+ <ActionIcon
+ icon={SquareArrowOutUpRight}
+ size="small"
+ onClick={(e) => handleOpenAgent(option.value as string, e)}
+ />
+ </span>
+ )}
+ />
+ </Form.Item>
+
+ {!isDatasetMode && (
+ <Form.Item
+ label={t('run.create.dataset')}
+ name="datasetId"
+ rules={[{ message: t('run.create.dataset.required'), required: true }]}
+ >
+ <Select
+ placeholder={t('run.create.dataset.placeholder')}
+ variant="filled"
+ options={datasetList.map((ds) => ({
+ label: (
+ <Space>
+ <span>{ds.name}</span>
+ {ds.testCaseCount !== undefined && (
+ <span style={{ color: 'var(--ant-color-text-quaternary)', fontSize: 12 }}>
+ {t('run.create.caseCount', { count: ds.testCaseCount })}
+ </span>
+ )}
+ </Space>
+ ),
+ value: ds.id,
+ }))}
+ />
+ </Form.Item>
+ )}
+
+ <Accordion defaultExpandedKeys={[]}>
+ <AccordionItem
+ itemKey="advanced"
+ paddingBlock={6}
+ paddingInline={4}
+ title={t('run.create.advanced')}
+ >
+ <Flexbox gap={16} style={{ paddingTop: 8 }}>
+ <Form.Item
+ extra={<span className={styles.hint}>{t('run.config.k.hint', { k: kValue })}</span>}
+ initialValue={1}
+ label={t('run.config.k')}
+ name="k"
+ style={{ marginBottom: 0 }}
+ >
+ <InputNumber max={10} min={1} step={1} style={{ width: '100%' }} variant="filled" />
+ </Form.Item>
+ <Form.Item
+ extra={<span className={styles.hint}>{t('run.config.maxSteps.hint')}</span>}
+ initialValue={DEFAULT_MAX_STEPS}
+ label={t('run.config.maxSteps')}
+ name="maxSteps"
+ style={{ marginBottom: 0 }}
+ >
+ <InputNumber
+ max={1000}
+ min={1}
+ step={10}
+ style={{ width: '100%' }}
+ variant="filled"
+ />
+ </Form.Item>
+ <Form.Item
+ initialValue={DEFAULT_TIMEOUT_MINUTES}
+ label={t('run.config.timeout')}
+ name="timeoutMinutes"
+ style={{ marginBottom: 0 }}
+ >
+ <InputNumber
+ max={MAX_TIMEOUT_MINUTES}
+ min={1}
+ style={{ width: '100%' }}
+ suffix={t('run.config.timeout.unit')}
+ variant="filled"
+ />
+ </Form.Item>
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
+ </Form>
+ );
+};
+
+export default RunCreateContent;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx
new file mode 100644
index 00000000000..27607802853
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx
@@ -0,0 +1,45 @@
+'use client';
+
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { Button, Dropdown, Space } from 'antd';
+import { ChevronDown } from 'lucide-react';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ loading: boolean;
+ onCreateAndStart: () => void;
+ onCreateOnly: () => void;
+}
+
+const RunCreateFooter: FC<FooterProps> = ({ loading, onCreateAndStart, onCreateOnly }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Space.Compact>
+ <Button loading={loading} type="primary" onClick={onCreateOnly}>
+ {t('run.create.createOnly')}
+ </Button>
+ <Dropdown
+ menu={{
+ items: [
+ {
+ key: 'createAndStart',
+ label: t('run.create.confirm'),
+ onClick: onCreateAndStart,
+ },
+ ],
+ }}
+ >
+ <Button icon={<ChevronDown size={14} />} loading={loading} type="primary" />
+ </Dropdown>
+ </Space.Compact>
+ </ModalFooter>
+ );
+};
+
+export default RunCreateFooter;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/index.tsx
index 5dae8b73aeb..24df9a3cd4d 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/index.tsx
@@ -1,343 +1,47 @@
'use client';
-import { AGENT_PROFILE_URL, DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
-import { Accordion, AccordionItem, ActionIcon, Avatar, Flexbox, Text } from '@lobehub/ui';
-import { Button, Dropdown, Form, Input, InputNumber, Modal, Select, Space } from 'antd';
-import { createStaticStyles } from 'antd-style';
-import { ChevronDown, SquareArrowOutUpRight } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
-
-import { agentService } from '@/services/agent';
-import { runSelectors, useEvalStore } from '@/store/eval';
-
-const DEFAULT_MAX_STEPS = 100;
-const DEFAULT_TIMEOUT_MINUTES = 30;
-const MAX_TIMEOUT_MINUTES = 240;
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- agentSelect: css`
- .ant-select-content-value {
- height: 22px !important;
- }
- `,
- hint: css`
- display: inline-block;
- margin-block-start: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- `,
- timestampLink: css`
- cursor: pointer;
-
- display: inline-block;
-
- margin-block-start: 4px;
-
- font-size: 12px;
-
- transition: color 0.2s;
-
- &:hover {
- color: ${cssVar.colorText};
- }
- `,
-}));
-
-interface AgentOption {
- avatar?: string | null;
- backgroundColor?: string | null;
- description?: string | null;
- id: string;
- title?: string | null;
-}
-
-interface RunCreateModalProps {
- benchmarkId: string;
- datasetId?: string;
- datasetName?: string;
- onClose: () => void;
- open: boolean;
-}
-
-const RunCreateModal = memo<RunCreateModalProps>(
- ({ open, onClose, benchmarkId, datasetId, datasetName }) => {
- const { t } = useTranslation('eval');
- const { t: tChat } = useTranslation('chat');
- const navigate = useNavigate();
- const createRun = useEvalStore((s) => s.createRun);
- const startRun = useEvalStore((s) => s.startRun);
- const isCreatingRun = useEvalStore(runSelectors.isCreatingRun);
- const datasetList = useEvalStore((s) => s.datasetList);
- const [form] = Form.useForm();
- const kValue = Form.useWatch('k', form) ?? 1;
-
- const isDatasetMode = !!datasetId && !!datasetName;
-
- const [agents, setAgents] = useState<AgentOption[]>([]);
- const [loadingAgents, setLoadingAgents] = useState(false);
-
- useEffect(() => {
- if (!open) return;
- setLoadingAgents(true);
- agentService
- .queryAgents()
- .then((list) => setAgents(list as AgentOption[]))
- .finally(() => setLoadingAgents(false));
- }, [open]);
-
- useEffect(() => {
- if (open && datasetId && !isDatasetMode) {
- form.setFieldsValue({ datasetId });
- }
- }, [open, datasetId, isDatasetMode]);
-
- const inboxAgent: AgentOption = useMemo(
- () => ({
- avatar: DEFAULT_INBOX_AVATAR,
- id: INBOX_SESSION_ID,
- title: tChat('inbox.title'),
- }),
- [tChat],
- );
-
- const allAgents = useMemo(() => [inboxAgent, ...agents], [inboxAgent, agents]);
-
- const agentOptions = useMemo(
- () =>
- allAgents.map((agent) => ({
- label: (
- <span style={{ alignItems: 'center', display: 'inline-flex', gap: 8 }}>
- <Avatar
- avatar={agent.avatar || undefined}
- background={agent.backgroundColor || undefined}
- size={20}
- title={agent.title || ''}
- />
- <span>{agent.title}</span>
- </span>
- ),
- searchLabel: agent.title || '',
- value: agent.id,
- })),
- [allAgents],
- );
-
- const handleOpenAgent = useCallback((agentId: string, e: React.MouseEvent) => {
- e.stopPropagation();
- e.preventDefault();
- window.open(AGENT_PROFILE_URL(agentId), `agent_${agentId}`, 'noopener,noreferrer');
- }, []);
-
- const handleSubmit = async (shouldStart: boolean) => {
- const values = await form.validateFields();
- const maxSteps = values.maxSteps ?? DEFAULT_MAX_STEPS;
- const timeoutMinutes = values.timeoutMinutes ?? DEFAULT_TIMEOUT_MINUTES;
- const k = values.k ?? 1;
- const run = await createRun({
- config: {
- k,
- maxSteps,
- timeout: timeoutMinutes * 60_000,
- },
- datasetId: isDatasetMode ? datasetId : values.datasetId,
- name: values.name,
- targetAgentId: values.targetAgentId,
- });
- if (run?.id) {
- if (shouldStart) {
- await startRun(run.id);
- }
- navigate(`/eval/bench/${benchmarkId}/runs/${run.id}`);
- }
- onClose();
- };
-
- const handleClose = () => {
- form.resetFields();
- onClose();
- };
-
- return (
- <Modal
- destroyOnHidden
- open={open}
- footer={
- <Space>
- <Button onClick={handleClose}>{t('common.cancel')}</Button>
- <Space.Compact>
- <Button loading={isCreatingRun} type="primary" onClick={() => handleSubmit(false)}>
- {t('run.create.createOnly')}
- </Button>
- <Dropdown
- menu={{
- items: [
- {
- key: 'createAndStart',
- label: t('run.create.confirm'),
- onClick: () => handleSubmit(true),
- },
- ],
- }}
- >
- <Button icon={<ChevronDown size={14} />} loading={isCreatingRun} type="primary" />
- </Dropdown>
- </Space.Compact>
- </Space>
- }
- title={
- isDatasetMode
- ? t('run.create.titleWithDataset', { dataset: datasetName })
- : t('run.create.title')
- }
- onCancel={handleClose}
- >
- <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
- <Form.Item
- label={t('run.create.name')}
- name="name"
- rules={[{ message: t('run.create.name.required'), required: true }]}
- extra={
- <Text
- className={styles.timestampLink}
- type="secondary"
- onClick={() => {
- const now = new Date();
- const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
- form.setFieldsValue({ name: ts });
- }}
- >
- {t('run.create.name.useTimestamp')}
- </Text>
- }
- >
- <Input placeholder={t('run.create.name.placeholder')} variant="filled" />
- </Form.Item>
-
- <Form.Item
- label={t('run.create.agent')}
- name="targetAgentId"
- rules={[{ message: t('run.create.agent.required'), required: true }]}
- >
- <Select
- allowClear
- showSearch
- className={styles.agentSelect}
- loading={loadingAgents}
- options={agentOptions}
- placeholder={t('run.create.agent.placeholder')}
- variant="filled"
- filterOption={(input, option) =>
- (option?.searchLabel as string)?.toLowerCase().includes(input.toLowerCase())
- }
- optionRender={(option) => (
- <span
- style={{
- alignItems: 'center',
- display: 'flex',
- gap: 8,
- justifyContent: 'space-between',
- }}
- >
- {option.label}
- <ActionIcon
- icon={SquareArrowOutUpRight}
- size="small"
- onClick={(e) => handleOpenAgent(option.value as string, e)}
- />
- </span>
- )}
- />
- </Form.Item>
-
- {!isDatasetMode && (
- <Form.Item
- label={t('run.create.dataset')}
- name="datasetId"
- rules={[{ message: t('run.create.dataset.required'), required: true }]}
- >
- <Select
- placeholder={t('run.create.dataset.placeholder')}
- variant="filled"
- options={datasetList.map((ds) => ({
- label: (
- <Space>
- <span>{ds.name}</span>
- {ds.testCaseCount !== undefined && (
- <span style={{ color: 'var(--ant-color-text-quaternary)', fontSize: 12 }}>
- {t('run.create.caseCount', { count: ds.testCaseCount })}
- </span>
- )}
- </Space>
- ),
- value: ds.id,
- }))}
- />
- </Form.Item>
- )}
-
- <Accordion defaultExpandedKeys={[]}>
- <AccordionItem
- itemKey="advanced"
- paddingBlock={6}
- paddingInline={4}
- title={t('run.create.advanced')}
- >
- <Flexbox gap={16} style={{ paddingTop: 8 }}>
- <Form.Item
- initialValue={1}
- label={t('run.config.k')}
- name="k"
- style={{ marginBottom: 0 }}
- extra={
- <span className={styles.hint}>{t('run.config.k.hint', { k: kValue })}</span>
- }
- >
- <InputNumber
- max={10}
- min={1}
- step={1}
- style={{ width: '100%' }}
- variant="filled"
- />
- </Form.Item>
- <Form.Item
- extra={<span className={styles.hint}>{t('run.config.maxSteps.hint')}</span>}
- initialValue={DEFAULT_MAX_STEPS}
- label={t('run.config.maxSteps')}
- name="maxSteps"
- style={{ marginBottom: 0 }}
- >
- <InputNumber
- max={1000}
- min={1}
- step={10}
- style={{ width: '100%' }}
- variant="filled"
- />
- </Form.Item>
- <Form.Item
- initialValue={DEFAULT_TIMEOUT_MINUTES}
- label={t('run.config.timeout')}
- name="timeoutMinutes"
- style={{ marginBottom: 0 }}
- >
- <InputNumber
- max={MAX_TIMEOUT_MINUTES}
- min={1}
- style={{ width: '100%' }}
- suffix={t('run.config.timeout.unit')}
- variant="filled"
- />
- </Form.Item>
- </Flexbox>
- </AccordionItem>
- </Accordion>
- </Form>
- </Modal>
- );
- },
-);
-
-export default RunCreateModal;
+import { createModal, type ImperativeModalProps, type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import RunCreateContent, { type RunCreateContentProps } from './Content';
+import RunCreateFooter from './Footer';
+
+type Props = Omit<RunCreateContentProps, 'onLoadingChange' | 'onSubmitReady'>;
+
+export const createRunCreateModal = (props: Props): ModalInstance => {
+ const ref: { instance?: ModalInstance } = {};
+ let submit: (shouldStart: boolean) => Promise<void> = async () => {};
+ let loading = false;
+
+ const renderFooter = () => (
+ <RunCreateFooter
+ loading={loading}
+ onCreateAndStart={() => submit(true)}
+ onCreateOnly={() => submit(false)}
+ />
+ );
+
+ const setLoading = (next: boolean) => {
+ loading = next;
+ ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
+ };
+
+ ref.instance = createModal({
+ content: (
+ <RunCreateContent
+ {...props}
+ onLoadingChange={setLoading}
+ onSubmitReady={(s) => {
+ submit = s;
+ }}
+ />
+ ),
+ footer: renderFooter(),
+ title:
+ props.datasetId && props.datasetName
+ ? t('run.create.titleWithDataset', { dataset: props.datasetName, ns: 'eval' })
+ : t('run.create.title', { ns: 'eval' }),
+ width: 520,
+ });
+ return ref.instance;
+};
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
new file mode 100644
index 00000000000..7a18ef799a8
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
@@ -0,0 +1,282 @@
+'use client';
+
+import { AGENT_PROFILE_URL, DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
+import type { AgentEvalRunStatus, EvalRunInputConfig } from '@lobechat/types';
+import { Accordion, AccordionItem, ActionIcon, Avatar, Flexbox } from '@lobehub/ui';
+import { useModalContext } from '@lobehub/ui/base-ui';
+import { App, Form, Input, InputNumber, Select, Space } from 'antd';
+import { createStaticStyles } from 'antd-style';
+import { SquareArrowOutUpRight } from 'lucide-react';
+import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import { agentService } from '@/services/agent';
+import { useEvalStore } from '@/store/eval';
+
+const MAX_TIMEOUT_MINUTES = 240;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ agentSelect: css`
+ .ant-select-content-value {
+ height: 22px !important;
+ }
+ `,
+ hint: css`
+ display: inline-block;
+ margin-block-start: 4px;
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+}));
+
+interface AgentOption {
+ avatar?: string | null;
+ backgroundColor?: string | null;
+ description?: string | null;
+ id: string;
+ title?: string | null;
+}
+
+export interface RunEditContentProps {
+ formId: string;
+ onLoadingChange?: (loading: boolean) => void;
+ run: {
+ config?: { k?: number; maxSteps?: number; timeout?: number } | null;
+ datasetId: string;
+ id: string;
+ name?: string | null;
+ status: AgentEvalRunStatus;
+ targetAgentId?: string | null;
+ };
+}
+
+const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run }) => {
+ const { t } = useTranslation('eval');
+ const { t: tChat } = useTranslation('chat');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const navigate = useNavigate();
+ const { benchmarkId } = useParams<{ benchmarkId: string }>();
+ const updateRun = useEvalStore((s) => s.updateRun);
+ const datasetList = useEvalStore((s) => s.datasetList);
+ const [form] = Form.useForm();
+ const kValue = Form.useWatch('k', form) ?? 1;
+
+ const [agents, setAgents] = useState<AgentOption[]>([]);
+ const [loadingAgents, setLoadingAgents] = useState(false);
+
+ const canChangeConfig = run?.status === 'idle';
+ const isFinished = run?.status === 'completed';
+
+ const currentDataset = useMemo(
+ () => datasetList.find((ds) => ds.id === run?.datasetId),
+ [datasetList, run?.datasetId],
+ );
+
+ useEffect(() => {
+ if (!canChangeConfig) return;
+ setLoadingAgents(true);
+ agentService
+ .queryAgents()
+ .then((list) => setAgents(list as AgentOption[]))
+ .finally(() => setLoadingAgents(false));
+ }, [canChangeConfig]);
+
+ useEffect(() => {
+ if (run) {
+ form.setFieldsValue({
+ k: run.config?.k,
+ maxSteps: run.config?.maxSteps,
+ name: run.name,
+ targetAgentId: run.targetAgentId,
+ timeoutMinutes: run.config?.timeout ? run.config.timeout / 60_000 : undefined,
+ });
+ }
+ }, [run, form]);
+
+ const inboxAgent: AgentOption = useMemo(
+ () => ({
+ avatar: DEFAULT_INBOX_AVATAR,
+ id: INBOX_SESSION_ID,
+ title: tChat('inbox.title'),
+ }),
+ [tChat],
+ );
+
+ const allAgents = useMemo(() => [inboxAgent, ...agents], [inboxAgent, agents]);
+
+ const agentOptions = useMemo(
+ () =>
+ allAgents.map((agent) => ({
+ label: (
+ <span style={{ alignItems: 'center', display: 'inline-flex', gap: 8 }}>
+ <Avatar
+ avatar={agent.avatar || undefined}
+ background={agent.backgroundColor || undefined}
+ size={20}
+ title={agent.title || ''}
+ />
+ <span>{agent.title}</span>
+ </span>
+ ),
+ searchLabel: agent.title || '',
+ value: agent.id,
+ })),
+ [allAgents],
+ );
+
+ const handleOpenAgent = useCallback((agentId: string, e: React.MouseEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+ window.open(AGENT_PROFILE_URL(agentId), `agent_${agentId}`, 'noopener,noreferrer');
+ }, []);
+
+ const handleFinish = async (values: any) => {
+ onLoadingChange?.(true);
+ try {
+ const config: EvalRunInputConfig = {};
+ if (!isFinished) {
+ if (values.maxSteps != null) config.maxSteps = values.maxSteps;
+ if (values.timeoutMinutes != null) config.timeout = values.timeoutMinutes * 60_000;
+ if (values.k != null) config.k = values.k;
+ }
+
+ await updateRun({
+ config: Object.keys(config).length > 0 ? config : undefined,
+ id: run.id,
+ name: values.name,
+ targetAgentId: canChangeConfig ? values.targetAgentId : undefined,
+ });
+ message.success(t('run.edit.success'));
+ close();
+ } catch {
+ message.error(t('run.edit.error'));
+ } finally {
+ onLoadingChange?.(false);
+ }
+ };
+
+ return (
+ <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form.Item label={t('run.create.dataset')}>
+ <Space>
+ <span>{currentDataset?.name || run.datasetId}</span>
+ {currentDataset?.testCaseCount !== undefined && (
+ <span style={{ color: 'var(--ant-color-text-quaternary)', fontSize: 12 }}>
+ {t('run.create.caseCount', { count: currentDataset.testCaseCount })}
+ </span>
+ )}
+ {benchmarkId && (
+ <ActionIcon
+ icon={SquareArrowOutUpRight}
+ size="small"
+ title={t('dataset.detail.viewDetail')}
+ onClick={() => navigate(`/eval/bench/${benchmarkId}/datasets/${run.datasetId}`)}
+ />
+ )}
+ </Space>
+ </Form.Item>
+
+ <Form.Item label={t('run.create.name')} name="name">
+ <Input placeholder={t('run.create.name.placeholder')} variant="filled" />
+ </Form.Item>
+
+ {canChangeConfig && (
+ <Form.Item
+ label={t('run.create.agent')}
+ name="targetAgentId"
+ rules={[{ message: t('run.create.agent.required'), required: true }]}
+ >
+ <Select
+ allowClear
+ showSearch
+ className={styles.agentSelect}
+ loading={loadingAgents}
+ options={agentOptions}
+ placeholder={t('run.create.agent.placeholder')}
+ variant="filled"
+ filterOption={(input, option) =>
+ (option?.searchLabel as string)?.toLowerCase().includes(input.toLowerCase())
+ }
+ optionRender={(option) => (
+ <span
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ gap: 8,
+ justifyContent: 'space-between',
+ }}
+ >
+ {option.label}
+ <ActionIcon
+ icon={SquareArrowOutUpRight}
+ size="small"
+ onClick={(e) => handleOpenAgent(option.value as string, e)}
+ />
+ </span>
+ )}
+ />
+ </Form.Item>
+ )}
+
+ <Accordion defaultExpandedKeys={[]}>
+ <AccordionItem
+ itemKey="advanced"
+ paddingBlock={6}
+ paddingInline={4}
+ title={t('run.create.advanced')}
+ >
+ <Flexbox gap={16} style={{ paddingTop: 8 }}>
+ <Form.Item
+ extra={<span className={styles.hint}>{t('run.config.k.hint', { k: kValue })}</span>}
+ label={t('run.config.k')}
+ name="k"
+ style={{ marginBottom: 0 }}
+ >
+ <InputNumber
+ disabled={isFinished}
+ max={10}
+ min={1}
+ step={1}
+ style={{ width: '100%' }}
+ variant="filled"
+ />
+ </Form.Item>
+ <Form.Item
+ extra={<span className={styles.hint}>{t('run.config.maxSteps.hint')}</span>}
+ label={t('run.config.maxSteps')}
+ name="maxSteps"
+ style={{ marginBottom: 0 }}
+ >
+ <InputNumber
+ disabled={isFinished}
+ max={1000}
+ min={1}
+ step={10}
+ style={{ width: '100%' }}
+ variant="filled"
+ />
+ </Form.Item>
+ <Form.Item
+ label={t('run.config.timeout')}
+ name="timeoutMinutes"
+ style={{ marginBottom: 0 }}
+ >
+ <InputNumber
+ disabled={isFinished}
+ max={MAX_TIMEOUT_MINUTES}
+ min={1}
+ style={{ width: '100%' }}
+ suffix={t('run.config.timeout.unit')}
+ variant="filled"
+ />
+ </Form.Item>
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
+ </Form>
+ );
+};
+
+export default RunEditContent;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Footer.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Footer.tsx
new file mode 100644
index 00000000000..ac21d0efccc
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Footer.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ formId: string;
+ loading: boolean;
+}
+
+const RunEditFooter: FC<FooterProps> = ({ formId, loading }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Button form={formId} htmlType="submit" loading={loading} type="primary">
+ {t('benchmark.edit.confirm')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default RunEditFooter;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/index.tsx
index 12a6dd5bb0a..a026183fe54 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/index.tsx
@@ -1,299 +1,21 @@
'use client';
-import { AGENT_PROFILE_URL, DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
-import type { AgentEvalRunStatus, EvalRunInputConfig } from '@lobechat/types';
-import { Accordion, AccordionItem, ActionIcon, Avatar, Flexbox } from '@lobehub/ui';
-import { App, Form, Input, InputNumber, Modal, Select, Space } from 'antd';
-import { createStaticStyles } from 'antd-style';
-import { SquareArrowOutUpRight } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useNavigate, useParams } from 'react-router-dom';
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
-import { agentService } from '@/services/agent';
-import { useEvalStore } from '@/store/eval';
+import { createFormModal } from '@/utils/createFormModal';
-const DEFAULT_MAX_STEPS = 100;
-const DEFAULT_TIMEOUT_MINUTES = 30;
-const MAX_TIMEOUT_MINUTES = 240;
+import RunEditContent, { type RunEditContentProps } from './Content';
+import RunEditFooter from './Footer';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- agentSelect: css`
- .ant-select-content-value {
- height: 22px !important;
- }
- `,
- hint: css`
- display: inline-block;
- margin-block-start: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextQuaternary};
- `,
-}));
+type Props = Omit<RunEditContentProps, 'formId' | 'onLoadingChange'>;
-interface AgentOption {
- avatar?: string | null;
- backgroundColor?: string | null;
- description?: string | null;
- id: string;
- title?: string | null;
-}
-
-interface RunEditModalProps {
- onClose: () => void;
- open: boolean;
- run: {
- config?: { k?: number; maxSteps?: number; timeout?: number } | null;
- datasetId: string;
- id: string;
- name?: string | null;
- status: AgentEvalRunStatus;
- targetAgentId?: string | null;
- };
-}
-
-const RunEditModal = memo<RunEditModalProps>(({ open, onClose, run }) => {
- const { t } = useTranslation('eval');
- const { t: tChat } = useTranslation('chat');
- const { message } = App.useApp();
- const navigate = useNavigate();
- const { benchmarkId } = useParams<{ benchmarkId: string }>();
- const updateRun = useEvalStore((s) => s.updateRun);
- const datasetList = useEvalStore((s) => s.datasetList);
- const [form] = Form.useForm();
- const kValue = Form.useWatch('k', form) ?? 1;
- const [loading, setLoading] = useState(false);
-
- const [agents, setAgents] = useState<AgentOption[]>([]);
- const [loadingAgents, setLoadingAgents] = useState(false);
-
- const canChangeConfig = run?.status === 'idle';
- const isFinished = run?.status === 'completed';
-
- const currentDataset = useMemo(
- () => datasetList.find((ds) => ds.id === run?.datasetId),
- [datasetList, run?.datasetId],
- );
-
- useEffect(() => {
- if (!open || !canChangeConfig) return;
- setLoadingAgents(true);
- agentService
- .queryAgents()
- .then((list) => setAgents(list as AgentOption[]))
- .finally(() => setLoadingAgents(false));
- }, [open, canChangeConfig]);
-
- useEffect(() => {
- if (open && run) {
- form.setFieldsValue({
- k: run.config?.k,
- maxSteps: run.config?.maxSteps,
- name: run.name,
- targetAgentId: run.targetAgentId,
- timeoutMinutes: run.config?.timeout ? run.config.timeout / 60_000 : undefined,
- });
- }
- }, [open, run]);
-
- const inboxAgent: AgentOption = useMemo(
- () => ({
- avatar: DEFAULT_INBOX_AVATAR,
- id: INBOX_SESSION_ID,
- title: tChat('inbox.title'),
- }),
- [tChat],
- );
-
- const allAgents = useMemo(() => [inboxAgent, ...agents], [inboxAgent, agents]);
-
- const agentOptions = useMemo(
- () =>
- allAgents.map((agent) => ({
- label: (
- <span style={{ alignItems: 'center', display: 'inline-flex', gap: 8 }}>
- <Avatar
- avatar={agent.avatar || undefined}
- background={agent.backgroundColor || undefined}
- size={20}
- title={agent.title || ''}
- />
- <span>{agent.title}</span>
- </span>
- ),
- searchLabel: agent.title || '',
- value: agent.id,
- })),
- [allAgents],
- );
-
- const handleOpenAgent = useCallback((agentId: string, e: React.MouseEvent) => {
- e.stopPropagation();
- e.preventDefault();
- window.open(AGENT_PROFILE_URL(agentId), `agent_${agentId}`, 'noopener,noreferrer');
- }, []);
-
- const handleSubmit = async () => {
- const values = await form.validateFields();
- setLoading(true);
- try {
- const config: EvalRunInputConfig = {};
- if (!isFinished) {
- if (values.maxSteps != null) config.maxSteps = values.maxSteps;
- if (values.timeoutMinutes != null) config.timeout = values.timeoutMinutes * 60_000;
- if (values.k != null) config.k = values.k;
- }
-
- await updateRun({
- config: Object.keys(config).length > 0 ? config : undefined,
- id: run.id,
- name: values.name,
- targetAgentId: canChangeConfig ? values.targetAgentId : undefined,
- });
- message.success(t('run.edit.success'));
- onClose();
- } catch {
- message.error(t('run.edit.error'));
- } finally {
- setLoading(false);
- }
- };
-
- const handleClose = () => {
- form.resetFields();
- onClose();
- };
-
- return (
- <Modal
- destroyOnClose
- confirmLoading={loading}
- okText={t('benchmark.edit.confirm')}
- open={open}
- title={t('run.edit.title')}
- onCancel={handleClose}
- onOk={handleSubmit}
- >
- <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
- <Form.Item label={t('run.create.dataset')}>
- <Space>
- <span>{currentDataset?.name || run.datasetId}</span>
- {currentDataset?.testCaseCount !== undefined && (
- <span style={{ color: 'var(--ant-color-text-quaternary)', fontSize: 12 }}>
- {t('run.create.caseCount', { count: currentDataset.testCaseCount })}
- </span>
- )}
- {benchmarkId && (
- <ActionIcon
- icon={SquareArrowOutUpRight}
- size="small"
- title={t('dataset.detail.viewDetail')}
- onClick={() => navigate(`/eval/bench/${benchmarkId}/datasets/${run.datasetId}`)}
- />
- )}
- </Space>
- </Form.Item>
-
- <Form.Item label={t('run.create.name')} name="name">
- <Input placeholder={t('run.create.name.placeholder')} variant="filled" />
- </Form.Item>
-
- {canChangeConfig && (
- <Form.Item
- label={t('run.create.agent')}
- name="targetAgentId"
- rules={[{ message: t('run.create.agent.required'), required: true }]}
- >
- <Select
- allowClear
- showSearch
- className={styles.agentSelect}
- loading={loadingAgents}
- options={agentOptions}
- placeholder={t('run.create.agent.placeholder')}
- variant="filled"
- filterOption={(input, option) =>
- (option?.searchLabel as string)?.toLowerCase().includes(input.toLowerCase())
- }
- optionRender={(option) => (
- <span
- style={{
- alignItems: 'center',
- display: 'flex',
- gap: 8,
- justifyContent: 'space-between',
- }}
- >
- {option.label}
- <ActionIcon
- icon={SquareArrowOutUpRight}
- size="small"
- onClick={(e) => handleOpenAgent(option.value as string, e)}
- />
- </span>
- )}
- />
- </Form.Item>
- )}
-
- <Accordion defaultExpandedKeys={[]}>
- <AccordionItem
- itemKey="advanced"
- paddingBlock={6}
- paddingInline={4}
- title={t('run.create.advanced')}
- >
- <Flexbox gap={16} style={{ paddingTop: 8 }}>
- <Form.Item
- extra={<span className={styles.hint}>{t('run.config.k.hint', { k: kValue })}</span>}
- label={t('run.config.k')}
- name="k"
- style={{ marginBottom: 0 }}
- >
- <InputNumber
- disabled={isFinished}
- max={10}
- min={1}
- step={1}
- style={{ width: '100%' }}
- variant="filled"
- />
- </Form.Item>
- <Form.Item
- extra={<span className={styles.hint}>{t('run.config.maxSteps.hint')}</span>}
- label={t('run.config.maxSteps')}
- name="maxSteps"
- style={{ marginBottom: 0 }}
- >
- <InputNumber
- disabled={isFinished}
- max={1000}
- min={1}
- step={10}
- style={{ width: '100%' }}
- variant="filled"
- />
- </Form.Item>
- <Form.Item
- label={t('run.config.timeout')}
- name="timeoutMinutes"
- style={{ marginBottom: 0 }}
- >
- <InputNumber
- disabled={isFinished}
- max={MAX_TIMEOUT_MINUTES}
- min={1}
- style={{ width: '100%' }}
- suffix={t('run.config.timeout.unit')}
- variant="filled"
- />
- </Form.Item>
- </Flexbox>
- </AccordionItem>
- </Accordion>
- </Form>
- </Modal>
- );
-});
-
-export default RunEditModal;
+export const createRunEditModal = (props: Props): ModalInstance =>
+ createFormModal({
+ renderContent: ({ formId, setLoading }) => (
+ <RunEditContent {...props} formId={formId} onLoadingChange={setLoading} />
+ ),
+ renderFooter: ({ formId, loading }) => <RunEditFooter formId={formId} loading={loading} />,
+ title: t('run.edit.title', { ns: 'eval' }),
+ width: 520,
+ });
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx
index b01f2d952ff..60184a97173 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/index.tsx
@@ -1,6 +1,5 @@
'use client';
-import type { AgentEvalRunListItem } from '@lobechat/types';
import { Button, Flexbox } from '@lobehub/ui';
import { Select } from '@lobehub/ui/base-ui';
import { Plus } from 'lucide-react';
@@ -9,8 +8,8 @@ import { useTranslation } from 'react-i18next';
import { runSelectors, useEvalStore } from '@/store/eval';
-import RunCreateModal from '../RunCreateModal';
-import RunEditModal from '../RunEditModal';
+import { createRunCreateModal } from '../RunCreateModal';
+import { createRunEditModal } from '../RunEditModal';
import EmptyState from './EmptyState';
import RunCard from './RunCard';
@@ -20,8 +19,6 @@ interface RunsTabProps {
const RunsTab = memo<RunsTabProps>(({ benchmarkId }) => {
const { t } = useTranslation('eval');
- const [createRunOpen, setCreateRunOpen] = useState(false);
- const [editingRun, setEditingRun] = useState<AgentEvalRunListItem | null>(null);
const [statusFilter, setStatusFilter] = useState<string>('all');
const useFetchRuns = useEvalStore((s) => s.useFetchRuns);
const runList = useEvalStore(runSelectors.runList);
@@ -70,14 +67,19 @@ const RunsTab = memo<RunsTabProps>(({ benchmarkId }) => {
onChange={setStatusFilter}
/>
</Flexbox>
- <Button icon={Plus} size="small" type="primary" onClick={() => setCreateRunOpen(true)}>
+ <Button
+ icon={Plus}
+ size="small"
+ type="primary"
+ onClick={() => createRunCreateModal({ benchmarkId })}
+ >
{t('run.actions.create')}
</Button>
</Flexbox>
)}
{sortedRuns.length === 0 ? (
- <EmptyState onCreate={() => setCreateRunOpen(true)} />
+ <EmptyState onCreate={() => createRunCreateModal({ benchmarkId })} />
) : filteredRuns.length === 0 ? (
<p style={{ color: 'var(--ant-color-text-tertiary)', fontSize: 14, textAlign: 'center' }}>
{t('run.filter.empty')}
@@ -89,23 +91,13 @@ const RunsTab = memo<RunsTabProps>(({ benchmarkId }) => {
benchmarkId={benchmarkId}
key={run.id}
run={run}
- onEdit={setEditingRun}
+ onEdit={(editingRun) => createRunEditModal({ run: editingRun })}
onRefresh={refreshRuns}
/>
))}
</Flexbox>
)}
</Flexbox>
-
- <RunCreateModal
- benchmarkId={benchmarkId}
- open={createRunOpen}
- onClose={() => setCreateRunOpen(false)}
- />
-
- {editingRun && (
- <RunEditModal open={!!editingRun} run={editingRun} onClose={() => setEditingRun(null)} />
- )}
</>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasePreviewModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasePreviewModal/Content.tsx
new file mode 100644
index 00000000000..d61d07a04cc
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasePreviewModal/Content.tsx
@@ -0,0 +1,101 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Badge } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css }) => ({
+ previewBlock: css`
+ padding: 12px;
+ border-radius: 8px;
+
+ font-size: 14px;
+ line-height: 1.6;
+ color: ${cssVar.colorText};
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ previewLabel: css`
+ margin: 0;
+
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
+ text-transform: uppercase;
+ `,
+}));
+
+const getDifficultyBadge = (difficulty: string) => {
+ const config: Record<string, { bg: string; color: string }> = {
+ easy: {
+ bg: cssVar.colorSuccessBg,
+ color: cssVar.colorSuccess,
+ },
+ hard: {
+ bg: cssVar.colorErrorBg,
+ color: cssVar.colorError,
+ },
+ medium: {
+ bg: cssVar.colorWarningBg,
+ color: cssVar.colorWarning,
+ },
+ };
+
+ const c = config[difficulty] || config.easy;
+ return (
+ <Badge
+ style={{
+ backgroundColor: c.bg,
+ borderColor: c.color + '30',
+ color: c.color,
+ fontSize: 11,
+ textTransform: 'capitalize',
+ }}
+ >
+ {difficulty}
+ </Badge>
+ );
+};
+
+export interface TestCasePreviewContentProps {
+ testCase: any;
+}
+
+const TestCasePreviewContent: FC<TestCasePreviewContentProps> = ({ testCase }) => {
+ const { t } = useTranslation('eval');
+
+ if (!testCase) return null;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={4}>
+ <p className={styles.previewLabel}>{t('testCase.preview.input')}</p>
+ <div className={styles.previewBlock}>{testCase.content?.input}</div>
+ </Flexbox>
+ <Flexbox gap={4}>
+ <p className={styles.previewLabel}>{t('testCase.preview.expected')}</p>
+ <div className={styles.previewBlock}>{testCase.content?.expectedOutput || '-'}</div>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={8}>
+ {testCase.metadata?.difficulty && getDifficultyBadge(testCase.metadata.difficulty)}
+ {testCase.metadata?.tags?.map((tag: string) => (
+ <Badge
+ key={tag}
+ style={{
+ backgroundColor: 'transparent',
+ borderColor: cssVar.colorBorder,
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ }}
+ >
+ {tag}
+ </Badge>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+export default TestCasePreviewContent;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasePreviewModal/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasePreviewModal/index.tsx
new file mode 100644
index 00000000000..1f7ae528553
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasePreviewModal/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import TestCasePreviewContent, { type TestCasePreviewContentProps } from './Content';
+
+export const createTestCasePreviewModal = (props: TestCasePreviewContentProps): ModalInstance =>
+ createModal({
+ content: <TestCasePreviewContent {...props} />,
+ footer: null,
+ title: t('testCase.preview.title', { ns: 'eval' }),
+ width: 600,
+ });
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasesTab/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasesTab/index.tsx
index 8fb1992bbca..3653284f771 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasesTab/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasesTab/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Button, Flexbox, Input } from '@lobehub/ui';
-import { Badge, Card, Modal, Table } from 'antd';
+import { Badge, Card, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { createStaticStyles } from 'antd-style';
import { Eye, Search } from 'lucide-react';
@@ -10,6 +10,8 @@ import { useTranslation } from 'react-i18next';
import { useEvalStore } from '@/store/eval';
+import { createTestCasePreviewModal } from '../TestCasePreviewModal';
+
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
.ant-card-body {
@@ -79,29 +81,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
text-overflow: ellipsis;
white-space: nowrap;
`,
- modalContent: css`
- .ant-modal-content {
- padding: 24px;
- }
- `,
- previewBlock: css`
- padding: 12px;
- border-radius: 8px;
-
- font-size: 14px;
- line-height: 1.6;
- color: ${cssVar.colorText};
-
- background: ${cssVar.colorFillSecondary};
- `,
- previewLabel: css`
- margin: 0;
-
- font-size: 12px;
- font-weight: 500;
- color: ${cssVar.colorTextTertiary};
- text-transform: uppercase;
- `,
searchIcon: css`
position: absolute;
inset-block-start: 50%;
@@ -150,7 +129,6 @@ const TestCasesTab = memo<TestCasesTabProps>(({ datasetId }) => {
const [pagination, setPagination] = useState({ current: 1, pageSize: 8 });
const [search, setSearch] = useState('');
const [diffFilter, setDiffFilter] = useState<'all' | 'easy' | 'medium' | 'hard'>('all');
- const [previewCase, setPreviewCase] = useState<any | null>(null);
const useFetchTestCases = useEvalStore((s) => s.useFetchTestCases);
@@ -261,7 +239,7 @@ const TestCasesTab = memo<TestCasesTabProps>(({ datasetId }) => {
icon={Eye}
size="small"
variant="text"
- onClick={() => setPreviewCase(record)}
+ onClick={() => createTestCasePreviewModal({ testCase: record })}
/>
),
width: 64,
@@ -324,48 +302,6 @@ const TestCasesTab = memo<TestCasesTabProps>(({ datasetId }) => {
/>
</div>
</Card>
-
- {/* Preview Modal */}
- <Modal
- className={styles.modalContent}
- footer={null}
- open={!!previewCase}
- title={t('testCase.preview.title')}
- width={600}
- onCancel={() => setPreviewCase(null)}
- >
- {previewCase && (
- <Flexbox gap={16}>
- <Flexbox gap={4}>
- <p className={styles.previewLabel}>{t('testCase.preview.input')}</p>
- <div className={styles.previewBlock}>{previewCase.content?.input}</div>
- </Flexbox>
- <Flexbox gap={4}>
- <p className={styles.previewLabel}>{t('testCase.preview.expected')}</p>
- <div className={styles.previewBlock}>
- {previewCase.content?.expectedOutput || '-'}
- </div>
- </Flexbox>
- <Flexbox horizontal align="center" gap={8}>
- {previewCase.metadata?.difficulty &&
- getDifficultyBadge(previewCase.metadata.difficulty)}
- {previewCase.metadata?.tags?.map((tag: string) => (
- <Badge
- key={tag}
- style={{
- backgroundColor: 'transparent',
- borderColor: 'var(--ant-color-border)',
- color: 'var(--ant-color-text-tertiary)',
- fontSize: 12,
- }}
- >
- {tag}
- </Badge>
- ))}
- </Flexbox>
- </Flexbox>
- )}
- </Modal>
</>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Content.tsx
new file mode 100644
index 00000000000..6c2a32ab507
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Content.tsx
@@ -0,0 +1,171 @@
+'use client';
+
+import { Badge, Checkbox, Skeleton, Table, Tag, Tooltip, Typography } from 'antd';
+import type { ColumnsType } from 'antd/es/table';
+import { type FC, 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];
+
+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>;
+});
+
+export interface BatchResumeContentProps {
+ onSelectionChange: (count: number) => void;
+ onSelectionReady: (api: { confirm: () => Promise<void>; selectedCount: () => number }) => void;
+ runId: string;
+ submitter: (targets: Array<{ testCaseId: string; threadId?: string }>) => Promise<void>;
+}
+
+const BatchResumeContent: FC<BatchResumeContentProps> = ({
+ onSelectionChange,
+ onSelectionReady,
+ runId,
+ submitter,
+}) => {
+ const { t } = useTranslation('eval');
+ const [cases, setCases] = useState<ResumableCase[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ const [pageSize, setPageSize] = useState(10);
+
+ useEffect(() => {
+ setLoading(true);
+ agentEvalService
+ .getResumableCases(runId)
+ .then((data) => {
+ setCases(data);
+ setSelectedIds(data.filter((c) => c.canResume).map((c) => c.testCaseId));
+ })
+ .finally(() => setLoading(false));
+ }, [runId]);
+
+ useEffect(() => {
+ onSelectionChange(selectedIds.length);
+ }, [onSelectionChange, selectedIds]);
+
+ 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 confirm = useCallback(async () => {
+ if (selectedIds.length === 0) return;
+ await submitter(
+ cases
+ .filter((item) => selectedIds.includes(item.testCaseId))
+ .map((item) => ({ testCaseId: item.testCaseId, threadId: item.threadId })),
+ );
+ }, [cases, selectedIds, submitter]);
+
+ useEffect(() => {
+ onSelectionReady({
+ confirm,
+ selectedCount: () => selectedIds.length,
+ });
+ }, [confirm, onSelectionReady, selectedIds]);
+
+ 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],
+ );
+
+ return 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),
+ }}
+ />
+ );
+};
+
+export default BatchResumeContent;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Footer.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Footer.tsx
new file mode 100644
index 00000000000..a23ba5a9992
--- /dev/null
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Footer.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ confirming: boolean;
+ onConfirm: () => void;
+ selectedCount: number;
+}
+
+const BatchResumeFooter: FC<FooterProps> = ({ confirming, onConfirm, selectedCount }) => {
+ const { t } = useTranslation('eval');
+ const { t: tc } = useTranslation('common');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={confirming} onClick={close}>
+ {tc('cancel')}
+ </Button>
+ <Button
+ disabled={selectedCount === 0}
+ loading={confirming}
+ type="primary"
+ onClick={onConfirm}
+ >
+ {t('run.actions.batchResume.modal.confirm')} ({selectedCount})
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default BatchResumeFooter;
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.tsx
index f4aeb11a799..2a7e9a5d888 100644
--- 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.tsx
@@ -1,192 +1,60 @@
'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 { createModal, type ImperativeModalProps, type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
-import { agentEvalService } from '@/services/agentEval';
+import BatchResumeContent from './Content';
+import BatchResumeFooter from './Footer';
-type ResumableCase = Awaited<ReturnType<typeof agentEvalService.getResumableCases>>[number];
-
-interface BatchResumeModalProps {
- onClose: () => void;
+interface CreateOptions {
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],
+export const createBatchResumeModal = ({ onConfirm, runId }: CreateOptions): ModalInstance => {
+ const ref: { instance?: ModalInstance } = {};
+ let confirming = false;
+ let selectedCount = 0;
+ let runConfirm: () => Promise<void> = async () => {};
+
+ const renderFooter = () => (
+ <BatchResumeFooter
+ confirming={confirming}
+ selectedCount={selectedCount}
+ onConfirm={async () => {
+ confirming = true;
+ ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
+ try {
+ await runConfirm();
+ ref.instance?.close();
+ } finally {
+ confirming = false;
+ ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
+ }
+ }}
+ />
);
- 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);
- }
+ const onSelectionChange = (count: number) => {
+ if (count === selectedCount) return;
+ selectedCount = count;
+ ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
};
- 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;
+ ref.instance = createModal({
+ content: (
+ <BatchResumeContent
+ runId={runId}
+ submitter={onConfirm}
+ onSelectionChange={onSelectionChange}
+ onSelectionReady={(api) => {
+ runConfirm = api.confirm;
+ }}
+ />
+ ),
+ footer: renderFooter(),
+ title: t('run.actions.batchResume.modal.title', { ns: 'eval' }),
+ width: 700,
+ });
+ return ref.instance;
+};
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
index f52b4fe4df4..4adac288ca7 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/RunHeader/index.tsx
@@ -20,7 +20,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
-import RunEditModal from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal';
+import { createRunEditModal } from '@/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal';
import StatusBadge from '@/routes/(main)/eval/features/StatusBadge';
import { useEvalStore } from '@/store/eval';
@@ -125,7 +125,6 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
const canStart = run.status === 'idle' || run.status === 'failed' || run.status === 'aborted';
const [starting, setStarting] = useState(false);
const [showConfig, setShowConfig] = useState(false);
- const [editOpen, setEditOpen] = useState(false);
const snapshot = run.config?.agentSnapshot;
const agentTitle = run.targetAgent?.title || t('run.detail.agent.unnamed');
@@ -278,7 +277,7 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
icon={Pencil}
size="small"
title={t('run.actions.edit')}
- onClick={() => setEditOpen(true)}
+ onClick={() => createRunEditModal({ run })}
/>
{isActive && (
<ActionIcon
@@ -358,8 +357,6 @@ const RunHeader = memo<RunHeaderProps>(({ run, benchmarkId, hideStart }) => {
</Flexbox>
)}
</Card>
-
- <RunEditModal open={editOpen} run={run} onClose={() => setEditOpen(false)} />
</Flexbox>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
index 128396675ee..19084242f36 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
@@ -10,7 +10,7 @@ import { useParams } from 'react-router-dom';
import { runSelectors, useEvalStore } from '@/store/eval';
-import { BatchResumeModal } from './features/BatchResumeModal';
+import { createBatchResumeModal } from './features/BatchResumeModal';
import CaseResultsTable from './features/CaseResultsTable';
import BenchmarkCharts from './features/Charts/BenchmarkCharts';
import IdleState from './features/IdleState';
@@ -35,7 +35,6 @@ const RunDetail = memo(() => {
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 };
@@ -154,7 +153,12 @@ const RunDetail = memo(() => {
<Button
icon={<Play size={14} />}
size="small"
- onClick={() => setBatchResumeOpen(true)}
+ onClick={() =>
+ createBatchResumeModal({
+ onConfirm: (targets) => batchResumeRunCases(runId!, targets),
+ runId: runId!,
+ })
+ }
>
{t('run.actions.batchResume')}
</Button>
@@ -202,13 +206,6 @@ const RunDetail = memo(() => {
/>
</Card>
)}
-
- <BatchResumeModal
- open={batchResumeOpen}
- runId={runId!}
- onClose={() => setBatchResumeOpen(false)}
- onConfirm={(targets) => batchResumeRunCases(runId!, targets)}
- />
</Flexbox>
);
});
diff --git a/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx b/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
new file mode 100644
index 00000000000..82d4ee1854e
--- /dev/null
+++ b/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
@@ -0,0 +1,122 @@
+'use client';
+
+import { Input, Select, TextArea } from '@lobehub/ui';
+import { useModalContext } from '@lobehub/ui/base-ui';
+import { App, Form } from 'antd';
+import { type FC, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useEvalStore } from '@/store/eval';
+
+const toIdentifier = (name: string) =>
+ name
+ .trim()
+ .toLowerCase()
+ .replaceAll(/\s+/g, '-')
+ .replaceAll(/[^\da-z-]/g, '');
+
+export interface BenchmarkEditContentProps {
+ benchmark: {
+ description?: string;
+ id: string;
+ identifier: string;
+ metadata?: any;
+ name: string;
+ tags?: string[];
+ };
+ formId: string;
+ onLoadingChange?: (loading: boolean) => void;
+ onSuccess?: () => void;
+}
+
+const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
+ benchmark,
+ formId,
+ onLoadingChange,
+ onSuccess,
+}) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const [form] = Form.useForm();
+ const [identifierTouched, setIdentifierTouched] = useState(false);
+ const updateBenchmark = useEvalStore((s) => s.updateBenchmark);
+
+ const nameValue = Form.useWatch('name', form);
+
+ useEffect(() => {
+ if (benchmark) {
+ form.setFieldsValue({
+ description: benchmark.description || '',
+ identifier: benchmark.identifier,
+ name: benchmark.name,
+ tags: benchmark.tags || [],
+ });
+ }
+ }, [benchmark, form]);
+
+ useEffect(() => {
+ if (!identifierTouched && nameValue) {
+ form.setFieldValue('identifier', toIdentifier(nameValue));
+ }
+ }, [nameValue, identifierTouched, form]);
+
+ const handleFinish = async (values: any) => {
+ onLoadingChange?.(true);
+ try {
+ await updateBenchmark({
+ description: values.description?.trim() || undefined,
+ id: benchmark.id,
+ identifier: values.identifier.trim(),
+ name: values.name.trim(),
+ tags: values.tags?.length > 0 ? values.tags : undefined,
+ });
+ message.success(t('benchmark.edit.success'));
+ close();
+ onSuccess?.();
+ } catch {
+ message.error(t('benchmark.edit.error'));
+ } finally {
+ onLoadingChange?.(false);
+ }
+ };
+
+ return (
+ <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form.Item
+ label={t('benchmark.create.name.label')}
+ name="name"
+ rules={[{ message: t('benchmark.create.nameRequired'), required: true }]}
+ >
+ <Input autoFocus placeholder={t('benchmark.create.name.placeholder')} />
+ </Form.Item>
+
+ <Form.Item
+ label={t('benchmark.create.identifier.label')}
+ name="identifier"
+ rules={[{ message: t('benchmark.create.identifierRequired'), required: true }]}
+ >
+ <Input
+ placeholder={t('benchmark.create.identifier.placeholder')}
+ onChange={() => setIdentifierTouched(true)}
+ />
+ </Form.Item>
+
+ <Form.Item label={t('benchmark.create.description.label')} name="description">
+ <TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
+ </Form.Item>
+
+ <Form.Item label={t('benchmark.create.tags.label')} name="tags" style={{ marginBottom: 0 }}>
+ <Select
+ mode="tags"
+ open={false}
+ placeholder={t('benchmark.create.tags.placeholder')}
+ style={{ width: '100%' }}
+ tokenSeparators={[',', ',', ' ']}
+ />
+ </Form.Item>
+ </Form>
+ );
+};
+
+export default BenchmarkEditContent;
diff --git a/src/routes/(main)/eval/features/BenchmarkEditModal/Footer.tsx b/src/routes/(main)/eval/features/BenchmarkEditModal/Footer.tsx
new file mode 100644
index 00000000000..9a3ba41bfb6
--- /dev/null
+++ b/src/routes/(main)/eval/features/BenchmarkEditModal/Footer.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ formId: string;
+ loading: boolean;
+}
+
+const BenchmarkEditFooter: FC<FooterProps> = ({ formId, loading }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Button form={formId} htmlType="submit" loading={loading} type="primary">
+ {t('benchmark.edit.confirm')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default BenchmarkEditFooter;
diff --git a/src/routes/(main)/eval/features/BenchmarkEditModal/index.tsx b/src/routes/(main)/eval/features/BenchmarkEditModal/index.tsx
index b7336207d11..22171183b68 100644
--- a/src/routes/(main)/eval/features/BenchmarkEditModal/index.tsx
+++ b/src/routes/(main)/eval/features/BenchmarkEditModal/index.tsx
@@ -1,142 +1,23 @@
'use client';
-import { Input, Modal, type ModalProps, Select, TextArea } from '@lobehub/ui';
-import { App, Form } from 'antd';
-import { memo, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useEvalStore } from '@/store/eval';
-
-const toIdentifier = (name: string) =>
- name
- .trim()
- .toLowerCase()
- .replaceAll(/\s+/g, '-')
- .replaceAll(/[^\da-z-]/g, '');
-
-interface BenchmarkEditModalProps extends ModalProps {
- benchmark: {
- description?: string;
- id: string;
- identifier: string;
- metadata?: any;
- name: string;
- tags?: string[];
- };
- onSuccess?: () => void;
-}
-
-const BenchmarkEditModal = memo<BenchmarkEditModalProps>(
- ({ open, onCancel, benchmark, onSuccess }) => {
- const { t } = useTranslation('eval');
- const { message } = App.useApp();
- const [form] = Form.useForm();
- const [loading, setLoading] = useState(false);
- const [identifierTouched, setIdentifierTouched] = useState(false);
- const updateBenchmark = useEvalStore((s) => s.updateBenchmark);
-
- const nameValue = Form.useWatch('name', form);
-
- // Initialize form with benchmark data when modal opens
- useEffect(() => {
- if (open && benchmark) {
- form.setFieldsValue({
- name: benchmark.name,
- identifier: benchmark.identifier,
- description: benchmark.description || '',
- tags: benchmark.tags || [],
- });
- setIdentifierTouched(false);
- }
- }, [open, benchmark, form]);
-
- // Auto-sync identifier from name, unless user has manually edited it
- useEffect(() => {
- if (!identifierTouched && nameValue) {
- form.setFieldValue('identifier', toIdentifier(nameValue));
- }
- }, [nameValue, identifierTouched, form]);
-
- return (
- <Modal
- allowFullscreen
- destroyOnHidden
- okButtonProps={{ loading }}
- okText={t('benchmark.edit.confirm')}
- open={open}
- title={t('benchmark.edit.title')}
- width={480}
- onCancel={(e) => {
- form.resetFields();
- setIdentifierTouched(false);
- onCancel?.(e);
- }}
- onOk={async (e) => {
- try {
- const values = await form.validateFields();
- setLoading(true);
-
- await updateBenchmark({
- id: benchmark.id,
- identifier: values.identifier.trim(),
- name: values.name.trim(),
- description: values.description?.trim() || undefined,
- tags: values.tags?.length > 0 ? values.tags : undefined,
- });
- message.success(t('benchmark.edit.success'));
- form.resetFields();
- setIdentifierTouched(false);
- onCancel?.(e);
- onSuccess?.();
- } catch (error: any) {
- if (error?.errorFields) return;
- message.error(t('benchmark.edit.error'));
- } finally {
- setLoading(false);
- }
- }}
- >
- <Form form={form} layout="vertical" style={{ paddingBlock: 16 }}>
- <Form.Item
- label={t('benchmark.create.name.label')}
- name="name"
- rules={[{ message: t('benchmark.create.nameRequired'), required: true }]}
- >
- <Input autoFocus placeholder={t('benchmark.create.name.placeholder')} />
- </Form.Item>
-
- <Form.Item
- label={t('benchmark.create.identifier.label')}
- name="identifier"
- rules={[{ message: t('benchmark.create.identifierRequired'), required: true }]}
- >
- <Input
- placeholder={t('benchmark.create.identifier.placeholder')}
- onChange={() => setIdentifierTouched(true)}
- />
- </Form.Item>
-
- <Form.Item label={t('benchmark.create.description.label')} name="description">
- <TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
- </Form.Item>
-
- <Form.Item
- label={t('benchmark.create.tags.label')}
- name="tags"
- style={{ marginBottom: 0 }}
- >
- <Select
- mode="tags"
- open={false}
- placeholder={t('benchmark.create.tags.placeholder')}
- style={{ width: '100%' }}
- tokenSeparators={[',', ',', ' ']}
- />
- </Form.Item>
- </Form>
- </Modal>
- );
- },
-);
-
-export default BenchmarkEditModal;
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import { createFormModal } from '@/utils/createFormModal';
+
+import BenchmarkEditContent, { type BenchmarkEditContentProps } from './Content';
+import BenchmarkEditFooter from './Footer';
+
+type Props = Omit<BenchmarkEditContentProps, 'formId' | 'onLoadingChange'>;
+
+export const createBenchmarkEditModal = (props: Props): ModalInstance =>
+ createFormModal({
+ renderContent: ({ formId, setLoading }) => (
+ <BenchmarkEditContent {...props} formId={formId} onLoadingChange={setLoading} />
+ ),
+ renderFooter: ({ formId, loading }) => (
+ <BenchmarkEditFooter formId={formId} loading={loading} />
+ ),
+ title: t('benchmark.edit.title', { ns: 'eval' }),
+ width: 480,
+ });
diff --git a/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
new file mode 100644
index 00000000000..10aac8a58d8
--- /dev/null
+++ b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
@@ -0,0 +1,100 @@
+'use client';
+
+import { Input, Select, TextArea } from '@lobehub/ui';
+import { useModalContext } from '@lobehub/ui/base-ui';
+import { App, Form } from 'antd';
+import { type FC, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { useEvalStore } from '@/store/eval';
+
+const toIdentifier = (name: string) =>
+ name
+ .trim()
+ .toLowerCase()
+ .replaceAll(/\s+/g, '-')
+ .replaceAll(/[^\da-z-]/g, '');
+
+export interface CreateBenchmarkContentProps {
+ formId: string;
+ onLoadingChange?: (loading: boolean) => void;
+}
+
+const CreateBenchmarkContent: FC<CreateBenchmarkContentProps> = ({ formId, onLoadingChange }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const navigate = useNavigate();
+ const [form] = Form.useForm();
+ const [identifierTouched, setIdentifierTouched] = useState(false);
+ const createBenchmark = useEvalStore((s) => s.createBenchmark);
+
+ const nameValue = Form.useWatch('name', form);
+
+ useEffect(() => {
+ if (!identifierTouched && nameValue) {
+ form.setFieldValue('identifier', toIdentifier(nameValue));
+ }
+ }, [nameValue, identifierTouched, form]);
+
+ const handleFinish = async (values: any) => {
+ onLoadingChange?.(true);
+ try {
+ const result = await createBenchmark({
+ description: values.description?.trim() || undefined,
+ identifier: values.identifier.trim(),
+ name: values.name.trim(),
+ tags: values.tags?.length > 0 ? values.tags : undefined,
+ });
+ message.success(t('benchmark.create.success'));
+ close();
+ if (result?.id) {
+ navigate(`/eval/bench/${result.id}`);
+ }
+ } catch {
+ message.error(t('benchmark.create.error'));
+ } finally {
+ onLoadingChange?.(false);
+ }
+ };
+
+ return (
+ <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form.Item
+ label={t('benchmark.create.name.label')}
+ name="name"
+ rules={[{ message: t('benchmark.create.nameRequired'), required: true }]}
+ >
+ <Input autoFocus placeholder={t('benchmark.create.name.placeholder')} />
+ </Form.Item>
+
+ <Form.Item
+ label={t('benchmark.create.identifier.label')}
+ name="identifier"
+ rules={[{ message: t('benchmark.create.identifierRequired'), required: true }]}
+ >
+ <Input
+ placeholder={t('benchmark.create.identifier.placeholder')}
+ onChange={() => setIdentifierTouched(true)}
+ />
+ </Form.Item>
+
+ <Form.Item label={t('benchmark.create.description.label')} name="description">
+ <TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
+ </Form.Item>
+
+ <Form.Item label={t('benchmark.create.tags.label')} name="tags" style={{ marginBottom: 0 }}>
+ <Select
+ mode="tags"
+ open={false}
+ placeholder={t('benchmark.create.tags.placeholder')}
+ style={{ width: '100%' }}
+ tokenSeparators={[',', ',', ' ']}
+ />
+ </Form.Item>
+ </Form>
+ );
+};
+
+export default CreateBenchmarkContent;
diff --git a/src/routes/(main)/eval/features/CreateBenchmarkModal/Footer.tsx b/src/routes/(main)/eval/features/CreateBenchmarkModal/Footer.tsx
new file mode 100644
index 00000000000..f7c8d583550
--- /dev/null
+++ b/src/routes/(main)/eval/features/CreateBenchmarkModal/Footer.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ formId: string;
+ loading: boolean;
+}
+
+const CreateBenchmarkFooter: FC<FooterProps> = ({ formId, loading }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Button form={formId} htmlType="submit" loading={loading} type="primary">
+ {t('benchmark.create.confirm')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default CreateBenchmarkFooter;
diff --git a/src/routes/(main)/eval/features/CreateBenchmarkModal/index.tsx b/src/routes/(main)/eval/features/CreateBenchmarkModal/index.tsx
index 836caa253cf..e955149d082 100644
--- a/src/routes/(main)/eval/features/CreateBenchmarkModal/index.tsx
+++ b/src/routes/(main)/eval/features/CreateBenchmarkModal/index.tsx
@@ -1,116 +1,21 @@
'use client';
-import { Input, Modal, type ModalProps, Select, TextArea } from '@lobehub/ui';
-import { App, Form } from 'antd';
-import { memo, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
-
-import { useEvalStore } from '@/store/eval';
-
-const toIdentifier = (name: string) =>
- name
- .trim()
- .toLowerCase()
- .replaceAll(/\s+/g, '-')
- .replaceAll(/[^\da-z-]/g, '');
-
-interface CreateBenchmarkModalProps extends ModalProps {}
-
-const CreateBenchmarkModal = memo<CreateBenchmarkModalProps>(({ open, onCancel }) => {
- const { t } = useTranslation('eval');
- const { message } = App.useApp();
- const navigate = useNavigate();
- const [form] = Form.useForm();
- const [loading, setLoading] = useState(false);
- const [identifierTouched, setIdentifierTouched] = useState(false);
- const createBenchmark = useEvalStore((s) => s.createBenchmark);
-
- const nameValue = Form.useWatch('name', form);
-
- // Auto-sync identifier from name, unless user has manually edited it
- useEffect(() => {
- if (!identifierTouched && nameValue) {
- form.setFieldValue('identifier', toIdentifier(nameValue));
- }
- }, [nameValue, identifierTouched, form]);
-
- return (
- <Modal
- allowFullscreen
- destroyOnHidden
- okButtonProps={{ loading }}
- okText={t('benchmark.create.confirm')}
- open={open}
- title={t('benchmark.create.title')}
- width={480}
- onCancel={(e) => {
- form.resetFields();
- setIdentifierTouched(false);
- onCancel?.(e);
- }}
- onOk={async (e) => {
- try {
- const values = await form.validateFields();
- setLoading(true);
-
- const result = await createBenchmark({
- identifier: values.identifier.trim(),
- name: values.name.trim(),
- description: values.description?.trim() || undefined,
- tags: values.tags?.length > 0 ? values.tags : undefined,
- });
- message.success(t('benchmark.create.success'));
- form.resetFields();
- setIdentifierTouched(false);
- onCancel?.(e);
- if (result?.id) {
- navigate(`/eval/bench/${result.id}`);
- }
- } catch (error: any) {
- if (error?.errorFields) return;
- message.error(t('benchmark.create.error'));
- } finally {
- setLoading(false);
- }
- }}
- >
- <Form form={form} layout="vertical" style={{ paddingBlock: 16 }}>
- <Form.Item
- label={t('benchmark.create.name.label')}
- name="name"
- rules={[{ message: t('benchmark.create.nameRequired'), required: true }]}
- >
- <Input autoFocus placeholder={t('benchmark.create.name.placeholder')} />
- </Form.Item>
-
- <Form.Item
- label={t('benchmark.create.identifier.label')}
- name="identifier"
- rules={[{ message: t('benchmark.create.identifierRequired'), required: true }]}
- >
- <Input
- placeholder={t('benchmark.create.identifier.placeholder')}
- onChange={() => setIdentifierTouched(true)}
- />
- </Form.Item>
-
- <Form.Item label={t('benchmark.create.description.label')} name="description">
- <TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
- </Form.Item>
-
- <Form.Item label={t('benchmark.create.tags.label')} name="tags" style={{ marginBottom: 0 }}>
- <Select
- mode="tags"
- open={false}
- placeholder={t('benchmark.create.tags.placeholder')}
- style={{ width: '100%' }}
- tokenSeparators={[',', ',', ' ']}
- />
- </Form.Item>
- </Form>
- </Modal>
- );
-});
-
-export default CreateBenchmarkModal;
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import { createFormModal } from '@/utils/createFormModal';
+
+import CreateBenchmarkContent from './Content';
+import CreateBenchmarkFooter from './Footer';
+
+export const createCreateBenchmarkModal = (): ModalInstance =>
+ createFormModal({
+ renderContent: ({ formId, setLoading }) => (
+ <CreateBenchmarkContent formId={formId} onLoadingChange={setLoading} />
+ ),
+ renderFooter: ({ formId, loading }) => (
+ <CreateBenchmarkFooter formId={formId} loading={loading} />
+ ),
+ title: t('benchmark.create.title', { ns: 'eval' }),
+ width: 480,
+ });
diff --git a/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx b/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
new file mode 100644
index 00000000000..5ece59f806f
--- /dev/null
+++ b/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
@@ -0,0 +1,215 @@
+'use client';
+
+import { Center, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Select, useModalContext } from '@lobehub/ui/base-ui';
+import { App, Form, Input } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { type FC, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { agentEvalService } from '@/services/agentEval';
+
+import { DATASET_PRESETS, getPresetsByCategory } from '../../config/datasetPresets';
+
+const toIdentifier = (name: string) =>
+ name
+ .trim()
+ .toLowerCase()
+ .replaceAll(/\s+/g, '-')
+ .replaceAll(/[^\da-z-]/g, '');
+
+const CATEGORY_LABELS: Record<string, string> = {
+ 'custom': 'Custom',
+ 'memory': 'Memory',
+ 'reference': 'Reference Formats',
+ 'research': 'Deep Research / QA',
+ 'tool-use': 'Tool Use',
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ presetIcon: css`
+ border: 1px solid ${cssVar.colorFillTertiary};
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorBgElevated};
+ `,
+}));
+
+export interface DatasetCreateContentProps {
+ benchmarkId: string;
+ formId: string;
+ onLoadingChange?: (loading: boolean) => void;
+ onSuccess?: (dataset: { id: string; name: string; preset: string }) => void;
+}
+
+const DatasetCreateContent: FC<DatasetCreateContentProps> = ({
+ benchmarkId,
+ formId,
+ onLoadingChange,
+ onSuccess,
+}) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const [form] = Form.useForm();
+ const [selectedPreset, setSelectedPreset] = useState<string>('custom');
+ const [identifierTouched, setIdentifierTouched] = useState(false);
+
+ const nameValue = Form.useWatch('name', form);
+ const evalModeValue = Form.useWatch('evalMode', form);
+
+ useEffect(() => {
+ if (!identifierTouched && nameValue) {
+ form.setFieldValue('identifier', toIdentifier(nameValue));
+ }
+ }, [nameValue, identifierTouched, form]);
+
+ const handleFinish = async (values: any) => {
+ onLoadingChange?.(true);
+ try {
+ const result = await agentEvalService.createDataset({
+ benchmarkId,
+ description: values.description,
+ evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : undefined,
+ evalMode: values.evalMode || undefined,
+ identifier: values.identifier.trim(),
+ metadata: {
+ preset: selectedPreset,
+ },
+ name: values.name,
+ });
+ close();
+ onSuccess?.({
+ id: result.id,
+ name: result.name,
+ preset: selectedPreset,
+ });
+ } catch (error: any) {
+ message.error(error?.message || t('dataset.create.error'));
+ } finally {
+ onLoadingChange?.(false);
+ }
+ };
+
+ const presetsByCategory = getPresetsByCategory();
+ const currentPreset = DATASET_PRESETS[selectedPreset];
+
+ const selectOptions = Object.entries(presetsByCategory)
+ .filter(([_, presets]) => presets.length > 0)
+ .map(([category, presets]) => ({
+ label: CATEGORY_LABELS[category] || category,
+ options: presets.map((preset) => ({
+ label: preset.name,
+ value: preset.id,
+ })),
+ }));
+
+ return (
+ <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form.Item
+ label={t('dataset.create.name.label')}
+ name="name"
+ rules={[{ message: t('dataset.create.nameRequired'), required: true }]}
+ >
+ <Input placeholder={t('dataset.create.name.placeholder')} />
+ </Form.Item>
+
+ <Form.Item
+ label={t('dataset.create.identifier.label')}
+ name="identifier"
+ rules={[{ message: t('dataset.create.identifierRequired'), required: true }]}
+ >
+ <Input
+ placeholder={t('dataset.create.identifier.placeholder')}
+ onChange={() => setIdentifierTouched(true)}
+ />
+ </Form.Item>
+
+ <Form.Item label={t('dataset.create.description.label')} name="description">
+ <Input.TextArea placeholder={t('dataset.create.description.placeholder')} rows={3} />
+ </Form.Item>
+
+ <Form.Item extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
+ <Select
+ allowClear
+ placeholder={t('evalMode.placeholder')}
+ optionRender={(option) => (
+ <Flexbox gap={2} style={{ padding: '4px 0' }}>
+ <div>{option.label}</div>
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t(`evalMode.${option.value}.desc` as any)}
+ </Text>
+ </Flexbox>
+ )}
+ options={[
+ { label: t('evalMode.equals'), value: 'equals' },
+ { label: t('evalMode.contains'), value: 'contains' },
+ { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ { label: t('evalMode.external'), value: 'external' },
+ ]}
+ />
+ </Form.Item>
+
+ {evalModeValue === 'llm-rubric' && (
+ <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ <Input.TextArea placeholder={t('evalMode.prompt.placeholder')} rows={3} />
+ </Form.Item>
+ )}
+
+ <Form.Item
+ label={t('dataset.create.preset.label')}
+ extra={
+ currentPreset ? (
+ <Flexbox gap={4} style={{ marginTop: 8 }}>
+ <p style={{ color: cssVar.colorTextSecondary, fontSize: 12, margin: 0 }}>
+ {currentPreset.formatDescription}
+ </p>
+ <div style={{ color: cssVar.colorTextTertiary, fontSize: 12 }}>
+ <strong>Required:</strong> {currentPreset.requiredFields.join(', ')}
+ {currentPreset.optionalFields.length > 0 && (
+ <>
+ {' · '}
+ <strong>Optional:</strong> {currentPreset.optionalFields.join(', ')}
+ </>
+ )}
+ </div>
+ </Flexbox>
+ ) : null
+ }
+ >
+ <Select
+ options={selectOptions}
+ placeholder="Select a preset"
+ value={selectedPreset}
+ optionRender={(option) => {
+ const preset = DATASET_PRESETS[option.value as string];
+ if (!preset) return option.label;
+
+ return (
+ <Flexbox
+ horizontal
+ align="flex-start"
+ gap={12}
+ style={{ overflow: 'hidden', width: '100%' }}
+ >
+ <Center className={styles.presetIcon} flex="none" height={40} width={40}>
+ <Icon icon={preset.icon} size={18} />
+ </Center>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
+ <Text ellipsis style={{ fontSize: 14, fontWeight: 500 }}>
+ {preset.name}
+ </Text>
+ <Text ellipsis style={{ fontSize: 12 }} type="secondary">
+ {preset.description}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+ }}
+ onChange={(value) => setSelectedPreset(value)}
+ />
+ </Form.Item>
+ </Form>
+ );
+};
+
+export default DatasetCreateContent;
diff --git a/src/routes/(main)/eval/features/DatasetCreateModal/Footer.tsx b/src/routes/(main)/eval/features/DatasetCreateModal/Footer.tsx
new file mode 100644
index 00000000000..03f6f686b2d
--- /dev/null
+++ b/src/routes/(main)/eval/features/DatasetCreateModal/Footer.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ formId: string;
+ loading: boolean;
+}
+
+const DatasetCreateFooter: FC<FooterProps> = ({ formId, loading }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Button form={formId} htmlType="submit" loading={loading} type="primary">
+ {t('common.create')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default DatasetCreateFooter;
diff --git a/src/routes/(main)/eval/features/DatasetCreateModal/index.tsx b/src/routes/(main)/eval/features/DatasetCreateModal/index.tsx
index 6382fddd4c1..e5bddb81dae 100644
--- a/src/routes/(main)/eval/features/DatasetCreateModal/index.tsx
+++ b/src/routes/(main)/eval/features/DatasetCreateModal/index.tsx
@@ -1,240 +1,23 @@
'use client';
-import { Center, Flexbox, Icon, Modal, Text } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { App, Form, Input } from 'antd';
-import { cssVar } from 'antd-style';
-import { memo, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { agentEvalService } from '@/services/agentEval';
-
-import { DATASET_PRESETS, getPresetsByCategory } from '../../config/datasetPresets';
-
-const toIdentifier = (name: string) =>
- name
- .trim()
- .toLowerCase()
- .replaceAll(/\s+/g, '-')
- .replaceAll(/[^\da-z-]/g, '');
-
-interface DatasetCreateModalProps {
- benchmarkId: string;
- onClose: () => void;
- onSuccess?: (dataset: { id: string; name: string; preset: string }) => void;
- open: boolean;
-}
-
-const CATEGORY_LABELS: Record<string, string> = {
- 'research': 'Deep Research / QA',
- 'tool-use': 'Tool Use',
- 'memory': 'Memory',
- 'reference': 'Reference Formats',
- 'custom': 'Custom',
-};
-
-const DatasetCreateModal = memo<DatasetCreateModalProps>(
- ({ open, onClose, benchmarkId, onSuccess }) => {
- const { t } = useTranslation('eval');
- const { message } = App.useApp();
- const [form] = Form.useForm();
-
- const [loading, setLoading] = useState(false);
- const [selectedPreset, setSelectedPreset] = useState<string>('custom');
- const [identifierTouched, setIdentifierTouched] = useState(false);
-
- const nameValue = Form.useWatch('name', form);
- const evalModeValue = Form.useWatch('evalMode', form);
-
- useEffect(() => {
- if (!identifierTouched && nameValue) {
- form.setFieldValue('identifier', toIdentifier(nameValue));
- }
- }, [nameValue, identifierTouched, form]);
-
- const handleClose = () => {
- form.resetFields();
- setSelectedPreset('custom');
- setIdentifierTouched(false);
- onClose();
- };
-
- const handleCreate = async () => {
- try {
- const values = await form.validateFields();
- setLoading(true);
-
- const result = await agentEvalService.createDataset({
- benchmarkId,
- identifier: values.identifier.trim(),
- name: values.name,
- description: values.description,
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : undefined,
- evalMode: values.evalMode || undefined,
- metadata: {
- preset: selectedPreset,
- },
- });
-
- handleClose();
- onSuccess?.({
- id: result.id,
- name: result.name,
- preset: selectedPreset,
- });
- } catch (error: any) {
- if (error.errorFields) {
- // Validation error, do nothing
- return;
- }
- message.error(error.message || t('dataset.create.error'));
- } finally {
- setLoading(false);
- }
- };
-
- const presetsByCategory = getPresetsByCategory();
- const currentPreset = DATASET_PRESETS[selectedPreset];
-
- // Build grouped options
- const selectOptions = Object.entries(presetsByCategory)
- .filter(([_, presets]) => presets.length > 0)
- .map(([category, presets]) => ({
- label: CATEGORY_LABELS[category] || category,
- options: presets.map((preset) => ({
- label: preset.name,
- value: preset.id,
- })),
- }));
-
- return (
- <Modal
- destroyOnHidden
- okButtonProps={{ loading }}
- okText={t('common.create')}
- open={open}
- title={t('dataset.create.title')}
- width={600}
- onCancel={handleClose}
- onOk={handleCreate}
- >
- <Form form={form} layout="vertical" style={{ paddingBlock: 16 }}>
- <Form.Item
- label={t('dataset.create.name.label')}
- name="name"
- rules={[{ required: true, message: t('dataset.create.nameRequired') }]}
- >
- <Input placeholder={t('dataset.create.name.placeholder')} />
- </Form.Item>
-
- <Form.Item
- label={t('dataset.create.identifier.label')}
- name="identifier"
- rules={[{ required: true, message: t('dataset.create.identifierRequired') }]}
- >
- <Input
- placeholder={t('dataset.create.identifier.placeholder')}
- onChange={() => setIdentifierTouched(true)}
- />
- </Form.Item>
-
- <Form.Item label={t('dataset.create.description.label')} name="description">
- <Input.TextArea placeholder={t('dataset.create.description.placeholder')} rows={3} />
- </Form.Item>
-
- <Form.Item extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
- <Select
- allowClear
- placeholder={t('evalMode.placeholder')}
- optionRender={(option) => (
- <Flexbox gap={2} style={{ padding: '4px 0' }}>
- <div>{option.label}</div>
- <Text style={{ fontSize: 12 }} type="secondary">
- {t(`evalMode.${option.value}.desc` as any)}
- </Text>
- </Flexbox>
- )}
- options={[
- { label: t('evalMode.equals'), value: 'equals' },
- { label: t('evalMode.contains'), value: 'contains' },
- { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
- { label: t('evalMode.external'), value: 'external' },
- ]}
- />
- </Form.Item>
-
- {evalModeValue === 'llm-rubric' && (
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
- <Input.TextArea placeholder={t('evalMode.prompt.placeholder')} rows={3} />
- </Form.Item>
- )}
-
- <Form.Item
- label={t('dataset.create.preset.label')}
- extra={
- currentPreset ? (
- <Flexbox gap={4} style={{ marginTop: 8 }}>
- <p style={{ color: 'var(--ant-color-text-secondary)', fontSize: 12, margin: 0 }}>
- {currentPreset.formatDescription}
- </p>
- <div style={{ color: 'var(--ant-color-text-tertiary)', fontSize: 12 }}>
- <strong>Required:</strong> {currentPreset.requiredFields.join(', ')}
- {currentPreset.optionalFields.length > 0 && (
- <>
- {' · '}
- <strong>Optional:</strong> {currentPreset.optionalFields.join(', ')}
- </>
- )}
- </div>
- </Flexbox>
- ) : null
- }
- >
- <Select
- options={selectOptions}
- placeholder="Select a preset"
- value={selectedPreset}
- optionRender={(option) => {
- const preset = DATASET_PRESETS[option.value as string];
- if (!preset) return option.label;
-
- return (
- <Flexbox
- horizontal
- align="flex-start"
- gap={12}
- style={{ overflow: 'hidden', width: '100%' }}
- >
- <Center
- flex="none"
- height={40}
- width={40}
- style={{
- border: `1px solid ${cssVar.colorFillTertiary}`,
- borderRadius: cssVar.borderRadius,
- background: cssVar.colorBgElevated,
- }}
- >
- <Icon icon={preset.icon} size={18} />
- </Center>
- <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
- <Text ellipsis style={{ fontSize: 14, fontWeight: 500 }}>
- {preset.name}
- </Text>
- <Text ellipsis style={{ fontSize: 12 }} type="secondary">
- {preset.description}
- </Text>
- </Flexbox>
- </Flexbox>
- );
- }}
- onChange={(value) => setSelectedPreset(value)}
- />
- </Form.Item>
- </Form>
- </Modal>
- );
- },
-);
-
-export default DatasetCreateModal;
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import { createFormModal } from '@/utils/createFormModal';
+
+import DatasetCreateContent, { type DatasetCreateContentProps } from './Content';
+import DatasetCreateFooter from './Footer';
+
+type Props = Omit<DatasetCreateContentProps, 'formId' | 'onLoadingChange'>;
+
+export const createDatasetCreateModal = (props: Props): ModalInstance =>
+ createFormModal({
+ renderContent: ({ formId, setLoading }) => (
+ <DatasetCreateContent {...props} formId={formId} onLoadingChange={setLoading} />
+ ),
+ renderFooter: ({ formId, loading }) => (
+ <DatasetCreateFooter formId={formId} loading={loading} />
+ ),
+ title: t('dataset.create.title', { ns: 'eval' }),
+ width: 600,
+ });
diff --git a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
new file mode 100644
index 00000000000..20611d4865b
--- /dev/null
+++ b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
@@ -0,0 +1,197 @@
+'use client';
+
+import { Center, Flexbox, Icon, Input, Text, TextArea } from '@lobehub/ui';
+import { Select, useModalContext } from '@lobehub/ui/base-ui';
+import { App, Form } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { type FC, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { agentEvalService } from '@/services/agentEval';
+
+import { DATASET_PRESETS, getPresetsByCategory } from '../../config/datasetPresets';
+
+const CATEGORY_LABELS: Record<string, string> = {
+ 'custom': 'Custom',
+ 'memory': 'Memory',
+ 'reference': 'Reference Formats',
+ 'research': 'Deep Research / QA',
+ 'tool-use': 'Tool Use',
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ presetIcon: css`
+ border: 1px solid ${cssVar.colorFillTertiary};
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorBgElevated};
+ `,
+}));
+
+export interface DatasetEditContentProps {
+ dataset: {
+ description?: string;
+ evalMode?: string | null;
+ id: string;
+ metadata?: Record<string, unknown>;
+ name: string;
+ };
+ formId: string;
+ onLoadingChange?: (loading: boolean) => void;
+ onSuccess?: () => void;
+}
+
+const DatasetEditContent: FC<DatasetEditContentProps> = ({
+ dataset,
+ formId,
+ onLoadingChange,
+ onSuccess,
+}) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const [form] = Form.useForm();
+ const [selectedPreset, setSelectedPreset] = useState<string>('custom');
+ const evalModeValue = Form.useWatch('evalMode', form);
+
+ useEffect(() => {
+ if (dataset) {
+ form.setFieldsValue({
+ description: dataset.description || '',
+ evalConfig: (dataset as any).evalConfig,
+ evalMode: dataset.evalMode || undefined,
+ name: dataset.name,
+ });
+ setSelectedPreset((dataset.metadata?.preset as string) || 'custom');
+ }
+ }, [dataset, form]);
+
+ const presetsByCategory = getPresetsByCategory();
+
+ const selectOptions = Object.entries(presetsByCategory)
+ .filter(([_, presets]) => presets.length > 0)
+ .map(([category, presets]) => ({
+ label: CATEGORY_LABELS[category] || category,
+ options: presets.map((preset) => ({
+ label: preset.name,
+ value: preset.id,
+ })),
+ }));
+
+ const handleFinish = async (values: any) => {
+ onLoadingChange?.(true);
+ try {
+ await agentEvalService.updateDataset({
+ description: values.description?.trim() || undefined,
+ evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : null,
+ evalMode: values.evalMode || null,
+ id: dataset.id,
+ metadata: {
+ ...dataset.metadata,
+ preset: selectedPreset,
+ },
+ name: values.name.trim(),
+ });
+ message.success(t('dataset.edit.success'));
+ close();
+ onSuccess?.();
+ } catch {
+ message.error(t('dataset.edit.error'));
+ } finally {
+ onLoadingChange?.(false);
+ }
+ };
+
+ return (
+ <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form.Item
+ label={t('dataset.create.name.label')}
+ name="name"
+ rules={[{ message: t('dataset.create.nameRequired'), required: true }]}
+ >
+ <Input autoFocus placeholder={t('dataset.create.name.placeholder')} />
+ </Form.Item>
+
+ <Form.Item label={t('dataset.create.description.label')} name="description">
+ <TextArea placeholder={t('dataset.create.description.placeholder')} rows={3} />
+ </Form.Item>
+
+ <Form.Item extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
+ <Select
+ allowClear
+ placeholder={t('evalMode.placeholder')}
+ optionRender={(option) => (
+ <Flexbox gap={2} style={{ padding: '4px 0' }}>
+ <div>{option.label}</div>
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t(`evalMode.${option.value}.desc` as any)}
+ </Text>
+ </Flexbox>
+ )}
+ options={[
+ { label: t('evalMode.equals'), value: 'equals' },
+ { label: t('evalMode.contains'), value: 'contains' },
+ { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ { label: t('evalMode.answer-relevance'), value: 'answer-relevance' },
+ { label: t('evalMode.external'), value: 'external' },
+ ]}
+ />
+ </Form.Item>
+
+ {(evalModeValue === 'llm-rubric' || evalModeValue === 'answer-relevance') && (
+ <>
+ <Form.Item initialValue="aihubmix" label={'Provider'} name={['evalConfig', 'provider']}>
+ <TextArea placeholder={'LLM provider (e.g. openai, azure)'} rows={1} />
+ </Form.Item>
+ <Form.Item initialValue="gpt-5-nano" label={'Model'} name={['evalConfig', 'model']}>
+ <TextArea placeholder={'LLM model to use for evaluation (e.g. gpt-4)'} rows={1} />
+ </Form.Item>
+ <Form.Item label={'System Prompt'} name={['evalConfig', 'systemRole']}>
+ <TextArea placeholder={'Optional system prompt for the LLM judge'} rows={3} />
+ </Form.Item>
+ <Form.Item label={'Eval Prompt'} name={['evalConfig', 'criteria']}>
+ <TextArea placeholder={'Prompt template for the LLM judge'} rows={3} />
+ </Form.Item>
+ <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ <TextArea placeholder={t('evalMode.prompt.placeholder')} rows={3} />
+ </Form.Item>
+ </>
+ )}
+
+ <Form.Item label={t('dataset.create.preset.label')} style={{ marginBottom: 0 }}>
+ <Select
+ options={selectOptions}
+ placeholder="Select a preset"
+ value={selectedPreset}
+ optionRender={(option) => {
+ const preset = DATASET_PRESETS[option.value as string];
+ if (!preset) return option.label;
+
+ return (
+ <Flexbox
+ horizontal
+ align="flex-start"
+ gap={12}
+ style={{ overflow: 'hidden', width: '100%' }}
+ >
+ <Center className={styles.presetIcon} flex="none" height={40} width={40}>
+ <Icon icon={preset.icon} size={18} />
+ </Center>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
+ <Text ellipsis style={{ fontSize: 14, fontWeight: 500 }}>
+ {preset.name}
+ </Text>
+ <Text ellipsis style={{ fontSize: 12 }} type="secondary">
+ {preset.description}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+ }}
+ onChange={(value) => setSelectedPreset(value)}
+ />
+ </Form.Item>
+ </Form>
+ );
+};
+
+export default DatasetEditContent;
diff --git a/src/routes/(main)/eval/features/DatasetEditModal/Footer.tsx b/src/routes/(main)/eval/features/DatasetEditModal/Footer.tsx
new file mode 100644
index 00000000000..2b1c129f842
--- /dev/null
+++ b/src/routes/(main)/eval/features/DatasetEditModal/Footer.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ formId: string;
+ loading: boolean;
+}
+
+const DatasetEditFooter: FC<FooterProps> = ({ formId, loading }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Button form={formId} htmlType="submit" loading={loading} type="primary">
+ {t('common.update')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default DatasetEditFooter;
diff --git a/src/routes/(main)/eval/features/DatasetEditModal/index.tsx b/src/routes/(main)/eval/features/DatasetEditModal/index.tsx
index 773e74fe89d..772a49c5c87 100644
--- a/src/routes/(main)/eval/features/DatasetEditModal/index.tsx
+++ b/src/routes/(main)/eval/features/DatasetEditModal/index.tsx
@@ -1,208 +1,21 @@
'use client';
-import { Center, Flexbox, Icon, Input, Modal, type ModalProps, Text, TextArea } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { App, Form } from 'antd';
-import { cssVar } from 'antd-style';
-import { memo, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
-import { agentEvalService } from '@/services/agentEval';
+import { createFormModal } from '@/utils/createFormModal';
-import { DATASET_PRESETS, getPresetsByCategory } from '../../config/datasetPresets';
+import DatasetEditContent, { type DatasetEditContentProps } from './Content';
+import DatasetEditFooter from './Footer';
-const CATEGORY_LABELS: Record<string, string> = {
- 'custom': 'Custom',
- 'memory': 'Memory',
- 'reference': 'Reference Formats',
- 'research': 'Deep Research / QA',
- 'tool-use': 'Tool Use',
-};
+type Props = Omit<DatasetEditContentProps, 'formId' | 'onLoadingChange'>;
-interface DatasetEditModalProps extends ModalProps {
- dataset: {
- description?: string;
- evalMode?: string | null;
- id: string;
- metadata?: Record<string, unknown>;
- name: string;
- };
- onSuccess?: () => void;
-}
-
-const DatasetEditModal = memo<DatasetEditModalProps>(({ open, onCancel, dataset, onSuccess }) => {
- const { t } = useTranslation('eval');
- const { message } = App.useApp();
- const [form] = Form.useForm();
- const [loading, setLoading] = useState(false);
- const [selectedPreset, setSelectedPreset] = useState<string>('custom');
- const evalModeValue = Form.useWatch('evalMode', form);
-
- useEffect(() => {
- if (open && dataset) {
- form.setFieldsValue({
- description: dataset.description || '',
- evalConfig: (dataset as any).evalConfig,
- evalMode: dataset.evalMode || undefined,
- name: dataset.name,
- });
- setSelectedPreset((dataset.metadata?.preset as string) || 'custom');
- }
- }, [open, dataset, form]);
-
- const presetsByCategory = getPresetsByCategory();
-
- const selectOptions = Object.entries(presetsByCategory)
- .filter(([_, presets]) => presets.length > 0)
- .map(([category, presets]) => ({
- label: CATEGORY_LABELS[category] || category,
- options: presets.map((preset) => ({
- label: preset.name,
- value: preset.id,
- })),
- }));
-
- return (
- <Modal
- allowFullscreen
- destroyOnHidden
- okButtonProps={{ loading }}
- okText={t('common.update')}
- open={open}
- title={t('dataset.edit.title')}
- width={480}
- onCancel={(e) => {
- form.resetFields();
- onCancel?.(e);
- }}
- onOk={async (e) => {
- try {
- const values = await form.validateFields();
- setLoading(true);
-
- await agentEvalService.updateDataset({
- id: dataset.id,
- name: values.name.trim(),
- description: values.description?.trim() || undefined,
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : null,
- evalMode: values.evalMode || null,
- metadata: {
- ...dataset.metadata,
- preset: selectedPreset,
- },
- });
- message.success(t('dataset.edit.success'));
- form.resetFields();
- onCancel?.(e);
- onSuccess?.();
- } catch (error: any) {
- if (error?.errorFields) return;
- message.error(t('dataset.edit.error'));
- } finally {
- setLoading(false);
- }
- }}
- >
- <Form form={form} layout="vertical" style={{ paddingBlock: 16 }}>
- <Form.Item
- label={t('dataset.create.name.label')}
- name="name"
- rules={[{ message: t('dataset.create.nameRequired'), required: true }]}
- >
- <Input autoFocus placeholder={t('dataset.create.name.placeholder')} />
- </Form.Item>
-
- <Form.Item label={t('dataset.create.description.label')} name="description">
- <TextArea placeholder={t('dataset.create.description.placeholder')} rows={3} />
- </Form.Item>
-
- <Form.Item extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
- <Select
- allowClear
- placeholder={t('evalMode.placeholder')}
- optionRender={(option) => (
- <Flexbox gap={2} style={{ padding: '4px 0' }}>
- <div>{option.label}</div>
- <Text style={{ fontSize: 12 }} type="secondary">
- {t(`evalMode.${option.value}.desc` as any)}
- </Text>
- </Flexbox>
- )}
- options={[
- { label: t('evalMode.equals'), value: 'equals' },
- { label: t('evalMode.contains'), value: 'contains' },
- { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
- { label: t('evalMode.answer-relevance'), value: 'answer-relevance' },
- { label: t('evalMode.external'), value: 'external' },
- ]}
- />
- </Form.Item>
-
- {(evalModeValue === 'llm-rubric' || evalModeValue === 'answer-relevance') && (
- <>
- <Form.Item initialValue="aihubmix" label={'Provider'} name={['evalConfig', 'provider']}>
- <TextArea placeholder={'LLM provider (e.g. openai, azure)'} rows={1} />
- </Form.Item>
- <Form.Item initialValue="gpt-5-nano" label={'Model'} name={['evalConfig', 'model']}>
- <TextArea placeholder={'LLM model to use for evaluation (e.g. gpt-4)'} rows={1} />
- </Form.Item>
- <Form.Item label={'System Prompt'} name={['evalConfig', 'systemRole']}>
- <TextArea placeholder={'Optional system prompt for the LLM judge'} rows={3} />
- </Form.Item>
- <Form.Item label={'Eval Prompt'} name={['evalConfig', 'criteria']}>
- <TextArea placeholder={'Prompt template for the LLM judge'} rows={3} />
- </Form.Item>
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
- <TextArea placeholder={t('evalMode.prompt.placeholder')} rows={3} />
- </Form.Item>
- </>
- )}
-
- <Form.Item label={t('dataset.create.preset.label')} style={{ marginBottom: 0 }}>
- <Select
- options={selectOptions}
- placeholder="Select a preset"
- value={selectedPreset}
- optionRender={(option) => {
- const preset = DATASET_PRESETS[option.value as string];
- if (!preset) return option.label;
-
- return (
- <Flexbox
- horizontal
- align="flex-start"
- gap={12}
- style={{ overflow: 'hidden', width: '100%' }}
- >
- <Center
- flex="none"
- height={40}
- width={40}
- style={{
- background: cssVar.colorBgElevated,
- border: `1px solid ${cssVar.colorFillTertiary}`,
- borderRadius: cssVar.borderRadius,
- }}
- >
- <Icon icon={preset.icon} size={18} />
- </Center>
- <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
- <Text ellipsis style={{ fontSize: 14, fontWeight: 500 }}>
- {preset.name}
- </Text>
- <Text ellipsis style={{ fontSize: 12 }} type="secondary">
- {preset.description}
- </Text>
- </Flexbox>
- </Flexbox>
- );
- }}
- onChange={(value) => setSelectedPreset(value)}
- />
- </Form.Item>
- </Form>
- </Modal>
- );
-});
-
-export default DatasetEditModal;
+export const createDatasetEditModal = (props: Props): ModalInstance =>
+ createFormModal({
+ renderContent: ({ formId, setLoading }) => (
+ <DatasetEditContent {...props} formId={formId} onLoadingChange={setLoading} />
+ ),
+ renderFooter: ({ formId, loading }) => <DatasetEditFooter formId={formId} loading={loading} />,
+ title: t('dataset.edit.title', { ns: 'eval' }),
+ width: 480,
+ });
diff --git a/src/routes/(main)/eval/features/DatasetImportModal/Content.tsx b/src/routes/(main)/eval/features/DatasetImportModal/Content.tsx
new file mode 100644
index 00000000000..0b0105e4667
--- /dev/null
+++ b/src/routes/(main)/eval/features/DatasetImportModal/Content.tsx
@@ -0,0 +1,205 @@
+'use client';
+
+import { App } from 'antd';
+import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { agentEvalService } from '@/services/agentEval';
+import { uploadService } from '@/services/upload';
+import { type FileUploadState } from '@/types/files/upload';
+
+import { getPresetById } from '../../config/datasetPresets';
+import MappingStep, { autoInferMapping, type FieldMappingValue } from './MappingStep';
+import UploadStep from './UploadStep';
+
+type MappingTarget =
+ | 'choices'
+ | 'category'
+ | 'expected'
+ | 'ignore'
+ | 'input'
+ | 'metadata'
+ | 'sortOrder';
+
+export interface DatasetImportContentProps {
+ close: () => void;
+ datasetId: string;
+ onImportReady: (api: { canImport: () => boolean; runImport: () => Promise<void> }) => void;
+ onStateChange: (state: { canImport: boolean; step: 0 | 1 }) => void;
+ onSuccess?: (datasetId: string) => void;
+ presetId?: string;
+ setPrev: (fn: () => void) => void;
+}
+
+const DatasetImportContent: FC<DatasetImportContentProps> = ({
+ close,
+ datasetId,
+ onImportReady,
+ onStateChange,
+ onSuccess,
+ presetId,
+ setPrev,
+}) => {
+ const { t } = useTranslation('eval');
+ const { message } = App.useApp();
+
+ const [step, setStep] = useState<0 | 1>(0);
+ const [uploading, setUploading] = useState(false);
+ const [uploadProgress, setUploadProgress] = useState<FileUploadState>();
+
+ const [pathname, setPathname] = useState('');
+ const [filename, setFilename] = useState('');
+
+ const [headers, setHeaders] = useState<string[]>([]);
+ const [preview, setPreview] = useState<Record<string, any>[]>([]);
+ const [totalCount, setTotalCount] = useState(0);
+ const [format, setFormat] = useState<'csv' | 'json' | 'jsonl' | 'xlsx'>();
+
+ const [mapping, setMapping] = useState<Record<string, MappingTarget>>({});
+ const [delimiter, setDelimiter] = useState('');
+
+ const preset = useMemo(() => (presetId ? getPresetById(presetId) : undefined), [presetId]);
+
+ const hasInputMapping = Object.values(mapping).includes('input');
+
+ useEffect(() => {
+ onStateChange({ canImport: hasInputMapping, step });
+ }, [hasInputMapping, onStateChange, step]);
+
+ useEffect(() => {
+ setPrev(() => setStep(0));
+ }, [setPrev]);
+
+ const handleFileSelect = useCallback(
+ async (file: File) => {
+ setUploading(true);
+ setUploadProgress(undefined);
+ try {
+ const metadata = await uploadService.uploadToServerS3(file, {
+ directory: 'eval-datasets',
+ onProgress: (status, state) => {
+ setUploadProgress(state);
+ },
+ });
+
+ setPathname(metadata.path);
+ setFilename(file.name);
+
+ const result = await agentEvalService.parseDatasetFile({
+ filename: file.name,
+ pathname: metadata.path,
+ });
+
+ setHeaders(result.headers);
+ setPreview(result.preview);
+ setTotalCount(result.totalCount);
+ setFormat(result.format as 'csv' | 'json' | 'jsonl' | 'xlsx');
+
+ const inferred = autoInferMapping(result.headers, preset);
+ setMapping(inferred);
+
+ setStep(1);
+ } catch {
+ setTimeout(() => {
+ message.error(t('dataset.import.parseError'));
+ }, 0);
+ } finally {
+ setUploading(false);
+ setUploadProgress(undefined);
+ }
+ },
+ [message, preset, t],
+ );
+
+ const buildFieldMapping = useCallback((): FieldMappingValue | null => {
+ const inputCol = Object.entries(mapping).find(([, v]) => v === 'input')?.[0];
+ if (!inputCol) return null;
+
+ const expectedCol = Object.entries(mapping).find(([, v]) => v === 'expected')?.[0];
+ const choicesCol = Object.entries(mapping).find(([, v]) => v === 'choices')?.[0];
+ const categoryCol = Object.entries(mapping).find(([, v]) => v === 'category')?.[0];
+ const sortOrderCol = Object.entries(mapping).find(([, v]) => v === 'sortOrder')?.[0];
+
+ const metadataCols = Object.entries(mapping).filter(([, v]) => v === 'metadata');
+ const metadataMap =
+ metadataCols.length > 0
+ ? Object.fromEntries(metadataCols.map(([col]) => [col, col]))
+ : undefined;
+
+ return {
+ category: categoryCol,
+ choices: choicesCol,
+ expected: expectedCol,
+ expectedDelimiter: delimiter || undefined,
+ input: inputCol,
+ metadata: metadataMap,
+ sortOrder: sortOrderCol,
+ };
+ }, [mapping, delimiter]);
+
+ const runImport = useCallback(async () => {
+ const fieldMapping = buildFieldMapping();
+ if (!fieldMapping) return;
+
+ try {
+ const result = await agentEvalService.importDataset({
+ datasetId,
+ fieldMapping: {
+ category: fieldMapping.category,
+ choices: fieldMapping.choices,
+ expected: fieldMapping.expected,
+ expectedDelimiter: fieldMapping.expectedDelimiter,
+ input: fieldMapping.input,
+ metadata: fieldMapping.metadata,
+ sortOrder: fieldMapping.sortOrder,
+ },
+ filename,
+ format,
+ pathname,
+ });
+ setTimeout(() => {
+ message.success(t('dataset.import.success', { count: result.count }));
+ }, 0);
+ close();
+ onSuccess?.(datasetId);
+ } catch {
+ setTimeout(() => {
+ message.error(t('dataset.import.error'));
+ }, 0);
+ }
+ }, [buildFieldMapping, close, datasetId, filename, format, message, onSuccess, pathname, t]);
+
+ useEffect(() => {
+ onImportReady({
+ canImport: () => hasInputMapping,
+ runImport,
+ });
+ }, [hasInputMapping, onImportReady, runImport]);
+
+ return (
+ <>
+ {step === 0 && (
+ <UploadStep
+ loading={uploading}
+ preset={preset}
+ uploadProgress={uploadProgress}
+ onFileSelect={handleFileSelect}
+ />
+ )}
+
+ {step === 1 && (
+ <MappingStep
+ delimiter={delimiter}
+ headers={headers}
+ mapping={mapping}
+ preview={preview}
+ totalCount={totalCount}
+ onDelimiterChange={setDelimiter}
+ onMappingChange={setMapping}
+ />
+ )}
+ </>
+ );
+};
+
+export default DatasetImportContent;
diff --git a/src/routes/(main)/eval/features/DatasetImportModal/Footer.tsx b/src/routes/(main)/eval/features/DatasetImportModal/Footer.tsx
new file mode 100644
index 00000000000..41837683f40
--- /dev/null
+++ b/src/routes/(main)/eval/features/DatasetImportModal/Footer.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ canImport: boolean;
+ importing: boolean;
+ onImport: () => void;
+ onPrev: () => void;
+}
+
+const DatasetImportFooter: FC<FooterProps> = ({ canImport, importing, onImport, onPrev }) => {
+ const { t } = useTranslation('eval');
+ return (
+ <ModalFooter>
+ <Button disabled={importing} onClick={onPrev}>
+ {t('dataset.import.prev')}
+ </Button>
+ <Button disabled={!canImport} loading={importing} type="primary" onClick={onImport}>
+ {t('dataset.import.confirm')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default DatasetImportFooter;
diff --git a/src/routes/(main)/eval/features/DatasetImportModal/index.tsx b/src/routes/(main)/eval/features/DatasetImportModal/index.tsx
index ad8f7eb6ba6..1f5a276dedd 100644
--- a/src/routes/(main)/eval/features/DatasetImportModal/index.tsx
+++ b/src/routes/(main)/eval/features/DatasetImportModal/index.tsx
@@ -1,252 +1,75 @@
'use client';
-import { Modal } from '@lobehub/ui';
-import { App } from 'antd';
-import { memo, useCallback, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
+import { createModal, type ImperativeModalProps, type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
-import { agentEvalService } from '@/services/agentEval';
-import { uploadService } from '@/services/upload';
-import { type FileUploadState } from '@/types/files/upload';
+import DatasetImportContent from './Content';
+import DatasetImportFooter from './Footer';
-import { getPresetById } from '../../config/datasetPresets';
-import MappingStep, { autoInferMapping, type FieldMappingValue } from './MappingStep';
-import UploadStep from './UploadStep';
-
-type MappingTarget =
- | 'choices'
- | 'category'
- | 'expected'
- | 'ignore'
- | 'input'
- | 'metadata'
- | 'sortOrder';
-
-interface DatasetImportModalProps {
+interface CreateOptions {
datasetId: string;
- onClose: () => void;
onSuccess?: (datasetId: string) => void;
- open: boolean;
presetId?: string;
}
-const DatasetImportModal = memo<DatasetImportModalProps>(
- ({ open, onClose, datasetId, onSuccess, presetId }) => {
- const { t } = useTranslation('eval');
- const { message } = App.useApp();
-
- const [step, setStep] = useState(0);
- const [uploading, setUploading] = useState(false);
- const [importing, setImporting] = useState(false);
- const [uploadProgress, setUploadProgress] = useState<FileUploadState>();
-
- // Upload result
- const [pathname, setPathname] = useState('');
- const [filename, setFilename] = useState('');
-
- // Parse result
- const [headers, setHeaders] = useState<string[]>([]);
- const [preview, setPreview] = useState<Record<string, any>[]>([]);
- const [totalCount, setTotalCount] = useState(0);
- const [format, setFormat] = useState<'csv' | 'json' | 'jsonl' | 'xlsx'>();
-
- // Mapping state
- const [mapping, setMapping] = useState<Record<string, MappingTarget>>({});
- const [delimiter, setDelimiter] = useState('');
-
- const preset = useMemo(() => (presetId ? getPresetById(presetId) : undefined), [presetId]);
-
- const reset = useCallback(() => {
- setStep(0);
- setUploading(false);
- setImporting(false);
- setUploadProgress(undefined);
- setPathname('');
- setFilename('');
- setHeaders([]);
- setPreview([]);
- setTotalCount(0);
- setFormat(undefined);
- setMapping({});
- setDelimiter('');
- }, []);
-
- const handleClose = useCallback(() => {
- reset();
- onClose();
- }, [onClose, reset]);
-
- const handleFileSelect = useCallback(
- async (file: File) => {
- setUploading(true);
- setUploadProgress(undefined);
- try {
- // 1. Upload to S3 with progress tracking
- const metadata = await uploadService.uploadToServerS3(file, {
- directory: 'eval-datasets',
- onProgress: (status, state) => {
- setUploadProgress(state);
- },
- });
-
- setPathname(metadata.path);
- setFilename(file.name);
-
- // 2. Parse the file on server
- const result = await agentEvalService.parseDatasetFile({
- pathname: metadata.path,
- filename: file.name,
- });
-
- setHeaders(result.headers);
- setPreview(result.preview);
- setTotalCount(result.totalCount);
- setFormat(result.format as 'csv' | 'json' | 'jsonl' | 'xlsx');
-
- // 3. Auto-infer field mapping using preset
- const inferred = autoInferMapping(result.headers, preset);
- setMapping(inferred);
-
- // 4. Advance to mapping step
- setStep(1);
- } catch {
- // Use setTimeout to avoid calling message during render
- setTimeout(() => {
- message.error(t('dataset.import.parseError'));
- }, 0);
- } finally {
- setUploading(false);
- setUploadProgress(undefined);
- }
- },
- [message, preset, t],
- );
-
- const buildFieldMapping = useCallback((): FieldMappingValue | null => {
- const inputCol = Object.entries(mapping).find(([, v]) => v === 'input')?.[0];
- if (!inputCol) return null;
-
- const expectedCol = Object.entries(mapping).find(([, v]) => v === 'expected')?.[0];
- const choicesCol = Object.entries(mapping).find(([, v]) => v === 'choices')?.[0];
- const categoryCol = Object.entries(mapping).find(([, v]) => v === 'category')?.[0];
- const sortOrderCol = Object.entries(mapping).find(([, v]) => v === 'sortOrder')?.[0];
-
- const metadataCols = Object.entries(mapping).filter(([, v]) => v === 'metadata');
- const metadataMap =
- metadataCols.length > 0
- ? Object.fromEntries(metadataCols.map(([col]) => [col, col]))
- : undefined;
-
- return {
- category: categoryCol,
- choices: choicesCol,
- expected: expectedCol,
- expectedDelimiter: delimiter || undefined,
- input: inputCol,
- metadata: metadataMap,
- sortOrder: sortOrderCol,
- };
- }, [mapping, delimiter]);
-
- const handleImport = useCallback(async () => {
- const fieldMapping = buildFieldMapping();
- if (!fieldMapping) return;
-
- setImporting(true);
- try {
- const result = await agentEvalService.importDataset({
- datasetId,
- pathname,
- filename,
- format,
- fieldMapping: {
- input: fieldMapping.input,
- expected: fieldMapping.expected,
- expectedDelimiter: fieldMapping.expectedDelimiter,
- choices: fieldMapping.choices,
- category: fieldMapping.category,
- sortOrder: fieldMapping.sortOrder,
- metadata: fieldMapping.metadata,
- },
- });
- setTimeout(() => {
- message.success(t('dataset.import.success', { count: result.count }));
- }, 0);
- handleClose();
- onSuccess?.(datasetId);
- } catch {
- setTimeout(() => {
- message.error(t('dataset.import.error'));
- }, 0);
- } finally {
- setImporting(false);
- }
- }, [
- buildFieldMapping,
- datasetId,
- filename,
- format,
- handleClose,
- message,
- onSuccess,
- pathname,
- t,
- ]);
-
- const hasInputMapping = Object.values(mapping).includes('input');
-
+export const createDatasetImportModal = ({
+ datasetId,
+ onSuccess,
+ presetId,
+}: CreateOptions): ModalInstance => {
+ const ref: { instance?: ModalInstance } = {};
+ let step: 0 | 1 = 0;
+ let canImport = false;
+ let importing = false;
+ let runImport: () => Promise<void> = async () => {};
+ let prev: () => void = () => {};
+
+ const renderFooter = () => {
+ if (step === 0) return null;
return (
- <Modal
- allowFullscreen
- destroyOnHidden
- cancelText={step === 1 ? t('dataset.import.prev') : undefined}
- centered={step === 1}
- footer={step === 0 ? null : undefined}
- maskClosable={false}
- okText={step === 1 ? t('dataset.import.confirm') : undefined}
- open={open}
- title={t('dataset.import.title')}
- width={step === 0 ? 720 : '98vw'}
- okButtonProps={{
- disabled: !hasInputMapping,
- loading: importing,
+ <DatasetImportFooter
+ canImport={canImport}
+ importing={importing}
+ onPrev={prev}
+ onImport={async () => {
+ importing = true;
+ ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
+ try {
+ await runImport();
+ } finally {
+ importing = false;
+ ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
+ }
}}
- styles={
- step === 1
- ? {
- container: { height: '95vh', display: 'flex', flexDirection: 'column' },
- body: { overflow: 'auto', maxHeight: 'unset', flex: 1 },
- }
- : undefined
- }
- onCancel={step === 1 ? () => setStep(0) : handleClose}
- onOk={step === 1 ? handleImport : undefined}
- >
- <div style={{ paddingBlock: 16 }}>
- {step === 0 && (
- <UploadStep
- loading={uploading}
- preset={preset}
- uploadProgress={uploadProgress}
- onFileSelect={handleFileSelect}
- />
- )}
-
- {step === 1 && (
- <MappingStep
- delimiter={delimiter}
- headers={headers}
- mapping={mapping}
- preview={preview}
- totalCount={totalCount}
- onDelimiterChange={setDelimiter}
- onMappingChange={setMapping}
- />
- )}
- </div>
- </Modal>
+ />
);
- },
-);
-
-export default DatasetImportModal;
+ };
+
+ ref.instance = createModal({
+ content: (
+ <DatasetImportContent
+ close={() => ref.instance?.close()}
+ datasetId={datasetId}
+ presetId={presetId}
+ setPrev={(fn) => {
+ prev = fn;
+ }}
+ onSuccess={onSuccess}
+ onImportReady={(api) => {
+ runImport = api.runImport;
+ }}
+ onStateChange={(next) => {
+ if (next.step === step && next.canImport === canImport) return;
+ step = next.step;
+ canImport = next.canImport;
+ ref.instance?.update({ footer: renderFooter() } as Partial<ImperativeModalProps>);
+ }}
+ />
+ ),
+ footer: renderFooter(),
+ maskClosable: false,
+ title: t('dataset.import.title', { ns: 'eval' }),
+ width: 720,
+ });
+ return ref.instance;
+};
diff --git a/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx b/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
new file mode 100644
index 00000000000..e7717393001
--- /dev/null
+++ b/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
@@ -0,0 +1,150 @@
+'use client';
+
+import { Accordion, AccordionItem, Flexbox, Text } from '@lobehub/ui';
+import { Select, useModalContext } from '@lobehub/ui/base-ui';
+import { App, Form, Input } from 'antd';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { agentEvalService } from '@/services/agentEval';
+
+export interface TestCaseCreateContentProps {
+ datasetId: string;
+ formId: string;
+ onLoadingChange?: (loading: boolean) => void;
+ onSuccess?: (datasetId: string) => void;
+}
+
+const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
+ datasetId,
+ formId,
+ onLoadingChange,
+ onSuccess,
+}) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const [form] = Form.useForm();
+ const evalModeValue = Form.useWatch('evalMode', form);
+
+ const handleFinish = async (values: any) => {
+ onLoadingChange?.(true);
+ try {
+ const tags = values.tags
+ ? values.tags
+ .split(',')
+ .map((t: string) => t.trim())
+ .filter(Boolean)
+ : undefined;
+
+ await agentEvalService.createTestCase({
+ content: {
+ expected: values.expected,
+ input: values.input,
+ },
+ datasetId,
+ evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : undefined,
+ evalMode: values.evalMode || undefined,
+ metadata: {
+ ...(values.difficulty ? { difficulty: values.difficulty } : {}),
+ ...(tags ? { tags } : {}),
+ },
+ });
+
+ setTimeout(() => {
+ message.success(t('testCase.create.success'));
+ }, 0);
+ close();
+ onSuccess?.(datasetId);
+ } catch {
+ setTimeout(() => {
+ message.error(t('testCase.create.error'));
+ }, 0);
+ } finally {
+ onLoadingChange?.(false);
+ }
+ };
+
+ return (
+ <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form.Item label={t('testCase.create.input.label')} name="input" rules={[{ required: true }]}>
+ <Input.TextArea
+ autoSize={{ maxRows: 6, minRows: 3 }}
+ placeholder={t('testCase.create.input.placeholder')}
+ />
+ </Form.Item>
+ <Form.Item
+ label={t('testCase.create.expected.label')}
+ name="expected"
+ rules={[{ message: t('testCase.create.expected.required'), required: true }]}
+ >
+ <Input.TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ placeholder={t('testCase.create.expected.placeholder')}
+ />
+ </Form.Item>
+ <Form.Item label={t('evalMode.label')} name="evalMode">
+ <Select
+ allowClear
+ placeholder={t('evalMode.placeholder')}
+ optionRender={(option) => (
+ <Flexbox gap={2} style={{ padding: '4px 0' }}>
+ <div>{option.label}</div>
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t(`evalMode.${option.value}.desc` as any)}
+ </Text>
+ </Flexbox>
+ )}
+ options={[
+ { label: t('evalMode.equals'), value: 'equals' },
+ { label: t('evalMode.contains'), value: 'contains' },
+ { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ ]}
+ />
+ </Form.Item>
+ {evalModeValue === 'llm-rubric' && (
+ <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ <Input.TextArea
+ autoSize={{ maxRows: 8, minRows: 3 }}
+ placeholder={t('evalMode.prompt.placeholder')}
+ />
+ </Form.Item>
+ )}
+ <Accordion>
+ <AccordionItem
+ itemKey="advanced"
+ paddingBlock={6}
+ paddingInline={4}
+ title={t('testCase.create.advanced')}
+ >
+ <Flexbox gap={16} style={{ paddingTop: 8 }}>
+ <Form.Item
+ label={t('testCase.create.difficulty.label')}
+ name="difficulty"
+ style={{ marginBottom: 0 }}
+ >
+ <Select
+ allowClear
+ placeholder={t('testCase.create.difficulty.label')}
+ options={[
+ { label: t('difficulty.easy'), value: 'easy' },
+ { label: t('difficulty.medium'), value: 'medium' },
+ { label: t('difficulty.hard'), value: 'hard' },
+ ]}
+ />
+ </Form.Item>
+ <Form.Item
+ label={t('testCase.create.tags.label')}
+ name="tags"
+ style={{ marginBottom: 0 }}
+ >
+ <Input placeholder={t('testCase.create.tags.placeholder')} />
+ </Form.Item>
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
+ </Form>
+ );
+};
+
+export default TestCaseCreateContent;
diff --git a/src/routes/(main)/eval/features/TestCaseCreateModal/Footer.tsx b/src/routes/(main)/eval/features/TestCaseCreateModal/Footer.tsx
new file mode 100644
index 00000000000..fde3140d621
--- /dev/null
+++ b/src/routes/(main)/eval/features/TestCaseCreateModal/Footer.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ formId: string;
+ loading: boolean;
+}
+
+const TestCaseCreateFooter: FC<FooterProps> = ({ formId, loading }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Button form={formId} htmlType="submit" loading={loading} type="primary">
+ {t('common.create')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default TestCaseCreateFooter;
diff --git a/src/routes/(main)/eval/features/TestCaseCreateModal/index.tsx b/src/routes/(main)/eval/features/TestCaseCreateModal/index.tsx
index 762936bb68e..1d7d9f2a4cb 100644
--- a/src/routes/(main)/eval/features/TestCaseCreateModal/index.tsx
+++ b/src/routes/(main)/eval/features/TestCaseCreateModal/index.tsx
@@ -1,168 +1,23 @@
'use client';
-import { Accordion, AccordionItem, Flexbox, Modal, Text } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { App, Form, Input } from 'antd';
-import { memo, useCallback, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { agentEvalService } from '@/services/agentEval';
-
-interface TestCaseCreateModalProps {
- datasetId: string;
- onClose: () => void;
- onSuccess?: (datasetId: string) => void;
- open: boolean;
-}
-
-const TestCaseCreateModal = memo<TestCaseCreateModalProps>(
- ({ open, onClose, datasetId, onSuccess }) => {
- const { t } = useTranslation('eval');
- const { message } = App.useApp();
- const [form] = Form.useForm();
- const [loading, setLoading] = useState(false);
- const evalModeValue = Form.useWatch('evalMode', form);
-
- const handleClose = useCallback(() => {
- form.resetFields();
- onClose();
- }, [form, onClose]);
-
- const handleSubmit = useCallback(async () => {
- const values = await form.validateFields();
- setLoading(true);
- try {
- const tags = values.tags
- ? values.tags
- .split(',')
- .map((t: string) => t.trim())
- .filter(Boolean)
- : undefined;
-
- await agentEvalService.createTestCase({
- content: {
- expected: values.expected,
- input: values.input,
- },
- datasetId,
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : undefined,
- evalMode: values.evalMode || undefined,
- metadata: {
- ...(values.difficulty ? { difficulty: values.difficulty } : {}),
- ...(tags ? { tags } : {}),
- },
- });
-
- setTimeout(() => {
- message.success(t('testCase.create.success'));
- }, 0);
- handleClose();
- onSuccess?.(datasetId);
- } catch {
- setTimeout(() => {
- message.error(t('testCase.create.error'));
- }, 0);
- } finally {
- setLoading(false);
- }
- }, [datasetId, form, handleClose, message, onSuccess, t]);
-
- return (
- <Modal
- destroyOnHidden
- okButtonProps={{ loading }}
- okText={t('common.create')}
- open={open}
- title={t('testCase.create.title')}
- width={520}
- onCancel={handleClose}
- onOk={handleSubmit}
- >
- <Form form={form} layout="vertical" style={{ paddingTop: 16 }}>
- <Form.Item
- label={t('testCase.create.input.label')}
- name="input"
- rules={[{ required: true }]}
- >
- <Input.TextArea
- autoSize={{ maxRows: 6, minRows: 3 }}
- placeholder={t('testCase.create.input.placeholder')}
- />
- </Form.Item>
- <Form.Item
- label={t('testCase.create.expected.label')}
- name="expected"
- rules={[{ message: t('testCase.create.expected.required'), required: true }]}
- >
- <Input.TextArea
- autoSize={{ maxRows: 6, minRows: 2 }}
- placeholder={t('testCase.create.expected.placeholder')}
- />
- </Form.Item>
- <Form.Item label={t('evalMode.label')} name="evalMode">
- <Select
- allowClear
- placeholder={t('evalMode.placeholder')}
- optionRender={(option) => (
- <Flexbox gap={2} style={{ padding: '4px 0' }}>
- <div>{option.label}</div>
- <Text style={{ fontSize: 12 }} type="secondary">
- {t(`evalMode.${option.value}.desc` as any)}
- </Text>
- </Flexbox>
- )}
- options={[
- { label: t('evalMode.equals'), value: 'equals' },
- { label: t('evalMode.contains'), value: 'contains' },
- { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
- ]}
- />
- </Form.Item>
- {evalModeValue === 'llm-rubric' && (
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
- <Input.TextArea
- autoSize={{ maxRows: 8, minRows: 3 }}
- placeholder={t('evalMode.prompt.placeholder')}
- />
- </Form.Item>
- )}
- <Accordion>
- <AccordionItem
- itemKey="advanced"
- paddingBlock={6}
- paddingInline={4}
- title={t('testCase.create.advanced')}
- >
- <Flexbox gap={16} style={{ paddingTop: 8 }}>
- <Form.Item
- label={t('testCase.create.difficulty.label')}
- name="difficulty"
- style={{ marginBottom: 0 }}
- >
- <Select
- allowClear
- placeholder={t('testCase.create.difficulty.label')}
- options={[
- { label: t('difficulty.easy'), value: 'easy' },
- { label: t('difficulty.medium'), value: 'medium' },
- { label: t('difficulty.hard'), value: 'hard' },
- ]}
- />
- </Form.Item>
- <Form.Item
- label={t('testCase.create.tags.label')}
- name="tags"
- style={{ marginBottom: 0 }}
- >
- <Input placeholder={t('testCase.create.tags.placeholder')} />
- </Form.Item>
- </Flexbox>
- </AccordionItem>
- </Accordion>
- </Form>
- </Modal>
- );
- },
-);
-
-export default TestCaseCreateModal;
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import { createFormModal } from '@/utils/createFormModal';
+
+import TestCaseCreateContent, { type TestCaseCreateContentProps } from './Content';
+import TestCaseCreateFooter from './Footer';
+
+type Props = Omit<TestCaseCreateContentProps, 'formId' | 'onLoadingChange'>;
+
+export const createTestCaseCreateModal = (props: Props): ModalInstance =>
+ createFormModal({
+ renderContent: ({ formId, setLoading }) => (
+ <TestCaseCreateContent {...props} formId={formId} onLoadingChange={setLoading} />
+ ),
+ renderFooter: ({ formId, loading }) => (
+ <TestCaseCreateFooter formId={formId} loading={loading} />
+ ),
+ title: t('testCase.create.title', { ns: 'eval' }),
+ width: 520,
+ });
diff --git a/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx b/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
new file mode 100644
index 00000000000..9f3e68742cf
--- /dev/null
+++ b/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
@@ -0,0 +1,168 @@
+'use client';
+
+import { Accordion, AccordionItem, Flexbox, Text } from '@lobehub/ui';
+import { Select, useModalContext } from '@lobehub/ui/base-ui';
+import { App, Form, Input } from 'antd';
+import { type FC, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { agentEvalService } from '@/services/agentEval';
+
+export interface TestCaseEditContentProps {
+ formId: string;
+ onLoadingChange?: (loading: boolean) => void;
+ onSuccess?: (datasetId: string) => void;
+ testCase: any;
+}
+
+const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
+ formId,
+ onLoadingChange,
+ onSuccess,
+ testCase,
+}) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ const { message } = App.useApp();
+ const [form] = Form.useForm();
+ const evalModeValue = Form.useWatch('evalMode', form);
+
+ useEffect(() => {
+ if (testCase) {
+ form.setFieldsValue({
+ category: testCase.content?.category,
+ difficulty: testCase.metadata?.difficulty,
+ evalConfig: testCase.evalConfig,
+ evalMode: testCase.evalMode || undefined,
+ expected: testCase.content?.expected,
+ input: testCase.content?.input,
+ tags: testCase.metadata?.tags?.join(', '),
+ });
+ }
+ }, [testCase, form]);
+
+ const handleFinish = async (values: any) => {
+ onLoadingChange?.(true);
+ try {
+ const tags = values.tags
+ ? values.tags
+ .split(',')
+ .map((t: string) => t.trim())
+ .filter(Boolean)
+ : undefined;
+
+ await agentEvalService.updateTestCase({
+ content: {
+ category: values.category || undefined,
+ expected: values.expected,
+ input: values.input,
+ },
+ evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : null,
+ evalMode: values.evalMode || null,
+ id: testCase.id,
+ metadata: {
+ ...(values.difficulty ? { difficulty: values.difficulty } : {}),
+ ...(tags ? { tags } : {}),
+ },
+ });
+
+ await onSuccess?.(testCase.datasetId);
+ message.success(t('testCase.edit.success'));
+ close();
+ } catch {
+ message.error(t('testCase.edit.error'));
+ } finally {
+ onLoadingChange?.(false);
+ }
+ };
+
+ return (
+ <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form.Item label={t('testCase.create.input.label')} name="input" rules={[{ required: true }]}>
+ <Input.TextArea
+ autoSize={{ maxRows: 6, minRows: 3 }}
+ placeholder={t('testCase.create.input.placeholder')}
+ />
+ </Form.Item>
+ <Form.Item
+ label={t('testCase.create.expected.label')}
+ name="expected"
+ rules={[{ message: t('testCase.create.expected.required'), required: true }]}
+ >
+ <Input.TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ placeholder={t('testCase.create.expected.placeholder')}
+ />
+ </Form.Item>
+ <Form.Item label={t('evalMode.label')} name="evalMode">
+ <Select
+ allowClear
+ placeholder={t('evalMode.placeholder')}
+ optionRender={(option) => (
+ <Flexbox gap={2} style={{ padding: '4px 0' }}>
+ <div>{option.label}</div>
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t(`evalMode.${option.value}.desc` as any)}
+ </Text>
+ </Flexbox>
+ )}
+ options={[
+ { label: t('evalMode.equals'), value: 'equals' },
+ { label: t('evalMode.contains'), value: 'contains' },
+ { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
+ ]}
+ />
+ </Form.Item>
+ {evalModeValue === 'llm-rubric' && (
+ <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ <Input.TextArea
+ autoSize={{ maxRows: 8, minRows: 3 }}
+ placeholder={t('evalMode.prompt.placeholder')}
+ />
+ </Form.Item>
+ )}
+ <Accordion>
+ <AccordionItem
+ itemKey="advanced"
+ paddingBlock={6}
+ paddingInline={4}
+ title={t('testCase.create.advanced')}
+ >
+ <Flexbox gap={16} style={{ paddingTop: 8 }}>
+ <Form.Item
+ label={t('table.columns.category')}
+ name="category"
+ style={{ marginBottom: 0 }}
+ >
+ <Input placeholder={t('dataset.import.categoryDesc')} />
+ </Form.Item>
+ <Form.Item
+ label={t('testCase.create.difficulty.label')}
+ name="difficulty"
+ style={{ marginBottom: 0 }}
+ >
+ <Select
+ allowClear
+ placeholder={t('testCase.create.difficulty.label')}
+ options={[
+ { label: t('difficulty.easy'), value: 'easy' },
+ { label: t('difficulty.medium'), value: 'medium' },
+ { label: t('difficulty.hard'), value: 'hard' },
+ ]}
+ />
+ </Form.Item>
+ <Form.Item
+ label={t('testCase.create.tags.label')}
+ name="tags"
+ style={{ marginBottom: 0 }}
+ >
+ <Input placeholder={t('testCase.create.tags.placeholder')} />
+ </Form.Item>
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
+ </Form>
+ );
+};
+
+export default TestCaseEditContent;
diff --git a/src/routes/(main)/eval/features/TestCaseEditModal/Footer.tsx b/src/routes/(main)/eval/features/TestCaseEditModal/Footer.tsx
new file mode 100644
index 00000000000..e6ad83e82b8
--- /dev/null
+++ b/src/routes/(main)/eval/features/TestCaseEditModal/Footer.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type FC } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface FooterProps {
+ formId: string;
+ loading: boolean;
+}
+
+const TestCaseEditFooter: FC<FooterProps> = ({ formId, loading }) => {
+ const { t } = useTranslation('eval');
+ const { close } = useModalContext();
+ return (
+ <ModalFooter>
+ <Button disabled={loading} onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ <Button form={formId} htmlType="submit" loading={loading} type="primary">
+ {t('common.update')}
+ </Button>
+ </ModalFooter>
+ );
+};
+
+export default TestCaseEditFooter;
diff --git a/src/routes/(main)/eval/features/TestCaseEditModal/index.tsx b/src/routes/(main)/eval/features/TestCaseEditModal/index.tsx
index bc70a8e3b18..c29912aabe0 100644
--- a/src/routes/(main)/eval/features/TestCaseEditModal/index.tsx
+++ b/src/routes/(main)/eval/features/TestCaseEditModal/index.tsx
@@ -1,184 +1,21 @@
'use client';
-import { Accordion, AccordionItem, Flexbox, Modal, Text } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { App, Form, Input } from 'antd';
-import { memo, useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
-import { agentEvalService } from '@/services/agentEval';
+import { createFormModal } from '@/utils/createFormModal';
-interface TestCaseEditModalProps {
- onClose: () => void;
- onSuccess?: (datasetId: string) => void;
- open: boolean;
- testCase: any;
-}
+import TestCaseEditContent, { type TestCaseEditContentProps } from './Content';
+import TestCaseEditFooter from './Footer';
-const TestCaseEditModal = memo<TestCaseEditModalProps>(({ open, onClose, testCase, onSuccess }) => {
- const { t } = useTranslation('eval');
- const { message } = App.useApp();
- const [form] = Form.useForm();
- const [loading, setLoading] = useState(false);
- const evalModeValue = Form.useWatch('evalMode', form);
+type Props = Omit<TestCaseEditContentProps, 'formId' | 'onLoadingChange'>;
- useEffect(() => {
- if (open && testCase) {
- form.setFieldsValue({
- category: testCase.content?.category,
- difficulty: testCase.metadata?.difficulty,
- evalConfig: testCase.evalConfig,
- evalMode: testCase.evalMode || undefined,
- expected: testCase.content?.expected,
- input: testCase.content?.input,
- tags: testCase.metadata?.tags?.join(', '),
- });
- }
- }, [open, testCase, form]);
-
- const handleClose = useCallback(() => {
- form.resetFields();
- onClose();
- }, [form, onClose]);
-
- const handleSubmit = useCallback(async () => {
- const values = await form.validateFields();
- setLoading(true);
- try {
- const tags = values.tags
- ? values.tags
- .split(',')
- .map((t: string) => t.trim())
- .filter(Boolean)
- : undefined;
-
- await agentEvalService.updateTestCase({
- content: {
- category: values.category || undefined,
- expected: values.expected,
- input: values.input,
- },
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : null,
- evalMode: values.evalMode || null,
- id: testCase.id,
- metadata: {
- ...(values.difficulty ? { difficulty: values.difficulty } : {}),
- ...(tags ? { tags } : {}),
- },
- });
-
- await onSuccess?.(testCase.datasetId);
- message.success(t('testCase.edit.success'));
- handleClose();
- } catch {
- message.error(t('testCase.edit.error'));
- } finally {
- setLoading(false);
- }
- }, [testCase, form, handleClose, message, onSuccess, t]);
-
- return (
- <Modal
- destroyOnHidden
- okButtonProps={{ loading }}
- okText={t('common.update')}
- open={open}
- title={t('testCase.edit.title')}
- width={520}
- onCancel={handleClose}
- onOk={handleSubmit}
- >
- <Form form={form} layout="vertical" style={{ paddingTop: 16 }}>
- <Form.Item
- label={t('testCase.create.input.label')}
- name="input"
- rules={[{ required: true }]}
- >
- <Input.TextArea
- autoSize={{ maxRows: 6, minRows: 3 }}
- placeholder={t('testCase.create.input.placeholder')}
- />
- </Form.Item>
- <Form.Item
- label={t('testCase.create.expected.label')}
- name="expected"
- rules={[{ message: t('testCase.create.expected.required'), required: true }]}
- >
- <Input.TextArea
- autoSize={{ maxRows: 6, minRows: 2 }}
- placeholder={t('testCase.create.expected.placeholder')}
- />
- </Form.Item>
- <Form.Item label={t('evalMode.label')} name="evalMode">
- <Select
- allowClear
- placeholder={t('evalMode.placeholder')}
- optionRender={(option) => (
- <Flexbox gap={2} style={{ padding: '4px 0' }}>
- <div>{option.label}</div>
- <Text style={{ fontSize: 12 }} type="secondary">
- {t(`evalMode.${option.value}.desc` as any)}
- </Text>
- </Flexbox>
- )}
- options={[
- { label: t('evalMode.equals'), value: 'equals' },
- { label: t('evalMode.contains'), value: 'contains' },
- { label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
- ]}
- />
- </Form.Item>
- {evalModeValue === 'llm-rubric' && (
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
- <Input.TextArea
- autoSize={{ maxRows: 8, minRows: 3 }}
- placeholder={t('evalMode.prompt.placeholder')}
- />
- </Form.Item>
- )}
- <Accordion>
- <AccordionItem
- itemKey="advanced"
- paddingBlock={6}
- paddingInline={4}
- title={t('testCase.create.advanced')}
- >
- <Flexbox gap={16} style={{ paddingTop: 8 }}>
- <Form.Item
- label={t('table.columns.category')}
- name="category"
- style={{ marginBottom: 0 }}
- >
- <Input placeholder={t('dataset.import.categoryDesc')} />
- </Form.Item>
- <Form.Item
- label={t('testCase.create.difficulty.label')}
- name="difficulty"
- style={{ marginBottom: 0 }}
- >
- <Select
- allowClear
- placeholder={t('testCase.create.difficulty.label')}
- options={[
- { label: t('difficulty.easy'), value: 'easy' },
- { label: t('difficulty.medium'), value: 'medium' },
- { label: t('difficulty.hard'), value: 'hard' },
- ]}
- />
- </Form.Item>
- <Form.Item
- label={t('testCase.create.tags.label')}
- name="tags"
- style={{ marginBottom: 0 }}
- >
- <Input placeholder={t('testCase.create.tags.placeholder')} />
- </Form.Item>
- </Flexbox>
- </AccordionItem>
- </Accordion>
- </Form>
- </Modal>
- );
-});
-
-export default TestCaseEditModal;
+export const createTestCaseEditModal = (props: Props): ModalInstance =>
+ createFormModal({
+ renderContent: ({ formId, setLoading }) => (
+ <TestCaseEditContent {...props} formId={formId} onLoadingChange={setLoading} />
+ ),
+ renderFooter: ({ formId, loading }) => <TestCaseEditFooter formId={formId} loading={loading} />,
+ title: t('testCase.edit.title', { ns: 'eval' }),
+ width: 520,
+ });
diff --git a/src/routes/(main)/eval/index.tsx b/src/routes/(main)/eval/index.tsx
index 40683a2f30f..29255587fe3 100644
--- a/src/routes/(main)/eval/index.tsx
+++ b/src/routes/(main)/eval/index.tsx
@@ -3,14 +3,14 @@
import { Button, Empty, Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { FlaskConical, Plus } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useEvalStore } from '@/store/eval';
import BenchmarkCard from './features/BenchmarkCard';
-import CreateBenchmarkModal from './features/CreateBenchmarkModal';
+import { createCreateBenchmarkModal } from './features/CreateBenchmarkModal';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -36,7 +36,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const EvalOverview = memo(() => {
const { t } = useTranslation('eval');
- const [createModalOpen, setCreateModalOpen] = useState(false);
const benchmarkList = useEvalStore((s) => s.benchmarkList);
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
const { isLoading } = useFetchBenchmarks();
@@ -50,7 +49,7 @@ const EvalOverview = memo(() => {
<p className={styles.subtitle}>{t('overview.subtitle')}</p>
</Flexbox>
{benchmarkList.length > 0 && (
- <Button icon={Plus} type="primary" onClick={() => setCreateModalOpen(true)}>
+ <Button icon={Plus} type="primary" onClick={() => createCreateBenchmarkModal()}>
{t('overview.createBenchmark')}
</Button>
)}
@@ -68,7 +67,7 @@ const EvalOverview = memo(() => {
icon={Plus}
style={{ marginTop: 16 }}
type="primary"
- onClick={() => setCreateModalOpen(true)}
+ onClick={() => createCreateBenchmarkModal()}
>
{t('overview.createBenchmark')}
</Button>
@@ -99,8 +98,6 @@ const EvalOverview = memo(() => {
))}
</div>
)}
-
- <CreateBenchmarkModal open={createModalOpen} onCancel={() => setCreateModalOpen(false)} />
</Flexbox>
);
});
diff --git a/src/utils/createFormModal.tsx b/src/utils/createFormModal.tsx
new file mode 100644
index 00000000000..bc67de891e5
--- /dev/null
+++ b/src/utils/createFormModal.tsx
@@ -0,0 +1,31 @@
+'use client';
+
+import { createModal, type ImperativeModalProps, type ModalInstance } from '@lobehub/ui/base-ui';
+import { type ReactNode } from 'react';
+
+let formIdSeed = 0;
+
+interface CreateFormModalOptions extends Omit<ImperativeModalProps, 'content' | 'footer'> {
+ renderContent: (api: { formId: string; setLoading: (loading: boolean) => void }) => ReactNode;
+ renderFooter: (api: { formId: string; loading: boolean }) => ReactNode;
+}
+
+export const createFormModal = ({
+ renderContent,
+ renderFooter,
+ ...rest
+}: CreateFormModalOptions): ModalInstance => {
+ const formId = `form-modal-${formIdSeed++}`;
+ const ref: { instance?: ModalInstance } = {};
+ const setLoading = (loading: boolean) => {
+ ref.instance?.update({
+ footer: renderFooter({ formId, loading }),
+ } as Partial<ImperativeModalProps>);
+ };
+ ref.instance = createModal({
+ ...rest,
+ content: renderContent({ formId, setLoading }),
+ footer: renderFooter({ formId, loading: false }),
+ });
+ return ref.instance;
+};