feat(agent): implement agent detail page with canvas view and version history

This commit is contained in:
2025-11-06 16:53:47 +08:00
parent 889d385709
commit e325beea4b
20 changed files with 672 additions and 26 deletions

View 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>
);
}

View 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;

View 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>
);
}

View 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>
);
}

View 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, id, 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>
);
}

View File

@@ -19,7 +19,7 @@ import {
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 type { IAgentTemplate } from '@/interfaces/database/agent';
import { useSnackbar } from '@/hooks/useSnackbar';
import { AgentCategory } from '@/constants/agent';
import { IAgentCreateRequestBody } from '@/interfaces/request/agent';
@@ -36,7 +36,7 @@ const CreateAgentDialog: React.FC<CreateAgentDialogProps> = ({ open, onClose, on
const { showMessage } = useSnackbar();
const ops = useAgentOperations();
const [loading, setLoading] = useState(false);
const [templates, setTemplates] = useState<IFlowTemplate[]>([]);
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';
@@ -101,7 +101,7 @@ const CreateAgentDialog: React.FC<CreateAgentDialogProps> = ({ open, onClose, on
return templates.filter((tpl) => tpl.canvas_type === activeCategory);
}, [templates, activeCategory]);
const handleUseTemplate = async (tpl: IFlowTemplate) => {
const handleUseTemplate = async (tpl: IAgentTemplate) => {
try {
setLoading(true);
const body: IAgentCreateRequestBody = {

View File

@@ -18,12 +18,12 @@ import {
} 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 type { IAgent } from '@/interfaces/database/agent';
import { useAgentOperations } from '@/hooks/agent-hooks';
export interface EditAgentDialogProps {
open: boolean;
agent: IFlow | null;
agent?: IAgent;
onClose: () => void;
onSaved?: () => void;
}

View 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 '@/pages/agent/canvas/node/ReadonlyNode';
import NoteNode from '@/pages/agent/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>
);
}

View 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 '@/pages/agent/components/AgentTopbar';
import AgentCanvas from '@/pages/agent/canvas';
import VersionListDialog from '@/pages/agent/components/VersionListDialog';
import EditAgentDialog from '@/pages/agent/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;

View File

@@ -16,6 +16,7 @@ import CreateAgentDialog from '@/pages/agent/components/CreateAgentDialog';
import EditAgentDialog from '@/pages/agent/components/EditAgentDialog';
import { useTranslation } from 'react-i18next';
import { useDialog } from '@/hooks/useDialog';
import { useNavigate } from 'react-router-dom';
function AgentListPage() {
const [searchValue, setSearchValue] = useState('');
@@ -34,6 +35,7 @@ function AgentListPage() {
} = useAgentList({ page: 1, page_size: 10 });
const { t } = useTranslation();
const navigate = useNavigate();
const dialog = useDialog();
const ops = useAgentOperations();
@@ -103,6 +105,9 @@ function AgentListPage() {
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'),