feat(agent): implement agent management UI and operations

This commit is contained in:
2025-11-05 17:20:58 +08:00
parent b34988e830
commit 889d385709
17 changed files with 1154 additions and 533 deletions

View File

@@ -0,0 +1,260 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
Box,
Typography,
List,
ListItemButton,
ListItemText,
Grid,
Card,
CardContent,
CardActions,
Avatar,
} from '@mui/material';
import { Add as AddIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import agentService from '@/services/agent_service';
import type { IFlowTemplate } from '@/interfaces/database/agent';
import { useSnackbar } from '@/hooks/useSnackbar';
import { AgentCategory } from '@/constants/agent';
import { IAgentCreateRequestBody } from '@/interfaces/request/agent';
import { useAgentOperations } from '@/hooks/agent-hooks';
interface CreateAgentDialogProps {
open: boolean;
onClose: () => void;
onCreated?: (newId?: string) => void;
}
const CreateAgentDialog: React.FC<CreateAgentDialogProps> = ({ open, onClose, onCreated }) => {
const { t, i18n } = useTranslation();
const { showMessage } = useSnackbar();
const ops = useAgentOperations();
const [loading, setLoading] = useState(false);
const [templates, setTemplates] = useState<IFlowTemplate[]>([]);
const [activeCategory, setActiveCategory] = useState<string>('Recommended');
const categoryRefs = useRef<Record<string, HTMLDivElement | null>>({});
const lang = i18n.language?.startsWith('zh') ? 'zh' : 'en';
useEffect(() => {
if (!open) return;
let mounted = true;
setLoading(true);
agentService
.listTemplates()
.then((res: any) => {
const data = res?.data?.data || [];
if (mounted) {
setTemplates(data);
}
})
.catch((err: any) => {
console.error('listTemplates error', err);
showMessage.error(t('common.fetchFailed'));
})
.finally(() => {
if (mounted) setLoading(false);
});
return () => {
mounted = false;
};
}, [open]);
const categories = useMemo(() => {
const set = new Set<string>();
templates.forEach((tpl) => {
if (tpl.canvas_type) set.add(tpl.canvas_type);
});
const arr = Array.from(set);
// 将 Recommended 放在第一位
arr.sort((a, b) => {
if (a === 'Recommended') return -1;
if (b === 'Recommended') return 1;
return a.localeCompare(b);
});
return arr;
}, [templates]);
// 当分类列表变化时,默认选中 Recommended 或第一个分类
useEffect(() => {
if (categories.length > 0) {
if (!categories.includes(activeCategory)) {
setActiveCategory(categories.includes('Recommended') ? 'Recommended' : categories[0]);
}
}
}, [categories]);
// 保证选中项在可视区域
useEffect(() => {
const el = categoryRefs.current[activeCategory];
if (el) {
el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}
}, [activeCategory]);
const filteredTemplates = useMemo(() => {
return templates.filter((tpl) => tpl.canvas_type === activeCategory);
}, [templates, activeCategory]);
const handleUseTemplate = async (tpl: IFlowTemplate) => {
try {
setLoading(true);
const body: IAgentCreateRequestBody = {
title: (tpl.title as any)?.[lang] || 'Untitled',
avatar: tpl.avatar,
description: (tpl.description as any)?.[lang] || '',
dsl: tpl.dsl,
canvas_category: (tpl as any).canvas_category || AgentCategory.AgentCanvas,
};
const result = await ops.createAgent(body);
if (result.success) {
if (onCreated) onCreated(result.id);
}
onClose();
} catch (err: any) {
console.error('create agent by template error', err);
} finally {
setLoading(false);
}
};
const handleCreateBlankAgent = async () => {
try {
setLoading(true);
const body: IAgentCreateRequestBody = {
title: lang === 'zh' ? '空白智能体' : 'Blank Agent',
dsl: {
components: {},
history: [],
globals: {},
retrieval: [],
graph: { nodes: [], edges: [] },
messages: [],
},
canvas_category: AgentCategory.AgentCanvas,
};
const result = await ops.createAgent(body);
if (result.success) {
if (onCreated) onCreated(result.id);
}
onClose();
} catch (err: any) {
console.error('create blank agent error', err);
} finally {
setLoading(false);
}
};
return (
<Dialog
open={open}
onClose={onClose}
fullWidth
maxWidth="lg"
PaperProps={{ sx: { height: '85%' } }}
>
<DialogTitle>{t('agent.createAgent')}</DialogTitle>
<DialogContent dividers sx={{ overflowY: 'auto', p: 2 }}>
<Box display="flex" gap={2} sx={{ height: 560 }}>
{/* 左侧分类 */}
<Box sx={{ width: 220, borderRight: '1px solid', borderColor: 'divider', overflowY: 'auto' }}>
<List>
{categories.map((cat) => (
<ListItemButton
key={cat}
selected={activeCategory === cat}
onClick={() => setActiveCategory(cat)}
ref={(el) => { categoryRefs.current[cat] = el; }}
>
<ListItemText
primary={cat}
primaryTypographyProps={{
color: activeCategory === cat ? 'primary' : 'text.primary',
fontWeight: activeCategory === cat ? 700 : 400,
}}
/>
</ListItemButton>
))}
</List>
</Box>
{/* 右侧模板网格 */}
<Box flex={1} px={2} sx={{ overflowY: 'auto' }}>
<Grid container spacing={2}>
{activeCategory === 'Recommended' && (
<Grid size={{ xs: 12, sm: 6, md: 4 }}>
<Card
variant="outlined"
sx={{
height: 220,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
p: 4,
}}
onClick={handleCreateBlankAgent}
>
<Box display="flex" flexDirection="column" alignItems="center" gap={1}>
<AddIcon fontSize="large" />
<Typography variant="subtitle1">
{lang === 'zh' ? '新建空白智能体' : 'New Blank Agent'}
</Typography>
</Box>
</Card>
</Grid>
)}
{filteredTemplates.map((tpl) => (
<Grid key={tpl.id} size={{ xs: 12, sm: 6, md: 4 }}>
<Card variant="outlined" sx={{ height: 220, display: 'flex', flexDirection: 'column' }}>
<CardContent sx={{ flexGrow: 1, pb: 0 }}>
<Box display="flex" alignItems="center" gap={2}>
<Avatar src={tpl.avatar} />
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1}}>
<Typography variant="h6" className='ellipsis2'>
{(tpl.title as any)?.[lang] || (tpl.title as any)}
</Typography>
<Typography
variant="body2"
color="text.secondary"
className='ellipsis3'
>
{(tpl.description as any)?.[lang] || ''}
</Typography>
</Box>
</Box>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end', mt: 'auto', p: 2, pt: 1 }}>
<Button
variant="contained"
onClick={() => handleUseTemplate(tpl)}
disabled={loading}
>
{t('agent.useTemplate')}
</Button>
</CardActions>
</Card>
</Grid>
))}
</Grid>
{(!loading && filteredTemplates.length === 0) && (
<Box sx={{ textAlign: 'center', py: 6 }}>
<Typography color="text.secondary">{t('agent.noTemplates')}</Typography>
</Box>
)}
</Box>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t('common.close')}</Button>
</DialogActions>
</Dialog >
);
};
export default CreateAgentDialog;

