feat(agent-mui): add agent canvas, nodes, and related components
docs(agent-hooks-guide): add comprehensive guide for agent hooks usage and implementation
This commit is contained in:
35
src/pages/agent-mui/canvas/NodeDrawer.tsx
Normal file
35
src/pages/agent-mui/canvas/NodeDrawer.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { Drawer, Box, Typography, Divider } from '@mui/material';
|
||||
|
||||
export interface NodeDrawerProps {
|
||||
open: boolean;
|
||||
node: any | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function NodeDrawer({ open, node, onClose }: NodeDrawerProps) {
|
||||
const label = node?.data?.label || '';
|
||||
const name = node?.data?.name || '';
|
||||
const type = node?.type || 'default';
|
||||
const form = node?.data?.form ?? {};
|
||||
|
||||
return (
|
||||
<Drawer anchor="right" open={open} onClose={onClose}>
|
||||
<Box sx={{ width: '45vw', p: 2 }}>
|
||||
<Typography variant="h6" fontWeight={600} gutterBottom>
|
||||
{`${label}${name ? ' · ' + name : ''}`}
|
||||
</Typography>
|
||||
<Divider sx={{ mb: 2 }} />
|
||||
<Typography variant="body2" color="text.secondary" gutterBottom>
|
||||
节点类型:{type}
|
||||
</Typography>
|
||||
<Divider sx={{ my: 2 }} />
|
||||
<Typography variant="subtitle2" gutterBottom>
|
||||
表单数据
|
||||
</Typography>
|
||||
<Box component="pre" sx={{ fontSize: 12, whiteSpace: 'pre-wrap', wordBreak: 'break-word', p: 1, bgcolor: 'action.hover', borderRadius: 1 }}>
|
||||
{JSON.stringify(form, null, 2)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
89
src/pages/agent-mui/canvas/index.tsx
Normal file
89
src/pages/agent-mui/canvas/index.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import { Box } from "@mui/material";
|
||||
import { ReactFlow, Background, Controls, MiniMap, SmoothStepEdge } from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
import { useMemo, useRef, useState, useCallback } from "react";
|
||||
import type { IGraph, IAgent } from '@/interfaces/database/agent';
|
||||
import NodeDrawer from './NodeDrawer';
|
||||
import ReadonlyNode from './node/ReadonlyNode';
|
||||
import NoteNode from './node/NoteNode';
|
||||
import { useAgentCanvas } from '@/hooks/agent-hooks';
|
||||
|
||||
const nodeTypes = {
|
||||
beginNode: ReadonlyNode,
|
||||
agentNode: ReadonlyNode,
|
||||
messageNode: ReadonlyNode,
|
||||
toolNode: ReadonlyNode,
|
||||
noteNode: NoteNode,
|
||||
retrievalNode: ReadonlyNode,
|
||||
ragNode: ReadonlyNode,
|
||||
switchNode: ReadonlyNode,
|
||||
categorizeNode: ReadonlyNode,
|
||||
iterationNode: ReadonlyNode,
|
||||
iterationStartNode: ReadonlyNode,
|
||||
keywordNode: ReadonlyNode,
|
||||
relevantNode: ReadonlyNode,
|
||||
logicNode: ReadonlyNode,
|
||||
emailNode: ReadonlyNode,
|
||||
tokenizerNode: ReadonlyNode,
|
||||
templateNode: ReadonlyNode,
|
||||
rewriteNode: ReadonlyNode,
|
||||
invokeNode: ReadonlyNode,
|
||||
parserNode: ReadonlyNode,
|
||||
fileNode: ReadonlyNode,
|
||||
extractorNode: ReadonlyNode,
|
||||
splitterNode: ReadonlyNode,
|
||||
placeholderNode: ReadonlyNode,
|
||||
contextNode: ReadonlyNode,
|
||||
group: ReadonlyNode,
|
||||
generateNode: ReadonlyNode,
|
||||
} as const;
|
||||
|
||||
const edgeTypes = {
|
||||
buttonEdge: SmoothStepEdge,
|
||||
ButtonEdge: SmoothStepEdge,
|
||||
} as const;
|
||||
|
||||
export interface AgentCanvasProps {
|
||||
agent?: IAgent | null;
|
||||
graph?: IGraph | null;
|
||||
onReady?: (api: { fitView: () => void }) => void;
|
||||
onAutoSaved?: (date: Date) => void;
|
||||
}
|
||||
|
||||
function AgentCanvas({ agent, graph, onReady, onAutoSaved }: AgentCanvasProps) {
|
||||
const { sanitized, selectedNode, hoverNode, onInit,
|
||||
onNodeClick, onPaneClick, onNodeMouseEnter } = useAgentCanvas({ agent, graph, onReady, onAutoSaved });
|
||||
|
||||
return (
|
||||
<Box sx={{ flex: 1, position: 'relative', height: '100%' }}>
|
||||
{sanitized && (
|
||||
<ReactFlow
|
||||
nodes={sanitized.nodes || []}
|
||||
edges={sanitized.edges || []}
|
||||
fitView
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
elementsSelectable={false}
|
||||
defaultEdgeOptions={{ animated: true, type: 'smoothstep' }}
|
||||
nodeTypes={nodeTypes as any}
|
||||
edgeTypes={edgeTypes as any}
|
||||
onNodeClick={onNodeClick}
|
||||
onPaneClick={onPaneClick}
|
||||
onNodeMouseEnter={onNodeMouseEnter}
|
||||
onInit={onInit}
|
||||
proOptions={{ hideAttribution: true }}
|
||||
minZoom={0.25}
|
||||
maxZoom={2}
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
>
|
||||
<Background />
|
||||
<MiniMap pannable zoomable />
|
||||
<Controls showInteractive={false} />
|
||||
</ReactFlow>
|
||||
)}
|
||||
<NodeDrawer open={!!selectedNode} node={hoverNode || selectedNode} onClose={onPaneClick} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default AgentCanvas;
|
||||
15
src/pages/agent-mui/canvas/node/NoteNode.tsx
Normal file
15
src/pages/agent-mui/canvas/node/NoteNode.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Box } from '@mui/material';
|
||||
import { Handle, Position, type NodeProps } from '@xyflow/react';
|
||||
|
||||
export default function NoteNode({ data }: NodeProps) {
|
||||
const text = (data as any)?.form?.text || '';
|
||||
const name = (data as any)?.name || 'Note';
|
||||
return (
|
||||
<Box sx={{ p: 1.25, bgcolor: 'background.paper', border: '1px dashed', borderColor: 'divider', borderRadius: 1.5, minWidth: 240 }}>
|
||||
<Box sx={{ fontSize: 12, color: 'text.secondary', mb: 0.5 }}>{name}</Box>
|
||||
<Box sx={{ fontSize: 13, lineHeight: 1.5, maxHeight: 120, overflow: 'auto' }}>{String(text)}</Box>
|
||||
<Handle type="target" position={Position.Left} id="left" />
|
||||
<Handle type="source" position={Position.Right} id="right" />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
15
src/pages/agent-mui/canvas/node/ReadonlyNode.tsx
Normal file
15
src/pages/agent-mui/canvas/node/ReadonlyNode.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Box } from '@mui/material';
|
||||
import { Handle, Position, type NodeProps } from '@xyflow/react';
|
||||
|
||||
export default function ReadonlyNode({ data }: NodeProps) {
|
||||
const label = (data as any)?.label || '';
|
||||
const name = (data as any)?.name || '';
|
||||
return (
|
||||
<Box sx={{ p: 1.25, bgcolor: 'background.paper', border: '1px solid', borderColor: 'divider', borderRadius: 1.5, minWidth: 160 }}>
|
||||
<Box sx={{ fontSize: 12, color: 'text.secondary', mb: 0.5 }}>{label}</Box>
|
||||
<Box sx={{ fontSize: 14, fontWeight: 600 }}>{name}</Box>
|
||||
<Handle type="target" position={Position.Left} id="left" />
|
||||
<Handle type="source" position={Position.Right} id="right" />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
47
src/pages/agent-mui/components/AgentTopbar.tsx
Normal file
47
src/pages/agent-mui/components/AgentTopbar.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Breadcrumbs, Button, Box, Typography, IconButton } from '@mui/material';
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
|
||||
export interface AgentTopbarProps {
|
||||
title?: string;
|
||||
id?: string;
|
||||
onRefresh?: () => void;
|
||||
subtitle?: string;
|
||||
actionsRight?: React.ReactNode;
|
||||
onOpenVersions?: () => void;
|
||||
onOpenSettings?: () => void;
|
||||
}
|
||||
|
||||
export default function AgentTopbar({ title, onRefresh, subtitle, actionsRight, onOpenVersions, onOpenSettings }: AgentTopbarProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Box sx={{
|
||||
p: 2,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
}}>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'left', gap: 1 }}>
|
||||
<Breadcrumbs aria-label="breadcrumb">
|
||||
<RouterLink to="/agents" style={{ textDecoration: 'none' }}>{t('header.agent')}</RouterLink>
|
||||
<Typography color="text.primary">{title}</Typography>
|
||||
</Breadcrumbs>
|
||||
{subtitle && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>{subtitle}</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<Box display="flex" gap={1}>
|
||||
{actionsRight}
|
||||
<Button variant="contained" onClick={onOpenVersions}>{t('agent.versions')}</Button>
|
||||
<Button variant="outlined" onClick={onRefresh}>{t('common.refresh')}</Button>
|
||||
<IconButton aria-label="setting" onClick={onOpenSettings}>
|
||||
<SettingsIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
260
src/pages/agent-mui/components/CreateAgentDialog.tsx
Normal file
260
src/pages/agent-mui/components/CreateAgentDialog.tsx
Normal 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 { IAgentTemplate } 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<IAgentTemplate[]>([]);
|
||||
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: IAgentTemplate) => {
|
||||
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;
|
||||
223
src/pages/agent-mui/components/EditAgentDialog.tsx
Normal file
223
src/pages/agent-mui/components/EditAgentDialog.tsx
Normal 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 { IAgent } from '@/interfaces/database/agent';
|
||||
import { useAgentOperations } from '@/hooks/agent-hooks';
|
||||
|
||||
export interface EditAgentDialogProps {
|
||||
open: boolean;
|
||||
agent?: IAgent;
|
||||
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;
|
||||
144
src/pages/agent-mui/components/VersionListDialog.tsx
Normal file
144
src/pages/agent-mui/components/VersionListDialog.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import { useEffect, useMemo, useState, useCallback } from 'react';
|
||||
import { Dialog, DialogTitle, DialogContent, Box, List, ListItemButton, ListItemText, Divider, Typography } from '@mui/material';
|
||||
import { ReactFlow, Background, MiniMap, Controls, SmoothStepEdge } from '@xyflow/react';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import agentService from '@/services/agent_service';
|
||||
import type { IAgentVersionItem, IAgent, IGraph } from '@/interfaces/database/agent';
|
||||
import ReadonlyNode from '../canvas/node/ReadonlyNode';
|
||||
import NoteNode from '../canvas/node/NoteNode';
|
||||
|
||||
function sanitizeGraph(g?: IGraph | null): IGraph | null {
|
||||
if (!g) return null;
|
||||
const nodes = (g.nodes || []).map((n: any) => ({ ...n, draggable: false, selectable: false }));
|
||||
const edges = (g.edges || []).map((e: any) => {
|
||||
const { sourceHandle, targetHandle, ...rest } = e || {};
|
||||
return { ...rest };
|
||||
});
|
||||
return { nodes, edges };
|
||||
}
|
||||
|
||||
const nodeTypes = {
|
||||
beginNode: ReadonlyNode,
|
||||
agentNode: ReadonlyNode,
|
||||
messageNode: ReadonlyNode,
|
||||
toolNode: ReadonlyNode,
|
||||
noteNode: NoteNode,
|
||||
retrievalNode: ReadonlyNode,
|
||||
ragNode: ReadonlyNode,
|
||||
switchNode: ReadonlyNode,
|
||||
categorizeNode: ReadonlyNode,
|
||||
iterationNode: ReadonlyNode,
|
||||
iterationStartNode: ReadonlyNode,
|
||||
keywordNode: ReadonlyNode,
|
||||
relevantNode: ReadonlyNode,
|
||||
logicNode: ReadonlyNode,
|
||||
emailNode: ReadonlyNode,
|
||||
tokenizerNode: ReadonlyNode,
|
||||
templateNode: ReadonlyNode,
|
||||
rewriteNode: ReadonlyNode,
|
||||
invokeNode: ReadonlyNode,
|
||||
parserNode: ReadonlyNode,
|
||||
fileNode: ReadonlyNode,
|
||||
extractorNode: ReadonlyNode,
|
||||
splitterNode: ReadonlyNode,
|
||||
placeholderNode: ReadonlyNode,
|
||||
contextNode: ReadonlyNode,
|
||||
group: ReadonlyNode,
|
||||
generateNode: ReadonlyNode,
|
||||
} as const;
|
||||
|
||||
const edgeTypes = { buttonEdge: SmoothStepEdge, ButtonEdge: SmoothStepEdge } as const;
|
||||
|
||||
export interface VersionListDialogProps {
|
||||
open: boolean;
|
||||
canvasId?: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function VersionListDialog({ open, canvasId, onClose }: VersionListDialogProps) {
|
||||
const [versions, setVersions] = useState<IAgentVersionItem[]>([]);
|
||||
const [selected, setSelected] = useState<IAgentVersionItem | null>(null);
|
||||
const [detail, setDetail] = useState<IAgent | null>(null);
|
||||
|
||||
const graph = useMemo(() => sanitizeGraph(detail?.dsl?.graph), [detail]);
|
||||
|
||||
const fetchList = useCallback(async () => {
|
||||
if (!canvasId) return;
|
||||
const res = await agentService.getAgentVersionList(canvasId);
|
||||
const list = res?.data?.data || res?.data || [];
|
||||
setVersions(list);
|
||||
const first = list?.[0] || null;
|
||||
setSelected(first);
|
||||
}, [canvasId]);
|
||||
|
||||
const fetchDetail = useCallback(async (versionId?: string) => {
|
||||
if (!versionId) return;
|
||||
const res = await agentService.getVersion(versionId);
|
||||
const data = res?.data?.data || res?.data;
|
||||
setDetail(data);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) fetchList();
|
||||
}, [open, fetchList]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selected?.id) fetchDetail(selected.id);
|
||||
}, [selected, fetchDetail]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} fullWidth maxWidth="lg">
|
||||
<DialogTitle>历史版本</DialogTitle>
|
||||
<DialogContent>
|
||||
<Box sx={{ display: 'flex', gap: 2, height: 520 }}>
|
||||
<Box sx={{ width: 280, borderRight: '1px solid', borderColor: 'divider', overflow: 'auto' }}>
|
||||
<List dense>
|
||||
{versions.map((v) => (
|
||||
<ListItemButton
|
||||
key={v.id}
|
||||
selected={selected?.id === v.id}
|
||||
onClick={() => setSelected(v)}
|
||||
>
|
||||
<ListItemText
|
||||
primary={v.title}
|
||||
secondary={`Created: ${v.create_date} ${new Date((String(v.create_time).length >= 13 ? v.create_time : v.create_time * 1000)).toLocaleTimeString()}`}
|
||||
/>
|
||||
</ListItemButton>
|
||||
))}
|
||||
</List>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ flex: 1, position: 'relative' }}>
|
||||
<Typography variant="subtitle1" gutterBottom>
|
||||
{detail?.title || selected?.title || '未选择版本'}
|
||||
</Typography>
|
||||
<Divider sx={{ mb: 2 }} />
|
||||
{graph && (
|
||||
<Box sx={{ height: 440 }}>
|
||||
<ReactFlow
|
||||
nodes={graph.nodes || []}
|
||||
edges={graph.edges || []}
|
||||
fitView
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
elementsSelectable={false}
|
||||
nodeTypes={nodeTypes as any}
|
||||
edgeTypes={edgeTypes as any}
|
||||
defaultEdgeOptions={{ animated: true, type: 'smoothstep' }}
|
||||
proOptions={{ hideAttribution: true }}
|
||||
minZoom={0.25}
|
||||
maxZoom={2}
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
>
|
||||
<Background />
|
||||
<MiniMap pannable zoomable />
|
||||
<Controls showInteractive={false} />
|
||||
</ReactFlow>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
65
src/pages/agent-mui/detail.tsx
Normal file
65
src/pages/agent-mui/detail.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { Box, Typography, Alert, CircularProgress } from "@mui/material";
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useAgentDetail } from '@/hooks/agent-hooks';
|
||||
import { useState } from 'react';
|
||||
import AgentTopbar from './components/AgentTopbar';
|
||||
import AgentCanvas from './canvas';
|
||||
import VersionListDialog from './components/VersionListDialog';
|
||||
import EditAgentDialog from './components/EditAgentDialog';
|
||||
import dayjs from "dayjs";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
function AgentDetailPage() {
|
||||
const { id } = useParams();
|
||||
const { agent, graph, loading, error, refresh } = useAgentDetail(id);
|
||||
const [canvasApi, setCanvasApi] = useState<{ fitView: () => void } | null>(null);
|
||||
const [lastAutoSavedAt, setLastAutoSavedAt] = useState<Date | null>(null);
|
||||
const [versionOpen, setVersionOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const subtitle = (() => {
|
||||
const ts = agent?.update_time ?? agent?.create_time;
|
||||
if (!ts) return undefined;
|
||||
const d = new Date(ts);
|
||||
const dStr = dayjs(d).format('YYYY-MM-DD HH:mm:ss');
|
||||
return t('agent.lastAutoSavedAt', { date: dStr });
|
||||
})();
|
||||
|
||||
return (
|
||||
<Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
<AgentTopbar
|
||||
title={agent?.title}
|
||||
id={id}
|
||||
onRefresh={refresh}
|
||||
subtitle={lastAutoSavedAt ? t('agent.lastAutoSavedAt', { date: dayjs(lastAutoSavedAt).format('YYYY-MM-DD HH:mm:ss') }) : subtitle}
|
||||
onOpenVersions={() => setVersionOpen(true)}
|
||||
onOpenSettings={() => setEditOpen(true)}
|
||||
/>
|
||||
|
||||
<Box sx={{ flex: 1, position: 'relative' }}>
|
||||
{loading && (
|
||||
<Box sx={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
)}
|
||||
{error && (
|
||||
<Box sx={{ p: 2 }}>
|
||||
<Alert severity="error">{error}</Alert>
|
||||
</Box>
|
||||
)}
|
||||
<AgentCanvas agent={agent} graph={graph} onReady={(api) => setCanvasApi(api)} onAutoSaved={(date) => setLastAutoSavedAt(date)} />
|
||||
<VersionListDialog open={versionOpen} canvasId={id} onClose={() => setVersionOpen(false)} />
|
||||
<EditAgentDialog
|
||||
open={editOpen}
|
||||
agent={agent as any}
|
||||
onClose={() => setEditOpen(false)}
|
||||
onSaved={() => { setEditOpen(false); refresh(); }}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default AgentDetailPage;
|
||||
162
src/pages/agent-mui/list.tsx
Normal file
162
src/pages/agent-mui/list.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import React, { useCallback, useMemo, useState, useEffect } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
TextField,
|
||||
InputAdornment,
|
||||
Paper,
|
||||
Button,
|
||||
Pagination,
|
||||
Stack,
|
||||
} from '@mui/material';
|
||||
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 './components/CreateAgentDialog';
|
||||
import EditAgentDialog from './components/EditAgentDialog';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDialog } from '@/hooks/useDialog';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
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,
|
||||
loading,
|
||||
currentPage,
|
||||
pageSize,
|
||||
setCurrentPage,
|
||||
setKeywords,
|
||||
refresh,
|
||||
} = useAgentList({ page: 1, page_size: 10 });
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const dialog = useDialog();
|
||||
const ops = useAgentOperations();
|
||||
|
||||
const totalPages = useMemo(() => {
|
||||
return Math.ceil((agents?.length || 0) / pageSize) || 1;
|
||||
}, [agents, pageSize]);
|
||||
|
||||
const currentPageData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * pageSize;
|
||||
const endIndex = startIndex + pageSize;
|
||||
return (agents || []).slice(startIndex, endIndex);
|
||||
}, [agents, currentPage, pageSize]);
|
||||
|
||||
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 }}>
|
||||
{/* 页面标题 */}
|
||||
<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) => handleSearch(e.target.value)}
|
||||
placeholder={t('agent.searchAgent')}
|
||||
size="small"
|
||||
InputProps={{
|
||||
startAdornment: (
|
||||
<InputAdornment position="start">
|
||||
<SearchIcon />
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<Button variant="outlined" startIcon={<RefreshIcon />} onClick={refresh}>
|
||||
{t('common.refresh')}
|
||||
</Button>
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
<AgentGridView
|
||||
agents={currentPageData}
|
||||
loading={loading}
|
||||
searchTerm={searchValue}
|
||||
onCreateAgent={() => setCreateOpen(true)}
|
||||
onEdit={(agent) => { setEditTarget(agent); setEditOpen(true); }}
|
||||
onView={(agent) => {
|
||||
navigate(`/agent/${agent.id}`);
|
||||
}}
|
||||
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 && (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
|
||||
<Stack spacing={2}>
|
||||
<Pagination
|
||||
count={totalPages}
|
||||
page={currentPage}
|
||||
onChange={(_, page) => setCurrentPage(page)}
|
||||
color="primary"
|
||||
size="large"
|
||||
showFirstButton
|
||||
showLastButton
|
||||
/>
|
||||
<Typography variant="body2" color="text.secondary" textAlign="center">
|
||||
共 {total} 个,当前第 {currentPage} / {totalPages} 页
|
||||
</Typography>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
export default AgentListPage;
|
||||
Reference in New Issue
Block a user