feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
# ============================================================
|
||||
# 项目级 npm 配置
|
||||
# 【目的】把 npm 缓存强制重定向到 D 盘,守住「C 盘零占用」硬要求
|
||||
# 【说明】npx 子进程可能不继承环境变量,故用项目级 .npmrc 兜底
|
||||
# 【依赖区】缓存统一在 D:\env 公共依赖区(原 D:\Agent\.npm-cache 留作备份)
|
||||
# ============================================================
|
||||
cache=D:\env\npm-cache
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>编程智能 Agent 系统</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+4273
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "agent-console",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "编程智能 Agent 系统管理前端(项目管理与任务入口)",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.5.2",
|
||||
"antd": "^5.22.2",
|
||||
"axios": "^1.7.7",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-markdown": "10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.3",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* 应用根组件(分组导航布局)
|
||||
*
|
||||
* 【功能说明】13 个功能按使用场景重组为 6 个功能组,
|
||||
* 左侧 Sider 菜单选组 → 组内 Tabs 切具体页面。
|
||||
* 【分组设计】
|
||||
* 工作台:任务中心、项目管理
|
||||
* 知识智能:文档问答、知识库管理
|
||||
* 工具集:图片识别、提示词优化、数据库管理、高级工具箱
|
||||
* 模型资源:平台账号、模型管理(Provider/模型配置/降级链)
|
||||
* 运维监控:监控仪表盘、日志中心
|
||||
* 系统配置:系统配置
|
||||
* 【技术选型理由】Sider + Menu 承载一级分组,Tabs 承载二级页面,
|
||||
* 层级清晰、可扩展,认知负担从 13 个平级 Tab 降到 6 个分组。
|
||||
*/
|
||||
import {
|
||||
ApiOutlined,
|
||||
AppstoreOutlined,
|
||||
CloudServerOutlined,
|
||||
MonitorOutlined,
|
||||
SettingOutlined,
|
||||
ToolOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { App as AntApp, Layout, Menu, Tabs, Typography, notification } from 'antd';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import AuditLog from './pages/AuditLog';
|
||||
import DatabaseManager from './pages/DatabaseManager';
|
||||
import DocQa from './pages/DocQa';
|
||||
import ImageRecognition from './pages/ImageRecognition';
|
||||
import KnowledgeList from './pages/KnowledgeList';
|
||||
import ModelManager from './pages/ModelManager';
|
||||
import MonitorDashboard from './pages/MonitorDashboard';
|
||||
import PlatformManager from './pages/PlatformManager';
|
||||
import ProjectList from './pages/ProjectList';
|
||||
import PromptPolish from './pages/PromptPolish';
|
||||
import SystemSettings from './pages/SystemSettings';
|
||||
import TaskCenter from './pages/TaskCenter';
|
||||
import Toolbox from './pages/Toolbox';
|
||||
import { getLoginExpired } from './api/client';
|
||||
|
||||
/** 功能组定义:key → 组名 + 组内页面列表 */
|
||||
const GROUPS: Record<
|
||||
string,
|
||||
{ label: string; icon: JSX.Element; pages: { key: string; label: string; children: JSX.Element }[] }
|
||||
> = {
|
||||
workbench: {
|
||||
label: '工作台',
|
||||
icon: <AppstoreOutlined />,
|
||||
pages: [
|
||||
{ key: 'task', label: '任务中心', children: <TaskCenter /> },
|
||||
{ key: 'project', label: '项目管理', children: <ProjectList /> },
|
||||
],
|
||||
},
|
||||
knowledge: {
|
||||
label: '知识智能',
|
||||
icon: <ApiOutlined />,
|
||||
pages: [
|
||||
{ key: 'docqa', label: '文档问答', children: <DocQa /> },
|
||||
{ key: 'knowledge', label: '知识库管理', children: <KnowledgeList /> },
|
||||
],
|
||||
},
|
||||
tools: {
|
||||
label: '工具集',
|
||||
icon: <ToolOutlined />,
|
||||
pages: [
|
||||
{ key: 'polish', label: '提示词优化', children: <PromptPolish /> },
|
||||
{ key: 'image', label: '图片识别', children: <ImageRecognition /> },
|
||||
{ key: 'database', label: '数据库管理', children: <DatabaseManager /> },
|
||||
{ key: 'toolbox', label: '高级工具箱', children: <Toolbox /> },
|
||||
],
|
||||
},
|
||||
models: {
|
||||
label: '模型资源',
|
||||
icon: <CloudServerOutlined />,
|
||||
pages: [
|
||||
{ key: 'platform', label: '平台账号', children: <PlatformManager /> },
|
||||
{ key: 'model', label: '模型管理', children: <ModelManager /> },
|
||||
],
|
||||
},
|
||||
ops: {
|
||||
label: '运维监控',
|
||||
icon: <MonitorOutlined />,
|
||||
pages: [
|
||||
{ key: 'monitor', label: '监控仪表盘', children: <MonitorDashboard /> },
|
||||
{ key: 'audit', label: '日志中心', children: <AuditLog /> },
|
||||
],
|
||||
},
|
||||
settings: {
|
||||
label: '系统配置',
|
||||
icon: <SettingOutlined />,
|
||||
pages: [
|
||||
{ key: 'settings', label: '系统配置', children: <SystemSettings /> },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default function App() {
|
||||
const [activeGroup, setActiveGroup] = useState('workbench');
|
||||
const currentGroup = GROUPS[activeGroup];
|
||||
|
||||
// 全局登录过期检测(任何页面都提示)
|
||||
const dismissedRef = useRef<Set<string>>(
|
||||
new Set(JSON.parse(localStorage.getItem('login_expired_dismissed') || '[]')),
|
||||
);
|
||||
|
||||
const checkLoginExpired = useCallback(async () => {
|
||||
try {
|
||||
const expired = await getLoginExpired();
|
||||
if (!expired || expired.length === 0) return;
|
||||
for (const acc of expired) {
|
||||
// 手动关过的不再展示(持久化到 localStorage)
|
||||
if (dismissedRef.current.has(acc.account_id)) continue;
|
||||
notification.warning({
|
||||
message: '登录已过期',
|
||||
description: `${acc.brand}-${acc.account_name} 的登录态已过期,请到「模型资源-平台账号」重新登录`,
|
||||
duration: 0,
|
||||
placement: 'topRight',
|
||||
key: `login-expired-${acc.account_id}`,
|
||||
onClose: () => {
|
||||
// 用户手动关闭 → 记住,不再展示
|
||||
dismissedRef.current.add(acc.account_id);
|
||||
localStorage.setItem('login_expired_dismissed', JSON.stringify([...dismissedRef.current]));
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// 启动时检测一次,之后每 60 秒检测一次
|
||||
checkLoginExpired();
|
||||
const timer = setInterval(checkLoginExpired, 60_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [checkLoginExpired]);
|
||||
|
||||
return (
|
||||
<AntApp>
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
{/* 顶栏 */}
|
||||
<Layout.Header
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
background: '#001529',
|
||||
}}
|
||||
>
|
||||
<Typography.Title level={4} style={{ color: '#fff', margin: 0 }}>
|
||||
编程智能 Agent 系统
|
||||
</Typography.Title>
|
||||
</Layout.Header>
|
||||
|
||||
<Layout style={{ flex: 1 }}>
|
||||
{/* 左侧功能组菜单 */}
|
||||
<Layout.Sider width={160} style={{ background: '#fff' }}>
|
||||
<Menu
|
||||
mode="inline"
|
||||
selectedKeys={[activeGroup]}
|
||||
style={{ height: '100%', borderRight: 0 }}
|
||||
items={Object.entries(GROUPS).map(([key, group]) => ({
|
||||
key,
|
||||
icon: group.icon,
|
||||
label: group.label,
|
||||
onClick: () => setActiveGroup(key),
|
||||
}))}
|
||||
/>
|
||||
</Layout.Sider>
|
||||
|
||||
{/* 右侧组内页面 */}
|
||||
<Layout.Content style={{ background: '#f5f5f5', padding: 0 }}>
|
||||
<Tabs
|
||||
defaultActiveKey={currentGroup.pages[0].key}
|
||||
type="card"
|
||||
style={{ background: '#fff', padding: '0 24px' }}
|
||||
items={currentGroup.pages}
|
||||
/>
|
||||
</Layout.Content>
|
||||
</Layout>
|
||||
</Layout>
|
||||
</AntApp>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 前端入口文件
|
||||
*
|
||||
* 【功能说明】挂载 React 根组件到 #root 节点。
|
||||
* 【技术选型理由】Vite 标准入口形态,保持与脚手架一致。
|
||||
* 【实现思路】StrictMode 便于开发期发现副作用问题。
|
||||
* 【潜在风险与应对】无(纯入口,无业务逻辑)。
|
||||
*/
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import App from './App';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* 日志中心页面组件(审计日志 + 日志查询合并)
|
||||
*
|
||||
* 【功能说明】统一的日志查看页:
|
||||
* - 时间范围:单日(合规精查)或最近 7 天(跨天排查)
|
||||
* - 关键词搜索:模糊匹配任意记录
|
||||
* - 操作类型过滤 + 统计卡片
|
||||
* 对应需求:两个日志功能合并成一个页面。
|
||||
* 【技术选型理由】AntD Table + DatePicker + Select + Input 组合,
|
||||
* 单日走 /audit 接口(带统计),跨天走 /logs 接口(关键字搜索)。
|
||||
*/
|
||||
import {
|
||||
FileProtectOutlined,
|
||||
FilterOutlined,
|
||||
ReloadOutlined,
|
||||
SearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
DatePicker,
|
||||
Input,
|
||||
Radio,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Statistic,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { getAuditLogs, getAuditSummary, queryLogs } from '../api/client';
|
||||
import type { AuditEntry, AuditSummary } from '../types';
|
||||
|
||||
/** 操作类型 → 颜色 */
|
||||
const ACTION_COLORS: Record<string, string> = {
|
||||
file_write: 'blue',
|
||||
file_edit: 'gold',
|
||||
file_read: 'default',
|
||||
file_restore: 'red',
|
||||
exec_command: 'purple',
|
||||
git_commit: 'green',
|
||||
git_branch: 'cyan',
|
||||
rollback_task: 'red',
|
||||
grep_files: 'default',
|
||||
find_files: 'default',
|
||||
};
|
||||
|
||||
/** 结果 → 颜色 */
|
||||
const RESULT_COLORS: Record<string, string> = {
|
||||
success: 'green',
|
||||
failure: 'red',
|
||||
denied: 'orange',
|
||||
};
|
||||
|
||||
export default function AuditLog() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [entries, setEntries] = useState<AuditEntry[]>([]);
|
||||
const [summary, setSummary] = useState<AuditSummary | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [actionFilter, setActionFilter] = useState<string>('');
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [date, setDate] = useState<Dayjs>(dayjs());
|
||||
// 查询模式:single=单日精查(带统计);week=最近7天(关键词搜索)
|
||||
const [mode, setMode] = useState<'single' | 'week'>('single');
|
||||
|
||||
/** 加载日志数据(按模式分流) */
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
if (mode === 'single') {
|
||||
// 单日模式:审计日志接口(带统计)
|
||||
const dateStr = date.format('YYYYMMDD');
|
||||
const [logs, sum] = await Promise.all([
|
||||
getAuditLogs(dateStr, actionFilter, 200),
|
||||
getAuditSummary(dateStr),
|
||||
]);
|
||||
let filtered = logs ?? [];
|
||||
// 前端关键词二次过滤
|
||||
if (keyword.trim()) {
|
||||
const kw = keyword.trim().toLowerCase();
|
||||
filtered = filtered.filter((e) =>
|
||||
JSON.stringify(e).toLowerCase().includes(kw),
|
||||
);
|
||||
}
|
||||
setEntries(filtered);
|
||||
setSummary(sum);
|
||||
} else {
|
||||
// 跨天模式:日志查询接口(最近 7 天 + 关键词)
|
||||
const result = await queryLogs(keyword, 500);
|
||||
let filtered = ((result as Record<string, unknown>).logs as AuditEntry[]) ?? [];
|
||||
if (actionFilter) {
|
||||
filtered = filtered.filter((e) => e.action === actionFilter);
|
||||
}
|
||||
setEntries(filtered);
|
||||
// 跨天模式基于结果计算统计
|
||||
const byResult: Record<string, number> = {};
|
||||
const byAction: Record<string, number> = {};
|
||||
for (const e of filtered) {
|
||||
byResult[e.result] = (byResult[e.result] || 0) + 1;
|
||||
byAction[e.action] = (byAction[e.action] || 0) + 1;
|
||||
}
|
||||
setSummary({
|
||||
total: filtered.length,
|
||||
by_action: byAction,
|
||||
by_result: byResult,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [mode, date, actionFilter, keyword, messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
/** 表格列定义 */
|
||||
const columns: ColumnsType<AuditEntry> = [
|
||||
{
|
||||
title: '时间',
|
||||
dataIndex: 'timestamp',
|
||||
key: 'timestamp',
|
||||
width: 165,
|
||||
render: (v: string) => (
|
||||
<Typography.Text style={{ fontSize: 12 }}>
|
||||
{v ? dayjs(v).format('YYYY-MM-DD HH:mm:ss') : '—'}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作类型',
|
||||
dataIndex: 'action',
|
||||
key: 'action',
|
||||
width: 130,
|
||||
render: (v: string) => (
|
||||
<Tag color={ACTION_COLORS[v] || 'default'}>{v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作对象',
|
||||
dataIndex: 'target',
|
||||
key: 'target',
|
||||
ellipsis: true,
|
||||
render: (v: string) => (
|
||||
<Typography.Text code style={{ fontSize: 12 }}>{v}</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '结果',
|
||||
dataIndex: 'result',
|
||||
key: 'result',
|
||||
width: 90,
|
||||
render: (v: string) => (
|
||||
<Tag color={RESULT_COLORS[v] || 'default'}>{v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '详情',
|
||||
dataIndex: 'details',
|
||||
key: 'details',
|
||||
ellipsis: true,
|
||||
render: (v: Record<string, unknown>) => (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{JSON.stringify(v || {}).slice(0, 80)}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
/** 操作类型选项(含动态发现的类型) */
|
||||
const allActions = new Set([...Object.keys(ACTION_COLORS)]);
|
||||
entries.forEach((e) => allActions.add(e.action));
|
||||
const actionOptions = Array.from(allActions).map((k) => ({
|
||||
label: k,
|
||||
value: k,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Typography.Title level={4}>
|
||||
<FileProtectOutlined /> 日志中心
|
||||
</Typography.Title>
|
||||
|
||||
{/* 统计卡片 */}
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="操作总数" value={summary?.total ?? 0} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card size="small">
|
||||
<Statistic
|
||||
title="成功"
|
||||
value={summary?.by_result?.success ?? 0}
|
||||
valueStyle={{ color: '#3f8600' }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card size="small">
|
||||
<Statistic
|
||||
title="失败"
|
||||
value={summary?.by_result?.failure ?? 0}
|
||||
valueStyle={{ color: '#cf1322' }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card size="small">
|
||||
<Statistic
|
||||
title="文件改动"
|
||||
value={
|
||||
(summary?.by_action?.file_write ?? 0) +
|
||||
(summary?.by_action?.file_edit ?? 0)
|
||||
}
|
||||
valueStyle={{ color: '#1677ff' }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 过滤工具栏 */}
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space wrap>
|
||||
{/* 模式切换 */}
|
||||
<Radio.Group
|
||||
value={mode}
|
||||
onChange={(e) => setMode(e.target.value)}
|
||||
optionType="button"
|
||||
buttonStyle="solid"
|
||||
>
|
||||
<Radio.Button value="single">按日查看</Radio.Button>
|
||||
<Radio.Button value="week">最近 7 天</Radio.Button>
|
||||
</Radio.Group>
|
||||
|
||||
{/* 日期选择(仅单日模式) */}
|
||||
{mode === 'single' && (
|
||||
<DatePicker
|
||||
value={date}
|
||||
onChange={(d) => d && setDate(d)}
|
||||
allowClear={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 关键词搜索 */}
|
||||
<Input
|
||||
placeholder="关键词搜索(命令/文件路径/错误信息)"
|
||||
prefix={<SearchOutlined style={{ color: '#999' }} />}
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
onPressEnter={load}
|
||||
allowClear
|
||||
style={{ width: 280 }}
|
||||
/>
|
||||
|
||||
{/* 操作类型过滤 */}
|
||||
<Select
|
||||
placeholder="操作类型"
|
||||
allowClear
|
||||
style={{ width: 160 }}
|
||||
options={actionOptions}
|
||||
value={actionFilter || undefined}
|
||||
onChange={(v) => setActionFilter(v || '')}
|
||||
suffixIcon={<FilterOutlined />}
|
||||
/>
|
||||
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{/* 日志表格 */}
|
||||
<Table<AuditEntry>
|
||||
rowKey={(r) => `${r.timestamp}-${r.action}-${r.target}`}
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={entries}
|
||||
pagination={{ pageSize: 20, showSizeChanger: true, showTotal: (t) => `共 ${t} 条` }}
|
||||
size="small"
|
||||
locale={{ emptyText: '暂无日志记录' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,893 @@
|
||||
/**
|
||||
* 数据库管理页面组件
|
||||
*
|
||||
* 【功能说明】数据库连接配置管理 + SQL 增删改查(CRUD)执行面板。
|
||||
* 【技术选型理由】AntD Table + Modal + Tabs + Input.TextArea,与各管理页同构。
|
||||
* 【安全设计】密码输入框 type=password;SQL 面板提示用参数化查询。
|
||||
* 【实现思路】上半部分连接配置 CRUD;下半部分 SQL 执行面板(选连接 → 写 SQL → 执行)。
|
||||
* 【潜在风险与应对】
|
||||
* 风险1:误执行 DELETE/UPDATE 全表。
|
||||
* 应对:危险操作加 Popconfirm 二次确认。
|
||||
* 风险2:SQL 太长看不清。
|
||||
* 结果面板用表格展示,支持全屏。
|
||||
*/
|
||||
import {
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
DatabaseOutlined,
|
||||
DeleteOutlined,
|
||||
DownloadOutlined,
|
||||
EditOutlined,
|
||||
HistoryOutlined,
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
SearchOutlined,
|
||||
TableOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
Alert,
|
||||
App as AntApp,
|
||||
AutoComplete,
|
||||
Button,
|
||||
Card,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
Table,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
alterTable,
|
||||
createDbConnection,
|
||||
deleteDbConnection,
|
||||
executeDbSql,
|
||||
getTableStructure,
|
||||
listDbConnections,
|
||||
listTables,
|
||||
queryDbSql,
|
||||
testDbConnection,
|
||||
updateDbConnection,
|
||||
} from '../api/client';
|
||||
import type {
|
||||
DatabaseConnection,
|
||||
DatabaseConnectionPayload,
|
||||
SqlExecuteResult,
|
||||
TableColumn,
|
||||
} from '../types';
|
||||
|
||||
const DB_TYPE_OPTIONS = [
|
||||
{ label: 'MySQL', value: 'mysql' },
|
||||
{ label: 'PostgreSQL', value: 'postgresql' },
|
||||
{ label: 'SQLite', value: 'sqlite' },
|
||||
];
|
||||
|
||||
const INITIAL_VALUES: DatabaseConnectionPayload = {
|
||||
name: '',
|
||||
db_type: 'mysql',
|
||||
host: 'localhost',
|
||||
port: 3306,
|
||||
database: '',
|
||||
username: '',
|
||||
password: '',
|
||||
description: '',
|
||||
};
|
||||
|
||||
export default function DatabaseManager() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [connections, setConnections] = useState<DatabaseConnection[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<DatabaseConnection | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [form] = Form.useForm<DatabaseConnectionPayload>();
|
||||
|
||||
// SQL 执行面板
|
||||
const [selectedConnId, setSelectedConnId] = useState<string>('');
|
||||
const [executing, setExecuting] = useState(false);
|
||||
const [tableName, setTableName] = useState('');
|
||||
|
||||
// SQL 编辑器(多标签页)
|
||||
interface SqlTab {
|
||||
key: string;
|
||||
label: string;
|
||||
sql: string;
|
||||
result: SqlExecuteResult | null;
|
||||
}
|
||||
const [sqlTabs, setSqlTabs] = useState<SqlTab[]>([
|
||||
{ key: 'tab_1', label: 'SQL 1', sql: '', result: null },
|
||||
]);
|
||||
const [activeTabKey, setActiveTabKey] = useState('tab_1');
|
||||
const tabCounterRef = useRef(1);
|
||||
const sqlTextareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
// 选区状态:onSelect 事件实时捕获(textarea 失焦后 ref 会丢失选区)
|
||||
const [selection, setSelection] = useState<{ start: number; end: number }>({
|
||||
start: 0,
|
||||
end: 0,
|
||||
});
|
||||
|
||||
// 当前激活的 tab 数据
|
||||
const activeTab = sqlTabs.find((t) => t.key === activeTabKey) || sqlTabs[0];
|
||||
const sqlText = activeTab?.sql ?? '';
|
||||
const queryResult = activeTab?.result ?? null;
|
||||
|
||||
// 更新当前 tab 的 SQL
|
||||
const setSqlText = (v: string) => {
|
||||
setSqlTabs((prev) => prev.map((t) => (t.key === activeTabKey ? { ...t, sql: v } : t)));
|
||||
};
|
||||
|
||||
// 更新当前 tab 的结果
|
||||
const setQueryResult = (r: SqlExecuteResult | null) => {
|
||||
setSqlTabs((prev) => prev.map((t) => (t.key === activeTabKey ? { ...t, result: r } : t)));
|
||||
};
|
||||
|
||||
// 新建 tab
|
||||
const addSqlTab = () => {
|
||||
tabCounterRef.current += 1;
|
||||
const key = `tab_${tabCounterRef.current}`;
|
||||
setSqlTabs((prev) => [
|
||||
...prev,
|
||||
{ key, label: `SQL ${tabCounterRef.current}`, sql: '', result: null },
|
||||
]);
|
||||
setActiveTabKey(key);
|
||||
};
|
||||
|
||||
// 关闭 tab
|
||||
const removeSqlTab = (key: string) => {
|
||||
setSqlTabs((prev) => {
|
||||
const filtered = prev.filter((t) => t.key !== key);
|
||||
if (filtered.length === 0) {
|
||||
// 至少保留一个 tab
|
||||
tabCounterRef.current += 1;
|
||||
const newKey = `tab_${tabCounterRef.current}`;
|
||||
setActiveTabKey(newKey);
|
||||
return [{ key: newKey, label: `SQL ${tabCounterRef.current}`, sql: '', result: null }];
|
||||
}
|
||||
// 关闭当前 tab 时自动切到相邻 tab
|
||||
if (key === activeTabKey) {
|
||||
const idx = prev.findIndex((t) => t.key === key);
|
||||
const next = filtered[Math.max(0, idx - 1)] || filtered[0];
|
||||
setActiveTabKey(next.key);
|
||||
}
|
||||
return filtered;
|
||||
});
|
||||
};
|
||||
|
||||
// 重命名 tab(双击可改名)
|
||||
const renameSqlTab = (key: string) => {
|
||||
const tab = sqlTabs.find((t) => t.key === key);
|
||||
if (!tab) return;
|
||||
Modal.confirm({
|
||||
title: '重命名标签页',
|
||||
content: (
|
||||
<Input
|
||||
defaultValue={tab.label}
|
||||
id="rename-tab-input"
|
||||
placeholder="输入新名称"
|
||||
/>
|
||||
),
|
||||
onOk: () => {
|
||||
const input = document.getElementById('rename-tab-input') as HTMLInputElement;
|
||||
const newLabel = input?.value?.trim();
|
||||
if (newLabel) {
|
||||
setSqlTabs((prev) => prev.map((t) => (t.key === key ? { ...t, label: newLabel } : t)));
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// SQL 历史(localStorage 持久化)
|
||||
const [sqlHistory, setSqlHistory] = useState<string[]>(() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('db_sql_history') || '[]');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
|
||||
// 表结构面板
|
||||
const [structureOpen, setStructureOpen] = useState(false);
|
||||
const [structureTable, setStructureTable] = useState('');
|
||||
const [structureColumns, setStructureColumns] = useState<TableColumn[]>([]);
|
||||
const [structureLoading, setStructureLoading] = useState(false);
|
||||
const [alterModalOpen, setAlterModalOpen] = useState(false);
|
||||
const [alterForm] = Form.useForm();
|
||||
|
||||
// 表列表(功能 6)
|
||||
const [tableList, setTableList] = useState<string[]>([]);
|
||||
const [tableListLoading, setTableListLoading] = useState(false);
|
||||
|
||||
/** 加载连接列表 */
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await listDbConnections();
|
||||
setConnections(data ?? []);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
/** 打开新建弹窗 */
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
form.setFieldsValue(INITIAL_VALUES);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
/** 打开编辑弹窗 */
|
||||
const openEdit = (record: DatabaseConnection) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
name: record.name,
|
||||
db_type: record.db_type,
|
||||
host: record.host,
|
||||
port: record.port,
|
||||
database: record.database,
|
||||
username: record.username,
|
||||
password: '',
|
||||
description: record.description,
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
/** 提交表单 */
|
||||
const handleSubmit = async () => {
|
||||
const values = await form.validateFields();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await updateDbConnection(editing.id, values);
|
||||
messageApi.success('连接配置更新成功');
|
||||
} else {
|
||||
await createDbConnection(values);
|
||||
messageApi.success('连接配置创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 测试连接 */
|
||||
const handleTest = async (record: DatabaseConnection) => {
|
||||
try {
|
||||
const result = await testDbConnection(record.id);
|
||||
if (result.success) {
|
||||
messageApi.success('连接成功');
|
||||
} else {
|
||||
messageApi.warning(result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除配置 */
|
||||
const handleDelete = async (record: DatabaseConnection) => {
|
||||
try {
|
||||
await deleteDbConnection(record.id);
|
||||
messageApi.success('删除成功');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存 SQL 到历史记录(最多 20 条) */
|
||||
const saveToHistory = (sql: string) => {
|
||||
if (!sql.trim()) return;
|
||||
const prev = sqlHistory.filter((s) => s !== sql.trim());
|
||||
const updated = [sql.trim(), ...prev].slice(0, 20);
|
||||
setSqlHistory(updated);
|
||||
try {
|
||||
localStorage.setItem('db_sql_history', JSON.stringify(updated));
|
||||
} catch {
|
||||
// localStorage 满了忽略
|
||||
}
|
||||
};
|
||||
|
||||
/** 导出查询结果为 CSV */
|
||||
const exportCsv = () => {
|
||||
if (!queryResult || queryResult.data.length === 0) {
|
||||
messageApi.warning('没有数据可导出');
|
||||
return;
|
||||
}
|
||||
const cols = queryResult.columns;
|
||||
const rows = queryResult.data.map((r) =>
|
||||
cols.map((c) => {
|
||||
const v = r[c];
|
||||
// CSV 转义:含逗号/引号/换行的值用引号包裹
|
||||
const s = v == null ? '' : String(v);
|
||||
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
}).join(','),
|
||||
);
|
||||
const csv = '' + [cols.join(','), ...rows].join('\n'); // BOM 防 Excel 乱码
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `query_result_${Date.now()}.csv`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
messageApi.success('CSV 导出成功');
|
||||
};
|
||||
|
||||
/** 加载表列表 */
|
||||
const loadTableList = useCallback(async () => {
|
||||
if (!selectedConnId) return;
|
||||
setTableListLoading(true);
|
||||
try {
|
||||
const tables = await listTables(selectedConnId);
|
||||
setTableList(tables ?? []);
|
||||
} catch {
|
||||
setTableList([]);
|
||||
} finally {
|
||||
setTableListLoading(false);
|
||||
}
|
||||
}, [selectedConnId]);
|
||||
|
||||
// 切换连接时自动加载表列表
|
||||
useEffect(() => {
|
||||
if (selectedConnId) {
|
||||
loadTableList();
|
||||
} else {
|
||||
setTableList([]);
|
||||
}
|
||||
}, [selectedConnId, loadTableList]);
|
||||
|
||||
/** 执行 SQL(选中文本优先执行选中部分) */
|
||||
const handleExecuteSql = async () => {
|
||||
if (!selectedConnId) {
|
||||
messageApi.warning('请先选择数据库连接');
|
||||
return;
|
||||
}
|
||||
|
||||
// 从 onSelect 捕获的选区状态读取(textarea 失焦后 ref 会丢选区)
|
||||
let sqlToRun = sqlText;
|
||||
if (selection.end > selection.start) {
|
||||
sqlToRun = sqlText.substring(selection.start, selection.end);
|
||||
}
|
||||
|
||||
if (!sqlToRun.trim()) {
|
||||
messageApi.warning('请输入或选中 SQL 语句');
|
||||
return;
|
||||
}
|
||||
saveToHistory(sqlToRun.trim());
|
||||
setExecuting(true);
|
||||
try {
|
||||
const upper = sqlToRun.trim().toUpperCase();
|
||||
if (upper.startsWith('SELECT') || upper.startsWith('WITH')) {
|
||||
const result = await queryDbSql(selectedConnId, sqlToRun, {}, 1, 50);
|
||||
setQueryResult(result);
|
||||
} else {
|
||||
const result = await executeDbSql(selectedConnId, sqlToRun, {});
|
||||
setQueryResult(result);
|
||||
messageApi.success(result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setExecuting(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 打开表结构面板 */
|
||||
const openStructure = async (tableName: string) => {
|
||||
if (!selectedConnId) {
|
||||
messageApi.warning('请先选择数据库连接');
|
||||
return;
|
||||
}
|
||||
setStructureTable(tableName);
|
||||
setStructureOpen(true);
|
||||
setStructureLoading(true);
|
||||
try {
|
||||
const result = await getTableStructure(selectedConnId, tableName);
|
||||
if (result.success) {
|
||||
setStructureColumns(result.columns);
|
||||
} else {
|
||||
messageApi.error(result.message || '查询表结构失败');
|
||||
setStructureColumns([]);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setStructureLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 提交表结构修改 */
|
||||
const handleAlter = async () => {
|
||||
const values = await alterForm.validateFields();
|
||||
try {
|
||||
const result = await alterTable(selectedConnId, {
|
||||
table: structureTable,
|
||||
action: values.action,
|
||||
column_name: values.column_name,
|
||||
column_type: values.column_type || '',
|
||||
nullable: values.nullable ?? true,
|
||||
default: values.default_value || '',
|
||||
comment: values.comment || '',
|
||||
});
|
||||
if (result.success) {
|
||||
messageApi.success(result.message);
|
||||
setAlterModalOpen(false);
|
||||
alterForm.resetFields();
|
||||
// 刷新表结构
|
||||
openStructure(structureTable);
|
||||
} else {
|
||||
messageApi.error(result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 连接表格列 */
|
||||
const columns: ColumnsType<DatabaseConnection> = [
|
||||
{
|
||||
title: '连接名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
render: (v: string) => <Typography.Text strong>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
dataIndex: 'db_type',
|
||||
key: 'db_type',
|
||||
width: 100,
|
||||
render: (v: string) => (
|
||||
<Tag color={v === 'mysql' ? 'orange' : v === 'postgresql' ? 'blue' : 'default'}>
|
||||
{v.toUpperCase()}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '主机:端口',
|
||||
key: 'host_port',
|
||||
width: 180,
|
||||
render: (_, r) => (
|
||||
<Typography.Text code style={{ fontSize: 12 }}>
|
||||
{r.host}:{r.port}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '数据库',
|
||||
dataIndex: 'database',
|
||||
key: 'database',
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 250,
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
<Button size="small" icon={<CheckCircleOutlined />} onClick={() => handleTest(record)}>
|
||||
测试
|
||||
</Button>
|
||||
<Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm title="确认删除?" onConfirm={() => handleDelete(record)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
/** 查询结果表格列(带字段筛选) */
|
||||
const resultColumns = queryResult?.columns.map((c) => ({
|
||||
title: c,
|
||||
dataIndex: c,
|
||||
key: c,
|
||||
ellipsis: true,
|
||||
// 字段筛选:取该列所有不重复值作为筛选项
|
||||
filters: [...new Set(queryResult.data.map((r) => String(r[c] ?? '')))].map((v) => ({
|
||||
text: v || '(空)',
|
||||
value: v,
|
||||
})),
|
||||
onFilter: (value: unknown, record: Record<string, unknown>) =>
|
||||
String(record[c] ?? '') === String(value),
|
||||
})) || [];
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
<DatabaseOutlined /> 数据库管理
|
||||
</Typography.Title>
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
|
||||
新增连接
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
{/* 连接配置列表 */}
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Table<DatabaseConnection>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={connections}
|
||||
pagination={{ pageSize: 5, showTotal: (t) => `共 ${t} 个连接` }}
|
||||
size="small"
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* SQL 执行面板 */}
|
||||
<Card
|
||||
size="small"
|
||||
title={
|
||||
<Space>
|
||||
<SearchOutlined />
|
||||
<span>SQL 执行面板</span>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: '100%' }} size="middle">
|
||||
<Space style={{ width: '100%' }}>
|
||||
<Select
|
||||
placeholder="选择数据库连接"
|
||||
style={{ width: 280 }}
|
||||
value={selectedConnId || undefined}
|
||||
onChange={(v) => setSelectedConnId(v)}
|
||||
options={connections.map((c) => ({
|
||||
label: `${c.name} (${c.db_type})`,
|
||||
value: c.id,
|
||||
}))}
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SearchOutlined />}
|
||||
loading={executing}
|
||||
onClick={handleExecuteSql}
|
||||
>
|
||||
执行 SQL
|
||||
</Button>
|
||||
<Button onClick={() => { setSqlText(''); setQueryResult(null); }}>
|
||||
清空
|
||||
</Button>
|
||||
</Space>
|
||||
|
||||
{/* 多标签 SQL 编辑器 */}
|
||||
<div style={{ border: '1px solid #d9d9d9', borderRadius: 6 }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
background: '#fafafa',
|
||||
borderBottom: '1px solid #d9d9d9',
|
||||
paddingLeft: 4,
|
||||
}}
|
||||
>
|
||||
{sqlTabs.map((tab) => (
|
||||
<div
|
||||
key={tab.key}
|
||||
onClick={() => setActiveTabKey(tab.key)}
|
||||
onDoubleClick={() => renameSqlTab(tab.key)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
cursor: 'pointer',
|
||||
borderRight: '1px solid #d9d9d9',
|
||||
background: tab.key === activeTabKey ? '#fff' : 'transparent',
|
||||
fontWeight: tab.key === activeTabKey ? 600 : 400,
|
||||
fontSize: 13,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 4,
|
||||
maxWidth: 160,
|
||||
}}
|
||||
>
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{tab.label}
|
||||
</span>
|
||||
{sqlTabs.length > 1 && (
|
||||
<CloseCircleOutlined
|
||||
style={{ fontSize: 12, color: '#999' }}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
removeSqlTab(tab.key);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={addSqlTab}
|
||||
title="新建 SQL 标签页"
|
||||
/>
|
||||
</div>
|
||||
<Input.TextArea
|
||||
ref={sqlTextareaRef}
|
||||
rows={6}
|
||||
placeholder={`请输入 SQL 语句\n选中部分内容可只执行选中的 SQL\nSELECT * FROM users WHERE id = :id`}
|
||||
value={sqlText}
|
||||
onChange={(e) => setSqlText(e.target.value)}
|
||||
onSelect={(e) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
setSelection({ start: target.selectionStart, end: target.selectionEnd });
|
||||
}}
|
||||
style={{
|
||||
fontFamily: 'monospace',
|
||||
resize: 'vertical',
|
||||
minHeight: 120,
|
||||
maxHeight: 500,
|
||||
border: 'none',
|
||||
borderRadius: '0 0 6px 6px',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 表结构工具条 */}
|
||||
<Space style={{ width: '100%', flexWrap: 'wrap' }}>
|
||||
{/* 表名下拉(功能 6) */}
|
||||
<AutoComplete
|
||||
style={{ width: 220 }}
|
||||
placeholder="选择或输入表名"
|
||||
value={tableName}
|
||||
onChange={(v) => setTableName(v)}
|
||||
options={tableList.map((t) => ({ label: t, value: t }))}
|
||||
filterOption={(input, option) =>
|
||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
notFoundContent={tableListLoading ? '加载中…' : '无表'}
|
||||
/>
|
||||
<Button
|
||||
icon={<TableOutlined />}
|
||||
disabled={!tableName.trim()}
|
||||
onClick={() => openStructure(tableName.trim())}
|
||||
>
|
||||
查看表结构
|
||||
</Button>
|
||||
|
||||
{/* SQL 历史(功能 4) */}
|
||||
{sqlHistory.length > 0 && (
|
||||
<Select
|
||||
style={{ width: 180 }}
|
||||
placeholder={<><HistoryOutlined /> SQL 历史</>}
|
||||
value={undefined}
|
||||
onChange={(v) => { if (v) setSqlText(String(v)); }}
|
||||
options={sqlHistory.map((s, i) => ({
|
||||
label: s.length > 30 ? s.slice(0, 30) + '…' : s,
|
||||
value: s,
|
||||
key: i,
|
||||
}))}
|
||||
showSearch
|
||||
filterOption={(input, option) =>
|
||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 导出 CSV(功能 5) */}
|
||||
<Tooltip title="导出查询结果为 CSV">
|
||||
<Button
|
||||
icon={<DownloadOutlined />}
|
||||
disabled={!queryResult || queryResult.data.length === 0}
|
||||
onClick={exportCsv}
|
||||
>
|
||||
导出 CSV
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Space>
|
||||
|
||||
{queryResult && (
|
||||
<div>
|
||||
<Alert
|
||||
type={queryResult.success ? 'success' : 'error'}
|
||||
showIcon
|
||||
icon={queryResult.success ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
|
||||
message={queryResult.message}
|
||||
description={
|
||||
queryResult.success && queryResult.data.length > 0
|
||||
? `返回 ${queryResult.data.length} 条记录`
|
||||
: queryResult.success && queryResult.affected_rows > 0
|
||||
? `影响 ${queryResult.affected_rows} 行`
|
||||
: ''
|
||||
}
|
||||
style={{ marginBottom: 8 }}
|
||||
/>
|
||||
{queryResult.data.length > 0 && (
|
||||
<Table
|
||||
rowKey={(_, i) => String(i)}
|
||||
columns={resultColumns}
|
||||
dataSource={queryResult.data}
|
||||
pagination={{ pageSize: 10, showTotal: (t) => `共 ${t} 条` }}
|
||||
size="small"
|
||||
scroll={{ x: true }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{/* 表结构面板 */}
|
||||
<Modal
|
||||
title={`表结构:${structureTable}`}
|
||||
open={structureOpen}
|
||||
onCancel={() => setStructureOpen(false)}
|
||||
width={720}
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={() => setAlterModalOpen(true)} icon={<EditOutlined />}>
|
||||
修改表结构
|
||||
</Button>
|
||||
<Button onClick={() => setStructureOpen(false)}>关闭</Button>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Table<TableColumn>
|
||||
rowKey="name"
|
||||
loading={structureLoading}
|
||||
dataSource={structureColumns}
|
||||
pagination={false}
|
||||
size="small"
|
||||
columns={[
|
||||
{ title: '列名', dataIndex: 'name', key: 'name',
|
||||
render: (v: string) => <Typography.Text code>{v}</Typography.Text> },
|
||||
{ title: '类型', dataIndex: 'type', key: 'type',
|
||||
render: (v: string) => <Tag color="blue">{v}</Tag> },
|
||||
{ title: '可空', dataIndex: 'nullable', key: 'nullable',
|
||||
width: 70,
|
||||
render: (v: boolean) => v ? '✅' : '❌' },
|
||||
{ title: '主键', dataIndex: 'key', key: 'key',
|
||||
width: 70,
|
||||
render: (v: string) => v === 'PRI' ? <Tag color="gold">PK</Tag> : '' },
|
||||
{ title: '默认值', dataIndex: 'default', key: 'default',
|
||||
width: 120,
|
||||
render: (v: string) => v || <Typography.Text type="secondary">—</Typography.Text> },
|
||||
{ title: '注释', dataIndex: 'comment', key: 'comment',
|
||||
ellipsis: true },
|
||||
]}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
{/* 修改表结构弹窗 */}
|
||||
<Modal
|
||||
title={`修改表结构:${structureTable}`}
|
||||
open={alterModalOpen}
|
||||
onOk={handleAlter}
|
||||
onCancel={() => setAlterModalOpen(false)}
|
||||
okText="执行"
|
||||
cancelText="取消"
|
||||
width={480}
|
||||
>
|
||||
<Form form={alterForm} layout="vertical">
|
||||
<Form.Item
|
||||
name="action"
|
||||
label="操作类型"
|
||||
rules={[{ required: true }]}
|
||||
initialValue="add"
|
||||
>
|
||||
<Select
|
||||
options={[
|
||||
{ label: '加列(ADD)', value: 'add' },
|
||||
{ label: '改列(MODIFY)', value: 'modify' },
|
||||
{ label: '删列(DROP)', value: 'drop' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="column_name"
|
||||
label="列名"
|
||||
rules={[{ required: true, message: '请输入列名' }]}
|
||||
>
|
||||
<Input placeholder="如:email" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="column_type"
|
||||
label="列类型"
|
||||
extra="加列/改列时必填,如 VARCHAR(255)、INT、TEXT"
|
||||
>
|
||||
<Input placeholder="VARCHAR(255)" />
|
||||
</Form.Item>
|
||||
<Space size="large" style={{ display: 'flex' }}>
|
||||
<Form.Item name="nullable" label="可空" valuePropName="checked" initialValue={true}>
|
||||
<Switch checkedChildren="是" unCheckedChildren="否" />
|
||||
</Form.Item>
|
||||
<Form.Item name="default_value" label="默认值" style={{ flex: 1 }}>
|
||||
<Input placeholder="留空则无默认值" />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
<Form.Item name="comment" label="列注释">
|
||||
<Input placeholder="列注释(MySQL)" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* 新建/编辑弹窗 */}
|
||||
<Modal
|
||||
title={editing ? '编辑连接配置' : '新增连接配置'}
|
||||
open={modalOpen}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={submitting}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
width={560}
|
||||
>
|
||||
<Form form={form} layout="vertical" initialValues={INITIAL_VALUES}>
|
||||
<Space size="large" style={{ display: 'flex' }}>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="连接名称"
|
||||
style={{ flex: 1 }}
|
||||
rules={[{ required: true, message: '请输入连接名称' }]}
|
||||
>
|
||||
<Input placeholder="如:生产库" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="db_type"
|
||||
label="数据库类型"
|
||||
style={{ flex: 1 }}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Select options={DB_TYPE_OPTIONS} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
|
||||
<Space size="large" style={{ display: 'flex' }}>
|
||||
<Form.Item name="host" label="主机地址" style={{ flex: 2 }}>
|
||||
<Input placeholder="localhost" />
|
||||
</Form.Item>
|
||||
<Form.Item name="port" label="端口" style={{ flex: 1 }}>
|
||||
<InputNumber style={{ width: '100%' }} min={1} max={65535} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
|
||||
<Form.Item
|
||||
name="database"
|
||||
label="数据库名 / 文件路径"
|
||||
rules={[{ required: true, message: '请输入数据库名' }]}
|
||||
extra="SQLite 填文件路径,如 D:\Project\data.db"
|
||||
>
|
||||
<Input placeholder="mydb" />
|
||||
</Form.Item>
|
||||
|
||||
<Space size="large" style={{ display: 'flex' }}>
|
||||
<Form.Item name="username" label="用户名" style={{ flex: 1 }}>
|
||||
<Input placeholder="root" />
|
||||
</Form.Item>
|
||||
<Form.Item name="password" label="密码" style={{ flex: 1 }}>
|
||||
<Input.Password placeholder="(编辑时留空表示不修改)" />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
|
||||
<Form.Item name="description" label="备注">
|
||||
<Input.TextArea rows={2} maxLength={200} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* 目录选择器弹窗组件
|
||||
*
|
||||
* 【功能说明】类似文件资源管理器,可逐层导航目录、选择目标目录后确认加载。
|
||||
* 【技术选型理由】AntD Modal + Breadcrumb + List,自研目录浏览器(不依赖 Electron)。
|
||||
* 【实现思路】
|
||||
* 1. 打开时显示 D:\ 根目录的子目录列表;
|
||||
* 2. 点击子目录进入下一级;点面包屑/上级按钮返回;
|
||||
* 3. 点击目录名选中,点「确认选择」回传路径。
|
||||
*/
|
||||
import {
|
||||
FileTextOutlined,
|
||||
FolderOpenOutlined,
|
||||
FolderOutlined,
|
||||
HomeOutlined,
|
||||
LeftOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Breadcrumb,
|
||||
Button,
|
||||
Empty,
|
||||
List,
|
||||
Modal,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { browseDirectory } from '../api/client';
|
||||
|
||||
interface DirItem {
|
||||
name: string;
|
||||
path: string;
|
||||
type: string;
|
||||
size?: number;
|
||||
ext?: string;
|
||||
}
|
||||
|
||||
export interface DirectoryPickerProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: (path: string, selectedFiles: string[]) => void;
|
||||
}
|
||||
|
||||
export default function DirectoryPicker({ open, onClose, onConfirm }: DirectoryPickerProps) {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [currentPath, setCurrentPath] = useState('D:\\');
|
||||
const [parentPath, setParentPath] = useState<string | null>(null);
|
||||
const [directories, setDirectories] = useState<DirItem[]>([]);
|
||||
const [files, setFiles] = useState<DirItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selectedPath, setSelectedPath] = useState('');
|
||||
const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
|
||||
|
||||
/** 加载目录列表 */
|
||||
const loadDir = useCallback(
|
||||
async (path: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await browseDirectory(path);
|
||||
if (result) {
|
||||
setCurrentPath(result.path);
|
||||
setParentPath(result.parent);
|
||||
setDirectories(result.directories || []);
|
||||
setFiles((result as unknown as { files?: DirItem[] }).files || []);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[messageApi],
|
||||
);
|
||||
|
||||
// 打开时加载根目录
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelectedPath('');
|
||||
loadDir('D:\\');
|
||||
}
|
||||
}, [open, loadDir]);
|
||||
|
||||
/** 进入子目录 */
|
||||
const enterDir = (path: string) => {
|
||||
setSelectedPath(path);
|
||||
loadDir(path);
|
||||
};
|
||||
|
||||
/** 返回上级 */
|
||||
const goBack = () => {
|
||||
if (parentPath) {
|
||||
loadDir(parentPath);
|
||||
}
|
||||
};
|
||||
|
||||
/** 确认选择 */
|
||||
const handleConfirm = () => {
|
||||
const target = selectedPath || currentPath;
|
||||
onConfirm(target, selectedFiles);
|
||||
onClose();
|
||||
};
|
||||
|
||||
/** 选中/取消选中文件 */
|
||||
const toggleFile = (filePath: string) => {
|
||||
setSelectedFiles((prev) =>
|
||||
prev.includes(filePath) ? prev.filter((p) => p !== filePath) : [...prev, filePath],
|
||||
);
|
||||
};
|
||||
|
||||
/** 文件大小格式化 */
|
||||
const formatSize = (bytes?: number) => {
|
||||
if (!bytes && bytes !== 0) return '';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
};
|
||||
|
||||
/** 面包屑 */
|
||||
const breadcrumbItems = currentPath
|
||||
.split(/[/\\]/)
|
||||
.filter(Boolean)
|
||||
.map((seg, i, arr) => {
|
||||
const segPath = arr.slice(0, i + 1).join('\\');
|
||||
return {
|
||||
title:
|
||||
i === 0 ? (
|
||||
<a onClick={() => loadDir(`${seg}\\`)}>
|
||||
<HomeOutlined /> {seg}
|
||||
</a>
|
||||
) : (
|
||||
<a onClick={() => loadDir(segPath)}>{seg}</a>
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={
|
||||
<Space>
|
||||
<FolderOpenOutlined />
|
||||
<span>选择文档目录</span>
|
||||
</Space>
|
||||
}
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
width={560}
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={onClose}>取消</Button>
|
||||
<Button type="primary" onClick={handleConfirm}>
|
||||
确认选择
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
{/* 路径导航 */}
|
||||
<Space style={{ width: '100%', marginBottom: 12, flexWrap: 'wrap' }}>
|
||||
<Button size="small" icon={<LeftOutlined />} disabled={!parentPath} onClick={goBack}>
|
||||
上级
|
||||
</Button>
|
||||
<Breadcrumb items={breadcrumbItems} />
|
||||
</Space>
|
||||
|
||||
{/* 当前选中路径 */}
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
当前选中:
|
||||
</Typography.Text>
|
||||
<Typography.Text code style={{ fontSize: 12 }}>
|
||||
{selectedPath || currentPath}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
|
||||
{/* 目录 + 文件列表 */}
|
||||
<div
|
||||
style={{
|
||||
maxHeight: 360,
|
||||
overflow: 'auto',
|
||||
border: '1px solid #f0f0f0',
|
||||
borderRadius: 6,
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<div style={{ textAlign: 'center', padding: 40 }}>
|
||||
<Spin tip="加载中…" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* 子目录 */}
|
||||
{directories.length > 0 && (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={directories}
|
||||
renderItem={(dir) => (
|
||||
<List.Item
|
||||
style={{
|
||||
padding: '8px 12px',
|
||||
cursor: 'pointer',
|
||||
background: selectedPath === dir.path ? '#e6f4ff' : 'transparent',
|
||||
}}
|
||||
onClick={() => enterDir(dir.path)}
|
||||
>
|
||||
<List.Item.Meta
|
||||
avatar={
|
||||
<FolderOutlined
|
||||
style={{
|
||||
color: selectedPath === dir.path ? '#1677ff' : '#faad14',
|
||||
fontSize: 18,
|
||||
}}
|
||||
/>
|
||||
}
|
||||
title={<Typography.Text>{dir.name}</Typography.Text>}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 文件(可多选) */}
|
||||
{files.length > 0 && (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={files}
|
||||
renderItem={(f) => {
|
||||
const isSelected = selectedFiles.includes(f.path);
|
||||
return (
|
||||
<List.Item
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
cursor: 'pointer',
|
||||
background: isSelected ? '#e6f4ff' : 'transparent',
|
||||
}}
|
||||
onClick={() => toggleFile(f.path)}
|
||||
>
|
||||
<List.Item.Meta
|
||||
avatar={<FileTextOutlined style={{ color: isSelected ? '#1677ff' : '#52c41a', fontSize: 16 }} />}
|
||||
title={
|
||||
<Typography.Text style={{ fontSize: 12 }} ellipsis={{ tooltip: f.name }}>
|
||||
{isSelected && '☑ '}
|
||||
{f.name}
|
||||
</Typography.Text>
|
||||
}
|
||||
description={
|
||||
<Space size={4}>
|
||||
{f.ext && <Tag style={{ fontSize: 10, margin: 0 }}>{f.ext}</Tag>}
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
{formatSize(f.size)}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
</List.Item>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 空目录 */}
|
||||
{directories.length === 0 && files.length === 0 && (
|
||||
<Empty description="此目录为空" style={{ padding: 40 }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11, display: 'block', marginTop: 8 }}>
|
||||
📁 点击目录进入下一级 | 📄 点击文件选中(可多选) | 已选 {selectedFiles.length} 个文件
|
||||
</Typography.Text>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
/**
|
||||
* 文档问答页面组件
|
||||
*
|
||||
* 【功能说明】选择目录 → 加载文档 → 多轮对话问答。
|
||||
* 左侧对话历史列表,点击可继续之前的对话。
|
||||
* 【技术选型理由】AntD Layout 左右分栏 + 自研气泡聊天 UI。
|
||||
*/
|
||||
import {
|
||||
DeleteOutlined,
|
||||
FolderOpenOutlined,
|
||||
PlusOutlined,
|
||||
QuestionCircleOutlined,
|
||||
RobotOutlined,
|
||||
SendOutlined,
|
||||
ThunderboltOutlined,
|
||||
UserOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Empty,
|
||||
Input,
|
||||
List,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
deleteDocQaConversation,
|
||||
docQaChat,
|
||||
docQaIndex,
|
||||
docQaVectorize,
|
||||
getDocQaConversations,
|
||||
getDocQaDetail,
|
||||
listModelOptions,
|
||||
} from '../api/client';
|
||||
import type { ModelOption } from '../types';
|
||||
import DirectoryPicker from './DirectoryPicker';
|
||||
|
||||
interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
model?: string;
|
||||
sources?: { filename: string; excerpt: string }[];
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
interface ConvItem {
|
||||
conversation_id: string;
|
||||
title: string;
|
||||
directory: string;
|
||||
file_count: number;
|
||||
history_count: number;
|
||||
vectorized: boolean;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export default function DocQa() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
// 左侧对话列表
|
||||
const [conversations, setConversations] = useState<ConvItem[]>([]);
|
||||
const [activeConvId, setActiveConvId] = useState('');
|
||||
// 当前对话
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [docFiles, setDocFiles] = useState<{ filename: string; chars: number }[]>([]);
|
||||
const [totalChars, setTotalChars] = useState(0);
|
||||
const [isVectorized, setIsVectorized] = useState(false);
|
||||
// 输入
|
||||
const [question, setQuestion] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [modelOptions, setModelOptions] = useState<ModelOption[]>([]);
|
||||
const [selectedModel, setSelectedModel] = useState<string>('auto');
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, [messages]);
|
||||
|
||||
useEffect(() => {
|
||||
listModelOptions().then(setModelOptions).catch(() => {});
|
||||
refreshConversations();
|
||||
}, []);
|
||||
|
||||
/** 刷新对话列表 */
|
||||
const refreshConversations = useCallback(async () => {
|
||||
try {
|
||||
const data = await getDocQaConversations();
|
||||
setConversations(data ?? []);
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** 选中对话 → 加载历史 */
|
||||
const selectConversation = async (convId: string) => {
|
||||
setActiveConvId(convId);
|
||||
try {
|
||||
const detail = await getDocQaDetail(convId);
|
||||
// 转换历史消息格式
|
||||
const msgs: ChatMessage[] = (detail.history || []).map((h) => ({
|
||||
role: h.role as 'user' | 'assistant',
|
||||
content: h.content,
|
||||
timestamp: '',
|
||||
}));
|
||||
setMessages(msgs);
|
||||
setTotalChars(detail.total_chars || 0);
|
||||
setIsVectorized(detail.vectorized);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 新建对话 */
|
||||
const newConversation = () => {
|
||||
setActiveConvId('');
|
||||
setMessages([]);
|
||||
setDocFiles([]);
|
||||
setTotalChars(0);
|
||||
setIsVectorized(false);
|
||||
};
|
||||
|
||||
/** 目录选择器确认 → 加载文档 */
|
||||
const handlePickerConfirm = async (path: string, selectedFiles: string[]) => {
|
||||
try {
|
||||
// 如果选了文件就加载文件,否则加载整个目录
|
||||
const payload =
|
||||
selectedFiles.length > 0
|
||||
? { file_paths: selectedFiles }
|
||||
: { directory: path };
|
||||
const result = await docQaIndex(payload);
|
||||
if (result.success) {
|
||||
setActiveConvId(result.conversation_id);
|
||||
setTotalChars(result.total_chars || 0);
|
||||
setIsVectorized(false);
|
||||
setDocFiles(
|
||||
(result.files || []).map((f) => ({ filename: f.filename, chars: f.chars })),
|
||||
);
|
||||
setMessages([]);
|
||||
messageApi.success(`文档加载完成:${result.file_count} 个文件`);
|
||||
await refreshConversations();
|
||||
} else {
|
||||
messageApi.warning(result.message || '加载失败');
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 向量化 */
|
||||
const handleVectorize = async () => {
|
||||
if (!activeConvId) return;
|
||||
try {
|
||||
const result = await docQaVectorize(activeConvId);
|
||||
if (result.success) {
|
||||
setIsVectorized(true);
|
||||
messageApi.success(result.message || '向量化完成');
|
||||
} else {
|
||||
messageApi.warning(result.message || '向量化失败');
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 发送问题(无文档也可对话) */
|
||||
const handleSend = async () => {
|
||||
const q = question.trim();
|
||||
if (!q) return;
|
||||
|
||||
// 如果没有对话,自动创建纯对话会话
|
||||
const convId = activeConvId || '';
|
||||
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
content: q,
|
||||
timestamp: new Date().toLocaleTimeString('zh-CN'),
|
||||
};
|
||||
setMessages((prev) => [...prev, userMsg]);
|
||||
setQuestion('');
|
||||
setSending(true);
|
||||
|
||||
try {
|
||||
const result = await docQaChat(convId, q, selectedModel);
|
||||
if (result.success) {
|
||||
// 后端自动创建了对话
|
||||
if (!convId && (result as unknown as { conversation_id?: string }).conversation_id) {
|
||||
setActiveConvId(
|
||||
(result as unknown as { conversation_id: string }).conversation_id,
|
||||
);
|
||||
}
|
||||
const aiMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: result.answer,
|
||||
model: result.model,
|
||||
sources: result.sources,
|
||||
timestamp: new Date().toLocaleTimeString('zh-CN'),
|
||||
};
|
||||
setMessages((prev) => [...prev, aiMsg]);
|
||||
await refreshConversations();
|
||||
} else {
|
||||
messageApi.error(result.message || '问答失败');
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除对话 */
|
||||
const handleDelete = async (convId: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
try {
|
||||
await deleteDocQaConversation(convId);
|
||||
if (convId === activeConvId) newConversation();
|
||||
await refreshConversations();
|
||||
messageApi.success('对话已删除');
|
||||
} catch (err) {
|
||||
messageApi.error((err as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', height: 'calc(100vh - 120px)', gap: 0 }}>
|
||||
{/* ========== 左侧:对话历史列表 ========== */}
|
||||
<div
|
||||
style={{
|
||||
width: 240,
|
||||
borderRight: '1px solid #f0f0f0',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
background: '#fafafa',
|
||||
}}
|
||||
>
|
||||
<div style={{ padding: 12 }}>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
block
|
||||
onClick={newConversation}
|
||||
>
|
||||
新建对话
|
||||
</Button>
|
||||
</div>
|
||||
<div style={{ flex: 1, overflow: 'auto' }}>
|
||||
{conversations.length === 0 ? (
|
||||
<div style={{ padding: 24, textAlign: 'center', color: '#999' }}>
|
||||
<QuestionCircleOutlined style={{ fontSize: 24, marginBottom: 8 }} />
|
||||
<br />
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
暂无对话记录
|
||||
</Typography.Text>
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={conversations}
|
||||
renderItem={(conv) => (
|
||||
<div
|
||||
style={{
|
||||
padding: '10px 12px',
|
||||
cursor: 'pointer',
|
||||
borderBottom: '1px solid #f0f0f0',
|
||||
background: conv.conversation_id === activeConvId ? '#e6f4ff' : 'transparent',
|
||||
position: 'relative',
|
||||
}}
|
||||
onClick={() => selectConversation(conv.conversation_id)}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography.Text
|
||||
strong
|
||||
style={{ fontSize: 13 }}
|
||||
ellipsis={{ tooltip: conv.title }}
|
||||
>
|
||||
{conv.title}
|
||||
</Typography.Text>
|
||||
<div>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
{conv.file_count} 个文件 · {conv.history_count} 条消息
|
||||
</Typography.Text>
|
||||
</div>
|
||||
<div>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 10 }}>
|
||||
{conv.updated_at}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<DeleteOutlined />}
|
||||
style={{ opacity: 0.5 }}
|
||||
onClick={(e) => handleDelete(conv.conversation_id, e)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ========== 右侧:聊天区 ========== */}
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
|
||||
{/* 顶部工具条 */}
|
||||
<Card size="small" style={{ borderRadius: 0 }}>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
|
||||
<Space>
|
||||
<Button icon={<FolderOpenOutlined />} onClick={() => setPickerOpen(true)}>
|
||||
加载文档
|
||||
</Button>
|
||||
{activeConvId && (
|
||||
<Space>
|
||||
<Tag color="green">
|
||||
{docFiles.length || '已加载'} 文件 / {(totalChars / 1000).toFixed(1)}K 字符
|
||||
</Tag>
|
||||
{isVectorized ? (
|
||||
<Tag color="blue">已向量化</Tag>
|
||||
) : (
|
||||
<Tooltip title="文档量大时向量化可提升检索效率">
|
||||
<Button size="small" icon={<ThunderboltOutlined />} onClick={handleVectorize}>
|
||||
向量化
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Space>
|
||||
)}
|
||||
</Space>
|
||||
<Select
|
||||
value={selectedModel}
|
||||
onChange={(v) => setSelectedModel(v)}
|
||||
options={modelOptions}
|
||||
style={{ width: 200 }}
|
||||
size="small"
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{/* 聊天区 */}
|
||||
<div style={{ flex: 1, overflow: 'auto', padding: 16 }}>
|
||||
{messages.length === 0 ? (
|
||||
<Empty
|
||||
description={
|
||||
<Space direction="vertical">
|
||||
<Typography.Text type="secondary">
|
||||
{activeConvId
|
||||
? '文档已就绪,开始提问吧!'
|
||||
: '点击「加载文档」选择目录开始'}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
}
|
||||
style={{ marginTop: 80 }}
|
||||
image={<QuestionCircleOutlined style={{ fontSize: 48, color: '#ccc' }} />}
|
||||
/>
|
||||
) : (
|
||||
messages.map((msg, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',
|
||||
marginBottom: 16,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
maxWidth: '75%',
|
||||
display: 'flex',
|
||||
gap: 8,
|
||||
flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 32,
|
||||
height: 32,
|
||||
borderRadius: '50%',
|
||||
background: msg.role === 'user' ? '#1677ff' : '#52c41a',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
{msg.role === 'user' ? (
|
||||
<UserOutlined style={{ color: '#fff', fontSize: 14 }} />
|
||||
) : (
|
||||
<RobotOutlined style={{ color: '#fff', fontSize: 14 }} />
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
background: msg.role === 'user' ? '#1677ff' : '#f6f6f6',
|
||||
color: msg.role === 'user' ? '#fff' : '#333',
|
||||
padding: '10px 14px',
|
||||
borderRadius: 12,
|
||||
whiteSpace: 'pre-wrap',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.7,
|
||||
}}
|
||||
>
|
||||
{msg.content}
|
||||
</div>
|
||||
{msg.sources && msg.sources.length > 0 && (
|
||||
<div style={{ marginTop: 6 }}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
📄 来源:
|
||||
</Typography.Text>
|
||||
{msg.sources.map((s, j) => (
|
||||
<Tag key={j} style={{ fontSize: 11, margin: '2px 0' }}>
|
||||
{s.filename}
|
||||
</Tag>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* 模型标注 */}
|
||||
{msg.role === 'assistant' && msg.model && (
|
||||
<div style={{ marginTop: 4, textAlign: 'right' }}>
|
||||
<Typography.Text
|
||||
type="secondary"
|
||||
style={{ fontSize: 10 }}
|
||||
>
|
||||
🤖 由 {msg.model} 生成
|
||||
</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{sending && (
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center', paddingLeft: 40 }}>
|
||||
<Spin size="small" />
|
||||
<Typography.Text type="secondary">正在思考…</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
|
||||
{/* 输入框 */}
|
||||
<Card size="small" style={{ borderRadius: 0 }}>
|
||||
<Space.Compact style={{ width: '100%' }}>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder={
|
||||
activeConvId ? '输入问题…(Enter 发送)' : '请先加载文档或选择对话'
|
||||
}
|
||||
value={question}
|
||||
onChange={(e) => setQuestion(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
}}
|
||||
disabled={sending}
|
||||
style={{ resize: 'none' }}
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SendOutlined />}
|
||||
loading={sending}
|
||||
disabled={!question.trim()}
|
||||
onClick={handleSend}
|
||||
style={{ height: 'auto' }}
|
||||
>
|
||||
发送
|
||||
</Button>
|
||||
</Space.Compact>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 目录选择器 */}
|
||||
<DirectoryPicker
|
||||
open={pickerOpen}
|
||||
onClose={() => setPickerOpen(false)}
|
||||
onConfirm={handlePickerConfirm}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* 模型降级链管理组件
|
||||
*
|
||||
* 【功能说明】维护模型降级链顺序(拖拽排序),额度用完后按此顺序无缝切换。
|
||||
* 对应痛点 2:模型额度用完自动切换。
|
||||
* 【技术选型理由】AntD Table + 上下箭头排序(同项目管理),直观易操作。
|
||||
*/
|
||||
import { ArrowDownOutlined, ArrowUpOutlined, ReloadOutlined, SaveOutlined } from '@ant-design/icons';
|
||||
import { App as AntApp, Button, Space, Table, Tag, Typography } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { getFallbackChain, updateFallbackChain } from '../api/client';
|
||||
|
||||
interface FallbackItem {
|
||||
id: string;
|
||||
display_name: string;
|
||||
model_id: string;
|
||||
provider_key: string;
|
||||
model_role: string;
|
||||
fallback_order: number;
|
||||
}
|
||||
|
||||
export default function FallbackChain() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [items, setItems] = useState<FallbackItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await getFallbackChain();
|
||||
setItems(data ?? []);
|
||||
setDirty(false);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
/** 上移 */
|
||||
const moveUp = (index: number) => {
|
||||
if (index <= 0) return;
|
||||
const next = [...items];
|
||||
[next[index - 1], next[index]] = [next[index], next[index - 1]];
|
||||
// 重排 fallback_order
|
||||
next.forEach((item, i) => (item.fallback_order = i + 1));
|
||||
setItems(next);
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
/** 下移 */
|
||||
const moveDown = (index: number) => {
|
||||
if (index >= items.length - 1) return;
|
||||
const next = [...items];
|
||||
[next[index], next[index + 1]] = [next[index + 1], next[index]];
|
||||
next.forEach((item, i) => (item.fallback_order = i + 1));
|
||||
setItems(next);
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
/** 保存顺序 */
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateFallbackChain(items.map((it) => ({ id: it.id, fallback_order: it.fallback_order })));
|
||||
messageApi.success('降级链顺序已保存');
|
||||
setDirty(false);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const roleLabels: Record<string, string> = {
|
||||
strong: '强模型',
|
||||
weak: '弱模型',
|
||||
general: '通用',
|
||||
};
|
||||
|
||||
const columns: ColumnsType<FallbackItem> = [
|
||||
{
|
||||
title: '顺序',
|
||||
key: 'order',
|
||||
width: 80,
|
||||
render: (_, __, i) => (
|
||||
<Tag color={i === 0 ? 'green' : i === 1 ? 'blue' : 'default'}>
|
||||
{i === 0 ? '🥇 首选' : i === 1 ? '🥈 备选' : `${i + 1} 级`}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '模型',
|
||||
dataIndex: 'display_name',
|
||||
key: 'display_name',
|
||||
ellipsis: true,
|
||||
render: (v: string) => <Typography.Text strong>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '模型 ID',
|
||||
dataIndex: 'model_id',
|
||||
key: 'model_id',
|
||||
width: 160,
|
||||
render: (v: string) => <Typography.Text code>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: 'Provider',
|
||||
dataIndex: 'provider_key',
|
||||
key: 'provider_key',
|
||||
width: 100,
|
||||
render: (v: string) => <Tag color="blue">{v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'model_role',
|
||||
key: 'model_role',
|
||||
width: 90,
|
||||
render: (v: string) => <Tag>{roleLabels[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 120,
|
||||
render: (_, __, index) => (
|
||||
<Space size={2}>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<ArrowUpOutlined />}
|
||||
disabled={index === 0}
|
||||
onClick={() => moveUp(index)}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<ArrowDownOutlined />}
|
||||
disabled={index === items.length - 1}
|
||||
onClick={() => moveDown(index)}
|
||||
/>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 12, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Text type="secondary">
|
||||
当前模型额度用完后,自动按此顺序无缝切换到下一个模型。上下箭头调整优先级。
|
||||
</Typography.Text>
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SaveOutlined />}
|
||||
loading={saving}
|
||||
disabled={!dirty}
|
||||
onClick={handleSave}
|
||||
>
|
||||
{dirty ? '保存顺序(有改动)' : '保存顺序'}
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
<Table<FallbackItem>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
pagination={false}
|
||||
size="small"
|
||||
locale={{ emptyText: '暂无可用模型,请先在 Provider 管理中拉取模型' }}
|
||||
/>
|
||||
|
||||
{dirty && (
|
||||
<Typography.Text type="warning" style={{ marginTop: 8, display: 'block' }}>
|
||||
⚠️ 顺序有改动,点击「保存顺序」生效
|
||||
</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* 文件选择入库弹窗组件
|
||||
*
|
||||
* 【功能说明】
|
||||
* 列出知识库素材目录下的全部可入库文档(递归),支持勾选文件/整个子目录,
|
||||
* 一键向量化选中项。对应 M6 优化方案 ③「A + 文件选择」。
|
||||
* 【技术选型理由】
|
||||
* AntD Tree 的 checkable 默认级联勾选(勾父节点自动勾全部子节点),
|
||||
* 正好满足「勾选整个子目录一键入库」的需求,无需自研递归勾选逻辑。
|
||||
* 【实现思路】
|
||||
* 1. 后端返回扁平文件列表(含 relative_path);
|
||||
* 2. 前端按路径层级构建成树(目录为父节点、文件为叶子);
|
||||
* 3. Tree 勾选状态 → 收集叶子节点 key(即文件相对路径)→ 映射回绝对路径;
|
||||
* 4. 提交时调 /knowledge/ingest-files 批量入库(后端按 source 替换,不重复)。
|
||||
* 【潜在风险与应对】
|
||||
* 风险1:文件列表为空(目录里没有 md/docx/pdf)。
|
||||
* 应对:空态提示「未发现可入库文档」,禁用提交按钮。
|
||||
* 风险2:勾选文件过多,入库耗时长。
|
||||
* 应对:底部按钮 loading 状态 + 明确提示「按选中数量预估耗时」。
|
||||
* 风险3:同名文件在不同子目录下(key 冲突)。
|
||||
* 应对:Tree 的 key 用完整相对路径(含目录),天然唯一。
|
||||
*/
|
||||
import {
|
||||
FileMarkdownOutlined,
|
||||
FilePdfOutlined,
|
||||
FileTextOutlined,
|
||||
FolderOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Empty,
|
||||
Modal,
|
||||
Space,
|
||||
Spin,
|
||||
Tree,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { DataNode } from 'antd/es/tree';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { ingestSelectedFiles, listKnowledgeFiles } from '../api/client';
|
||||
import type { KnowledgeFileItem } from '../types';
|
||||
|
||||
/** 文件类型 → 图标 */
|
||||
function iconForType(fileType: string): JSX.Element {
|
||||
switch (fileType) {
|
||||
case 'md':
|
||||
case 'markdown':
|
||||
return <FileMarkdownOutlined style={{ color: '#1677ff' }} />;
|
||||
case 'pdf':
|
||||
return <FilePdfOutlined style={{ color: '#cf1322' }} />;
|
||||
default:
|
||||
return <FileTextOutlined style={{ color: '#8c8c8c' }} />;
|
||||
}
|
||||
}
|
||||
|
||||
/** 文件大小格式化 */
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把扁平文件列表构建成 AntD Tree 数据(目录为父节点,文件为叶子)
|
||||
*/
|
||||
function buildTreeData(files: KnowledgeFileItem[]): {
|
||||
treeData: DataNode[];
|
||||
keyToPath: Record<string, string>;
|
||||
} {
|
||||
const keyToPath: Record<string, string> = {};
|
||||
const root: DataNode[] = [];
|
||||
|
||||
for (const f of files) {
|
||||
const parts = f.relative_path.split('/');
|
||||
let current = root;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
const isLeaf = i === parts.length - 1;
|
||||
const key = parts.slice(0, i + 1).join('/');
|
||||
let node = current.find((n) => n.key === key) as
|
||||
| (DataNode & { children?: DataNode[] })
|
||||
| undefined;
|
||||
if (!node) {
|
||||
node = {
|
||||
key,
|
||||
// 叶子节点(文件)显示文件名 + 大小;父节点(目录)只显示目录名
|
||||
title: isLeaf ? `${part} · ${formatSize(f.size)}` : part,
|
||||
icon: isLeaf ? iconForType(f.file_type) : <FolderOutlined />,
|
||||
isLeaf,
|
||||
children: isLeaf ? undefined : [],
|
||||
};
|
||||
current.push(node);
|
||||
}
|
||||
if (isLeaf) {
|
||||
keyToPath[key] = f.path;
|
||||
} else if (node.children) {
|
||||
current = node.children;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { treeData: root, keyToPath };
|
||||
}
|
||||
|
||||
export interface FileIngestModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function FileIngestModal({
|
||||
open,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: FileIngestModalProps) {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [files, setFiles] = useState<KnowledgeFileItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
|
||||
|
||||
const { treeData, keyToPath } = useMemo(() => buildTreeData(files), [files]);
|
||||
|
||||
/** 打开时加载文件列表 */
|
||||
const loadFiles = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await listKnowledgeFiles();
|
||||
setFiles(data ?? []);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
// open 变为 true 时加载一次
|
||||
const [lastOpen, setLastOpen] = useState(false);
|
||||
if (open && !lastOpen) {
|
||||
setLastOpen(true);
|
||||
void loadFiles();
|
||||
}
|
||||
if (!open && lastOpen) {
|
||||
setLastOpen(false);
|
||||
}
|
||||
|
||||
/** 收集勾选的叶子节点(文件)的绝对路径 */
|
||||
const collectSelectedPaths = (): string[] => {
|
||||
return checkedKeys
|
||||
.map((k) => keyToPath[k])
|
||||
.filter((p): p is string => Boolean(p));
|
||||
};
|
||||
|
||||
/** 提交选中文件入库 */
|
||||
const handleSubmit = async () => {
|
||||
const paths = collectSelectedPaths();
|
||||
if (paths.length === 0) {
|
||||
messageApi.warning('请至少勾选一个文件');
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
messageApi.info(`开始向量化 ${paths.length} 个文件,请耐心等待…`);
|
||||
try {
|
||||
const result = await ingestSelectedFiles(paths);
|
||||
if (result.ingested_chunks > 0) {
|
||||
messageApi.success(
|
||||
`入库完成:${result.success_files}/${result.requested_files} 个文件,共 ${result.ingested_chunks} 个文本块`,
|
||||
);
|
||||
onSuccess();
|
||||
onClose();
|
||||
} else {
|
||||
messageApi.warning(result.warnings.join(';') || '未入库任何文本');
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const selectedCount = collectSelectedPaths().length;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="选择要向量化的文档"
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
width={640}
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={onClose}>取消</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
loading={submitting}
|
||||
disabled={selectedCount === 0}
|
||||
onClick={handleSubmit}
|
||||
>
|
||||
向量化选中项({selectedCount})
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: '100%' }} size="small">
|
||||
<Space>
|
||||
<Typography.Text type="secondary">
|
||||
来源目录:D:\Agent\需向量化数据(递归扫描)
|
||||
</Typography.Text>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => setCheckedKeys(Object.keys(keyToPath))}
|
||||
>
|
||||
全选
|
||||
</Button>
|
||||
<Button size="small" onClick={() => setCheckedKeys([])}>
|
||||
清空
|
||||
</Button>
|
||||
</Space>
|
||||
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
已选 {selectedCount} 个文件
|
||||
{selectedCount > 0 && (
|
||||
<span>
|
||||
;预计耗时 {Math.ceil(selectedCount * 3)}~
|
||||
{Math.ceil(selectedCount * 5)} 秒
|
||||
</span>
|
||||
)}
|
||||
;勾选目录会自动勾选其下全部文档
|
||||
</Typography.Text>
|
||||
|
||||
<div
|
||||
style={{
|
||||
maxHeight: 380,
|
||||
overflow: 'auto',
|
||||
border: '1px solid #f0f0f0',
|
||||
borderRadius: 6,
|
||||
padding: 8,
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<div style={{ textAlign: 'center', padding: 40 }}>
|
||||
<Spin tip="加载文件列表…" />
|
||||
</div>
|
||||
) : files.length === 0 ? (
|
||||
<Empty description="未发现可入库文档(支持 md/docx/pdf)" />
|
||||
) : (
|
||||
<Tree
|
||||
checkable
|
||||
defaultExpandAll
|
||||
showIcon
|
||||
selectable={false}
|
||||
treeData={treeData}
|
||||
checkedKeys={checkedKeys}
|
||||
onCheck={(keys) => {
|
||||
const list = Array.isArray(keys) ? keys : (keys as { checked: React.Key[] }).checked;
|
||||
setCheckedKeys(list.map((k) => String(k)));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* 图片识别页面组件
|
||||
*
|
||||
* 【功能说明】独立的图片内容识别模块:上传图片 → GLM-4V-Flash 识别 → 展示结果。
|
||||
* 可复制识别结果、多张批量识别、图片预览。
|
||||
* 【技术选型理由】AntD Upload + Card + Typography,与各管理页同构。
|
||||
* 【实现思路】上传图片到后端 → 调 /uploads/images/analyze → 展示识别文本。
|
||||
*/
|
||||
import {
|
||||
CopyOutlined,
|
||||
DeleteOutlined,
|
||||
PictureOutlined,
|
||||
ReloadOutlined,
|
||||
ScanOutlined,
|
||||
UploadOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Image,
|
||||
Input,
|
||||
Row,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Typography,
|
||||
Upload,
|
||||
} from 'antd';
|
||||
import { useState } from 'react';
|
||||
import { analyzeImages } from '../api/client';
|
||||
|
||||
interface UploadedImage {
|
||||
uid: string;
|
||||
name: string;
|
||||
url: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export default function ImageRecognition() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [images, setImages] = useState<UploadedImage[]>([]);
|
||||
const [analyzing, setAnalyzing] = useState(false);
|
||||
const [result, setResult] = useState('');
|
||||
const [customPrompt, setCustomPrompt] = useState('');
|
||||
|
||||
/** 上传图片 */
|
||||
const handleUpload = async (file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const resp = await fetch('/api/uploads/images', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.code === 0) {
|
||||
setImages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
uid: data.data.filename,
|
||||
name: file.name,
|
||||
url: data.data.url,
|
||||
size: data.data.size,
|
||||
},
|
||||
]);
|
||||
messageApi.success('图片上传成功');
|
||||
} else {
|
||||
messageApi.error(data.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除图片 */
|
||||
const handleRemove = (uid: string) => {
|
||||
setImages((prev) => prev.filter((img) => img.uid !== uid));
|
||||
};
|
||||
|
||||
/** 执行识别 */
|
||||
const handleAnalyze = async () => {
|
||||
if (images.length === 0) {
|
||||
messageApi.warning('请先上传图片');
|
||||
return;
|
||||
}
|
||||
setAnalyzing(true);
|
||||
setResult('');
|
||||
try {
|
||||
const urls = images.map((img) => img.url);
|
||||
const data = await analyzeImages(urls, customPrompt);
|
||||
setResult(data.description);
|
||||
messageApi.success(`识别完成(${data.count} 张图片)`);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setAnalyzing(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 复制识别结果 */
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText(result).then(() => {
|
||||
messageApi.success('已复制到剪贴板');
|
||||
});
|
||||
};
|
||||
|
||||
/** 清空 */
|
||||
const handleClear = () => {
|
||||
setImages([]);
|
||||
setResult('');
|
||||
setCustomPrompt('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
<PictureOutlined /> 图片识别
|
||||
</Typography.Title>
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={handleClear}>
|
||||
清空
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<ScanOutlined />}
|
||||
loading={analyzing}
|
||||
disabled={images.length === 0}
|
||||
onClick={handleAnalyze}
|
||||
>
|
||||
开始识别({images.length} 张)
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
<Row gutter={16}>
|
||||
{/* 左侧:上传与图片列表 */}
|
||||
<Col span={10}>
|
||||
<Card size="small" title="上传图片" style={{ marginBottom: 16 }}>
|
||||
<Upload
|
||||
accept=".png,.jpg,.jpeg,.gif,.bmp,.webp"
|
||||
listType="picture-card"
|
||||
maxCount={10}
|
||||
showUploadList={false}
|
||||
beforeUpload={(file) => {
|
||||
handleUpload(file);
|
||||
return false; // 阻止自动上传,手动控制
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<UploadOutlined />
|
||||
<div style={{ marginTop: 8, fontSize: 12 }}>点击或拖拽上传</div>
|
||||
</div>
|
||||
</Upload>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
支持 PNG/JPG/GIF/WebP,单张 ≤ 10MB,最多 10 张
|
||||
</Typography.Text>
|
||||
</Card>
|
||||
|
||||
{images.length > 0 && (
|
||||
<Card size="small" title={`已上传图片(${images.length})`}>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
{images.map((img) => (
|
||||
<div
|
||||
key={img.uid}
|
||||
style={{
|
||||
position: 'relative',
|
||||
width: 80,
|
||||
height: 80,
|
||||
borderRadius: 6,
|
||||
overflow: 'hidden',
|
||||
border: '1px solid #d9d9d9',
|
||||
}}
|
||||
>
|
||||
<Image
|
||||
src={img.url}
|
||||
alt={img.name}
|
||||
width={80}
|
||||
height={80}
|
||||
style={{ objectFit: 'cover' }}
|
||||
preview={{ mask: '预览' }}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<DeleteOutlined />}
|
||||
danger
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
right: 0,
|
||||
background: 'rgba(255,255,255,0.8)',
|
||||
}}
|
||||
onClick={() => handleRemove(img.uid)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card size="small" title="自定义提示词(可选)" style={{ marginTop: 16 }}>
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
placeholder="留空则默认识别图片全部内容。可自定义,如:只提取错误信息 / 描述UI布局"
|
||||
value={customPrompt}
|
||||
onChange={(e) => setCustomPrompt(e.target.value)}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
|
||||
{/* 右侧:识别结果 */}
|
||||
<Col span={14}>
|
||||
<Card
|
||||
size="small"
|
||||
title={
|
||||
<Space>
|
||||
<ScanOutlined />
|
||||
<span>识别结果</span>
|
||||
{result && <Tag color="green">识别完成</Tag>}
|
||||
</Space>
|
||||
}
|
||||
extra={
|
||||
result && (
|
||||
<Button size="small" icon={<CopyOutlined />} onClick={handleCopy}>
|
||||
复制结果
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
style={{ minHeight: 500 }}
|
||||
>
|
||||
{analyzing ? (
|
||||
<div style={{ textAlign: 'center', padding: 80 }}>
|
||||
<Spin tip="正在识别图片内容…" size="large" />
|
||||
</div>
|
||||
) : result ? (
|
||||
<Typography.Paragraph
|
||||
style={{ whiteSpace: 'pre-wrap', fontSize: 14, lineHeight: 1.8 }}
|
||||
>
|
||||
{result}
|
||||
</Typography.Paragraph>
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 80, color: '#999' }}>
|
||||
<PictureOutlined style={{ fontSize: 48, marginBottom: 16 }} />
|
||||
<br />
|
||||
上传图片后点击「开始识别」,AI 将分析图片内容
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* 知识库管理页面组件
|
||||
*
|
||||
* 【功能说明】提供知识库的入库、重建、检索、统计能力,
|
||||
* 对应《核心诉求》文档知识管理模块的可视化入口。
|
||||
* 【技术选型理由】AntD Card + List + Input.Search + Table 组合,
|
||||
* 与项目管理页同构,保证交互一致性。
|
||||
* 【实现思路】
|
||||
* - 顶部:统计卡片(chunk 总数、向量化实现);
|
||||
* - 中部:入库/重建按钮 + 检索框;
|
||||
* - 下部:检索结果列表(带来源与相关度)。
|
||||
* - 【入库】按钮改为弹出 FileIngestModal:勾选文件后批量向量化(M6 方案 ③)。
|
||||
* 【潜在风险与应对】
|
||||
* 风险1:入库耗时长(按文件数预估 3-5 秒/篇)。
|
||||
* 应对:Modal 内按钮 loading + 预估耗时提示。
|
||||
* 风险2:检索无结果。
|
||||
* 应对:空态提示「请先执行入库」,不展示空白列表。
|
||||
*/
|
||||
import {
|
||||
DatabaseOutlined,
|
||||
FileAddOutlined,
|
||||
ReloadOutlined,
|
||||
SearchOutlined,
|
||||
ThunderboltOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Input,
|
||||
List,
|
||||
Popconfirm,
|
||||
Row,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
getKnowledgeStats,
|
||||
queryKnowledge,
|
||||
rebuildKnowledge,
|
||||
} from '../api/client';
|
||||
import type { KnowledgeHit, KnowledgeStats } from '../types';
|
||||
import FileIngestModal from './FileIngestModal';
|
||||
|
||||
export default function KnowledgeList() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [stats, setStats] = useState<KnowledgeStats | null>(null);
|
||||
const [hits, setHits] = useState<KnowledgeHit[]>([]);
|
||||
const [loadingStats, setLoadingStats] = useState(false);
|
||||
const [ingesting, setIngesting] = useState(false);
|
||||
const [querying, setQuerying] = useState(false);
|
||||
const [question, setQuestion] = useState('');
|
||||
const [ingestModalOpen, setIngestModalOpen] = useState(false);
|
||||
|
||||
/** 加载统计 */
|
||||
const loadStats = useCallback(async () => {
|
||||
setLoadingStats(true);
|
||||
try {
|
||||
const data = await getKnowledgeStats();
|
||||
setStats(data);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoadingStats(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
loadStats();
|
||||
}, [loadStats]);
|
||||
|
||||
/** 入库:打开文件选择弹窗(M6 方案 ③) */
|
||||
const openIngestModal = () => {
|
||||
setIngestModalOpen(true);
|
||||
};
|
||||
|
||||
/** 重建索引(全量清空后重建) */
|
||||
const handleRebuild = async () => {
|
||||
setIngesting(true);
|
||||
messageApi.info('重建索引中,约需 1 分钟…');
|
||||
try {
|
||||
const result = await rebuildKnowledge();
|
||||
messageApi.success(`重建完成:${result.ingested_chunks} 个文本块`);
|
||||
await loadStats();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setIngesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 检索 */
|
||||
const handleQuery = async () => {
|
||||
if (!question.trim()) {
|
||||
messageApi.warning('请输入检索问题');
|
||||
return;
|
||||
}
|
||||
setQuerying(true);
|
||||
try {
|
||||
const data = await queryKnowledge(question.trim(), 5);
|
||||
setHits(data ?? []);
|
||||
if (!data || data.length === 0) {
|
||||
messageApi.info('无匹配结果,请确认已执行入库');
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setQuerying(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Typography.Title level={4}>知识库管理</Typography.Title>
|
||||
|
||||
{/* 统计卡片 */}
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={8}>
|
||||
<Card loading={loadingStats} size="small">
|
||||
<Space>
|
||||
<DatabaseOutlined style={{ fontSize: 24, color: '#1677ff' }} />
|
||||
<div>
|
||||
<div style={{ color: '#999', fontSize: 12 }}>文本块总数</div>
|
||||
<div style={{ fontSize: 24, fontWeight: 600 }}>
|
||||
{stats?.total_chunks ?? 0}
|
||||
</div>
|
||||
</div>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Card loading={loadingStats} size="small">
|
||||
<Space>
|
||||
<ThunderboltOutlined style={{ fontSize: 24, color: '#52c41a' }} />
|
||||
<div>
|
||||
<div style={{ color: '#999', fontSize: 12 }}>向量化实现</div>
|
||||
<div style={{ fontSize: 16, fontWeight: 600 }}>
|
||||
<Tag color="green">{stats?.embedding_provider ?? '-'}</Tag>
|
||||
</div>
|
||||
</div>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Card size="small">
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<FileAddOutlined />}
|
||||
onClick={openIngestModal}
|
||||
block
|
||||
>
|
||||
入库(选择文档)
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认重建整个知识库索引?"
|
||||
description="会清空现有向量数据后重新解析全部素材,约需 1 分钟"
|
||||
onConfirm={handleRebuild}
|
||||
okText="确认重建"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button icon={<ReloadOutlined />} loading={ingesting} block>
|
||||
重建索引(全量)
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 检索区 */}
|
||||
<Card
|
||||
title="知识检索"
|
||||
size="small"
|
||||
extra={
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SearchOutlined />}
|
||||
loading={querying}
|
||||
onClick={handleQuery}
|
||||
>
|
||||
检索
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Input.Search
|
||||
placeholder="用自然语言提问,如:网关离线怎么排查"
|
||||
value={question}
|
||||
onChange={(e) => setQuestion(e.target.value)}
|
||||
onSearch={handleQuery}
|
||||
enterButton={<SearchOutlined />}
|
||||
loading={querying}
|
||||
size="large"
|
||||
/>
|
||||
|
||||
<div style={{ marginTop: 16 }}>
|
||||
{querying ? (
|
||||
<div style={{ textAlign: 'center', padding: 40 }}>
|
||||
<Spin tip="检索中…" />
|
||||
</div>
|
||||
) : hits.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
|
||||
暂无检索结果,请先执行入库后提问
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
itemLayout="vertical"
|
||||
dataSource={hits}
|
||||
renderItem={(item, index) => (
|
||||
<List.Item key={index}>
|
||||
<List.Item.Meta
|
||||
title={
|
||||
<Space>
|
||||
<Tag color="blue">{index + 1}</Tag>
|
||||
<Typography.Text strong>
|
||||
{item.filename || '未知来源'}
|
||||
</Typography.Text>
|
||||
{item.score !== null && item.score !== undefined && (
|
||||
<Tag color={item.score < 0.6 ? 'green' : 'orange'}>
|
||||
相关度 {(1 - item.score).toFixed(2)}
|
||||
</Tag>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
description={
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
来源:{item.source}
|
||||
{item.metadata?.section ? ` · ${item.metadata.section}` : ''}
|
||||
</Typography.Text>
|
||||
}
|
||||
/>
|
||||
<Typography.Paragraph
|
||||
style={{ marginBottom: 0, whiteSpace: 'pre-wrap' }}
|
||||
>
|
||||
{item.text}
|
||||
</Typography.Paragraph>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* 文件选择入库弹窗(M6 方案 ③) */}
|
||||
<FileIngestModal
|
||||
open={ingestModalOpen}
|
||||
onClose={() => setIngestModalOpen(false)}
|
||||
onSuccess={loadStats}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
/**
|
||||
* 模型配置管理页面组件
|
||||
*
|
||||
* 【功能说明】对模型偏好配置做增删改查,支持启用/停用、排序、备注。
|
||||
* 对应用户需求:模型偏好可配置化(不再硬编码)。
|
||||
* 【技术选型理由】AntD Table + Modal Form + Switch + Popconfirm,与项目管理页同构。
|
||||
* 【安全设计】API key 不在前端展示/编辑,只配置 provider_key 引用。
|
||||
* 【实现思路】列表 + 新建/编辑弹窗 + 删除确认 + 启用开关。
|
||||
* 【潜在风险与应对】
|
||||
* 风险1:用户删光所有模型导致下拉框无选项。
|
||||
* 应对:保留「auto」固定选项,删除最后一个模型时提示。
|
||||
* 风险2:model_id 拼错导致调用失败。
|
||||
* 应对:表单提示「需与 ccswitch 配置的模型 ID 一致」。
|
||||
*/
|
||||
import {
|
||||
ApiOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
Table,
|
||||
Tabs,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
createModelConfig,
|
||||
deleteModelConfig,
|
||||
listModelConfigs,
|
||||
updateModelConfig,
|
||||
} from '../api/client';
|
||||
import ProviderManager from './ProviderManager';
|
||||
import FallbackChain from './FallbackChain';
|
||||
import type { ModelConfig, ModelConfigPayload } from '../types';
|
||||
|
||||
/** 模型角色选项 */
|
||||
const ROLE_OPTIONS = [
|
||||
{ label: '强模型(改码/评估)', value: 'strong' },
|
||||
{ label: '弱模型(解析/报告)', value: 'weak' },
|
||||
{ label: '通用', value: 'general' },
|
||||
];
|
||||
|
||||
/** 初始表单值 */
|
||||
const INITIAL_VALUES: ModelConfigPayload = {
|
||||
display_name: '',
|
||||
model_id: '',
|
||||
provider_key: 'ccswitch',
|
||||
model_role: 'general',
|
||||
is_enabled: true,
|
||||
sort_order: 50,
|
||||
description: '',
|
||||
};
|
||||
|
||||
export default function ModelManager() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [configs, setConfigs] = useState<ModelConfig[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<ModelConfig | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [form] = Form.useForm<ModelConfigPayload>();
|
||||
|
||||
/** 加载配置列表 */
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await listModelConfigs();
|
||||
setConfigs(data ?? []);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
/** 打开新建弹窗 */
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
form.setFieldsValue(INITIAL_VALUES);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
/** 打开编辑弹窗 */
|
||||
const openEdit = (record: ModelConfig) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
display_name: record.display_name,
|
||||
model_id: record.model_id,
|
||||
provider_key: record.provider_key,
|
||||
model_role: record.model_role,
|
||||
is_enabled: record.is_enabled,
|
||||
sort_order: record.sort_order,
|
||||
description: record.description,
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
/** 提交表单 */
|
||||
const handleSubmit = async () => {
|
||||
const values = await form.validateFields();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await updateModelConfig(editing.id, values);
|
||||
messageApi.success('模型配置更新成功');
|
||||
} else {
|
||||
await createModelConfig(values);
|
||||
messageApi.success('模型配置创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除配置 */
|
||||
const handleDelete = async (record: ModelConfig) => {
|
||||
try {
|
||||
await deleteModelConfig(record.id);
|
||||
messageApi.success('删除成功');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 启用/停用切换 */
|
||||
const handleToggle = async (record: ModelConfig, checked: boolean) => {
|
||||
try {
|
||||
await updateModelConfig(record.id, { is_enabled: checked });
|
||||
messageApi.success(checked ? '已启用' : '已停用');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 表格列定义 */
|
||||
const columns: ColumnsType<ModelConfig> = [
|
||||
{
|
||||
title: '排序',
|
||||
dataIndex: 'sort_order',
|
||||
key: 'sort_order',
|
||||
width: 70,
|
||||
sorter: (a, b) => a.sort_order - b.sort_order,
|
||||
},
|
||||
{
|
||||
title: '显示名称',
|
||||
dataIndex: 'display_name',
|
||||
key: 'display_name',
|
||||
render: (v: string) => <Typography.Text strong>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '模型 ID',
|
||||
dataIndex: 'model_id',
|
||||
key: 'model_id',
|
||||
width: 160,
|
||||
render: (v: string) => <Typography.Text code>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: 'Provider',
|
||||
dataIndex: 'provider_key',
|
||||
key: 'provider_key',
|
||||
width: 110,
|
||||
render: (v: string) => (
|
||||
<Tag color={v === 'ccswitch' ? 'blue' : 'green'}>{v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'model_role',
|
||||
key: 'model_role',
|
||||
width: 110,
|
||||
render: (v: string) => {
|
||||
const colors: Record<string, string> = {
|
||||
strong: 'red',
|
||||
weak: 'cyan',
|
||||
general: 'default',
|
||||
};
|
||||
const labels: Record<string, string> = {
|
||||
strong: '强模型',
|
||||
weak: '弱模型',
|
||||
general: '通用',
|
||||
};
|
||||
return <Tag color={colors[v] || 'default'}>{labels[v] || v}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '启用',
|
||||
key: 'is_enabled',
|
||||
width: 80,
|
||||
render: (_, record) => (
|
||||
<Switch
|
||||
size="small"
|
||||
checked={record.is_enabled}
|
||||
onChange={(checked) => handleToggle(record, checked)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'description',
|
||||
key: 'description',
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 140,
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => openEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除该模型配置?"
|
||||
onConfirm={() => handleDelete(record)}
|
||||
okText="确认"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button type="link" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Typography.Title level={4}>
|
||||
<ApiOutlined /> 模型配置管理
|
||||
</Typography.Title>
|
||||
<Typography.Paragraph type="secondary" style={{ marginBottom: 16 }}>
|
||||
Provider 管理 AI 平台连接(服务地址+密钥),模型配置定义可用模型(含角色/排序)。
|
||||
提交任务时从这里选择模型。
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Tabs
|
||||
defaultActiveKey="providers"
|
||||
onChange={(key) => {
|
||||
// 切换到模型配置 Tab 时自动刷新(拉取/启用模型后无需手点刷新)
|
||||
if (key === 'models') {
|
||||
load();
|
||||
}
|
||||
}}
|
||||
items={[
|
||||
{
|
||||
key: 'providers',
|
||||
label: 'Provider 管理',
|
||||
children: <ProviderManager />,
|
||||
},
|
||||
{
|
||||
key: 'models',
|
||||
label: '模型配置',
|
||||
children: (
|
||||
<>
|
||||
<Space style={{ marginBottom: 12, width: '100%', justifyContent: 'flex-end' }}>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
|
||||
新增模型
|
||||
</Button>
|
||||
</Space>
|
||||
<Table<ModelConfig>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={configs}
|
||||
pagination={{ pageSize: 10, showTotal: (t) => `共 ${t} 个模型` }}
|
||||
size="small"
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'fallback',
|
||||
label: '降级链',
|
||||
children: <FallbackChain />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
{/* 新建/编辑弹窗 */}
|
||||
<Modal
|
||||
title={editing ? '编辑模型配置' : '新增模型配置'}
|
||||
open={modalOpen}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={submitting}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
width={560}
|
||||
>
|
||||
<Form form={form} layout="vertical" initialValues={INITIAL_VALUES}>
|
||||
<Form.Item
|
||||
name="display_name"
|
||||
label="显示名称"
|
||||
rules={[{ required: true, message: '请输入显示名称' }]}
|
||||
extra="前端下拉框展示的名称"
|
||||
>
|
||||
<Input placeholder="如:GLM-5.3 — 强模型" maxLength={100} />
|
||||
</Form.Item>
|
||||
|
||||
<div style={{ display: 'flex', gap: 16 }}>
|
||||
<Form.Item
|
||||
name="model_id"
|
||||
label="模型 ID"
|
||||
style={{ flex: 1, marginBottom: 16 }}
|
||||
extra="来自 Provider 拉取,不可修改"
|
||||
>
|
||||
<Input disabled maxLength={100} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="provider_key"
|
||||
label="Provider"
|
||||
style={{ flex: 1, marginBottom: 16 }}
|
||||
extra="来自 Provider 拉取,不可修改"
|
||||
>
|
||||
<Input disabled />
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 16 }}>
|
||||
<Form.Item name="model_role" label="模型角色" style={{ flex: 1, marginBottom: 16 }}>
|
||||
<Select options={ROLE_OPTIONS} />
|
||||
</Form.Item>
|
||||
<Form.Item name="sort_order" label="排序值" style={{ flex: 1, marginBottom: 16 }}>
|
||||
<InputNumber min={0} max={999} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<Form.Item name="description" label="备注">
|
||||
<Input.TextArea rows={2} maxLength={200} placeholder="备注说明" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="is_enabled"
|
||||
label="启用状态"
|
||||
valuePropName="checked"
|
||||
extra="停用后不出现在提交任务的下拉框中"
|
||||
>
|
||||
<Switch checkedChildren="启用" unCheckedChildren="停用" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
/**
|
||||
* 监控仪表盘页面组件
|
||||
*
|
||||
* 【功能说明】展示模型调用统计(token/成本/延迟/次数)+ 任务状态分布 + 系统健康。
|
||||
* 【技术选型理由】AntD Card + Table + Statistic + Progress,与各管理页同构。
|
||||
*/
|
||||
import {
|
||||
CheckCircleOutlined,
|
||||
ClockCircleOutlined,
|
||||
DollarOutlined,
|
||||
FireOutlined,
|
||||
ReloadOutlined,
|
||||
RobotOutlined,
|
||||
ThunderboltOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Progress,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Statistic,
|
||||
Table,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { getCostForecast, getHealthCheck, getMetricsDashboard, getMetricsTrend } from '../api/client';
|
||||
|
||||
interface ModelStats {
|
||||
model: string;
|
||||
provider?: string;
|
||||
calls: number;
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
total_tokens: number;
|
||||
cost: number;
|
||||
avg_latency_ms: number;
|
||||
success_rate: number;
|
||||
}
|
||||
|
||||
interface ProviderStats {
|
||||
provider: string;
|
||||
calls: number;
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
total_tokens: number;
|
||||
cost: number;
|
||||
avg_latency_ms: number;
|
||||
success_rate: number;
|
||||
models: string[];
|
||||
}
|
||||
|
||||
interface DashboardData {
|
||||
period_hours: number;
|
||||
model_stats: ModelStats[];
|
||||
provider_stats: ProviderStats[];
|
||||
task_stats: {
|
||||
total: number;
|
||||
status_distribution: Record<string, number>;
|
||||
avg_duration_s: number;
|
||||
};
|
||||
totals: {
|
||||
model_calls: number;
|
||||
total_tokens: number;
|
||||
total_cost: number;
|
||||
avg_latency_ms: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface HealthCheck {
|
||||
name: string;
|
||||
status: string;
|
||||
message: string;
|
||||
latency_ms: number;
|
||||
}
|
||||
|
||||
export default function MonitorDashboard() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [dashboard, setDashboard] = useState<DashboardData | null>(null);
|
||||
const [health, setHealth] = useState<{ status: string; checks: HealthCheck[] } | null>(null);
|
||||
const [trend, setTrend] = useState<{
|
||||
daily: { date: string; calls: number; total_tokens: number; cost: number; avg_latency_ms: number }[];
|
||||
summary: { avg_daily_cost: number; avg_daily_calls: number; peak_day: { date: string; cost: number; calls: number } | null; total_days: number };
|
||||
} | null>(null);
|
||||
const [forecast, setForecast] = useState<{
|
||||
forecast_30d: number;
|
||||
avg_daily_cost: number;
|
||||
basis_days: number;
|
||||
} | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [hours, setHours] = useState(24);
|
||||
// 趋势天数由顶部时间选择器推导(hours / 24)
|
||||
const trendDays = Math.max(1, Math.round(hours / 24));
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [dash, healthData, trendData, forecastData] = await Promise.all([
|
||||
getMetricsDashboard(hours),
|
||||
getHealthCheck(),
|
||||
getMetricsTrend(trendDays),
|
||||
getCostForecast(trendDays),
|
||||
]);
|
||||
setDashboard(dash);
|
||||
setHealth(healthData);
|
||||
setTrend(trendData);
|
||||
setForecast(forecastData);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [hours, messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
/** 模型统计表格列 */
|
||||
const modelColumns: ColumnsType<ModelStats> = [
|
||||
{
|
||||
title: '模型',
|
||||
dataIndex: 'model',
|
||||
key: 'model',
|
||||
render: (v: string) => (
|
||||
<Space>
|
||||
<RobotOutlined style={{ color: '#1677ff' }} />
|
||||
<Typography.Text code>{v}</Typography.Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '调用次数',
|
||||
dataIndex: 'calls',
|
||||
key: 'calls',
|
||||
width: 100,
|
||||
},
|
||||
{
|
||||
title: '输入 Tokens',
|
||||
dataIndex: 'input_tokens',
|
||||
key: 'input_tokens',
|
||||
width: 120,
|
||||
render: (v: number) => v.toLocaleString(),
|
||||
},
|
||||
{
|
||||
title: '输出 Tokens',
|
||||
dataIndex: 'output_tokens',
|
||||
key: 'output_tokens',
|
||||
width: 120,
|
||||
render: (v: number) => v.toLocaleString(),
|
||||
},
|
||||
{
|
||||
title: '总 Tokens',
|
||||
dataIndex: 'total_tokens',
|
||||
key: 'total_tokens',
|
||||
width: 120,
|
||||
render: (v: number) => v.toLocaleString(),
|
||||
},
|
||||
{
|
||||
title: '成本(元)',
|
||||
dataIndex: 'cost',
|
||||
key: 'cost',
|
||||
width: 100,
|
||||
render: (v: number) => (
|
||||
<Typography.Text type="warning">¥{v.toFixed(4)}</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '平均延迟',
|
||||
dataIndex: 'avg_latency_ms',
|
||||
key: 'avg_latency_ms',
|
||||
width: 100,
|
||||
render: (v: number) => `${(v / 1000).toFixed(1)}s`,
|
||||
},
|
||||
{
|
||||
title: '成功率',
|
||||
dataIndex: 'success_rate',
|
||||
key: 'success_rate',
|
||||
width: 120,
|
||||
render: (v: number) => (
|
||||
<Progress
|
||||
percent={v}
|
||||
size="small"
|
||||
status={v >= 95 ? 'success' : v >= 80 ? 'normal' : 'exception'}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
done: 'green',
|
||||
running: 'blue',
|
||||
failed: 'red',
|
||||
degraded: 'orange',
|
||||
waiting_approval: 'gold',
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
<FireOutlined /> 监控仪表盘
|
||||
</Typography.Title>
|
||||
<Space>
|
||||
<Select
|
||||
value={hours}
|
||||
onChange={(v) => setHours(v)}
|
||||
style={{ width: 140 }}
|
||||
options={[
|
||||
{ label: '最近 1 小时', value: 1 },
|
||||
{ label: '最近 6 小时', value: 6 },
|
||||
{ label: '最近 24 小时', value: 24 },
|
||||
{ label: '最近 7 天', value: 168 },
|
||||
{ label: '最近 14 天', value: 336 },
|
||||
{ label: '最近 30 天', value: 720 },
|
||||
]}
|
||||
/>
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>
|
||||
刷新
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
{/* 系统健康 */}
|
||||
{health && (
|
||||
<Card
|
||||
size="small"
|
||||
title={
|
||||
<Space>
|
||||
<CheckCircleOutlined
|
||||
style={{
|
||||
color:
|
||||
health.status === 'healthy'
|
||||
? '#52c41a'
|
||||
: health.status === 'degraded'
|
||||
? '#faad14'
|
||||
: '#cf1322',
|
||||
}}
|
||||
/>
|
||||
<span>系统健康</span>
|
||||
<Tag
|
||||
color={
|
||||
health.status === 'healthy'
|
||||
? 'green'
|
||||
: health.status === 'degraded'
|
||||
? 'orange'
|
||||
: 'red'
|
||||
}
|
||||
>
|
||||
{health.status}
|
||||
</Tag>
|
||||
</Space>
|
||||
}
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<Row gutter={16}>
|
||||
{health.checks.map((check) => (
|
||||
<Col span={4} key={check.name}>
|
||||
<Space direction="vertical" size={4}>
|
||||
<Tag
|
||||
color={
|
||||
check.status === 'healthy'
|
||||
? 'green'
|
||||
: check.status === 'degraded'
|
||||
? 'orange'
|
||||
: 'red'
|
||||
}
|
||||
>
|
||||
{check.name}
|
||||
</Tag>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
{check.message}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 总览卡片 */}
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="模型调用次数"
|
||||
value={dashboard?.totals?.model_calls ?? 0}
|
||||
prefix={<RobotOutlined />}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="Token 总消耗"
|
||||
value={dashboard?.totals?.total_tokens ?? 0}
|
||||
prefix={<ThunderboltOutlined />}
|
||||
valueStyle={{ color: '#1677ff' }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="预估成本(元)"
|
||||
value={dashboard?.totals?.total_cost ?? 0}
|
||||
precision={4}
|
||||
prefix={<DollarOutlined />}
|
||||
valueStyle={{ color: '#cf1322' }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="平均延迟"
|
||||
value={((dashboard?.totals?.avg_latency_ms ?? 0) / 1000).toFixed(1)}
|
||||
suffix="秒"
|
||||
prefix={<ClockCircleOutlined />}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 用量趋势 + 成本预测(B2:用量深度分析) */}
|
||||
{trend && (
|
||||
<Card
|
||||
size="small"
|
||||
title="用量趋势"
|
||||
style={{ marginBottom: 16 }}
|
||||
extra={
|
||||
forecast && (
|
||||
<Space>
|
||||
<Tag color="blue">日均 ¥{forecast.avg_daily_cost}</Tag>
|
||||
<Tag color="red">30 天预测 ¥{forecast.forecast_30d}</Tag>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
>
|
||||
{/* 柱状图(CSS 实现) */}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-end',
|
||||
gap: 8,
|
||||
height: 160,
|
||||
padding: '0 8px',
|
||||
borderBottom: '1px solid #f0f0f0',
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
{trend.daily.map((d) => {
|
||||
const maxCost = Math.max(...trend.daily.map((x) => x.cost), 0.01);
|
||||
const heightPercent = (d.cost / maxCost) * 100;
|
||||
return (
|
||||
<div
|
||||
key={d.date}
|
||||
style={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
gap: 4,
|
||||
}}
|
||||
>
|
||||
<Tooltip title={`${d.date}: ¥${d.cost} | ${d.calls} 次`}>
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
height: `${Math.max(heightPercent, 4)}%`,
|
||||
background:
|
||||
d.cost === Math.max(...trend.daily.map((x) => x.cost))
|
||||
? '#ff4d4f'
|
||||
: '#1677ff',
|
||||
borderRadius: '4px 4px 0 0',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Typography.Text style={{ fontSize: 10 }}>
|
||||
{d.date.slice(5)}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 汇总信息 */}
|
||||
<Row gutter={16}>
|
||||
<Col span={6}>
|
||||
<Statistic title="日均成本" value={trend.summary.avg_daily_cost} precision={4} prefix="¥" />
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Statistic title="日均调用" value={Math.round(trend.summary.avg_daily_calls)} />
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
{trend.summary.peak_day && (
|
||||
<Statistic
|
||||
title={`峰值(${trend.summary.peak_day.date})`}
|
||||
value={trend.summary.peak_day.cost}
|
||||
precision={4}
|
||||
prefix="¥"
|
||||
valueStyle={{ color: '#cf1322' }}
|
||||
/>
|
||||
)}
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
{forecast && (
|
||||
<Statistic
|
||||
title="30 天成本预测"
|
||||
value={forecast.forecast_30d}
|
||||
precision={2}
|
||||
prefix="¥"
|
||||
valueStyle={{ color: '#fa8c16' }}
|
||||
/>
|
||||
)}
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Provider 用量总览(痛点 1:多平台用量统一查看) */}
|
||||
<Card
|
||||
size="small"
|
||||
title="Provider 用量总览"
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<Table<ProviderStats>
|
||||
rowKey="provider"
|
||||
loading={loading}
|
||||
dataSource={dashboard?.provider_stats ?? []}
|
||||
pagination={false}
|
||||
size="small"
|
||||
locale={{ emptyText: '暂无用量数据' }}
|
||||
columns={[
|
||||
{
|
||||
title: 'Provider',
|
||||
dataIndex: 'provider',
|
||||
key: 'provider',
|
||||
width: 140,
|
||||
render: (v: string) => (
|
||||
<Tag color="blue">{v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '调用次数',
|
||||
dataIndex: 'calls',
|
||||
key: 'calls',
|
||||
width: 100,
|
||||
},
|
||||
{
|
||||
title: '总 Tokens',
|
||||
dataIndex: 'total_tokens',
|
||||
key: 'total_tokens',
|
||||
width: 120,
|
||||
render: (v: number) => v.toLocaleString(),
|
||||
},
|
||||
{
|
||||
title: '成本(元)',
|
||||
dataIndex: 'cost',
|
||||
key: 'cost',
|
||||
width: 100,
|
||||
render: (v: number) => (
|
||||
<Typography.Text type="warning">¥{v.toFixed(4)}</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '平均延迟',
|
||||
dataIndex: 'avg_latency_ms',
|
||||
key: 'avg_latency_ms',
|
||||
width: 100,
|
||||
render: (v: number) => `${(v / 1000).toFixed(1)}s`,
|
||||
},
|
||||
{
|
||||
title: '成功率',
|
||||
dataIndex: 'success_rate',
|
||||
key: 'success_rate',
|
||||
width: 120,
|
||||
render: (v: number) => (
|
||||
<Progress
|
||||
percent={v}
|
||||
size="small"
|
||||
status={v >= 95 ? 'success' : v >= 80 ? 'normal' : 'exception'}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '包含模型',
|
||||
dataIndex: 'models',
|
||||
key: 'models',
|
||||
ellipsis: true,
|
||||
render: (v: string[]) => (
|
||||
<Space size={4} wrap>
|
||||
{v.map((m) => (
|
||||
<Tag key={m} style={{ fontSize: 11 }}>{m}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* 模型统计表格 */}
|
||||
<Card
|
||||
size="small"
|
||||
title="模型调用明细"
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<Table<ModelStats>
|
||||
rowKey="model"
|
||||
loading={loading}
|
||||
columns={modelColumns}
|
||||
dataSource={dashboard?.model_stats ?? []}
|
||||
pagination={false}
|
||||
size="small"
|
||||
locale={{ emptyText: '暂无模型调用记录' }}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* 任务状态分布 */}
|
||||
<Card size="small" title="任务执行统计">
|
||||
<Row gutter={16}>
|
||||
<Col span={6}>
|
||||
<Statistic
|
||||
title="任务总数"
|
||||
value={dashboard?.task_stats?.total ?? 0}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Statistic
|
||||
title="平均耗时"
|
||||
value={dashboard?.task_stats?.avg_duration_s ?? 0}
|
||||
suffix="秒"
|
||||
/>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Typography.Text type="secondary">状态分布:</Typography.Text>
|
||||
<Space size={8} wrap style={{ marginTop: 8 }}>
|
||||
{Object.entries(dashboard?.task_stats?.status_distribution ?? {}).map(
|
||||
([status, count]) => (
|
||||
<Tag key={status} color={statusColors[status] || 'default'}>
|
||||
{status}: {count}
|
||||
</Tag>
|
||||
),
|
||||
)}
|
||||
</Space>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,861 @@
|
||||
/**
|
||||
* 平台账号管理页面组件
|
||||
*
|
||||
* 【功能说明】管理多平台多账号的控制台访问,登录保存 Cookie,自动抓取用量。
|
||||
* 对应痛点:登录各平台看用量太麻烦 → Agent 统一管理 + 自动抓取。
|
||||
* 【技术选型理由】AntD Table + Modal + Card,与各管理页同构。
|
||||
*/
|
||||
import {
|
||||
CloudDownloadOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
GlobalOutlined,
|
||||
LoginOutlined,
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Alert,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Progress,
|
||||
Row,
|
||||
Space,
|
||||
Steps,
|
||||
Switch,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import dayjs from 'dayjs';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
clearLoginExpired,
|
||||
createPlatformAccount,
|
||||
deletePlatformAccount,
|
||||
getLoginExpired,
|
||||
getPlatformUsage,
|
||||
getScrapeProgress,
|
||||
getScrapeSchedule,
|
||||
listPlatformAccounts,
|
||||
cancelLogin,
|
||||
finishLogin,
|
||||
scrapeAllPlatformAccounts,
|
||||
scrapePlatformAccount,
|
||||
startLogin,
|
||||
triggerScrapeNow,
|
||||
updatePlatformAccount,
|
||||
updateScrapeSchedule,
|
||||
} from '../api/client';
|
||||
|
||||
interface PlatformAccount {
|
||||
id: string;
|
||||
brand: string;
|
||||
account_name: string;
|
||||
plan_name: string;
|
||||
console_url: string;
|
||||
description: string;
|
||||
is_active: boolean;
|
||||
has_cookies: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface UsageSnapshot {
|
||||
usage_percent: number;
|
||||
used_amount: string;
|
||||
total_amount: string;
|
||||
remain_amount: string;
|
||||
expire_date: string;
|
||||
captured_at: string;
|
||||
usage_5h?: string;
|
||||
usage_1w?: string;
|
||||
usage_1m?: string;
|
||||
reset_5h?: string;
|
||||
reset_1w?: string;
|
||||
reset_1m?: string;
|
||||
valid_until?: string;
|
||||
}
|
||||
|
||||
export default function PlatformManager() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [accounts, setAccounts] = useState<PlatformAccount[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<PlatformAccount | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [scraping, setScraping] = useState<string>('');
|
||||
const [scrapingAll, setScrapingAll] = useState(false);
|
||||
// 定时抓取配置
|
||||
const [scheduleConfig, setScheduleConfig] = useState<{
|
||||
enabled: boolean;
|
||||
interval_minutes: number;
|
||||
account_ids: string[];
|
||||
last_run_at: string;
|
||||
last_run_result: string;
|
||||
scheduler_running: boolean;
|
||||
login_detect_enabled: boolean;
|
||||
login_detect_interval: number;
|
||||
} | null>(null);
|
||||
const [scheduleLoading, setScheduleLoading] = useState(false);
|
||||
const [triggering, setTriggering] = useState(false);
|
||||
// 抓取进度
|
||||
const [scrapeProgress, setScrapeProgress] = useState<{
|
||||
running: boolean;
|
||||
total: number;
|
||||
completed: number;
|
||||
current_account: string;
|
||||
} | null>(null);
|
||||
const [progressOpen, setProgressOpen] = useState(false);
|
||||
const [usages, setUsages] = useState<Record<string, UsageSnapshot>>({});
|
||||
// 登录引导弹框(两步式)
|
||||
const [loginModalOpen, setLoginModalOpen] = useState(false);
|
||||
const [loginAccount, setLoginAccount] = useState<PlatformAccount | null>(null);
|
||||
const [loginStep, setLoginStep] = useState(0); // 0=引导 1=浏览器已开 2=完成
|
||||
const [loginLoading, setLoginLoading] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await listPlatformAccounts();
|
||||
setAccounts(data ?? []);
|
||||
// 并行加载各账号用量
|
||||
const usageMap: Record<string, UsageSnapshot> = {};
|
||||
await Promise.all(
|
||||
(data ?? []).map(async (acc) => {
|
||||
try {
|
||||
const u = await getPlatformUsage(acc.id);
|
||||
if (u) usageMap[acc.id] = u as UsageSnapshot;
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}),
|
||||
);
|
||||
setUsages(usageMap);
|
||||
// 加载定时抓取配置
|
||||
try {
|
||||
const schedule = await getScrapeSchedule();
|
||||
setScheduleConfig(schedule);
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
/** 登录过期检测(全局弹窗在 App.tsx,这里只维护过期 ID 集合用于状态展示) */
|
||||
const [expiredIds, setExpiredIds] = useState<Set<string>>(new Set());
|
||||
const checkLoginExpired = useCallback(async () => {
|
||||
try {
|
||||
const expired = await getLoginExpired();
|
||||
setExpiredIds(new Set((expired || []).map((a: { account_id: string }) => a.account_id)));
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 组件加载时 + 按配置间隔检测登录过期
|
||||
useEffect(() => {
|
||||
if (!scheduleConfig?.login_detect_enabled) return;
|
||||
checkLoginExpired();
|
||||
const intervalMs = (scheduleConfig?.login_detect_interval || 60) * 1000;
|
||||
const timer = setInterval(checkLoginExpired, intervalMs);
|
||||
return () => clearInterval(timer);
|
||||
}, [checkLoginExpired, scheduleConfig?.login_detect_enabled, scheduleConfig?.login_detect_interval]);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
form.setFieldsValue({ brand: '', account_name: '', plan_name: '', console_url: '', description: '' });
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (record: PlatformAccount) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
brand: record.brand,
|
||||
account_name: record.account_name,
|
||||
plan_name: record.plan_name,
|
||||
console_url: record.console_url,
|
||||
description: record.description,
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const values = await form.validateFields();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await updatePlatformAccount(editing.id, values);
|
||||
messageApi.success('账号更新成功');
|
||||
} else {
|
||||
await createPlatformAccount(values);
|
||||
messageApi.success('账号创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 打开登录引导弹框 */
|
||||
const handleLogin = (record: PlatformAccount) => {
|
||||
setLoginAccount(record);
|
||||
setLoginStep(0);
|
||||
setLoginModalOpen(true);
|
||||
};
|
||||
|
||||
/** 第一步:打开浏览器 */
|
||||
const handleOpenBrowser = async () => {
|
||||
if (!loginAccount) return;
|
||||
setLoginLoading(true);
|
||||
try {
|
||||
const result = await startLogin(loginAccount.id);
|
||||
if (result.success) {
|
||||
setLoginStep(1);
|
||||
messageApi.success('浏览器已打开,请完成登录');
|
||||
} else {
|
||||
messageApi.warning(result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoginLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 第二步:登录完成,保存 Cookie */
|
||||
const handleLoginFinish = async () => {
|
||||
if (!loginAccount) return;
|
||||
setLoginLoading(true);
|
||||
try {
|
||||
const result = await finishLogin(loginAccount.id);
|
||||
if (result.success) {
|
||||
setLoginStep(2);
|
||||
messageApi.success(result.message || '登录态已保存');
|
||||
} else {
|
||||
messageApi.warning(result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoginLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 取消登录 */
|
||||
const handleLoginCancel = async () => {
|
||||
if (loginAccount) {
|
||||
try {
|
||||
await cancelLogin(loginAccount.id);
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}
|
||||
setLoginModalOpen(false);
|
||||
};
|
||||
|
||||
/** 完成登录 */
|
||||
const handleLoginDone = () => {
|
||||
setLoginModalOpen(false);
|
||||
// 清除该账号的登录过期标记
|
||||
if (loginAccount) {
|
||||
clearLoginExpired(loginAccount.id).catch(() => {});
|
||||
}
|
||||
// 刷新登录过期状态(清除 expiredIds 中的标记)
|
||||
checkLoginExpired();
|
||||
load();
|
||||
};
|
||||
|
||||
/** 单账号抓取用量 */
|
||||
const handleScrape = async (record: PlatformAccount) => {
|
||||
setScraping(record.id);
|
||||
try {
|
||||
const result = await scrapePlatformAccount(record.id);
|
||||
if (result.success) {
|
||||
messageApi.success(result.message);
|
||||
await load();
|
||||
} else {
|
||||
messageApi.warning(result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setScraping('');
|
||||
}
|
||||
};
|
||||
|
||||
/** 批量抓取 */
|
||||
/** 批量抓取(带进度弹窗) */
|
||||
const handleScrapeAll = async () => {
|
||||
setScrapingAll(true);
|
||||
setProgressOpen(true);
|
||||
setScrapeProgress({ running: true, total: 0, completed: 0, current_account: '准备中…' });
|
||||
|
||||
// 启动进度轮询
|
||||
const pollTimer = setInterval(async () => {
|
||||
try {
|
||||
const progress = await getScrapeProgress();
|
||||
setScrapeProgress(progress);
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}, 1500);
|
||||
|
||||
try {
|
||||
const results = await scrapeAllPlatformAccounts();
|
||||
const success = results.filter((r) => r.success).length;
|
||||
messageApi.success(`批量抓取完成:${success}/${results.length} 成功`);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
clearInterval(pollTimer);
|
||||
setScrapingAll(false);
|
||||
setScrapeProgress(null);
|
||||
await checkLoginExpired(); // 抓取完成后检测登录过期
|
||||
// 延迟关闭弹窗让用户看到最终进度
|
||||
setTimeout(() => setProgressOpen(false), 1500);
|
||||
}
|
||||
};
|
||||
|
||||
/** 立即执行(带进度弹窗) */
|
||||
const handleTriggerNow = async () => {
|
||||
setTriggering(true);
|
||||
setProgressOpen(true);
|
||||
setScrapeProgress({ running: true, total: 0, completed: 0, current_account: '准备中…' });
|
||||
|
||||
const pollTimer = setInterval(async () => {
|
||||
try {
|
||||
const progress = await getScrapeProgress();
|
||||
setScrapeProgress(progress);
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}, 1500);
|
||||
|
||||
try {
|
||||
const result = await triggerScrapeNow();
|
||||
messageApi[result.success ? 'success' : 'warning'](result.message);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
clearInterval(pollTimer);
|
||||
setTriggering(false);
|
||||
setScrapeProgress(null);
|
||||
await checkLoginExpired(); // 抓取完成后检测登录过期
|
||||
setTimeout(() => setProgressOpen(false), 1500);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (record: PlatformAccount) => {
|
||||
try {
|
||||
await deletePlatformAccount(record.id);
|
||||
messageApi.success('删除成功');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<PlatformAccount> = [
|
||||
{
|
||||
title: '品牌',
|
||||
dataIndex: 'brand',
|
||||
key: 'brand',
|
||||
width: 100,
|
||||
render: (v: string) => <Tag color="blue">{v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '账号',
|
||||
dataIndex: 'account_name',
|
||||
key: 'account_name',
|
||||
width: 120,
|
||||
render: (v: string) => <Typography.Text strong>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '套餐',
|
||||
dataIndex: 'plan_name',
|
||||
key: 'plan_name',
|
||||
width: 120,
|
||||
render: (v: string) => v || '—',
|
||||
},
|
||||
{
|
||||
title: '控制台',
|
||||
dataIndex: 'console_url',
|
||||
key: 'console_url',
|
||||
ellipsis: true,
|
||||
render: (v: string) => (
|
||||
<Typography.Text code style={{ fontSize: 11 }}>{v}</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '登录状态',
|
||||
key: 'login',
|
||||
width: 90,
|
||||
render: (_, record) => {
|
||||
if (!record.has_cookies) return <Tag color="orange">未登录</Tag>;
|
||||
// 检查是否在过期列表里(与全局检测共享数据)
|
||||
const isExpired = expiredIds.has(record.id);
|
||||
return isExpired ? <Tag color="red">已过期</Tag> : <Tag color="green">已登录</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '用量详情',
|
||||
key: 'usage',
|
||||
width: 220,
|
||||
render: (_, record) => {
|
||||
const u = usages[record.id];
|
||||
if (!u) return <Typography.Text type="secondary">—</Typography.Text>;
|
||||
|
||||
// 火山引擎式:四指标(近5小时/近一周/近一月 + 剩余时间)
|
||||
const hasTimeMetrics = u.usage_5h || u.usage_1w || u.usage_1m;
|
||||
|
||||
if (hasTimeMetrics) {
|
||||
return (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
剩余时间:<strong>{u.remain_amount || '—'}</strong>
|
||||
</Typography.Text>
|
||||
{u.usage_5h !== undefined && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
近5小时:<strong>{u.usage_5h}%</strong>
|
||||
{u.reset_5h && <em style={{ fontStyle: 'normal', color: '#999' }}> · {u.reset_5h}</em>}
|
||||
</Typography.Text>
|
||||
)}
|
||||
{u.usage_1w !== undefined && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
近一周:<strong>{u.usage_1w}%</strong>
|
||||
{u.reset_1w && <em style={{ fontStyle: 'normal', color: '#999' }}> · {u.reset_1w}</em>}
|
||||
</Typography.Text>
|
||||
)}
|
||||
{u.usage_1m !== undefined && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
近一月:<strong>{u.usage_1m}%</strong>
|
||||
{u.reset_1m && <em style={{ fontStyle: 'normal', color: '#999' }}> · {u.reset_1m}</em>}
|
||||
</Typography.Text>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
|
||||
// 小米式:已用用量 + 剩余用量 + 有效期至
|
||||
return (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
已用用量:<strong>{u.used_amount || '—'}</strong>
|
||||
</Typography.Text>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
剩余用量:<strong>{u.remain_amount || '—'}</strong>
|
||||
</Typography.Text>
|
||||
{u.valid_until && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
有效期至:<strong>{u.valid_until}</strong>
|
||||
</Typography.Text>
|
||||
)}
|
||||
{u.usage_percent > 0 && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
使用率:<strong>{u.usage_percent}%</strong>
|
||||
</Typography.Text>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 260,
|
||||
render: (_, record) => (
|
||||
<Space size={4} wrap>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<LoginOutlined />}
|
||||
onClick={() => handleLogin(record)}
|
||||
>
|
||||
登录
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CloudDownloadOutlined />}
|
||||
loading={scraping === record.id}
|
||||
onClick={() => handleScrape(record)}
|
||||
>
|
||||
抓取
|
||||
</Button>
|
||||
<Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm title="确认删除该账号?" onConfirm={() => handleDelete(record)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Space>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
<GlobalOutlined /> 平台账号管理
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
管理多平台账号,登录后自动抓取用量
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
loading={scrapingAll}
|
||||
onClick={handleScrapeAll}
|
||||
>
|
||||
批量抓取
|
||||
</Button>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
|
||||
新增账号
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
{/* 定时抓取配置 */}
|
||||
{scheduleConfig && (
|
||||
<Card size="small" title="定时抓取" style={{ marginBottom: 16 }}>
|
||||
<Space wrap style={{ display: 'flex' }}>
|
||||
<Space style={{ minWidth: 130 }}>
|
||||
<Typography.Text type="secondary">自动抓取</Typography.Text>
|
||||
</Space>
|
||||
<Switch
|
||||
checked={scheduleConfig.enabled}
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
loading={scheduleLoading}
|
||||
onChange={async (checked) => {
|
||||
setScheduleLoading(true);
|
||||
try {
|
||||
await updateScrapeSchedule({ enabled: checked });
|
||||
const updated = await getScrapeSchedule();
|
||||
setScheduleConfig(updated);
|
||||
messageApi.success(checked ? '定时抓取已开启' : '定时抓取已关闭');
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setScheduleLoading(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Typography.Text type="secondary">间隔(分钟):</Typography.Text>
|
||||
<InputNumber
|
||||
min={10}
|
||||
max={1440}
|
||||
value={scheduleConfig.interval_minutes}
|
||||
style={{ width: 100 }}
|
||||
onChange={(v) => {
|
||||
// 立即更新本地状态(受控组件,保证 UI 即时响应)
|
||||
const minutes = v ?? 360;
|
||||
setScheduleConfig((prev) =>
|
||||
prev ? { ...prev, interval_minutes: minutes } : prev,
|
||||
);
|
||||
}}
|
||||
onBlur={async () => {
|
||||
try {
|
||||
await updateScrapeSchedule({
|
||||
interval_minutes: scheduleConfig.interval_minutes,
|
||||
});
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
icon={<CloudDownloadOutlined />}
|
||||
loading={triggering}
|
||||
onClick={handleTriggerNow}
|
||||
>
|
||||
立即执行
|
||||
</Button>
|
||||
{scheduleConfig.last_run_at && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
上次运行:{dayjs(scheduleConfig.last_run_at).format('YYYY-MM-DD HH:mm:ss')}
|
||||
</Typography.Text>
|
||||
)}
|
||||
{scheduleConfig.scheduler_running && (
|
||||
<Tag color="green">调度器运行中</Tag>
|
||||
)}
|
||||
</Space>
|
||||
{/* 登录过期检测配置(独立一行,与自动抓取左对齐) */}
|
||||
<Space wrap style={{ display: 'flex', marginTop: 8 }}>
|
||||
<Space style={{ minWidth: 130 }}>
|
||||
<Typography.Text type="secondary">登录过期检测</Typography.Text>
|
||||
</Space>
|
||||
<Switch
|
||||
checked={scheduleConfig.login_detect_enabled}
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
onChange={async (checked) => {
|
||||
try {
|
||||
await updateScrapeSchedule({ login_detect_enabled: checked });
|
||||
const updated = await getScrapeSchedule();
|
||||
setScheduleConfig(updated);
|
||||
messageApi.success(checked ? '登录检测已开启' : '登录检测已关闭');
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Typography.Text type="secondary">检测间隔(秒):</Typography.Text>
|
||||
<InputNumber
|
||||
min={30}
|
||||
max={3600}
|
||||
value={scheduleConfig.login_detect_interval}
|
||||
style={{ width: 100 }}
|
||||
onChange={(v) => {
|
||||
const seconds = v ?? 60;
|
||||
setScheduleConfig((prev) =>
|
||||
prev ? { ...prev, login_detect_interval: seconds } : prev,
|
||||
);
|
||||
}}
|
||||
onBlur={async () => {
|
||||
try {
|
||||
await updateScrapeSchedule({
|
||||
login_detect_interval: scheduleConfig.login_detect_interval,
|
||||
});
|
||||
messageApi.success(`检测间隔已设为 ${scheduleConfig.login_detect_interval} 秒`);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Table<PlatformAccount>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={accounts}
|
||||
pagination={{ pageSize: 5, showTotal: (t) => `共 ${t} 个账号` }}
|
||||
size="small"
|
||||
/>
|
||||
|
||||
{/* 新建/编辑弹窗 */}
|
||||
<Modal
|
||||
title={editing ? '编辑账号' : '新增账号'}
|
||||
open={modalOpen}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={submitting}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
width={560}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Row gutter={16}>
|
||||
<Col span={12}>
|
||||
<Form.Item
|
||||
name="brand"
|
||||
label="品牌"
|
||||
rules={[{ required: true, message: '请输入品牌' }]}
|
||||
>
|
||||
<Input placeholder="如:小米 / 火山引擎" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Form.Item
|
||||
name="account_name"
|
||||
label="账号名称"
|
||||
rules={[{ required: true, message: '请输入账号名称' }]}
|
||||
>
|
||||
<Input placeholder="如:主力账号 / 测试账号" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
<Form.Item name="plan_name" label="套餐名称">
|
||||
<Input placeholder="如:Coding 套餐 / 企业版" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="console_url"
|
||||
label="控制台 URL"
|
||||
rules={[{ required: true, message: '请输入控制台地址' }]}
|
||||
extra="登录后查看用量的页面地址"
|
||||
>
|
||||
<Input placeholder="https://..." />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="备注">
|
||||
<Input.TextArea rows={2} maxLength={200} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* 登录引导弹框 */}
|
||||
<Modal
|
||||
title={
|
||||
<Space>
|
||||
<LoginOutlined />
|
||||
<span>
|
||||
登录 {loginAccount?.brand} — {loginAccount?.account_name}
|
||||
</span>
|
||||
</Space>
|
||||
}
|
||||
open={loginModalOpen}
|
||||
onCancel={() => setLoginModalOpen(false)}
|
||||
width={560}
|
||||
footer={
|
||||
loginStep === 2 ? (
|
||||
<Button type="primary" onClick={handleLoginDone}>
|
||||
完成
|
||||
</Button>
|
||||
) : loginStep === 1 ? (
|
||||
// 浏览器已打开,等待用户登录完成
|
||||
<Space>
|
||||
<Button onClick={handleLoginCancel}>取消登录</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
loading={loginLoading}
|
||||
onClick={handleLoginFinish}
|
||||
>
|
||||
✅ 登录完成(保存 Cookie)
|
||||
</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Button onClick={() => setLoginModalOpen(false)}>取消</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
loading={loginLoading}
|
||||
onClick={handleOpenBrowser}
|
||||
>
|
||||
打开浏览器登录
|
||||
</Button>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
>
|
||||
<Steps
|
||||
current={loginStep}
|
||||
direction="vertical"
|
||||
items={[
|
||||
{
|
||||
title: '打开浏览器',
|
||||
description: (
|
||||
<div>
|
||||
<Typography.Text type="secondary">
|
||||
点击下方按钮,系统会打开浏览器窗口并跳转到登录页
|
||||
</Typography.Text>
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<Typography.Text code style={{ fontSize: 11 }}>
|
||||
{loginAccount?.console_url}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '在浏览器中完成登录',
|
||||
description: (
|
||||
<Typography.Text type="secondary">
|
||||
在弹出的浏览器窗口中输入账号密码完成登录,登录成功后系统会自动保存 Cookie
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '登录完成',
|
||||
description: (
|
||||
<Typography.Text type="secondary">
|
||||
Cookie 已保存,后续抓取用量将自动使用该登录态
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{loginStep === 1 && (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message="正在等待登录…"
|
||||
description="请在弹出的浏览器窗口中完成登录,登录成功后 Cookie 会自动保存"
|
||||
style={{ marginTop: 12 }}
|
||||
/>
|
||||
)}
|
||||
{loginStep === 2 && (
|
||||
<Alert
|
||||
type="success"
|
||||
showIcon
|
||||
message="登录成功!"
|
||||
description="Cookie 已保存,现在可以抓取用量了"
|
||||
style={{ marginTop: 12 }}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* 抓取进度弹窗 */}
|
||||
<Modal
|
||||
title="抓取进度"
|
||||
open={progressOpen}
|
||||
closable={false}
|
||||
footer={null}
|
||||
width={480}
|
||||
>
|
||||
{scrapeProgress && (
|
||||
<div>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<Typography.Text>
|
||||
{scrapeProgress.running
|
||||
? `正在抓取:${scrapeProgress.current_account || '准备中…'}`
|
||||
: '抓取完成'}
|
||||
</Typography.Text>
|
||||
<Typography.Text strong>
|
||||
{scrapeProgress.completed} / {scrapeProgress.total || '?'}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
<Progress
|
||||
percent={
|
||||
scrapeProgress.total > 0
|
||||
? Math.round((scrapeProgress.completed / scrapeProgress.total) * 100)
|
||||
: scrapeProgress.running
|
||||
? 50
|
||||
: 100
|
||||
}
|
||||
status={scrapeProgress.running ? 'active' : 'success'}
|
||||
showInfo={false}
|
||||
/>
|
||||
{scrapeProgress.current_account && scrapeProgress.running && (
|
||||
<Typography.Text
|
||||
type="secondary"
|
||||
style={{ fontSize: 12, marginTop: 8, display: 'block' }}
|
||||
>
|
||||
当前:{scrapeProgress.current_account}
|
||||
</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
/**
|
||||
* 项目管理页面组件
|
||||
*
|
||||
* 【功能说明】承担「待开发的系统/项目」的增删改查,展示本地代码路径、
|
||||
* 前端/后端仓库分支,并提供需求输入入口(M3 起接入任务提交)。
|
||||
* 【技术选型理由】Ant Design 的 Table + Form + Modal + Select 组合,
|
||||
* 是企业级后台的成熟形态,表格/表单/校验开箱即用,减少自研成本。
|
||||
* 【实现思路】
|
||||
* - 列表加载 → 表格展示;
|
||||
* - 新建/编辑走 Modal 表单,提交后刷新列表;
|
||||
* - 编辑时读取该项目的 Git 分支填入下拉框(对应核心诉求第 2 条)。
|
||||
* 【潜在风险与应对】
|
||||
* 风险1:分支读取失败(路径非 git 仓库)。
|
||||
* 应对:warning 提示后仍展示项目数据,下拉框允许手输分支名,不阻塞。
|
||||
* 风险2:删除项目误操作。
|
||||
* 应对:Popconfirm 二次确认。
|
||||
*/
|
||||
import {
|
||||
ArrowDownOutlined,
|
||||
ArrowUpOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
FolderOpenOutlined,
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
SearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
AutoComplete,
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
createProject,
|
||||
deleteProject,
|
||||
getProjectBranches,
|
||||
listProjects,
|
||||
updateProject,
|
||||
} from '../api/client';
|
||||
import type { Project, ProjectPayload } from '../types';
|
||||
|
||||
/** 表单初始值(与后端 ProjectCreate 默认值保持一致) */
|
||||
const INITIAL_VALUES: ProjectPayload = {
|
||||
name: '',
|
||||
code_root_path: 'D:\\Project\\',
|
||||
backend_path: '.',
|
||||
frontend_path: 'frontend',
|
||||
backend_branch: 'master',
|
||||
frontend_branch: 'master',
|
||||
backends: [{ label: '后端', path: 'D:\\Project\\', branch: 'master' }],
|
||||
frontends: [{ label: '前端', path: 'D:\\Project\\', branch: 'master' }],
|
||||
description: '',
|
||||
};
|
||||
|
||||
export default function ProjectList() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<Project | null>(null);
|
||||
const [branchOptions, setBranchOptions] = useState<{
|
||||
backend: string[];
|
||||
frontend: string[];
|
||||
}>({ backend: [], frontend: [] });
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [searchName, setSearchName] = useState('');
|
||||
// 分页受控
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(8);
|
||||
const [form] = Form.useForm<ProjectPayload>();
|
||||
|
||||
/** 加载项目列表 */
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await listProjects();
|
||||
setProjects(data ?? []);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
/** 打开新建弹窗 */
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setBranchOptions({ backend: [], frontend: [] });
|
||||
form.setFieldsValue(INITIAL_VALUES);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
/** 打开编辑弹窗,并尝试读取该项目的 Git 分支 */
|
||||
const openEdit = async (record: Project) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
name: record.name,
|
||||
code_root_path: record.code_root_path,
|
||||
backend_path: record.backend_path,
|
||||
frontend_path: record.frontend_path,
|
||||
backend_branch: record.backend_branch,
|
||||
frontend_branch: record.frontend_branch,
|
||||
backends: record.backends?.length
|
||||
? record.backends
|
||||
: [{ label: '后端', path: record.backend_path, branch: record.backend_branch }],
|
||||
frontends: record.frontends?.length
|
||||
? record.frontends
|
||||
: [{ label: '前端', path: record.frontend_path, branch: record.frontend_branch }],
|
||||
description: record.description,
|
||||
});
|
||||
setModalOpen(true);
|
||||
// 读取分支(失败不阻塞,仅提示)
|
||||
try {
|
||||
const { data, warning } = await getProjectBranches(record.id);
|
||||
setBranchOptions({ backend: data.backend, frontend: data.frontend });
|
||||
if (warning) {
|
||||
messageApi.warning(warning);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.warning(`读取 Git 分支失败:${(e as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
/** 提交表单(新建或更新) */
|
||||
const handleSubmit = async () => {
|
||||
const values = await form.validateFields();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await updateProject(editing.id, values);
|
||||
messageApi.success('项目更新成功');
|
||||
} else {
|
||||
await createProject(values);
|
||||
messageApi.success('项目创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除项目 */
|
||||
/** 上移项目(用 record 定位真实位置,不依赖页内索引) */
|
||||
const handleMoveUp = async (record: Project) => {
|
||||
const index = projects.findIndex((p) => p.id === record.id);
|
||||
if (index <= 0) return;
|
||||
const current = projects[index];
|
||||
const prev = projects[index - 1];
|
||||
try {
|
||||
await updateProject(current.id, { sort_order: prev.sort_order });
|
||||
await updateProject(prev.id, { sort_order: current.sort_order });
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 下移项目 */
|
||||
const handleMoveDown = async (record: Project) => {
|
||||
const index = projects.findIndex((p) => p.id === record.id);
|
||||
if (index >= projects.length - 1) return;
|
||||
const current = projects[index];
|
||||
const next = projects[index + 1];
|
||||
try {
|
||||
await updateProject(current.id, { sort_order: next.sort_order });
|
||||
await updateProject(next.id, { sort_order: current.sort_order });
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (record: Project) => {
|
||||
try {
|
||||
await deleteProject(record.id);
|
||||
messageApi.success('项目删除成功');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 表格列定义 */
|
||||
const columns: ColumnsType<Project> = [
|
||||
{
|
||||
title: '项目名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 160,
|
||||
render: (v: string) => <Typography.Text strong>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '本地代码路径',
|
||||
dataIndex: 'code_root_path',
|
||||
key: 'code_root_path',
|
||||
width: 220,
|
||||
ellipsis: true,
|
||||
render: (_, record) => (
|
||||
<Space size={4}>
|
||||
<FolderOpenOutlined style={{ color: '#999', flexShrink: 0 }} />
|
||||
<Typography.Text
|
||||
code
|
||||
style={{ fontSize: 12 }}
|
||||
ellipsis={{ tooltip: `${record.code_root_path}\\${record.backend_path}` }}
|
||||
>
|
||||
{record.backend_path}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '后端分支',
|
||||
dataIndex: 'backend_branch',
|
||||
key: 'backend_branch',
|
||||
width: 130,
|
||||
render: (v: string) => <Tag color="blue">{v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '前端分支',
|
||||
dataIndex: 'frontend_branch',
|
||||
key: 'frontend_branch',
|
||||
width: 130,
|
||||
render: (v: string) => <Tag color="green">{v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'description',
|
||||
key: 'description',
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
render: (v: string) =>
|
||||
v ? (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{v}
|
||||
</Typography.Text>
|
||||
) : (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
—
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 220,
|
||||
render: (_, record) => {
|
||||
const globalIndex = projects.findIndex((p) => p.id === record.id);
|
||||
return (
|
||||
<Space>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<ArrowUpOutlined />}
|
||||
disabled={globalIndex <= 0}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleMoveUp(record);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<ArrowDownOutlined />}
|
||||
disabled={globalIndex >= projects.length - 1}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleMoveDown(record);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => openEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除该项目?"
|
||||
description="删除后项目登记信息不可恢复"
|
||||
onConfirm={() => handleDelete(record)}
|
||||
okText="确认"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button type="link" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
项目管理
|
||||
</Typography.Title>
|
||||
<Space>
|
||||
<Input
|
||||
placeholder="按项目名称搜索"
|
||||
prefix={<SearchOutlined style={{ color: '#999' }} />}
|
||||
value={searchName}
|
||||
onChange={(e) => setSearchName(e.target.value)}
|
||||
allowClear
|
||||
style={{ width: 220 }}
|
||||
/>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
|
||||
新建项目
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
<Table<Project>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={searchName
|
||||
? projects.filter((p) =>
|
||||
p.name.toLowerCase().includes(searchName.trim().toLowerCase()),
|
||||
)
|
||||
: projects}
|
||||
pagination={{
|
||||
current: currentPage,
|
||||
pageSize: pageSize,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [5, 8, 10, 20, 50],
|
||||
showTotal: (t) => `共 ${t} 个项目`,
|
||||
onChange: (page, size) => {
|
||||
setCurrentPage(page);
|
||||
setPageSize(size);
|
||||
},
|
||||
onShowSizeChange: (_, size) => {
|
||||
setPageSize(size);
|
||||
setCurrentPage(1);
|
||||
},
|
||||
}}
|
||||
locale={{ emptyText: '暂无项目,点击右上角「新建项目」开始' }}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
title={editing ? '编辑项目' : '新建项目'}
|
||||
open={modalOpen}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={submitting}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
width={640}
|
||||
>
|
||||
<Form form={form} layout="vertical" initialValues={INITIAL_VALUES}>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="项目名称"
|
||||
rules={[{ required: true, message: '请输入项目名称' }]}
|
||||
>
|
||||
<Input placeholder="如:IOT 管理平台" maxLength={100} />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="code_root_path"
|
||||
label="本地代码根路径"
|
||||
rules={[
|
||||
{ required: true, message: '请输入本地代码根路径' },
|
||||
{
|
||||
validator: (_, v: string) =>
|
||||
!v || v.trim().toUpperCase().startsWith('D:')
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error('路径必须位于 D 盘(硬约束 6)')),
|
||||
},
|
||||
]}
|
||||
extra="必须位于 D 盘,如 D:\Agent\code\demo"
|
||||
>
|
||||
<Input placeholder="D:\Agent\code\demo" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="后端服务(可多个)" style={{ marginBottom: 8 }}>
|
||||
<Form.List name="backends">
|
||||
{(fields, { add, remove }) => (
|
||||
<>
|
||||
{fields.map((field) => (
|
||||
<Space key={field.key} style={{ display: 'flex', marginBottom: 4 }} align="start">
|
||||
<Form.Item name={[field.name, 'label']} rules={[{ required: true, message: '名称' }]} style={{ marginBottom: 0, width: 120 }}>
|
||||
<Input placeholder="名称" />
|
||||
</Form.Item>
|
||||
<Form.Item name={[field.name, 'path']} rules={[{ required: true, message: '路径' }]} style={{ marginBottom: 0, flex: 1, minWidth: 180 }}>
|
||||
<Input placeholder="代码路径" />
|
||||
</Form.Item>
|
||||
<Form.Item name={[field.name, 'branch']} style={{ marginBottom: 0, width: 140 }}>
|
||||
<AutoComplete
|
||||
placeholder="分支"
|
||||
options={branchOptions.backend.map((b) => ({ label: b, value: b }))}
|
||||
filterOption={(input, option) =>
|
||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button type="text" danger icon={<DeleteOutlined />} onClick={() => remove(field.name)} />
|
||||
</Space>
|
||||
))}
|
||||
<Button type="dashed" block icon={<PlusOutlined />} onClick={() => add({ label: '', path: '', branch: 'master' })}>
|
||||
添加后端服务
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="前端服务(可多个)" style={{ marginBottom: 8 }}>
|
||||
<Form.List name="frontends">
|
||||
{(fields, { add, remove }) => (
|
||||
<>
|
||||
{fields.map((field) => (
|
||||
<Space key={field.key} style={{ display: 'flex', marginBottom: 4 }} align="start">
|
||||
<Form.Item name={[field.name, 'label']} rules={[{ required: true, message: '名称' }]} style={{ marginBottom: 0, width: 120 }}>
|
||||
<Input placeholder="名称" />
|
||||
</Form.Item>
|
||||
<Form.Item name={[field.name, 'path']} rules={[{ required: true, message: '路径' }]} style={{ marginBottom: 0, flex: 1, minWidth: 180 }}>
|
||||
<Input placeholder="代码路径" />
|
||||
</Form.Item>
|
||||
<Form.Item name={[field.name, 'branch']} style={{ marginBottom: 0, width: 140 }}>
|
||||
<AutoComplete
|
||||
placeholder="分支"
|
||||
options={branchOptions.frontend.map((b) => ({ label: b, value: b }))}
|
||||
filterOption={(input, option) =>
|
||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button type="text" danger icon={<DeleteOutlined />} onClick={() => remove(field.name)} />
|
||||
</Space>
|
||||
))}
|
||||
<Button type="dashed" block icon={<PlusOutlined />} onClick={() => add({ label: '', path: '', branch: 'master' })}>
|
||||
添加前端服务
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="description" label="备注">
|
||||
<Input.TextArea rows={3} maxLength={500} placeholder="项目说明、注意事项等" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* 提示词优化页面组件
|
||||
*
|
||||
* 【功能说明】把粗糙/口语化的想法通过 AI 润色成高质量提示词。
|
||||
* 基于 prompt-polisher Skill 规则执行润色。
|
||||
* 【技术选型理由】AntD Card + Input.TextArea + 结果展示区,与各管理页同构。
|
||||
*/
|
||||
import {
|
||||
CopyOutlined,
|
||||
EditOutlined,
|
||||
RobotOutlined,
|
||||
SwapOutlined,
|
||||
ThunderboltOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Input,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { listModelOptions, polishPrompt } from '../api/client';
|
||||
import type { ModelOption } from '../types';
|
||||
|
||||
interface PolishResult {
|
||||
polish_result: string;
|
||||
changes: string[];
|
||||
questions: string[];
|
||||
model: string;
|
||||
}
|
||||
|
||||
export default function PromptPolish() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [inputText, setInputText] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [result, setResult] = useState<PolishResult | null>(null);
|
||||
const [modelOptions, setModelOptions] = useState<ModelOption[]>([]);
|
||||
const [selectedModel, setSelectedModel] = useState('auto');
|
||||
|
||||
useEffect(() => {
|
||||
listModelOptions().then(setModelOptions).catch(() => {});
|
||||
}, []);
|
||||
|
||||
/** 执行优化 */
|
||||
const handlePolish = async () => {
|
||||
if (!inputText.trim()) {
|
||||
messageApi.warning('请输入要优化的内容');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setResult(null);
|
||||
try {
|
||||
const data = await polishPrompt(inputText.trim(), selectedModel);
|
||||
setResult(data);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 复制优化结果 */
|
||||
const handleCopy = () => {
|
||||
if (!result) return;
|
||||
navigator.clipboard.writeText(result.polish_result).then(() => {
|
||||
messageApi.success('已复制到剪贴板');
|
||||
});
|
||||
};
|
||||
|
||||
/** 用优化结果替换原始输入 */
|
||||
const handleReplace = () => {
|
||||
if (!result) return;
|
||||
setInputText(result.polish_result);
|
||||
messageApi.success('已替换到输入框');
|
||||
};
|
||||
|
||||
/** 清空 */
|
||||
const handleClear = () => {
|
||||
setInputText('');
|
||||
setResult(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Typography.Title level={4}>
|
||||
<EditOutlined /> 提示词优化
|
||||
</Typography.Title>
|
||||
<Typography.Paragraph type="secondary" style={{ marginBottom: 16 }}>
|
||||
把粗糙的想法、口语化的表达、不完整的需求,润色成 AI 能精准理解的高质量提示词。
|
||||
只优化「怎么说」,不替你做决定。
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Row gutter={16}>
|
||||
{/* 左侧:输入 */}
|
||||
<Col span={11}>
|
||||
<Card
|
||||
size="small"
|
||||
title="原始输入(待优化)"
|
||||
extra={
|
||||
<Select
|
||||
value={selectedModel}
|
||||
onChange={(v) => setSelectedModel(v)}
|
||||
options={modelOptions}
|
||||
size="small"
|
||||
style={{ width: 180 }}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={10}
|
||||
placeholder={'把你粗糙的想法写在这里…\n\n例如:帮我弄个周报,把这周做的事整理一下,老板想看。'}
|
||||
value={inputText}
|
||||
onChange={(e) => setInputText(e.target.value)}
|
||||
style={{ resize: 'vertical' }}
|
||||
/>
|
||||
<Space style={{ width: '100%', marginTop: 12, justifyContent: 'space-between' }}>
|
||||
<Button onClick={handleClear}>清空</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<ThunderboltOutlined />}
|
||||
loading={loading}
|
||||
disabled={!inputText.trim()}
|
||||
onClick={handlePolish}
|
||||
>
|
||||
优化提示词
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
|
||||
{/* 右侧:结果 */}
|
||||
<Col span={13}>
|
||||
<Card
|
||||
size="small"
|
||||
title={
|
||||
<Space>
|
||||
<RobotOutlined />
|
||||
<span>优化结果</span>
|
||||
{result && (
|
||||
<Tag color="green">
|
||||
<RobotOutlined style={{ fontSize: 10 }} /> {result.model}
|
||||
</Tag>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
extra={
|
||||
result && (
|
||||
<Space>
|
||||
<Button size="small" icon={<CopyOutlined />} onClick={handleCopy}>
|
||||
复制
|
||||
</Button>
|
||||
<Button size="small" icon={<SwapOutlined />} onClick={handleReplace}>
|
||||
替换输入
|
||||
</Button>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
style={{ minHeight: 500 }}
|
||||
>
|
||||
{loading ? (
|
||||
<div style={{ textAlign: 'center', padding: 80 }}>
|
||||
<Spin tip="正在优化提示词…" size="large" />
|
||||
</div>
|
||||
) : result ? (
|
||||
<Space direction="vertical" style={{ width: '100%' }} size="middle">
|
||||
{/* 润色后 */}
|
||||
<div>
|
||||
<Typography.Title level={5} style={{ marginBottom: 8 }}>
|
||||
📝 润色后
|
||||
</Typography.Title>
|
||||
<div
|
||||
style={{
|
||||
background: '#f6ffed',
|
||||
border: '1px solid #b7eb8f',
|
||||
borderRadius: 6,
|
||||
padding: 12,
|
||||
whiteSpace: 'pre-wrap',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.8,
|
||||
}}
|
||||
>
|
||||
{result.polish_result}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 改了什么 */}
|
||||
{result.changes.length > 0 && (
|
||||
<div>
|
||||
<Typography.Title level={5} style={{ marginBottom: 8 }}>
|
||||
✏️ 改了什么
|
||||
</Typography.Title>
|
||||
<ul style={{ paddingLeft: 20, margin: 0 }}>
|
||||
{result.changes.map((c, i) => (
|
||||
<li key={i} style={{ marginBottom: 4 }}>
|
||||
<Typography.Text style={{ fontSize: 13 }}>{c}</Typography.Text>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 待定问题 */}
|
||||
{result.questions.length > 0 && (
|
||||
<div>
|
||||
<Typography.Title level={5} style={{ marginBottom: 8 }}>
|
||||
❓ 还需要你定
|
||||
</Typography.Title>
|
||||
<ul style={{ paddingLeft: 20, margin: 0 }}>
|
||||
{result.questions.map((q, i) => (
|
||||
<li key={i} style={{ marginBottom: 4 }}>
|
||||
<Typography.Text type="warning" style={{ fontSize: 13 }}>
|
||||
{q}
|
||||
</Typography.Text>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 80, color: '#999' }}>
|
||||
<EditOutlined style={{ fontSize: 48, marginBottom: 16 }} />
|
||||
<br />
|
||||
在左侧输入你的想法,点击「优化提示词」
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
/**
|
||||
* Provider 管理组件(服务通道配置)
|
||||
*
|
||||
* 【功能说明】管理多个 AI 平台的连接配置(base_url + api_key),
|
||||
* 实现 ccswitch 的核心能力:统一管理多平台、按 model_id 路由。
|
||||
* 【技术选型理由】AntD Table + Modal Form,与各管理页同构。
|
||||
* 【安全设计】API key 加密存储,前端脱敏显示。
|
||||
*/
|
||||
import {
|
||||
ApiOutlined,
|
||||
CheckCircleOutlined,
|
||||
CloudDownloadOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
EyeInvisibleOutlined,
|
||||
EyeOutlined,
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
List,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Space,
|
||||
Spin,
|
||||
Switch,
|
||||
Table,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
createModelConfig,
|
||||
createProvider,
|
||||
deleteModelConfig,
|
||||
deleteProvider,
|
||||
fetchProviderModels,
|
||||
listModelConfigs,
|
||||
listProviders,
|
||||
testProvider,
|
||||
updateModelConfig,
|
||||
updateProvider,
|
||||
} from '../api/client';
|
||||
|
||||
interface FetchedModel {
|
||||
id: string;
|
||||
enabled: boolean;
|
||||
/** 来源:api=接口拉取,custom=用户手动添加 */
|
||||
source: 'api' | 'custom';
|
||||
/** 已入库的模型配置 ID(用于自定义模型的删除) */
|
||||
configId?: string;
|
||||
}
|
||||
|
||||
/** 密钥展示组件(小眼睛切换显示/隐藏) */
|
||||
function ApiKeyCell({ value }: { value: string }) {
|
||||
const [visible, setVisible] = useState(false);
|
||||
return (
|
||||
<Space size={4}>
|
||||
<Typography.Text code style={{ fontSize: 12 }}>
|
||||
{visible ? value : '•'.repeat(Math.min(value.length, 20))}
|
||||
</Typography.Text>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={visible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
|
||||
onClick={() => setVisible(!visible)}
|
||||
/>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
|
||||
interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
base_url: string;
|
||||
api_key: string;
|
||||
description: string;
|
||||
is_enabled: boolean;
|
||||
}
|
||||
|
||||
export default function ProviderManager() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [providers, setProviders] = useState<Provider[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<Provider | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [testing, setTesting] = useState<string>('');
|
||||
const [form] = Form.useForm();
|
||||
// 模型拉取弹窗
|
||||
const [fetchModalOpen, setFetchModalOpen] = useState(false);
|
||||
const [fetchProvider, setFetchProvider] = useState<Provider | null>(null);
|
||||
const [fetchedModels, setFetchedModels] = useState<FetchedModel[]>([]);
|
||||
const [fetchLoading, setFetchLoading] = useState(false);
|
||||
const [modelQuery, setModelQuery] = useState('');
|
||||
const [modelPage, setModelPage] = useState(1);
|
||||
const [customModelInput, setCustomModelInput] = useState('');
|
||||
const MODEL_PAGE_SIZE = 10;
|
||||
|
||||
/** 打开模型拉取弹窗(合并 API 拉取 + 已有自定义模型) */
|
||||
const openFetchModels = async (record: Provider) => {
|
||||
setFetchProvider(record);
|
||||
setFetchModalOpen(true);
|
||||
setFetchLoading(true);
|
||||
setFetchedModels([]);
|
||||
setModelQuery('');
|
||||
setModelPage(1);
|
||||
setCustomModelInput('');
|
||||
try {
|
||||
// 1. 拉取 API 模型列表
|
||||
const modelIds = await fetchProviderModels(record.id);
|
||||
const apiSet = new Set(modelIds);
|
||||
|
||||
// 2. 读取已有模型配置,区分「已启用」和「自定义」
|
||||
const existing = await listModelConfigs();
|
||||
const providerModels = existing.filter((m) => m.provider_key === record.name);
|
||||
const enabledSet = new Set(
|
||||
providerModels.filter((m) => m.is_enabled).map((m) => m.model_id),
|
||||
);
|
||||
|
||||
const apiModels: FetchedModel[] = modelIds.map((id) => ({
|
||||
id,
|
||||
enabled: enabledSet.has(id),
|
||||
source: 'api' as const,
|
||||
configId: providerModels.find((m) => m.model_id === id)?.id,
|
||||
}));
|
||||
|
||||
// 3. 已有配置中不在 API 列表里的 → 自定义模型
|
||||
const customModels: FetchedModel[] = providerModels
|
||||
.filter((m) => !apiSet.has(m.model_id))
|
||||
.map((m) => ({
|
||||
id: m.model_id,
|
||||
enabled: m.is_enabled,
|
||||
source: 'custom' as const,
|
||||
configId: m.id,
|
||||
}));
|
||||
|
||||
setFetchedModels([...apiModels, ...customModels]);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setFetchLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 添加自定义模型(写入模型配置表 + 刷新列表) */
|
||||
const addCustomModel = async () => {
|
||||
const modelId = customModelInput.trim();
|
||||
if (!modelId || !fetchProvider) return;
|
||||
// 去重检查
|
||||
if (fetchedModels.some((m) => m.id === modelId)) {
|
||||
messageApi.warning(`模型 ${modelId} 已存在`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const created = await createModelConfig({
|
||||
display_name: modelId,
|
||||
model_id: modelId,
|
||||
provider_key: fetchProvider.name,
|
||||
model_role: 'general',
|
||||
is_enabled: true,
|
||||
sort_order: 50,
|
||||
description: '自定义模型',
|
||||
});
|
||||
setFetchedModels((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: modelId,
|
||||
enabled: true,
|
||||
source: 'custom',
|
||||
configId: created.id,
|
||||
},
|
||||
]);
|
||||
setCustomModelInput('');
|
||||
messageApi.success(`已添加自定义模型 ${modelId}`);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除自定义模型(从配置表移除 + 刷新列表) */
|
||||
const removeCustomModel = async (modelId: string, configId?: string) => {
|
||||
try {
|
||||
if (configId) {
|
||||
await deleteModelConfig(configId);
|
||||
}
|
||||
setFetchedModels((prev) => prev.filter((m) => m.id !== modelId));
|
||||
messageApi.success(`已删除自定义模型 ${modelId}`);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 启用/停用模型(同步到模型配置表) */
|
||||
const toggleModel = async (modelId: string, enabled: boolean) => {
|
||||
if (!fetchProvider) return;
|
||||
try {
|
||||
const existing = await listModelConfigs();
|
||||
const found = existing.find(
|
||||
(m) => m.provider_key === fetchProvider.name && m.model_id === modelId,
|
||||
);
|
||||
if (enabled) {
|
||||
if (found) {
|
||||
await updateModelConfig(found.id, { is_enabled: true });
|
||||
} else {
|
||||
await createModelConfig({
|
||||
display_name: modelId,
|
||||
model_id: modelId,
|
||||
provider_key: fetchProvider.name,
|
||||
model_role: 'general',
|
||||
is_enabled: true,
|
||||
sort_order: 50,
|
||||
description: `从 ${fetchProvider.name} 拉取`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (found) {
|
||||
await updateModelConfig(found.id, { is_enabled: false });
|
||||
}
|
||||
}
|
||||
setFetchedModels((prev) =>
|
||||
prev.map((m) => (m.id === modelId ? { ...m, enabled } : m)),
|
||||
);
|
||||
messageApi.success(enabled ? `已启用 ${modelId}` : `已停用 ${modelId}`);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await listProviders();
|
||||
setProviders(data ?? []);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
form.setFieldsValue({ name: '', base_url: '', api_key: '', description: '' });
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (record: Provider) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
name: record.name,
|
||||
base_url: record.base_url,
|
||||
api_key: record.api_key,
|
||||
description: record.description,
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const values = await form.validateFields();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await updateProvider(editing.id, values);
|
||||
messageApi.success('Provider 更新成功');
|
||||
} else {
|
||||
await createProvider(values);
|
||||
messageApi.success('Provider 创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = async (record: Provider) => {
|
||||
setTesting(record.id);
|
||||
try {
|
||||
const result = await testProvider(record.id);
|
||||
if (result.success) {
|
||||
messageApi.success(result.message);
|
||||
} else {
|
||||
messageApi.warning(result.message);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setTesting('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (record: Provider) => {
|
||||
try {
|
||||
await deleteProvider(record.id);
|
||||
messageApi.success('删除成功');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<Provider> = [
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
render: (v: string) => (
|
||||
<Space size={4}>
|
||||
<ApiOutlined style={{ color: '#1677ff', flexShrink: 0 }} />
|
||||
<Typography.Text strong ellipsis={{ tooltip: v }}>{v}</Typography.Text>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '服务地址',
|
||||
dataIndex: 'base_url',
|
||||
key: 'base_url',
|
||||
width: 220,
|
||||
ellipsis: true,
|
||||
render: (v: string) => (
|
||||
<Typography.Text code style={{ fontSize: 12 }} ellipsis={{ tooltip: v }}>
|
||||
{v}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'API 密钥',
|
||||
dataIndex: 'api_key',
|
||||
key: 'api_key',
|
||||
width: 160,
|
||||
ellipsis: true,
|
||||
render: (v: string) => <ApiKeyCell value={v} />,
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'description',
|
||||
key: 'description',
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
render: (v: string) => (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{v || '—'}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '启用',
|
||||
key: 'is_enabled',
|
||||
width: 70,
|
||||
render: (_, record) => (
|
||||
<Switch
|
||||
size="small"
|
||||
checked={record.is_enabled}
|
||||
onChange={async (checked) => {
|
||||
await updateProvider(record.id, { is_enabled: checked });
|
||||
await load();
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 200,
|
||||
render: (_, record) => (
|
||||
<Space size={4} wrap>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CheckCircleOutlined />}
|
||||
loading={testing === record.id}
|
||||
onClick={() => handleTest(record)}
|
||||
>
|
||||
测试
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CloudDownloadOutlined />}
|
||||
onClick={() => openFetchModels(record)}
|
||||
>
|
||||
拉取
|
||||
</Button>
|
||||
<Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm title="确认删除该 Provider?" onConfirm={() => handleDelete(record)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 12, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Text type="secondary">
|
||||
配置各 AI 平台的连接信息(服务地址 + 密钥),模型管理中的模型将按 Provider 路由调用
|
||||
</Typography.Text>
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
|
||||
新增 Provider
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
<Table<Provider>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={providers}
|
||||
pagination={false}
|
||||
size="small"
|
||||
locale={{ emptyText: '暂无 Provider,请添加一个 AI 平台' }}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
title={editing ? '编辑 Provider' : '新增 Provider'}
|
||||
open={modalOpen}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={submitting}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
width={520}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Provider 名称"
|
||||
rules={[{ required: true, message: '请输入名称' }]}
|
||||
extra="模型管理中按此名称引用,如 ccswitch / zhipu / deepseek"
|
||||
>
|
||||
<Input placeholder="如:zhipu" disabled={!!editing} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="base_url"
|
||||
label="服务地址"
|
||||
rules={[{ required: true, message: '请输入服务地址' }]}
|
||||
extra="OpenAI 兼容 API 地址,如 https://open.bigmodel.cn/api/paas/v4"
|
||||
>
|
||||
<Input placeholder="https://xxx.com/v1" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="api_key"
|
||||
label="API 密钥"
|
||||
extra="点击右侧小眼睛可显示/隐藏密钥"
|
||||
>
|
||||
<Input.Password placeholder="sk-xxx" />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="备注">
|
||||
<Input placeholder="如:智谱 GLM 平台" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* 模型拉取弹窗 */}
|
||||
<Modal
|
||||
title={
|
||||
<Space>
|
||||
<CloudDownloadOutlined />
|
||||
<span>拉取模型 — {fetchProvider?.name}</span>
|
||||
</Space>
|
||||
}
|
||||
open={fetchModalOpen}
|
||||
onCancel={() => setFetchModalOpen(false)}
|
||||
width={520}
|
||||
footer={
|
||||
<Button onClick={() => setFetchModalOpen(false)}>关闭</Button>
|
||||
}
|
||||
>
|
||||
{fetchLoading ? (
|
||||
<div style={{ textAlign: 'center', padding: 40 }}>
|
||||
<Spin tip="正在拉取模型列表…" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* 自定义模型添加区 */}
|
||||
<Space.Compact style={{ width: '100%', marginBottom: 12 }}>
|
||||
<Input
|
||||
placeholder="输入自定义模型 ID,如 gpt-4o-mini / my-finetuned"
|
||||
value={customModelInput}
|
||||
onChange={(e) => setCustomModelInput(e.target.value)}
|
||||
onPressEnter={addCustomModel}
|
||||
/>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={addCustomModel}>
|
||||
添加
|
||||
</Button>
|
||||
</Space.Compact>
|
||||
|
||||
{/* 搜索框:按模型 ID 过滤 */}
|
||||
<Input
|
||||
placeholder="搜索模型 ID…"
|
||||
allowClear
|
||||
value={modelQuery}
|
||||
onChange={(e) => {
|
||||
setModelQuery(e.target.value);
|
||||
setModelPage(1);
|
||||
}}
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
|
||||
{fetchedModels.length === 0 ? (
|
||||
<Typography.Text type="secondary">未拉取到可用模型,可手动添加自定义模型</Typography.Text>
|
||||
) : (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={fetchedModels.filter((m) =>
|
||||
m.id.toLowerCase().includes(modelQuery.toLowerCase())
|
||||
)}
|
||||
pagination={{
|
||||
current: modelPage,
|
||||
pageSize: MODEL_PAGE_SIZE,
|
||||
showSizeChanger: false,
|
||||
showTotal: (t) => `共 ${t} 个模型`,
|
||||
size: 'small',
|
||||
onChange: (page) => setModelPage(page),
|
||||
}}
|
||||
renderItem={(item) => (
|
||||
<List.Item
|
||||
actions={[
|
||||
<Switch
|
||||
key="toggle"
|
||||
checked={item.enabled}
|
||||
checkedChildren="启用"
|
||||
unCheckedChildren="停用"
|
||||
onChange={(checked) => toggleModel(item.id, checked)}
|
||||
/>,
|
||||
item.source === 'custom' ? (
|
||||
<Popconfirm
|
||||
key="del"
|
||||
title="确认删除该自定义模型?"
|
||||
onConfirm={() => removeCustomModel(item.id, item.configId)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button type="text" size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
) : null,
|
||||
]}
|
||||
>
|
||||
<List.Item.Meta
|
||||
avatar={<ApiOutlined style={{ color: item.enabled ? '#52c41a' : '#d9d9d9' }} />}
|
||||
title={
|
||||
<Space size={6}>
|
||||
<Typography.Text code>{item.id}</Typography.Text>
|
||||
{item.source === 'custom' ? (
|
||||
<Tooltip title="用户手动添加的模型">
|
||||
<Tag color="blue" style={{ marginInlineEnd: 0 }}>自定义</Tag>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tag color="green" style={{ marginInlineEnd: 0 }}>API</Tag>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
description={
|
||||
item.enabled ? (
|
||||
<Tag color="green">已启用</Tag>
|
||||
) : (
|
||||
<Tag color="default">未启用</Tag>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
/**
|
||||
* 系统配置页面组件
|
||||
*
|
||||
* 【功能说明】.env 配置项的增删改查 + 分组表单快速编辑。
|
||||
* 【技术选型理由】AntD Table CRUD + Card 分组表单,双模式互补。
|
||||
* 【安全设计】敏感字段脱敏显示,保存时不修改则保留原值。
|
||||
*/
|
||||
import {
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
PlusOutlined,
|
||||
ReloadOutlined,
|
||||
SaveOutlined,
|
||||
SearchOutlined,
|
||||
SettingOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Table,
|
||||
Tabs,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
createEnvItem,
|
||||
deleteEnvItem,
|
||||
getEnvConfig,
|
||||
getEnvItems,
|
||||
saveEnvConfig,
|
||||
updateEnvItem,
|
||||
} from '../api/client';
|
||||
|
||||
interface EnvItem {
|
||||
key: string;
|
||||
value: string;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
/** 分组表单配置(快速编辑常用配置) */
|
||||
const CONFIG_GROUPS = [
|
||||
{
|
||||
key: 'app',
|
||||
title: '应用基础',
|
||||
fields: [
|
||||
{ name: 'APP_NAME', label: '应用名称', type: 'text' },
|
||||
{ name: 'APP_HOST', label: '监听地址', type: 'text' },
|
||||
{ name: 'APP_PORT', label: '监听端口', type: 'number' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'ccswitch',
|
||||
title: 'ccswitch 代理(模型服务通道)',
|
||||
fields: [
|
||||
{ name: 'CCSWITCH_BASE_URL', label: '代理地址', type: 'text' },
|
||||
{ name: 'CCSWITCH_API_KEY', label: '代理密钥', type: 'password' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'engine',
|
||||
title: '改码引擎',
|
||||
fields: [
|
||||
{
|
||||
name: 'CODING_ENGINE',
|
||||
label: '改码引擎',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ label: 'builtin', value: 'builtin' },
|
||||
{ label: 'claude_code', value: 'claude_code' },
|
||||
],
|
||||
},
|
||||
{ name: 'CLAUDE_TIMEOUT_SECONDS', label: 'Claude 超时', type: 'number' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export default function SystemSettings() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
// 配置项列表模式
|
||||
const [items, setItems] = useState<EnvItem[]>([]);
|
||||
const [itemsLoading, setItemsLoading] = useState(false);
|
||||
const [searchKey, setSearchKey] = useState('');
|
||||
// 新增/编辑弹窗
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<EnvItem | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [itemForm] = Form.useForm();
|
||||
// 分组表单模式
|
||||
const [formLoading, setFormLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [groupForm] = Form.useForm();
|
||||
// 分页受控
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(12);
|
||||
|
||||
/** 加载配置项列表 */
|
||||
const loadItems = useCallback(async () => {
|
||||
setItemsLoading(true);
|
||||
try {
|
||||
const data = await getEnvItems(searchKey);
|
||||
setItems(data ?? []);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setItemsLoading(false);
|
||||
}
|
||||
}, [searchKey, messageApi]);
|
||||
|
||||
/** 加载分组表单 */
|
||||
const loadGroupForm = useCallback(async () => {
|
||||
setFormLoading(true);
|
||||
try {
|
||||
const data = await getEnvConfig();
|
||||
if (data) groupForm.setFieldsValue(data);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setFormLoading(false);
|
||||
}
|
||||
}, [groupForm, messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
loadItems();
|
||||
loadGroupForm();
|
||||
}, [loadItems, loadGroupForm]);
|
||||
|
||||
/** 打开新增弹窗 */
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
itemForm.setFieldsValue({ key: '', value: '', remark: '' });
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
/** 打开编辑弹窗 */
|
||||
const openEdit = (record: EnvItem) => {
|
||||
setEditing(record);
|
||||
itemForm.setFieldsValue({ key: record.key, value: record.value, remark: record.remark });
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
/** 提交新增/编辑 */
|
||||
const handleItemSubmit = async () => {
|
||||
const values = await itemForm.validateFields();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await updateEnvItem(editing.key, {
|
||||
value: values.value,
|
||||
new_key: values.key,
|
||||
remark: values.remark || '',
|
||||
});
|
||||
messageApi.success('配置项已更新');
|
||||
} else {
|
||||
await createEnvItem(values);
|
||||
messageApi.success('配置项已添加');
|
||||
}
|
||||
setModalOpen(false);
|
||||
await loadItems();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除配置项 */
|
||||
const handleItemDelete = async (record: EnvItem) => {
|
||||
try {
|
||||
await deleteEnvItem(record.key);
|
||||
messageApi.success(`配置 ${record.key} 已删除`);
|
||||
await loadItems();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存分组表单 */
|
||||
const handleGroupSave = async () => {
|
||||
const values = await groupForm.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
await saveEnvConfig(values);
|
||||
messageApi.success('配置已保存到 .env');
|
||||
await loadGroupForm();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 配置项表格列 */
|
||||
const itemColumns: ColumnsType<EnvItem> = [
|
||||
{
|
||||
title: '配置名',
|
||||
dataIndex: 'key',
|
||||
key: 'key',
|
||||
width: 220,
|
||||
render: (v: string) => <Typography.Text code strong>{v}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '值',
|
||||
dataIndex: 'value',
|
||||
key: 'value',
|
||||
width: 220,
|
||||
ellipsis: true,
|
||||
render: (v: string) => (
|
||||
<Typography.Text code style={{ fontSize: 12 }}>{v}</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'remark',
|
||||
key: 'remark',
|
||||
ellipsis: true,
|
||||
render: (v: string) =>
|
||||
v ? (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>{v}</Typography.Text>
|
||||
) : (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>—</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 150,
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
<Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={`确认删除配置 ${record.key}?`}
|
||||
description="删除后将从 .env 文件中移除"
|
||||
onConfirm={() => handleItemDelete(record)}
|
||||
>
|
||||
<Button size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
/** 渲染分组表单字段 */
|
||||
const renderGroupField = (field: { name: string; label: string; type: string; options?: Array<{ label: string; value: string }> }) => {
|
||||
switch (field.type) {
|
||||
case 'password':
|
||||
return <Form.Item name={field.name} label={field.label}><Input.Password placeholder="****** 表示不修改" /></Form.Item>;
|
||||
case 'number':
|
||||
return <Form.Item name={field.name} label={field.label}><InputNumber style={{ width: '100%' }} /></Form.Item>;
|
||||
case 'select':
|
||||
return <Form.Item name={field.name} label={field.label}><Select options={field.options} /></Form.Item>;
|
||||
default:
|
||||
return <Form.Item name={field.name} label={field.label}><Input /></Form.Item>;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Typography.Title level={4}>
|
||||
<SettingOutlined /> 系统配置
|
||||
</Typography.Title>
|
||||
|
||||
<Tabs
|
||||
defaultActiveKey="items"
|
||||
items={[
|
||||
// ========== 模式一:配置项 CRUD 表格 ==========
|
||||
{
|
||||
key: 'items',
|
||||
label: '配置项管理',
|
||||
children: (
|
||||
<Space direction="vertical" style={{ width: '100%' }} size="middle">
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
|
||||
<Input
|
||||
placeholder="按配置名搜索"
|
||||
prefix={<SearchOutlined style={{ color: '#999' }} />}
|
||||
value={searchKey}
|
||||
onChange={(e) => setSearchKey(e.target.value)}
|
||||
allowClear
|
||||
style={{ width: 260 }}
|
||||
/>
|
||||
<Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={loadItems}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
|
||||
新增配置项
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
<Table<EnvItem>
|
||||
rowKey="key"
|
||||
loading={itemsLoading}
|
||||
columns={itemColumns}
|
||||
dataSource={items}
|
||||
pagination={{
|
||||
current: currentPage,
|
||||
pageSize: pageSize,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [10, 12, 20, 50, 100],
|
||||
showTotal: (t) => `共 ${t} 项配置`,
|
||||
onChange: (page, size) => {
|
||||
setCurrentPage(page);
|
||||
setPageSize(size);
|
||||
},
|
||||
onShowSizeChange: (_, size) => {
|
||||
setPageSize(size);
|
||||
setCurrentPage(1);
|
||||
},
|
||||
}}
|
||||
size="small"
|
||||
/>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
// ========== 模式二:分组表单快速编辑 ==========
|
||||
{
|
||||
key: 'groups',
|
||||
label: '常用配置(分组编辑)',
|
||||
children: (
|
||||
<Spin spinning={formLoading}>
|
||||
<Space style={{ width: '100%', justifyContent: 'flex-end', marginBottom: 16 }}>
|
||||
<Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleGroupSave}>
|
||||
保存到 .env
|
||||
</Button>
|
||||
</Space>
|
||||
<Form form={groupForm} layout="vertical">
|
||||
<Row gutter={[16, 0]}>
|
||||
{CONFIG_GROUPS.map((group) => (
|
||||
<Col span={12} key={group.key}>
|
||||
<Card size="small" title={group.title} style={{ marginBottom: 16 }}>
|
||||
{group.fields.map((field) => (
|
||||
<div key={field.name}>{renderGroupField(field)}</div>
|
||||
))}
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
</Form>
|
||||
</Spin>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
{/* 新增/编辑配置项弹窗 */}
|
||||
<Modal
|
||||
title={editing ? `编辑配置:${editing.key}` : '新增配置项'}
|
||||
open={modalOpen}
|
||||
onOk={handleItemSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={submitting}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
width={480}
|
||||
>
|
||||
<Form form={itemForm} layout="vertical">
|
||||
<Form.Item
|
||||
name="key"
|
||||
label="配置名"
|
||||
rules={[
|
||||
{ required: true, message: '请输入配置名' },
|
||||
{ pattern: /^[A-Za-z_][A-Za-z0-9_]*$/, message: '只能包含字母、数字、下划线' },
|
||||
]}
|
||||
>
|
||||
<Input placeholder="如:MY_CONFIG_KEY" disabled={!!editing} />
|
||||
</Form.Item>
|
||||
<Form.Item name="value" label="配置值" rules={[{ required: true, message: '请输入配置值' }]}>
|
||||
<Input.TextArea rows={3} placeholder="配置值" />
|
||||
</Form.Item>
|
||||
<Form.Item name="remark" label="备注" extra="说明这个配置是做什么的,便于后期维护">
|
||||
<Input.TextArea rows={2} maxLength={200} placeholder="如:模型服务的 API 密钥" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,834 @@
|
||||
/**
|
||||
* 任务中心页面组件(重构版)
|
||||
*
|
||||
* 【功能说明】一条任务 = 一个完整对话。
|
||||
* - 左侧任务列表(可搜索、可删除)
|
||||
* - 点击任务 → 弹出对话框,展示历史对话,可继续对话
|
||||
* - 「新建需求」→ 弹出对话框,选项目后展示项目信息,然后开始对话
|
||||
* 【设计】极简布局:单列表 + 对话弹窗,去掉批量提交。
|
||||
*/
|
||||
import {
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
DeleteOutlined,
|
||||
ExclamationCircleOutlined,
|
||||
PlayCircleOutlined,
|
||||
PlusOutlined,
|
||||
QuestionCircleOutlined,
|
||||
ReloadOutlined,
|
||||
RollbackOutlined,
|
||||
SafetyOutlined,
|
||||
SearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Col,
|
||||
Descriptions,
|
||||
Empty,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
Table,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import {
|
||||
batchDeleteTasks,
|
||||
continueChat,
|
||||
createTask,
|
||||
getTask,
|
||||
listModelOptions,
|
||||
listProjects,
|
||||
listTasks,
|
||||
rollbackTask,
|
||||
stopTask,
|
||||
submitApproval,
|
||||
} from '../api/client';
|
||||
import type { ModelOption, Project, Task, TaskEvent } from '../types';
|
||||
|
||||
/** 状态 → 标签配置 */
|
||||
const STATUS_CONFIG: Record<string, { color: string; label: string; icon: JSX.Element }> = {
|
||||
running: { color: 'processing', label: '执行中', icon: <PlayCircleOutlined /> },
|
||||
waiting_approval: { color: 'warning', label: '待审批', icon: <SafetyOutlined /> },
|
||||
done: { color: 'success', label: '已完成', icon: <CheckCircleOutlined /> },
|
||||
failed: { color: 'error', label: '失败', icon: <CloseCircleOutlined /> },
|
||||
degraded: { color: 'default', label: '降级完成', icon: <ExclamationCircleOutlined /> },
|
||||
};
|
||||
|
||||
/** 解析 chat_history JSON */
|
||||
function parseChatHistory(json: string): { role: 'user' | 'assistant'; content: string }[] {
|
||||
try {
|
||||
return (JSON.parse(json || '[]') as { role: string; content: string }[]).map((m) => ({
|
||||
role: m.role === 'user' ? 'user' : 'assistant',
|
||||
content: m.content,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** 渲染 Claude 输出:流式时半截 markdown 做兜底,完整后正常渲染 */
|
||||
function RenderClaudeOutput({ content, streaming }: { content: string; streaming?: boolean }) {
|
||||
if (!content) return <span style={{ color: '#bbb' }}>(输出中…)</span>;
|
||||
|
||||
// 流式过程中:半截代码块/表格可能渲染异常,用 pre-wrap 平铺
|
||||
if (streaming) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
fontSize: 14,
|
||||
lineHeight: 1.8,
|
||||
color: '#1a1a1a',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
fontFamily: 'system-ui, -apple-system, "Segoe UI", sans-serif',
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 完整后:react-markdown 正常渲染
|
||||
return (
|
||||
<div style={{ fontSize: 14, lineHeight: 1.8, color: '#1a1a1a' }}>
|
||||
<ReactMarkdown>{content}</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
/** 解析服务列表:兼容数组对象和 JSON 字符串 */
|
||||
function parseServices(val: unknown): { label: string; branch: string; path?: string }[] {
|
||||
if (Array.isArray(val)) return val as { label: string; branch: string; path?: string }[];
|
||||
try {
|
||||
return JSON.parse((val as string) || '[]');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export default function TaskCenter() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
const [tasks, setTasks] = useState<Task[]>([]);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [modelOptions, setModelOptions] = useState<ModelOption[]>([]);
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([]);
|
||||
const [searchKey, setSearchKey] = useState('');
|
||||
|
||||
// 对话弹窗
|
||||
const [chatOpen, setChatOpen] = useState(false);
|
||||
const [chatTask, setChatTask] = useState<Task | null>(null); // 已有任务(续聊)
|
||||
const [chatMessages, setChatMessages] = useState<
|
||||
{ role: 'user' | 'assistant'; content: string }[]
|
||||
>([]);
|
||||
const [chatInput, setChatInput] = useState('');
|
||||
// 输入框高度固定为 96px(不再提供拖拽伸缩)
|
||||
const [chatStreaming, setChatStreaming] = useState(false);
|
||||
const [chatModel, setChatModel] = useState<string>('auto');
|
||||
const [useVectorSearch, setUseVectorSearch] = useState(false);
|
||||
const [chatProject, setChatProject] = useState<Project | null>(null);
|
||||
|
||||
// 新建需求配置
|
||||
const [form] = Form.useForm();
|
||||
const eventSourceRef = useRef<EventSource | null>(null);
|
||||
// 【L5】用 ref 转发 subscribeStream 自身,避免 useCallback 自引用造成循环依赖
|
||||
const subscribeStreamRef = useRef<(taskId: string, attempt?: number) => void>(() => {});
|
||||
// 对话滚动容器 + 「用户是否贴在底部」标记
|
||||
// 【滚动条跳动修复】流式输出每来一段就触发一次自动滚动,
|
||||
// 若用 scrollIntoView({behavior:'smooth'}) 会动画打架,视觉上就是滚动条一直自己跳;
|
||||
// 且用户上翻阅读时会被强行拽回底部。故改为:只在用户本来就贴底时才滚,且瞬时滚动。
|
||||
const chatScrollRef = useRef<HTMLDivElement>(null);
|
||||
const stickToBottomRef = useRef(true);
|
||||
|
||||
/** 加载任务与项目列表 */
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const [taskList, projectList, models] = await Promise.all([
|
||||
listTasks(),
|
||||
listProjects(),
|
||||
listModelOptions(),
|
||||
]);
|
||||
setTasks(taskList ?? []);
|
||||
setProjects(projectList ?? []);
|
||||
setModelOptions(models ?? []);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
}, [messageApi]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
return () => {
|
||||
eventSourceRef.current?.close();
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
/** 用户滚动对话区:据此判断是否还贴在底部 */
|
||||
const handleChatScroll = useCallback(() => {
|
||||
const el = chatScrollRef.current;
|
||||
if (!el) return;
|
||||
// 距离底部 80px 以内视为「贴底」,否则认为用户在翻阅历史
|
||||
const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||
stickToBottomRef.current = distanceFromBottom < 80;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 自动滚动到底部。
|
||||
* 【对话框跳动修复 · 第 2 版】
|
||||
* 1. 只在用户本来就贴底时才滚,上翻阅读不打扰;
|
||||
* 2. 用 useLayoutEffect 而非 useEffect+rAF:
|
||||
* 它在 DOM 变更后、浏览器绘制**前**同步执行,scrollHeight 一定是最准的,
|
||||
* 不会出现「先按旧高度滚 → 再按新高度滚」的两段跳;
|
||||
* 3. 瞬时 scrollTop,绝不用 smooth——流式高频更新时动画会互相打架;
|
||||
* 4. 容器设 overflowAnchor:none,关掉浏览器滚动锚定(它会和我们抢 scrollTop)。
|
||||
*/
|
||||
useLayoutEffect(() => {
|
||||
if (!stickToBottomRef.current) return;
|
||||
const el = chatScrollRef.current;
|
||||
if (el) {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
// chatStreaming 也要盯:流式结束切 markdown 时高度会突变,需重新对齐
|
||||
}, [chatMessages, chatStreaming]);
|
||||
|
||||
/** 订阅任务 SSE 流式输出 */
|
||||
const subscribeStream = useCallback(
|
||||
(taskId: string, attempt = 0) => {
|
||||
eventSourceRef.current?.close();
|
||||
const es = new EventSource(`/api/tasks/${taskId}/stream`);
|
||||
eventSourceRef.current = es;
|
||||
|
||||
es.addEventListener('claude_output', (e) => {
|
||||
const payload = JSON.parse((e as MessageEvent).data) as TaskEvent;
|
||||
const text = payload.message || '';
|
||||
// 过滤 Claude SDK 的模型名校验噪音
|
||||
if (text.includes('[claude-code:unrecognized_model]')) return;
|
||||
setChatMessages((prev) => {
|
||||
const updated = [...prev];
|
||||
const last = updated[updated.length - 1];
|
||||
if (last && last.role === 'assistant') {
|
||||
updated[updated.length - 1] = {
|
||||
...last,
|
||||
content: last.content + text,
|
||||
};
|
||||
} else {
|
||||
updated.push({ role: 'assistant', content: text });
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
});
|
||||
|
||||
es.addEventListener('done', async () => {
|
||||
// 【滚动条跳动根因】必须关闭连接:
|
||||
// EventSource 默认自动重连。服务端推完 done 就关流,
|
||||
// 浏览器随即重连 → 又收到 done → 又关流……无限循环。
|
||||
// 每轮都触发 setChatMessages 全量替换 + load(),
|
||||
// ReactMarkdown 整体重渲染 → 滚动条忽长忽短、页面周期性跳动。
|
||||
es.close();
|
||||
if (eventSourceRef.current === es) eventSourceRef.current = null;
|
||||
setChatStreaming(false);
|
||||
// 从后端拉完整对话历史,确保即使流式事件丢失也能展示完整回复
|
||||
try {
|
||||
const fresh = await getTask(taskId);
|
||||
setChatTask(fresh);
|
||||
setChatMessages(parseChatHistory(fresh.chat_history));
|
||||
} catch {
|
||||
// 拉取失败不阻塞
|
||||
}
|
||||
load();
|
||||
});
|
||||
|
||||
es.addEventListener('error', async () => {
|
||||
// 【L5】SSE 断线(后端重启等)不再直接放弃:
|
||||
// 任务若仍在执行,自动重连继续收流式输出;
|
||||
// 只有任务已终态才收口展示最终结果。
|
||||
// 无论走哪条分支,终态都必须 es.close(),否则 EventSource 会无限自动重连。
|
||||
try {
|
||||
const fresh = await getTask(taskId);
|
||||
setChatTask(fresh);
|
||||
|
||||
if (fresh.status === 'running') {
|
||||
// 仍在执行 → 先关掉这条已死的连接,再退避重连
|
||||
es.close();
|
||||
if (eventSourceRef.current === es) eventSourceRef.current = null;
|
||||
const nextAttempt = attempt + 1;
|
||||
const delay = Math.min(2000 * nextAttempt, 15000);
|
||||
if (nextAttempt <= 30) {
|
||||
window.setTimeout(
|
||||
() => subscribeStreamRef.current(taskId, nextAttempt),
|
||||
delay,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// 重试次数用尽:给明确提示,不再假装正常
|
||||
setChatStreaming(false);
|
||||
setChatMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
role: 'assistant',
|
||||
content:
|
||||
'⚠️ 与服务端的实时连接已断开且重连失败,但任务仍在后台执行。请稍后重新打开该对话查看完整结果。',
|
||||
},
|
||||
]);
|
||||
load();
|
||||
return;
|
||||
}
|
||||
|
||||
// 已终态 → 关连接收口,避免无限重连反复重渲染
|
||||
es.close();
|
||||
if (eventSourceRef.current === es) eventSourceRef.current = null;
|
||||
setChatStreaming(false);
|
||||
setChatMessages(parseChatHistory(fresh.chat_history));
|
||||
} catch {
|
||||
// 拉取失败也走重连,避免网络抖动直接判死
|
||||
es.close();
|
||||
if (eventSourceRef.current === es) eventSourceRef.current = null;
|
||||
const nextAttempt = attempt + 1;
|
||||
if (nextAttempt <= 30) {
|
||||
const delay = Math.min(2000 * nextAttempt, 15000);
|
||||
window.setTimeout(
|
||||
() => subscribeStreamRef.current(taskId, nextAttempt),
|
||||
delay,
|
||||
);
|
||||
return;
|
||||
}
|
||||
setChatStreaming(false);
|
||||
}
|
||||
load();
|
||||
});
|
||||
},
|
||||
[load],
|
||||
);
|
||||
|
||||
// 保持 ref 指向最新的 subscribeStream
|
||||
useEffect(() => {
|
||||
subscribeStreamRef.current = subscribeStream;
|
||||
}, [subscribeStream]);
|
||||
|
||||
/** 打开已有任务的对话框 */
|
||||
const openTaskChat = async (task: Task) => {
|
||||
try {
|
||||
eventSourceRef.current?.close(); // 【BUG-1 修复】关旧 SSE,防止旧任务输出串到新对话
|
||||
stickToBottomRef.current = true; // 打开对话时从底部开始看
|
||||
const fresh = await getTask(task.id);
|
||||
setChatTask(fresh);
|
||||
setChatMessages(parseChatHistory(fresh.chat_history));
|
||||
setChatModel(fresh.model_preference || 'auto');
|
||||
const proj = projects.find((p) => p.id === fresh.project_id) || null;
|
||||
setChatProject(proj);
|
||||
setChatInput('');
|
||||
setChatStreaming(false); // 【BUG-1 修复】切换对话时重置流式状态
|
||||
setChatOpen(true);
|
||||
// 如果正在执行,订阅流式输出
|
||||
if (fresh.status === 'running') {
|
||||
setChatStreaming(true);
|
||||
subscribeStream(fresh.id);
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 新建需求:打开空对话框 */
|
||||
const openNewChat = () => {
|
||||
eventSourceRef.current?.close(); // 【BUG-1 修复】关旧 SSE,防止旧任务输出串到新对话
|
||||
stickToBottomRef.current = true;
|
||||
setChatTask(null);
|
||||
setChatMessages([]);
|
||||
setChatProject(null);
|
||||
setChatInput('');
|
||||
setChatModel('auto');
|
||||
setUseVectorSearch(false);
|
||||
setChatStreaming(false); // 【BUG-1 修复】切换对话时重置流式状态
|
||||
setChatOpen(true);
|
||||
form.resetFields();
|
||||
};
|
||||
|
||||
/** 项目选择变化 → 展示项目信息 */
|
||||
const handleProjectChange = (projectId: string) => {
|
||||
const proj = projects.find((p) => p.id === projectId) || null;
|
||||
setChatProject(proj);
|
||||
if (proj) {
|
||||
const backends = parseServices(proj.backends);
|
||||
const frontends = parseServices(proj.frontends);
|
||||
const lines = [`已选择项目「${proj.name}」`];
|
||||
if (backends.length > 0) {
|
||||
lines.push(`后端服务:${backends.map((b) => `${b.label} → ${proj.code_root_path}\\${b.path || b.label} (${b.branch})`).join('\n')}`);
|
||||
}
|
||||
if (frontends.length > 0) {
|
||||
lines.push(`前端服务:${frontends.map((f) => `${f.label} → ${proj.code_root_path}\\${f.path || f.label} (${f.branch})`).join('\n')}`);
|
||||
}
|
||||
lines.push('请描述你的需求…');
|
||||
setChatMessages([{ role: 'assistant', content: lines.join('\n') }]);
|
||||
}
|
||||
};
|
||||
|
||||
/** 发送消息 */
|
||||
const handleChatSend = async () => {
|
||||
const text = chatInput.trim();
|
||||
if (!text || chatStreaming) return;
|
||||
|
||||
// 用户主动发消息 = 想看最新内容,强制恢复自动滚到底
|
||||
stickToBottomRef.current = true;
|
||||
setChatMessages((prev) => [...prev, { role: 'user', content: text }]);
|
||||
setChatInput('');
|
||||
setChatStreaming(true);
|
||||
|
||||
try {
|
||||
if (chatTask) {
|
||||
// 续聊:追加到已有任务,支持切换模型
|
||||
await continueChat(chatTask.id, text, chatModel);
|
||||
subscribeStream(chatTask.id);
|
||||
await load(); // 自动刷新任务列表
|
||||
} else {
|
||||
// 新建:创建任务
|
||||
const values = form.getFieldsValue();
|
||||
if (!values.project_id) {
|
||||
messageApi.warning('请先选择项目');
|
||||
setChatStreaming(false);
|
||||
return;
|
||||
}
|
||||
const task = await createTask({
|
||||
project_id: values.project_id,
|
||||
requirement_text: text,
|
||||
task_type: 'feature',
|
||||
execution_mode: values.execution_mode || 'direct_claude',
|
||||
model_preference: chatModel || 'auto',
|
||||
use_vector_search: useVectorSearch,
|
||||
});
|
||||
setChatTask(task);
|
||||
// 追加空的 assistant 消息(流式填充)
|
||||
setChatMessages((prev) => [...prev, { role: 'assistant', content: '' }]);
|
||||
subscribeStream(task.id);
|
||||
await load(); // 自动刷新任务列表
|
||||
}
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
// 【BUG-2 修复】API 失败时移除刚加的用户消息(后端没收到)
|
||||
setChatMessages((prev) => {
|
||||
const updated = [...prev];
|
||||
if (updated.length > 0 && updated[updated.length - 1].role === 'user') {
|
||||
updated.pop();
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
setChatStreaming(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 审批 */
|
||||
const handleApprove = async (task: Task, decision: 'approve' | 'reject') => {
|
||||
try {
|
||||
await submitApproval(task.id, { decision });
|
||||
messageApi.success(decision === 'approve' ? '已批准' : '已驳回');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 回滚 */
|
||||
const handleRollback = async (task: Task) => {
|
||||
try {
|
||||
await rollbackTask(task.id);
|
||||
messageApi.success('已回滚');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 停止 */
|
||||
const handleStop = async (task: Task) => {
|
||||
try {
|
||||
await stopTask(task.id);
|
||||
messageApi.success('已停止');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
// 过滤搜索 + 按创建时间倒序排序(最新在前)
|
||||
const filteredTasks = tasks
|
||||
.filter((t) =>
|
||||
!searchKey || t.requirement_text.toLowerCase().includes(searchKey.toLowerCase()),
|
||||
)
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
|
||||
/** 任务列表列定义 */
|
||||
const columns: ColumnsType<Task> = [
|
||||
{
|
||||
title: '需求',
|
||||
dataIndex: 'requirement_text',
|
||||
key: 'requirement_text',
|
||||
ellipsis: true,
|
||||
render: (v: string) => (
|
||||
<Typography.Text style={{ maxWidth: 300 }} ellipsis={{ tooltip: v }}>
|
||||
{v}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: 'status',
|
||||
width: 100,
|
||||
render: (_, task) => {
|
||||
const cfg = STATUS_CONFIG[task.status] ?? STATUS_CONFIG.running;
|
||||
return <Tag icon={cfg.icon} color={cfg.color}>{cfg.label}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '模式',
|
||||
key: 'execution_mode',
|
||||
width: 80,
|
||||
render: (_, task) => (
|
||||
<Tag color={task.execution_mode === 'direct_claude' ? 'purple' : 'blue'}>
|
||||
{task.execution_mode === 'direct_claude' ? '直调' : 'Agent'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '时间',
|
||||
key: 'created_at',
|
||||
width: 150,
|
||||
render: (_, task) => (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{new Date(task.created_at).toLocaleString('zh-CN')}
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 200,
|
||||
render: (_, task) => (
|
||||
<Space size={4} wrap>
|
||||
<Button type="primary" size="small" onClick={() => openTaskChat(task)}>
|
||||
对话
|
||||
</Button>
|
||||
{task.status === 'waiting_approval' && (
|
||||
<>
|
||||
<Button size="small" type="primary" onClick={() => handleApprove(task, 'approve')}>
|
||||
批准
|
||||
</Button>
|
||||
<Button size="small" danger onClick={() => handleApprove(task, 'reject')}>
|
||||
驳回
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{task.status === 'running' && (
|
||||
<Button size="small" danger onClick={() => handleStop(task)}>
|
||||
停止
|
||||
</Button>
|
||||
)}
|
||||
{(task.status === 'done' || task.status === 'degraded' || task.status === 'failed') && (
|
||||
<Popconfirm title="确认回滚代码改动?" onConfirm={() => handleRollback(task)}>
|
||||
<Button size="small" icon={<RollbackOutlined />} />
|
||||
</Popconfirm>
|
||||
)}
|
||||
<Popconfirm title="确认删除?" onConfirm={() => handleDelete(task)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const handleDelete = async (task: Task) => {
|
||||
try {
|
||||
await batchDeleteTasks([task.id]);
|
||||
messageApi.success('已删除');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
{/* 顶部标题栏 */}
|
||||
<Row gutter={16} align="middle" style={{ marginBottom: 16 }}>
|
||||
<Col flex="auto">
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
任务中心
|
||||
</Typography.Title>
|
||||
</Col>
|
||||
<Col>
|
||||
<Space>
|
||||
<Input
|
||||
placeholder="搜索需求…"
|
||||
prefix={<SearchOutlined />}
|
||||
value={searchKey}
|
||||
onChange={(e) => setSearchKey(e.target.value)}
|
||||
style={{ width: 200 }}
|
||||
allowClear
|
||||
/>
|
||||
<Button icon={<ReloadOutlined />} onClick={load}>刷新</Button>
|
||||
<Popconfirm
|
||||
title={`确认删除选中的 ${selectedIds.length} 个任务?`}
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await batchDeleteTasks(selectedIds);
|
||||
setSelectedIds([]);
|
||||
messageApi.success('已删除');
|
||||
await load();
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
}
|
||||
}}
|
||||
disabled={selectedIds.length === 0}
|
||||
>
|
||||
<Button danger icon={<DeleteOutlined />} disabled={selectedIds.length === 0}>
|
||||
批量删除({selectedIds.length})
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openNewChat}>
|
||||
新建需求
|
||||
</Button>
|
||||
</Space>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 任务列表 */}
|
||||
<Table<Task>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={filteredTasks}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedIds,
|
||||
onChange: (keys) => setSelectedIds(keys as string[]),
|
||||
}}
|
||||
pagination={{ pageSize: 10, showTotal: (t) => `共 ${t} 个任务` }}
|
||||
size="middle"
|
||||
locale={{ emptyText: <Empty description="暂无任务,点击「新建需求」开始" /> }}
|
||||
onRow={(task) => ({ onClick: () => openTaskChat(task), style: { cursor: 'pointer' } })}
|
||||
/>
|
||||
|
||||
{/* 对话弹窗 */}
|
||||
<Modal
|
||||
title={
|
||||
<Space>
|
||||
{chatTask ? '任务对话' : '新建需求'}
|
||||
{chatTask && (
|
||||
<Tag color={STATUS_CONFIG[chatTask.status]?.color}>
|
||||
{STATUS_CONFIG[chatTask.status]?.label}
|
||||
</Tag>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
open={chatOpen}
|
||||
onCancel={() => {
|
||||
setChatOpen(false);
|
||||
eventSourceRef.current?.close();
|
||||
setChatStreaming(false);
|
||||
}}
|
||||
width="70vw"
|
||||
footer={null}
|
||||
/* 【对话框跳动修复】
|
||||
弹窗外框尺寸必须锁死:高度随内容变就会整体上下窜。
|
||||
用 flex 纵向布局,对话区 flex:1 填满剩余空间,成为唯一滚动区。
|
||||
overflowAnchor:'none' 关掉浏览器滚动锚定——它是流式输出时
|
||||
「内容自己上下抖」的常见元凶(浏览器自动调 scrollTop 与我们抢)。 */
|
||||
styles={{
|
||||
body: {
|
||||
height: 'calc(82vh - 110px)',
|
||||
overflowY: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflowAnchor: 'none',
|
||||
},
|
||||
}}
|
||||
>
|
||||
{/* 配置区 */}
|
||||
{!chatTask && (
|
||||
<Form form={form} layout="vertical" size="small" style={{ marginBottom: 12, flexShrink: 0 }}>
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<Form.Item
|
||||
name="project_id"
|
||||
label="所属项目"
|
||||
rules={[{ required: true, message: '请选择项目' }]}
|
||||
style={{ flex: 2, marginBottom: 8 }}
|
||||
>
|
||||
<Select
|
||||
placeholder="选择目标项目"
|
||||
options={projects.map((p) => ({ label: p.name, value: p.id }))}
|
||||
onChange={handleProjectChange}
|
||||
showSearch
|
||||
filterOption={(input, option) =>
|
||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="execution_mode" label="执行模式" initialValue="direct_claude" style={{ flex: 1, marginBottom: 8 }}>
|
||||
<Select
|
||||
options={[
|
||||
{ label: '直调 Claude', value: 'direct_claude' },
|
||||
{ label: 'Agent 编排', value: 'agent' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
</Form>
|
||||
)}
|
||||
{/* 模型选择器(新建和续聊都显示,对话过程中可切换) */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8, flexShrink: 0 }}>
|
||||
<Space size={8}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>模型:</Typography.Text>
|
||||
<Select
|
||||
value={chatModel}
|
||||
onChange={setChatModel}
|
||||
options={modelOptions}
|
||||
style={{ width: 220 }}
|
||||
size="small"
|
||||
/>
|
||||
</Space>
|
||||
<Space size={8}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>知识检索:</Typography.Text>
|
||||
<Switch
|
||||
checked={useVectorSearch}
|
||||
onChange={setUseVectorSearch}
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
size="small"
|
||||
/>
|
||||
<Tooltip title="开启后会查询知识库向量检索相关经验,关闭则跳过(适合简单需求)">
|
||||
<QuestionCircleOutlined style={{ color: '#bbb', fontSize: 12 }} />
|
||||
</Tooltip>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{/* 项目信息展示 */}
|
||||
{chatProject && (
|
||||
<Descriptions size="small" column={1} style={{ marginBottom: 8, flexShrink: 0 }} bordered>
|
||||
<Descriptions.Item label="项目名称">{chatProject.name}</Descriptions.Item>
|
||||
{parseServices(chatProject.backends).map((b, i) => (
|
||||
<Descriptions.Item key={`b${i}`} label={`后端服务 ${b.label}`}>
|
||||
<Space size={8}>
|
||||
<Typography.Text code>
|
||||
{chatProject.code_root_path}\{b.path || b.label}
|
||||
</Typography.Text>
|
||||
<Tag color="blue">{b.branch}</Tag>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
))}
|
||||
{parseServices(chatProject.frontends).map((f, i) => (
|
||||
<Descriptions.Item key={`f${i}`} label={`前端服务 ${f.label}`}>
|
||||
<Space size={8}>
|
||||
<Typography.Text code>
|
||||
{chatProject.code_root_path}\{f.path || f.label}
|
||||
</Typography.Text>
|
||||
<Tag color="green">{f.branch}</Tag>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
))}
|
||||
</Descriptions>
|
||||
)}
|
||||
|
||||
{/* 对话区(唯一滚动区,flex:1 填满剩余空间,外框尺寸不变) */}
|
||||
<div
|
||||
ref={chatScrollRef}
|
||||
onScroll={handleChatScroll}
|
||||
style={{
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
overflowY: 'auto',
|
||||
overflowAnchor: 'none',
|
||||
// 【布局稳定】滚动条常驻占位:内容高度变化时不会因滚动条出现/消失导致横向抖动
|
||||
scrollbarGutter: 'stable',
|
||||
border: '1px solid #f0f0f0',
|
||||
borderRadius: 8,
|
||||
padding: 16,
|
||||
background: '#fff',
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
{chatMessages.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#bbb', paddingTop: 120 }}>
|
||||
{chatTask ? '暂无对话记录' : '选择项目后,输入需求开始对话'}
|
||||
</div>
|
||||
) : (
|
||||
chatMessages.map((msg, i) => (
|
||||
<div key={i} style={{ marginBottom: 12 }}>
|
||||
{/* 用户消息:右对齐蓝色气泡 */}
|
||||
{msg.role === 'user' && (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<div
|
||||
style={{
|
||||
maxWidth: '70%',
|
||||
padding: '10px 14px',
|
||||
borderRadius: 12,
|
||||
background: '#1677ff',
|
||||
color: '#fff',
|
||||
whiteSpace: 'pre-wrap',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.6,
|
||||
}}
|
||||
>
|
||||
{msg.content}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Claude 回复:markdown 渲染 */}
|
||||
{msg.role === 'assistant' && (
|
||||
<div
|
||||
style={{
|
||||
padding: '12px 16px',
|
||||
borderRadius: 8,
|
||||
background: '#f7f8fa',
|
||||
border: '1px solid #e8e8e8',
|
||||
}}
|
||||
>
|
||||
<RenderClaudeOutput
|
||||
content={msg.content}
|
||||
streaming={chatStreaming && i === chatMessages.length - 1}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 输入区(高度固定) */}
|
||||
<div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
|
||||
{/* 左侧:输入框 */}
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
|
||||
<Input.TextArea
|
||||
style={{ height: 96, resize: 'none' }}
|
||||
placeholder="输入需求…(Enter 发送,Shift+Enter 换行)"
|
||||
value={chatInput}
|
||||
onChange={(e) => setChatInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleChatSend();
|
||||
}
|
||||
}}
|
||||
disabled={chatStreaming}
|
||||
/>
|
||||
</div>
|
||||
{/* 发送按钮 */}
|
||||
<Button
|
||||
type="primary"
|
||||
loading={chatStreaming}
|
||||
disabled={!chatInput.trim()}
|
||||
onClick={handleChatSend}
|
||||
style={{ alignSelf: 'flex-end' }}
|
||||
>
|
||||
发送
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* 高级工具箱页面组件
|
||||
*
|
||||
* 【功能说明】汇总展示长期记忆、备份管理、MCP工具等企业级功能。
|
||||
*/
|
||||
import {
|
||||
ApiOutlined,
|
||||
BookOutlined,
|
||||
PlusOutlined,
|
||||
SaveOutlined,
|
||||
ThunderboltOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import {
|
||||
App as AntApp,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Input,
|
||||
List,
|
||||
Row,
|
||||
Space,
|
||||
Statistic,
|
||||
Tabs,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
backupNow,
|
||||
createMemory,
|
||||
deleteMemory,
|
||||
getMemories,
|
||||
getMcpTools,
|
||||
} from '../api/client';
|
||||
|
||||
export default function Toolbox() {
|
||||
const { message: messageApi } = AntApp.useApp();
|
||||
// 记忆
|
||||
const [memories, setMemories] = useState<Record<string, unknown>[]>([]);
|
||||
const [memoryContent, setMemoryContent] = useState('');
|
||||
// MCP
|
||||
const [mcpTools, setMcpTools] = useState<Record<string, unknown>[]>([]);
|
||||
// 备份
|
||||
const [backing, setBacking] = useState(false);
|
||||
|
||||
const loadAll = useCallback(async () => {
|
||||
try {
|
||||
const [mem, mcp] = await Promise.all([
|
||||
getMemories(),
|
||||
getMcpTools(),
|
||||
]);
|
||||
setMemories(mem ?? []);
|
||||
setMcpTools(mcp ?? []);
|
||||
} catch {
|
||||
// 静默
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, [loadAll]);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Typography.Title level={4}>
|
||||
<ThunderboltOutlined /> 高级工具箱
|
||||
</Typography.Title>
|
||||
|
||||
<Tabs
|
||||
defaultActiveKey="memory"
|
||||
items={[
|
||||
{
|
||||
key: 'memory',
|
||||
label: <><BookOutlined /> 长期记忆</>,
|
||||
children: (
|
||||
<Row gutter={16}>
|
||||
<Col span={10}>
|
||||
<Card size="small" title="记录记忆">
|
||||
<Input.TextArea
|
||||
rows={4}
|
||||
placeholder="输入项目约定、编码规范、历史决策…"
|
||||
value={memoryContent}
|
||||
onChange={(e) => setMemoryContent(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
style={{ marginTop: 8 }}
|
||||
onClick={async () => {
|
||||
if (!memoryContent.trim()) return;
|
||||
await createMemory({ content: memoryContent.trim(), category: 'general' });
|
||||
setMemoryContent('');
|
||||
messageApi.success('记忆已保存');
|
||||
loadAll();
|
||||
}}
|
||||
>
|
||||
保存记忆
|
||||
</Button>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={14}>
|
||||
<Card size="small" title={`记忆列表(${memories.length})`}>
|
||||
<List
|
||||
size="small"
|
||||
dataSource={memories.slice(0, 20)}
|
||||
renderItem={(m) => (
|
||||
<List.Item
|
||||
actions={[
|
||||
<Button
|
||||
key="del"
|
||||
size="small"
|
||||
danger
|
||||
onClick={async () => {
|
||||
await deleteMemory(String(m.id));
|
||||
loadAll();
|
||||
}}
|
||||
>
|
||||
删除
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<List.Item.Meta
|
||||
title={String(m.content || '').slice(0, 60)}
|
||||
description={
|
||||
<Space>
|
||||
<Tag>{String(m.category || 'general')}</Tag>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
{String(m.created_at || '')}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'backup',
|
||||
label: <><SaveOutlined /> 备份管理</>,
|
||||
children: (
|
||||
<Card size="small">
|
||||
<Space direction="vertical" size="large">
|
||||
<Statistic title="自动备份" value="每 12 小时" />
|
||||
<Statistic title="保留策略" value="最近 30 天" />
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SaveOutlined />}
|
||||
loading={backing}
|
||||
onClick={async () => {
|
||||
setBacking(true);
|
||||
try {
|
||||
const result = await backupNow();
|
||||
messageApi.success(`备份完成:${((result as Record<string, unknown>).files as unknown[])?.length ?? 0} 个文件`);
|
||||
} catch (e) {
|
||||
messageApi.error((e as Error).message);
|
||||
} finally {
|
||||
setBacking(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
立即备份
|
||||
</Button>
|
||||
<Typography.Text type="secondary">
|
||||
备份内容:SQLite 数据库 + .env 配置 + 向量库元数据
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
</Card>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'mcp',
|
||||
label: <><ApiOutlined /> MCP 工具</>,
|
||||
children: (
|
||||
<Card size="small" title={`已注册 MCP 工具(${mcpTools.length})`}>
|
||||
<List
|
||||
dataSource={mcpTools}
|
||||
renderItem={(t) => (
|
||||
<List.Item>
|
||||
<List.Item.Meta
|
||||
title={<Typography.Text code>{String(t.name)}</Typography.Text>}
|
||||
description={String(t.description || '')}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</Card>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* 类型定义模块
|
||||
*
|
||||
* 【功能说明】定义与后端 Pydantic 模型一一对应的前端数据结构,
|
||||
* 保证接口出参与页面展示字段强一致。
|
||||
* 【技术选型理由】TS 接口 + 与后端 schemas/project.py 字段对齐,
|
||||
* 一处改动两处可见,避免前后端字段漂移。
|
||||
* 【实现思路】Project 对应后端 Project 实体;ApiResponse 为统一响应包裹。
|
||||
* 【潜在风险与应对】后端字段增减时需同步更新本文件——已在后端模型注释中标注对照关系。
|
||||
*/
|
||||
|
||||
/** 统一 API 响应包裹(对应后端 ApiResponse) */
|
||||
export interface ApiResponse<T> {
|
||||
code: number;
|
||||
message: string;
|
||||
data: T | null;
|
||||
}
|
||||
|
||||
/** 服务条目(后端/前端) */
|
||||
export interface ServiceEntry {
|
||||
label: string;
|
||||
path: string;
|
||||
branch: string;
|
||||
}
|
||||
|
||||
/** 项目实体(对应后端 schemas/project.py 的 Project) */
|
||||
export interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
code_root_path: string;
|
||||
backend_path: string;
|
||||
frontend_path: string;
|
||||
backend_branch: string;
|
||||
frontend_branch: string;
|
||||
backends: ServiceEntry[];
|
||||
frontends: ServiceEntry[];
|
||||
description: string;
|
||||
sort_order: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** 创建/更新项目的表单载荷 */
|
||||
export interface ProjectPayload {
|
||||
name: string;
|
||||
code_root_path: string;
|
||||
backend_path: string;
|
||||
frontend_path: string;
|
||||
backend_branch: string;
|
||||
frontend_branch: string;
|
||||
backends?: ServiceEntry[];
|
||||
frontends?: ServiceEntry[];
|
||||
description: string;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
/** 项目 Git 分支读取结果 */
|
||||
export interface BranchResult {
|
||||
backend: string[];
|
||||
frontend: string[];
|
||||
}
|
||||
|
||||
/** 知识库统计(对应后端 /api/knowledge/stats) */
|
||||
export interface KnowledgeStats {
|
||||
total_chunks: number;
|
||||
embedding_provider: string;
|
||||
}
|
||||
|
||||
/** 知识库检索命中项 */
|
||||
export interface KnowledgeHit {
|
||||
text: string;
|
||||
metadata: Record<string, unknown>;
|
||||
score: number | null;
|
||||
source: string;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
/** 知识库入库结果 */
|
||||
export interface KnowledgeIngestResult {
|
||||
scanned_files: number;
|
||||
ingested_chunks: number;
|
||||
deleted_old_chunks?: number;
|
||||
skipped?: number;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/** 知识库批量入库(指定文件)结果 */
|
||||
export interface KnowledgeIngestFilesResult {
|
||||
requested_files: number;
|
||||
success_files: number;
|
||||
ingested_chunks: number;
|
||||
deleted_old_chunks: number;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/** 可入库文件项 */
|
||||
export interface KnowledgeFileItem {
|
||||
path: string;
|
||||
relative_path: string;
|
||||
name: string;
|
||||
size: number;
|
||||
file_type: string;
|
||||
}
|
||||
|
||||
/** 任务实体(对应后端 schemas/task.py 的 Task) */
|
||||
export interface Task {
|
||||
id: string;
|
||||
project_id: string;
|
||||
requirement_text: string;
|
||||
task_type: string;
|
||||
status: string;
|
||||
thread_id: string;
|
||||
model_preference: string;
|
||||
use_vector_search: boolean;
|
||||
execution_mode: string;
|
||||
sort_order: number;
|
||||
report: string;
|
||||
error: string;
|
||||
pending_approval: string;
|
||||
chat_history: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** 任务提交载荷 */
|
||||
export interface TaskCreatePayload {
|
||||
project_id: string;
|
||||
requirement_text: string;
|
||||
task_type: string;
|
||||
model_preference?: string;
|
||||
/** 是否查询向量数据库(提交前可选) */
|
||||
use_vector_search?: boolean;
|
||||
/** 执行模式:agent=LangGraph 全流程;direct_claude=直接调 Claude CLI */
|
||||
execution_mode?: 'agent' | 'direct_claude';
|
||||
}
|
||||
|
||||
/** 可用模型选项 */
|
||||
export interface ModelOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** 模型配置(对应后端 schemas/model_config.py) */
|
||||
export interface ModelConfig {
|
||||
id: string;
|
||||
display_name: string;
|
||||
model_id: string;
|
||||
provider_key: string;
|
||||
model_role: string;
|
||||
is_enabled: boolean;
|
||||
sort_order: number;
|
||||
description: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** 模型配置创建/更新载荷 */
|
||||
export interface ModelConfigPayload {
|
||||
display_name: string;
|
||||
model_id: string;
|
||||
provider_key: string;
|
||||
model_role: string;
|
||||
is_enabled: boolean;
|
||||
sort_order: number;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/** SSE 事件 */
|
||||
export interface TaskEvent {
|
||||
event: string;
|
||||
node: string;
|
||||
message: string;
|
||||
data: Record<string, unknown>;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
/** 审计日志条目 */
|
||||
export interface AuditEntry {
|
||||
timestamp: string;
|
||||
action: string;
|
||||
target: string;
|
||||
result: string;
|
||||
details: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 审计统计 */
|
||||
export interface AuditSummary {
|
||||
total: number;
|
||||
by_action: Record<string, number>;
|
||||
by_result: Record<string, number>;
|
||||
}
|
||||
|
||||
/** 回滚结果 */
|
||||
export interface RollbackResult {
|
||||
success: boolean;
|
||||
strategy_used: string;
|
||||
restored_files: string[];
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** 数据库连接配置 */
|
||||
export interface DatabaseConnection {
|
||||
id: string;
|
||||
name: string;
|
||||
db_type: string;
|
||||
host: string;
|
||||
port: number;
|
||||
database: string;
|
||||
username: string;
|
||||
password: string;
|
||||
description: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** 数据库连接创建/更新载荷 */
|
||||
export interface DatabaseConnectionPayload {
|
||||
name: string;
|
||||
db_type: string;
|
||||
host: string;
|
||||
port: number;
|
||||
database: string;
|
||||
username: string;
|
||||
password: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/** SQL 执行结果 */
|
||||
export interface SqlExecuteResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
affected_rows: number;
|
||||
data: Record<string, unknown>[];
|
||||
columns: string[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
/** 表结构列信息 */
|
||||
export interface TableColumn {
|
||||
name: string;
|
||||
type: string;
|
||||
nullable: boolean;
|
||||
key: string;
|
||||
default: string;
|
||||
comment: string;
|
||||
}
|
||||
|
||||
/** .env 配置项 */
|
||||
export interface EnvItem {
|
||||
key: string;
|
||||
value: string;
|
||||
remark: string;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Vite 构建配置
|
||||
*
|
||||
* 【功能说明】配置开发代理、构建输出目录与路径别名。
|
||||
* 【技术选型理由】Vite 启动快、对 React/TS 原生支持好,是当前主流脚手架。
|
||||
* 【实现思路】开发期把 /api 代理到 FastAPI(8000),避免跨域;产物落 dist。
|
||||
* 【潜在风险与应对】代理失效时前端会报跨域——已在 main.py 配置 CORS 兜底。
|
||||
*/
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
// 开发期把 API 请求转发到 FastAPI,避免跨域
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:8002',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
sourcemap: false,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user