View File

@@ -0,0 +1,223 @@
import React, { useEffect, useMemo, useState, useRef } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
Box,
TextField,
Avatar,
Grid,
IconButton,
FormControl,
InputLabel,
Select,
MenuItem,
Typography,
} from '@mui/material';
import { PhotoCamera as PhotoCameraIcon, Delete as DeleteIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import type { IFlow } from '@/interfaces/database/agent';
import { useAgentOperations } from '@/hooks/agent-hooks';
export interface EditAgentDialogProps {
open: boolean;
agent: IFlow | null;
onClose: () => void;
onSaved?: () => void;
}
const PERMISSION_OPTIONS = [
{ value: 'me', labelKey: 'common.onlyMe' },
{ value: 'team', labelKey: 'common.team' },
] as const;
const EditAgentDialog: React.FC<EditAgentDialogProps> = ({ open, agent, onClose, onSaved }) => {
const { t } = useTranslation();
const ops = useAgentOperations();
const [title, setTitle] = useState('');
const [avatar, setAvatar] = useState('');
const [description, setDescription] = useState('');
const [permission, setPermission] = useState<'me' | 'team' | 'public'>('me');
const fileInputRef = useRef<HTMLInputElement>(null);
const resizeImageToDataUrl = (file: File, maxDim = 256): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return reject(new Error('Canvas not supported'));
const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
// prefer jpeg for smaller size, fallback to png
const mime = file.type === 'image/png' ? 'image/png' : 'image/jpeg';
const dataUrl = canvas.toDataURL(mime, 0.85);
resolve(dataUrl.replace(/\s/g, ''));
};
img.onerror = () => reject(new Error('Invalid image'));
img.src = e.target?.result as string;
};
reader.onerror = () => reject(new Error('Read failed'));
reader.readAsDataURL(file);
});
};
const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
try {
if (!file.type.startsWith('image/')) {
console.warn('Not an image file');
return;
}
const dataUrl = await resizeImageToDataUrl(file, 256);
setAvatar(dataUrl);
} catch (err) {
console.error('Avatar upload error:', err);
}
};
const handleAvatarDelete = () => {
setAvatar('');
};
const handleAvatarClick = () => {
fileInputRef.current?.click();
};
useEffect(() => {
if (open && agent) {
setTitle(agent.title || '');
setAvatar(agent.avatar || '');
setDescription(agent.description || '');
setPermission((agent.permission as any) || 'me');
}
if (!open) {
// reset when closing to avoid stale state
setTitle('');
setAvatar('');
setDescription('');
setPermission('me');
}
}, [open, agent]);
const canSubmit = useMemo(() => {
return Boolean(title && title.trim().length > 0 && agent?.id);
}, [title, agent]);
const handleSave = async () => {
if (!agent?.id) return;
const res = await ops.editAgent({
id: agent.id,
title: title.trim(),
avatar: avatar || undefined,
description: description?.trim() ? description.trim() : null,
permission,
canvas_category: agent.canvas_category as any,
} as any);
if (res.success) {
if (onSaved) onSaved();
onClose();
}
};
return (
<Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
<DialogTitle>{t('common.edit')}</DialogTitle>
<DialogContent dividers>
<Box display="flex" flexDirection="column" gap={2}>
<Grid container spacing={2} alignItems="center">
<Grid size={{ xs: 12 }}>
<Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 2 }}>
<Avatar
src={avatar}
sx={{ width: 96, height: 96, cursor: 'pointer' }}
onClick={handleAvatarClick}
>
{!avatar && <PhotoCameraIcon sx={{ fontSize: 40 }} />}
</Avatar>
<Box sx={{ display: 'flex', gap: 1 }}>
<Button
variant="outlined"
size="small"
startIcon={<PhotoCameraIcon />}
onClick={handleAvatarClick}
>
{t('knowledge.uploadAvatar')}
</Button>
{avatar && (
<IconButton size="small" color="error" onClick={handleAvatarDelete}>
<DeleteIcon />
</IconButton>
)}
</Box>
<input
ref={fileInputRef}
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={handleAvatarUpload}
/>
</Box>
</Grid>
</Grid>
<TextField
label={t('agent.forms.title')}
value={title}
onChange={(e) => setTitle(e.target.value)}
fullWidth
required
/>
<TextField
label={t('agent.forms.description')}
value={description}
onChange={(e) => setDescription(e.target.value)}
fullWidth
multiline
minRows={3}
/>
<FormControl fullWidth>
<InputLabel>{t('agent.forms.permissionSettings')}</InputLabel>
<Select
value={permission}
label={t('agent.forms.permissionSettings')}
onChange={(e) => setPermission(e.target.value as any)}
>
{PERMISSION_OPTIONS.map((opt) => (
<MenuItem key={opt.value} value={opt.value}>
{t(opt.labelKey)}
</MenuItem>
))}
</Select>
</FormControl>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t('dialog.cancel')}</Button>
<Button
variant="contained"
onClick={handleSave}
disabled={!canSubmit || ops.loading}
>
{t('common.confirm')}
</Button>
</DialogActions>
</Dialog>
);
};
export default EditAgentDialog;

View File

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useMemo, useState } from 'react';
import React, { useCallback, useMemo, useState, useEffect } from 'react';
import {
Box,
Typography,
@@ -9,12 +9,19 @@ import {
Pagination,
Stack,
} from '@mui/material';
import { Search as SearchIcon, Refresh as RefreshIcon } from '@mui/icons-material';
import { useAgentList } from '@/hooks/agent-hooks';
import { Search as SearchIcon, Refresh as RefreshIcon, Add as AddIcon } from '@mui/icons-material';
import { useAgentList, useAgentOperations } from '@/hooks/agent-hooks';
import AgentGridView from '@/components/agent/AgentGridView';
import CreateAgentDialog from '@/pages/agent/components/CreateAgentDialog';
import EditAgentDialog from '@/pages/agent/components/EditAgentDialog';
import { useTranslation } from 'react-i18next';
import { useDialog } from '@/hooks/useDialog';
function AgentListPage() {
const [searchValue, setSearchValue] = useState('');
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [editTarget, setEditTarget] = useState<any>(null);
const {
agents,
total,
@@ -26,6 +33,10 @@ function AgentListPage() {
refresh,
} = useAgentList({ page: 1, page_size: 10 });
const { t } = useTranslation();
const dialog = useDialog();
const ops = useAgentOperations();
const totalPages = useMemo(() => {
return Math.ceil((agents?.length || 0) / pageSize) || 1;
}, [agents, pageSize]);
@@ -36,20 +47,42 @@ function AgentListPage() {
return (agents || []).slice(startIndex, endIndex);
}, [agents, currentPage, pageSize]);
const handleSearch = useCallback(() => {
setKeywords(searchValue);
setCurrentPage(1);
const handleSearch = useCallback((value: string) => {
// 仅更新输入值,实际搜索在 500ms 防抖后触发
setSearchValue(value);
}, []);
// 500ms 防抖:在用户停止输入 500ms 后触发搜索
useEffect(() => {
const handler = setTimeout(() => {
setKeywords(searchValue);
setCurrentPage(1);
}, 500);
return () => clearTimeout(handler);
}, [searchValue, setKeywords, setCurrentPage]);
return (
<Box sx={{ p: 3 }}>
<Typography variant="h4" fontWeight={600} mb={2}>Agent </Typography>
{/* 页面标题 */}
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
<Typography variant="h4" fontWeight={600}>
{t('agent.agentList')}
</Typography>
<Button
variant="contained"
startIcon={<AddIcon />}
onClick={() => setCreateOpen(true)}
sx={{ borderRadius: 2 }}
>
{t('agent.createAgent')}
</Button>
</Box>
<Paper sx={{ p: 2, mb: 2 }}>
<Box display="flex" gap={2} alignItems="center">
<TextField
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
onChange={(e) => handleSearch(e.target.value)}
placeholder="搜索名称或描述"
size="small"
InputProps={{
@@ -60,7 +93,6 @@ function AgentListPage() {
)
}}
/>
<Button variant="contained" onClick={handleSearch}></Button>
<Button variant="outlined" startIcon={<RefreshIcon />} onClick={refresh}></Button>
</Box>
</Paper>
@@ -69,6 +101,19 @@ function AgentListPage() {
agents={currentPageData}
loading={loading}
searchTerm={searchValue}
onCreateAgent={() => setCreateOpen(true)}
onEdit={(agent) => { setEditTarget(agent); setEditOpen(true); }}
onDelete={async (agent) => {
const confirmed = await dialog.confirm({
title: t('dialog.confirmDelete'),
content: t('dialog.confirmDeleteMessage'),
confirmText: t('dialog.delete'),
cancelText: t('dialog.cancel'),
});
if (!confirmed) return;
const res = await ops.deleteAgents([agent.id]);
if (res.success) refresh();
}}
/>
{totalPages >= 1 && (
@@ -89,6 +134,20 @@ function AgentListPage() {
</Stack>
</Box>
)}
<CreateAgentDialog
open={createOpen}
onClose={() => setCreateOpen(false)}
onCreated={() => {
setCreateOpen(false);
refresh();
}}
/>
<EditAgentDialog
open={editOpen}
agent={editTarget}
onClose={() => { setEditOpen(false); setEditTarget(null); }}
onSaved={() => { setEditOpen(false); setEditTarget(null); refresh(); }}
/>
</Box>
);
}