chore: initial commit for Pretor v0.1.0-alpha

正式发布 Pretor 平台的首个 alpha 版本。本项目旨在构建一个基于分布式架构的多智能体协同工作流水线。

核心功能实现:
1. 建立基于 BaseIndividual 的动态插件加载机制。
2. 实现三类核心 worker_individual 子个体。
3. 集成 Ray 框架支持分布式集群调度。
4. 基于 PostgreSQL 的全量持久化存储方案。
5. 提供完整的 FastAPI 后端与 React 前端交互界面。
This commit is contained in:
2026-04-29 10:09:07 +08:00
commit d84212f780
163 changed files with 19251 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>pretor-dashboard</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+3612
View File
File diff suppressed because it is too large Load Diff
+34
View File
@@ -0,0 +1,34 @@
{
"name": "pretor-dashboard",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.15.1",
"lucide-react": "^1.8.0",
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@tailwindcss/vite": "^4.2.2",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"tailwindcss": "^4.2.2",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.4"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+69
View File
@@ -0,0 +1,69 @@
import { useState, useEffect } from 'react';
import { Sidebar } from './components/Layout/Sidebar';
import { SettingsLayout } from './components/Settings/SettingsLayout';
import { AgentLayout } from './components/Agent/AgentLayout';
import { ResourceLayout } from './components/Resource/ResourceLayout';
import { LeftPanel } from './components/Chat/LeftPanel';
import { ChatPanel } from './components/Chat/ChatPanel';
import { RightPanel } from './components/Chat/RightPanel';
import { AuthPage } from './components/Auth/AuthPage';
function App() {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [activeTab, setActiveTab] = useState('chats'); // For LeftPanel
const [currentView, setCurrentView] = useState('dashboard'); // 'dashboard', 'settings', 'agent', 'resource'
const [settingsTab, setSettingsTab] = useState('users'); // For SettingsLayout
const [agentTab, setAgentTab] = useState('worker'); // For AgentLayout
const [resourceTab, setResourceTab] = useState('skill'); // For ResourceLayout
const [selectedWorkflow, setSelectedWorkflow] = useState<string | null>(null);
useEffect(() => {
// Check if token exists in localStorage on mount
const token = localStorage.getItem('token');
if (token) {
setIsAuthenticated(true);
}
}, []);
if (!isAuthenticated) {
return <AuthPage onLoginSuccess={() => setIsAuthenticated(true)} />;
}
return (
<div className="flex h-screen w-screen bg-slate-50 text-slate-800 font-sans overflow-hidden">
{/* 1. Sidebar (Leftmost) */}
<Sidebar currentView={currentView} setCurrentView={setCurrentView} />
{/* Main Content Area depending on view */}
{currentView === 'agent' ? (
<AgentLayout agentTab={agentTab} setAgentTab={setAgentTab} />
) : currentView === 'resource' ? (
<ResourceLayout resourceTab={resourceTab} setResourceTab={setResourceTab} />
) : currentView === 'dashboard' ? (
<>
{/* 2. Left Panel - Cluster Status & Workflows/Chats */}
<LeftPanel
activeTab={activeTab}
setActiveTab={setActiveTab}
selectedWorkflow={selectedWorkflow}
setSelectedWorkflow={setSelectedWorkflow}
/>
{/* 3. Middle Panel - AI Chat */}
<ChatPanel />
{/* 4. Right Panel - Workflow Execution Status (Only show when viewing workflows) */}
{activeTab === 'workflows' && <RightPanel selectedWorkflow={selectedWorkflow} />}
</>
) : (
/* Settings View */
<SettingsLayout settingsTab={settingsTab} setSettingsTab={setSettingsTab} />
)}
</div>
);
}
export default App;
+36
View File
@@ -0,0 +1,36 @@
import axios from 'axios';
// The base URL should typically come from an environment variable in a real app.
// If missing, defaulting to '' means requests will be relative to the current browser origin.
export const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || '',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Interceptor to attach token to requests if we have one
apiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Interceptor to catch 401 Unauthorized errors and force login
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && error.response.status === 401) {
// Clear token
localStorage.removeItem('token');
// Reload the page to force the user back to the Auth view
window.location.reload();
}
return Promise.reject(error);
}
);
export default apiClient;
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

@@ -0,0 +1,43 @@
import { Bot, Key } from 'lucide-react';
import { ProvidersSettings } from './ProvidersSettings';
import { WorkerIndividualSettings } from './WorkerIndividualSettings';
interface AgentLayoutProps {
agentTab: string;
setAgentTab: (tab: string) => void;
}
export function AgentLayout({ agentTab, setAgentTab }: AgentLayoutProps) {
return (
<div className="flex-1 flex bg-slate-50 overflow-hidden">
{/* Agent Inner Sidebar */}
<div className="w-64 bg-white border-r border-slate-200 flex flex-col z-0">
<div className="p-6 border-b border-slate-100">
<h2 className="text-lg font-semibold text-slate-800">Agents</h2>
</div>
<div className="flex-1 p-4 space-y-2 overflow-y-auto">
<button
onClick={() => setAgentTab('worker')}
className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all ${agentTab === 'worker' ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}
>
<Bot size={18} className="mr-3" />
Individual
</button>
<button
onClick={() => setAgentTab('providers')}
className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all ${agentTab === 'providers' ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}
>
<Key size={18} className="mr-3" />
Provider Management
</button>
</div>
</div>
{/* Agent Main Content */}
<div className="flex-1 overflow-y-auto p-8">
{agentTab === 'worker' && <WorkerIndividualSettings />}
{agentTab === 'providers' && <ProvidersSettings />}
</div>
</div>
);
}
@@ -0,0 +1,258 @@
import { useState, useEffect } from 'react';
import { Box, Plus, X } from 'lucide-react';
import type { Provider } from '../../types';
import apiClient from '../../api/client';
export function ProvidersSettings() {
const [providers, setProviders] = useState<Provider[]>([]);
const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [formData, setFormData] = useState({
provider_type: 'openai',
provider_title: '',
provider_url: '',
provider_apikey: ''
});
const [submitLoading, setSubmitLoading] = useState(false);
const [error, setError] = useState('');
const fetchProviders = async () => {
setLoading(true);
try {
const response = await apiClient.get('/api/v1/provider/list');
const data = response.data.provider_list || {};
const providerArray: Provider[] = Object.values(data);
setProviders(providerArray);
} catch (error) {
console.error("Failed to fetch providers", error);
setProviders([]);
} finally {
setLoading(false);
}
};
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
fetchProviders();
}, []);
const handleOpenModal = () => {
setFormData({
provider_type: 'openai',
provider_title: '',
provider_url: '',
provider_apikey: ''
});
setError('');
setIsModalOpen(true);
};
const handleCloseModal = () => {
setIsModalOpen(false);
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.provider_title || !formData.provider_url || !formData.provider_apikey) {
setError('Please fill in all fields.');
return;
}
setSubmitLoading(true);
setError('');
try {
await apiClient.post('/api/v1/provider', formData);
await fetchProviders();
handleCloseModal();
} catch (err) {
console.error("Error adding provider", err);
setError('Failed to add provider. Please check your inputs and try again.');
} finally {
setSubmitLoading(false);
}
};
return (
<div className="max-w-4xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h3 className="text-xl font-semibold text-slate-800">Provider Management</h3>
<p className="text-sm text-slate-500 mt-1">Configure external AI model providers and API keys.</p>
</div>
<button
onClick={handleOpenModal}
className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium transition-colors shadow-sm cursor-pointer"
>
<Plus size={16} className="mr-2" />
Add Provider
</button>
</div>
{loading ? (
<div className="text-center text-slate-500 py-8">Loading providers...</div>
) : providers.length === 0 ? (
<div className="text-center text-slate-500 py-8 bg-white rounded-xl border border-slate-200">
No providers configured yet. Click "Add Provider" to get started.
</div>
) : (
<div className="grid grid-cols-2 gap-6">
{providers.map((provider, i) => (
<div key={i} className="bg-white border border-slate-200 p-5 rounded-xl shadow-sm hover:border-blue-200 transition-colors flex flex-col justify-between">
<div>
<div className="flex justify-between items-start mb-4">
<div className="flex items-center">
<div className="w-10 h-10 rounded-lg bg-slate-50 border border-slate-100 flex items-center justify-center mr-3">
<Box size={20} className="text-slate-600" />
</div>
<div>
<h4 className="font-semibold text-slate-800">{provider.provider_title}</h4>
<span className="text-xs text-slate-500 font-mono uppercase">{provider.provider_type}</span>
</div>
</div>
<span className={`flex items-center text-xs font-medium px-2 py-1 rounded-md border ${provider.status === 'Connected' ? 'bg-green-50 text-green-700 border-green-200' : 'bg-slate-50 text-slate-500 border-slate-200'}`}>
{provider.status === 'Connected' && <span className="w-1.5 h-1.5 rounded-full bg-green-500 mr-1.5"></span>}
{provider.status || 'Unknown'}
</span>
</div>
<div className="mb-4">
<p className="text-sm text-slate-600 mb-1">URL / Endpoint:</p>
<div className="bg-slate-50 border border-slate-100 rounded text-sm px-3 py-1.5 font-mono text-slate-700 truncate" title={provider.provider_url}>
{provider.provider_url || 'Default'}
</div>
</div>
</div>
<div className="flex justify-end space-x-2 mt-2">
<button className="px-3 py-1.5 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded hover:bg-slate-50 transition-colors cursor-pointer">Edit</button>
<button
onClick={async () => {
if (!confirm('Are you sure you want to delete this provider?')) return;
try {
await apiClient.delete(`/api/v1/provider/${provider.provider_title}`);
fetchProviders();
} catch (err) {
console.error('Failed to delete provider', err);
alert('Failed to delete provider');
}
}}
className="px-3 py-1.5 text-sm font-medium text-red-600 bg-white border border-slate-200 rounded hover:bg-red-50 transition-colors cursor-pointer"
>
Delete
</button>
</div>
</div>
))}
</div>
)}
{/* Add Provider Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in-95 duration-200">
<div className="flex justify-between items-center p-5 border-b border-slate-100">
<h3 className="text-lg font-semibold text-slate-800">Add New Provider</h3>
<button
onClick={handleCloseModal}
className="text-slate-400 hover:text-slate-600 p-1 rounded-md transition-colors cursor-pointer"
>
<X size={20} />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-4">
{error && (
<div className="p-3 bg-red-50 text-red-600 text-sm rounded-lg border border-red-100">
{error}
</div>
)}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">Provider Type</label>
<select
name="provider_type"
value={formData.provider_type}
onChange={handleChange}
className="w-full bg-slate-50 border border-slate-200 text-sm rounded-lg px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all cursor-pointer"
>
<option value="openai">OpenAI</option>
<option value="deepseek">DeepSeek</option>
<option value="claude">Claude</option>
<option value="local">Local</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">Provider Title</label>
<input
type="text"
name="provider_title"
placeholder="e.g. My OpenAI Instance"
value={formData.provider_title}
onChange={handleChange}
className="w-full bg-white border border-slate-200 text-sm rounded-lg px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">Base URL</label>
<input
type="url"
name="provider_url"
placeholder="e.g. https://api.openai.com/v1"
value={formData.provider_url}
onChange={handleChange}
className="w-full bg-white border border-slate-200 text-sm rounded-lg px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">API Key</label>
<input
type="password"
name="provider_apikey"
placeholder="sk-..."
value={formData.provider_apikey}
onChange={handleChange}
className="w-full bg-white border border-slate-200 text-sm rounded-lg px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400 font-mono"
/>
</div>
<div className="pt-4 flex justify-end space-x-3">
<button
type="button"
onClick={handleCloseModal}
className="px-4 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors cursor-pointer"
>
Cancel
</button>
<button
type="submit"
disabled={submitLoading}
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer disabled:opacity-70 flex items-center"
>
{submitLoading ? (
<span className="flex items-center">
<svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Saving...
</span>
) : (
'Add Provider'
)}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,452 @@
import { useState, useEffect } from 'react';
import apiClient from '../../api/client';
import { Save, Plus, Edit2, Trash2, X } from 'lucide-react';
import type { Provider } from '../../types';
interface WorkerIndividual {
agent_id: string;
agent_name: string;
agent_type: string;
description?: string;
provider_title: string;
model_id: string;
system_prompt?: string;
output_template?: string; // Change to string for the form state
bound_skill?: string; // Change to string for the form state
workspace?: string; // Change to string for the form state
tools?: string; // Form state for tools JSON array
}
export function WorkerIndividualSettings() {
const [providers, setProviders] = useState<Provider[]>([]);
const [workers, setWorkers] = useState<WorkerIndividual[]>([]);
const [systemNodes, setSystemNodes] = useState<any[]>([]);
const [availableSkills, setAvailableSkills] = useState<string[]>([]);
const [availableTools, setAvailableTools] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [isEditing, setIsEditing] = useState(false);
const [editData, setEditData] = useState<Partial<WorkerIndividual>>({});
const [isNew, setIsNew] = useState(false);
const [modalMessage, setModalMessage] = useState('');
const fetchData = async () => {
setLoading(true);
try {
const [provRes, workRes, sysRes, toolsRes, skillsRes] = await Promise.all([
apiClient.get('/api/v1/provider/list'),
apiClient.get('/api/v1/agent/worker'),
apiClient.get('/api/v1/agent'),
apiClient.get('/api/v1/resource/tool'),
apiClient.get('/api/v1/resource/skill')
]);
setProviders(Object.values(provRes.data.provider_list || {}));
setWorkers(workRes.data.workers || []);
const allTools = toolsRes.data.tools || [];
setAvailableTools(allTools);
setAvailableSkills(Object.keys(skillsRes.data.skills || {}));
const sysNodesData = sysRes.data.system_nodes || [];
const defaultSysNodes = ['supervisory_node', 'consciousness_node', 'control_node'];
const providersList = Object.values(provRes.data.provider_list || {}) as Provider[];
const defaultProvider = providersList.length > 0 ? providersList[0].provider_title : '';
const formattedSysNodes = defaultSysNodes.map(nodeName => {
const found = sysNodesData.find((n: any) => n.node_name === nodeName);
return {
agent_id: nodeName,
agent_name: nodeName,
agent_type: 'System Node',
provider_title: found && found.provider_title ? found.provider_title : defaultProvider,
model_id: found && found.model_id ? found.model_id : '',
tools: found && found.tools ? JSON.stringify(found.tools) : '[]',
is_system: true
};
});
setSystemNodes(formattedSysNodes);
} catch (err: any) {
console.error(err);
setError('Failed to load data');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
const handleEdit = (worker: any) => { // Accept the backend object which might have objects instead of strings
setEditData({
...worker,
output_template: typeof worker.output_template === 'string' ? worker.output_template : JSON.stringify(worker.output_template || {}),
bound_skill: typeof worker.bound_skill === 'string' ? worker.bound_skill : JSON.stringify(worker.bound_skill || {}),
workspace: typeof worker.workspace === 'string' ? worker.workspace : JSON.stringify(worker.workspace || []),
tools: typeof worker.tools === 'string' ? worker.tools : JSON.stringify(worker.tools || [])
});
setIsNew(false);
setIsEditing(true);
setModalMessage('');
};
const handleAddNew = () => {
setEditData({
agent_name: '',
agent_type: 'ordinary_individual',
description: '',
provider_title: providers.length > 0 ? providers[0].provider_title : '',
model_id: '',
system_prompt: '',
output_template: '{}',
bound_skill: '{}',
workspace: '[]',
tools: '[]'
});
setIsNew(true);
setIsEditing(true);
setModalMessage('');
};
const handleDelete = async (agent_id: string) => {
if (!confirm('Are you sure you want to delete this agent?')) return;
try {
await apiClient.delete(`/api/v1/agent/worker/${agent_id}`);
fetchData();
} catch (err: any) {
console.error(err);
alert('Failed to delete agent');
}
};
const handleModalSave = async (e: React.FormEvent) => {
e.preventDefault();
setModalMessage('');
try {
if ((editData as any).is_system) {
const payload = {
individual_name: editData.agent_name,
provider_title: editData.provider_title,
model_id: editData.model_id,
tools: JSON.parse(editData.tools || '[]')
};
await apiClient.post('/api/v1/agent', payload);
} else {
const payload = {
...editData,
output_template: JSON.parse(editData.output_template || '{}'),
bound_skill: JSON.parse(editData.bound_skill || '{}'),
workspace: JSON.parse(editData.workspace || '[]'),
tools: JSON.parse(editData.tools || '[]')
};
if (isNew) {
await apiClient.post('/api/v1/agent/worker', payload);
} else {
await apiClient.put(`/api/v1/agent/worker/${editData.agent_id}`, payload);
}
}
setIsEditing(false);
fetchData();
} catch (err: any) {
console.error(err);
setModalMessage(err.response?.data?.detail || err.message || 'Failed to save');
}
};
return (
<div className="max-w-5xl space-y-6 relative">
<div className="mb-8 flex justify-between items-end">
<div>
<h1 className="text-2xl font-bold text-slate-800">Individual</h1>
<p className="text-slate-500 mt-1">Manage all system nodes and custom workers.</p>
</div>
<button
onClick={handleAddNew}
className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
>
<Plus size={16} className="mr-2" />
Add Worker
</button>
</div>
{error && <div className="text-red-600">{error}</div>}
<div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
<div className="p-0">
{loading ? (
<div className="p-6 text-slate-500">Loading...</div>
) : (workers.length === 0 && systemNodes.length === 0) ? (
<div className="p-6 text-slate-500">No individuals found.</div>
) : (
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-slate-50 border-b border-slate-200 text-slate-600 text-sm">
<th className="p-4 font-semibold">Name</th>
<th className="p-4 font-semibold">Type</th>
<th className="p-4 font-semibold">Provider / Model ID</th>
<th className="p-4 font-semibold text-right">Actions</th>
</tr>
</thead>
<tbody>
{systemNodes.map((w) => (
<tr key={w.agent_id} className="border-b border-slate-100 bg-slate-50 hover:bg-slate-100 transition-colors">
<td className="p-4 font-medium text-slate-800">{w.agent_name}</td>
<td className="p-4 text-slate-600">
<span className="px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs">{w.agent_type}</span>
</td>
<td className="p-4 text-slate-600 text-sm">
{w.provider_title} <span className="text-slate-400">/</span> {w.model_id}
</td>
<td className="p-4 text-right space-x-2">
<button onClick={() => handleEdit(w)} className="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors" title="Edit">
<Edit2 size={16} />
</button>
</td>
</tr>
))}
{workers.map((w) => (
<tr key={w.agent_id} className="border-b border-slate-100 hover:bg-slate-50 transition-colors">
<td className="p-4 font-medium text-slate-800">{w.agent_name}</td>
<td className="p-4 text-slate-600">
<span className="px-2 py-1 bg-slate-100 rounded text-xs">{w.agent_type}</span>
</td>
<td className="p-4 text-slate-600 text-sm">
{w.provider_title} <span className="text-slate-400">/</span> {w.model_id}
</td>
<td className="p-4 text-right space-x-2">
<button onClick={() => handleEdit(w)} className="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors" title="Edit">
<Edit2 size={16} />
</button>
<button onClick={() => handleDelete(w.agent_id)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors" title="Delete">
<Trash2 size={16} />
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
{/* Edit/Create Modal */}
{isEditing && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
<div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-center p-6 border-b border-slate-100 sticky top-0 bg-white z-10">
<h2 className="text-xl font-bold text-slate-800">
{(editData as any).is_system ? 'Edit System Node' : (isNew ? 'Create Worker' : 'Edit Worker')}
</h2>
<button onClick={() => setIsEditing(false)} className="text-slate-400 hover:text-slate-600">
<X size={24} />
</button>
</div>
<form onSubmit={handleModalSave} className="p-6 space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Agent Name</label>
<input
type="text"
required
value={editData.agent_name || ''}
onChange={(e) => setEditData({...editData, agent_name: e.target.value})}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
disabled={(editData as any).is_system}
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Agent Type</label>
<select
value={editData.agent_type || 'ordinary_individual'}
onChange={(e) => setEditData({...editData, agent_type: e.target.value})}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
disabled={(editData as any).is_system}
>
<option value="ordinary_individual">Ordinary Individual</option>
<option value="skill_individual">Skill Individual</option>
<option value="special_individual">Special Individual</option>
{(editData as any).is_system && (
<option value="System Node">System Node</option>
)}
</select>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Provider Title</label>
<select
value={editData.provider_title || ''}
onChange={(e) => setEditData({...editData, provider_title: e.target.value, model_id: ''})}
required
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
>
<option value="" disabled>Select Provider</option>
{providers.map((p) => (
<option key={p.provider_title} value={p.provider_title}>{p.provider_title}</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Model ID</label>
{(() => {
const selectedProvider = providers.find(p => p.provider_title === editData.provider_title);
const models = selectedProvider?.provider_models || [];
return (
<select
value={editData.model_id || ''}
onChange={(e) => setEditData({...editData, model_id: e.target.value})}
required
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
>
<option value="" disabled>Select a model</option>
{models.map(m => <option key={m} value={m}>{m}</option>)}
</select>
);
})()}
</div>
</div>
{!(editData as any).is_system && (
<>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Description</label>
<textarea
value={editData.description || ''}
onChange={(e) => setEditData({...editData, description: e.target.value})}
rows={2}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">System Prompt</label>
<textarea
value={editData.system_prompt || ''}
onChange={(e) => setEditData({...editData, system_prompt: e.target.value})}
rows={3}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 font-mono text-sm"
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Output Template (JSON)</label>
<textarea
value={editData.output_template || '{}'}
onChange={(e) => setEditData({...editData, output_template: e.target.value})}
rows={3}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 font-mono text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Bound Skill (Select)</label>
<select
value={(() => {
try {
const parsed = JSON.parse(editData.bound_skill || '{}');
return Object.keys(parsed)[0] || '';
} catch { return ''; }
})()}
onChange={(e) => {
const val = e.target.value;
const newSkill = val ? { [val]: [] } : {};
setEditData({...editData, bound_skill: JSON.stringify(newSkill)});
}}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
disabled={editData.agent_type !== 'skill_individual'}
>
<option value="">No Skill Bound</option>
{availableSkills.map(skill => (
<option key={skill} value={skill}>{skill}</option>
))}
</select>
</div>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Workspace (JSON Array)</label>
<textarea
value={editData.workspace || '[]'}
onChange={(e) => setEditData({...editData, workspace: e.target.value})}
rows={2}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 font-mono text-sm"
/>
</div>
</>
)}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Tools (Select Multiple)</label>
<div className="flex flex-wrap gap-2 p-4 border border-slate-200 rounded-lg max-h-48 overflow-y-auto">
{availableTools.map(tool => {
let currentTools: string[] = [];
try {
currentTools = JSON.parse(editData.tools || '[]');
} catch { currentTools = []; }
const isSelected = currentTools.includes(tool);
return (
<button
key={tool}
type="button"
onClick={() => {
let updatedTools = [...currentTools];
if (isSelected) {
updatedTools = updatedTools.filter(t => t !== tool);
} else {
updatedTools.push(tool);
}
setEditData({...editData, tools: JSON.stringify(updatedTools)});
}}
className={`px-3 py-1.5 text-sm rounded-full transition-colors ${
isSelected
? 'bg-indigo-100 text-indigo-700 border border-indigo-200'
: 'bg-slate-50 text-slate-600 border border-slate-200 hover:bg-slate-100'
}`}
>
{tool}
</button>
);
})}
{availableTools.length === 0 && (
<span className="text-sm text-slate-500">No tools available</span>
)}
</div>
</div>
{modalMessage && (
<div className="p-3 bg-red-50 text-red-700 text-sm rounded-lg">
{modalMessage}
</div>
)}
<div className="pt-4 flex justify-end space-x-3 border-t border-slate-100">
<button
type="button"
onClick={() => setIsEditing(false)}
className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
>
Cancel
</button>
<button
type="submit"
className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
>
<Save size={16} className="mr-2" />
Save Worker
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}
+123
View File
@@ -0,0 +1,123 @@
import React, { useState } from 'react';
import apiClient from '../../api/client';
import { Activity } from 'lucide-react';
interface AuthPageProps {
onLoginSuccess: () => void;
}
export function AuthPage({ onLoginSuccess }: AuthPageProps) {
const [isLogin, setIsLogin] = useState(true);
const [userName, setUserName] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
if (isLogin) {
// Login
const response = await apiClient.post('/api/v1/auth/login', {
user_name: userName,
password: password,
});
if (response.data.token) {
localStorage.setItem('token', response.data.token);
onLoginSuccess();
}
} else {
// Register
const response = await apiClient.post('/api/v1/auth/register', {
user_name: userName,
password: password,
});
// After successful register, we can automatically log them in
// or just show a message and switch to login. Let's switch to login.
if (response.data.message === 'success') {
setIsLogin(true);
setError('Registration successful. Please log in.');
}
}
} catch (err: any) {
console.error(err);
setError(err.response?.data?.detail || err.response?.data?.message || 'Authentication failed');
} finally {
setLoading(false);
}
};
return (
<div className="flex min-h-screen w-full items-center justify-center bg-slate-50">
<div className="w-full max-w-md bg-white rounded-xl shadow-lg p-8 border border-slate-100">
<div className="flex flex-col items-center mb-8">
<div className="w-12 h-12 bg-blue-600 rounded-xl flex items-center justify-center text-white mb-4 shadow-md shadow-blue-200">
<Activity size={24} />
</div>
<h2 className="text-2xl font-bold text-slate-800">
{isLogin ? 'Welcome Back' : 'Create Account'}
</h2>
<p className="text-slate-500 mt-2 text-sm">
{isLogin ? 'Enter your credentials to access your account' : 'Sign up to start using the platform'}
</p>
</div>
{error && (
<div className={`mb-4 p-3 rounded-lg text-sm ${error.includes('successful') ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Username</label>
<input
type="text"
value={userName}
onChange={(e) => setUserName(e.target.value)}
className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-shadow"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-shadow"
required
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2.5 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors disabled:opacity-50"
>
{loading ? 'Processing...' : (isLogin ? 'Sign In' : 'Sign Up')}
</button>
</form>
<div className="mt-6 text-center text-sm text-slate-500">
{isLogin ? "Don't have an account? " : "Already have an account? "}
<button
onClick={() => {
setIsLogin(!isLogin);
setError('');
}}
className="text-blue-600 font-medium hover:text-blue-700 focus:outline-none"
>
{isLogin ? 'Sign up' : 'Sign in'}
</button>
</div>
</div>
</div>
);
}
+217
View File
@@ -0,0 +1,217 @@
import React, { useState } from 'react';
import { MessageSquare, Activity, Terminal, ChevronRight, Plus } from 'lucide-react';
import apiClient from '../../api/client';
interface ChatMessage {
id: string;
sender: 'user' | 'ai';
text: string;
timestamp: Date;
eventId?: string;
}
export function ChatPanel() {
const [messages, setMessages] = useState<ChatMessage[]>([
{
id: '1',
sender: 'ai',
text: "Hello! I am Pretor Assistant. How can I help you today?",
timestamp: new Date()
}
]);
const [input, setInput] = useState('');
const [loading, setLoading] = useState(false);
const fileInputRef = React.useRef<HTMLInputElement>(null);
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const formData = new FormData();
formData.append('file', file);
setLoading(true);
try {
const response = await apiClient.post('/api/v1/adapter/client/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
const aiMessage: ChatMessage = {
id: Date.now().toString(),
sender: 'ai',
text: `已上传文件: ${response.data.filename}`,
timestamp: new Date()
};
setMessages(prev => [...prev, aiMessage]);
} catch (error) {
console.error("Error uploading file", error);
const errorMessage: ChatMessage = {
id: Date.now().toString(),
sender: 'ai',
text: "文件上传失败。",
timestamp: new Date()
};
setMessages(prev => [...prev, errorMessage]);
} finally {
setLoading(false);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
};
const handleSendMessage = async () => {
if (!input.trim()) return;
const userMessage: ChatMessage = {
id: Date.now().toString(),
sender: 'user',
text: input,
timestamp: new Date()
};
setMessages(prev => [...prev, userMessage]);
setInput('');
setLoading(true);
try {
// Assuming a token might be needed, apiClient should handle it if set
const promptModifier = mode === 'deploy' ? '[DEPLOY TASK] ' : '';
const response = await apiClient.post('/api/v1/adapter/client', {
message: promptModifier + userMessage.text
});
const aiMessage: ChatMessage = {
id: (Date.now() + 1).toString(),
sender: 'ai',
text: typeof response.data.message === 'string' && response.data.message.includes('-')
? "Task has been created." // It's an event ID
: response.data.message || "I received your message.",
eventId: typeof response.data.message === 'string' && response.data.message.includes('-') ? response.data.message : undefined,
timestamp: new Date()
};
setMessages(prev => [...prev, aiMessage]);
// If we got an event_id, we could potentially open a websocket to listen to its stream
if (aiMessage.eventId) {
console.log(`Open WS to track event: ${aiMessage.eventId}`);
// Implement WS tracking if needed
}
} catch (error) {
console.error("Error sending message", error);
const errorMessage: ChatMessage = {
id: (Date.now() + 1).toString(),
sender: 'ai',
text: "Sorry, I encountered an error communicating with the server.",
timestamp: new Date()
};
setMessages(prev => [...prev, errorMessage]);
} finally {
setLoading(false);
}
};
const [mode, setMode] = useState<'chat' | 'deploy'>('chat');
return (
<div className="flex-1 flex flex-col bg-slate-50">
<div className="h-14 border-b border-slate-200 bg-white flex items-center justify-between px-6 shadow-sm z-10">
<div className="flex items-center">
<MessageSquare size={18} className="text-blue-600 mr-3" />
<h1 className="font-semibold text-slate-800">Pretor Assistant</h1>
</div>
<div className="flex space-x-2 bg-slate-100 p-1 rounded-lg">
<button
onClick={() => setMode('chat')}
className={`px-3 py-1 text-sm font-medium rounded-md transition-colors ${mode === 'chat' ? 'bg-white text-blue-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
>
Chat
</button>
<button
onClick={() => setMode('deploy')}
className={`px-3 py-1 text-sm font-medium rounded-md transition-colors ${mode === 'deploy' ? 'bg-white text-blue-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
>
Deploy Task
</button>
</div>
</div>
{/* Chat History */}
<div className="flex-1 p-6 overflow-y-auto space-y-6">
<div className="flex justify-center">
<span className="text-xs text-slate-400 bg-slate-200/50 px-3 py-1 rounded-full">Today</span>
</div>
{messages.map((msg) => (
<div key={msg.id} className={`flex ${msg.sender === 'user' ? 'justify-end' : 'justify-start'}`}>
{msg.sender === 'ai' && (
<div className="w-8 h-8 rounded-full bg-white border border-blue-100 flex items-center justify-center mr-3 mt-1 shadow-sm flex-shrink-0">
<Activity size={16} className="text-blue-600" />
</div>
)}
<div className={`${msg.sender === 'user' ? 'bg-blue-600 text-white rounded-2xl rounded-tr-sm' : 'bg-white border border-slate-100 text-slate-700 rounded-2xl rounded-tl-sm'} p-4 max-w-[80%] shadow-sm`}>
<p className="text-sm leading-relaxed mb-3">{msg.text}</p>
{msg.eventId && (
<div className="bg-slate-50 border border-slate-100 rounded-lg p-3 flex items-center text-sm">
<Terminal size={16} className="text-slate-400 mr-2" />
<span className="font-mono text-slate-600 text-xs">Task ID: {msg.eventId}</span>
</div>
)}
</div>
</div>
))}
{loading && (
<div className="flex justify-start">
<div className="w-8 h-8 rounded-full bg-white border border-blue-100 flex items-center justify-center mr-3 mt-1 shadow-sm flex-shrink-0">
<Activity size={16} className="text-blue-600 animate-spin" />
</div>
<div className="bg-white border border-slate-100 text-slate-700 p-4 rounded-2xl rounded-tl-sm max-w-[80%] shadow-sm">
<span className="flex space-x-1">
<span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce"></span>
<span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce delay-75"></span>
<span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce delay-150"></span>
</span>
</div>
</div>
)}
</div>
{/* Chat Input */}
<div className="p-4 bg-white border-t border-slate-200">
<div className="relative flex items-center">
<input
type="file"
ref={fileInputRef}
onChange={handleFileUpload}
className="hidden"
/>
<button
onClick={() => fileInputRef.current?.click()}
className="absolute left-2 p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors z-10 cursor-pointer"
title="Add attachment"
>
<Plus size={20} />
</button>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
placeholder="Ask Pretor to do something..."
className="w-full bg-slate-50 border border-slate-200 text-sm rounded-xl pl-12 pr-12 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all shadow-inner"
/>
<button
onClick={handleSendMessage}
disabled={loading || !input.trim()}
className="absolute right-2 p-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors shadow-sm disabled:opacity-50 cursor-pointer"
>
<ChevronRight size={18} />
</button>
</div>
</div>
</div>
);
}
+171
View File
@@ -0,0 +1,171 @@
import { useState, useEffect } from 'react';
import { Server, Box, Cpu, HardDrive, List, MessageCircle } from 'lucide-react';
import { useClusterState } from '../../hooks/useClusterState';
import apiClient from '../../api/client';
import type { Workflow } from '../../types';
interface LeftPanelProps {
activeTab: string;
setActiveTab: (tab: string) => void;
selectedWorkflow: string | null;
setSelectedWorkflow: (id: string | null) => void;
}
export function LeftPanel({ activeTab, setActiveTab, selectedWorkflow, setSelectedWorkflow }: LeftPanelProps) {
const { nodes } = useClusterState();
const [workflows, setWorkflows] = useState<Workflow[]>([]);
const [loadingWorkflows, setLoadingWorkflows] = useState(false);
const totalNodes = nodes.length;
const aliveNodes = nodes.filter(n => n.alive).length;
let totalCpu = 0;
let usedCpu = 0;
let totalMemory = 0;
let usedMemory = 0;
nodes.forEach(node => {
const nodeTotalCpu = node.resources?.CPU || 0;
const nodeRemainingCpu = node.remaining?.CPU || 0;
totalCpu += nodeTotalCpu;
usedCpu += (nodeTotalCpu - nodeRemainingCpu);
const nodeTotalMem = node.resources?.memory || 0;
const nodeRemainingMem = node.remaining?.memory || 0;
totalMemory += nodeTotalMem;
usedMemory += (nodeTotalMem - nodeRemainingMem);
});
const cpuPercent = totalCpu > 0 ? (usedCpu / totalCpu) * 100 : 0;
const memPercent = totalMemory > 0 ? (usedMemory / totalMemory) * 100 : 0;
useEffect(() => {
let intervalId: ReturnType<typeof setInterval>;
const fetchWorkflows = async (isInitial = false) => {
if (isInitial) setLoadingWorkflows(true);
try {
const response = await apiClient.get('/api/v1/workflow/list');
// Fallback parsing just in case it returns an object or array
const data = response.data;
let parsedWorkflows: Workflow[] = [];
if (Array.isArray(data)) {
parsedWorkflows = data;
} else if (data && typeof data === 'object') {
// Suppose backend sends { workflows: [...] }
parsedWorkflows = data.workflows || Object.values(data);
}
setWorkflows(parsedWorkflows);
} catch (error) {
console.error("Failed to fetch workflows", error);
setWorkflows([]);
} finally {
if (isInitial) setLoadingWorkflows(false);
}
};
if (activeTab === 'workflows') {
fetchWorkflows(true);
intervalId = setInterval(() => fetchWorkflows(false), 2000);
}
return () => {
if (intervalId) clearInterval(intervalId);
};
}, [activeTab]);
return (
<div className="w-72 bg-white border-r border-slate-200 flex flex-col z-0 shrink-0">
{/* Top: Cluster Status */}
<div className="h-1/3 p-4 border-b border-slate-100 flex flex-col">
<h2 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-4 flex items-center">
<Server size={16} className="mr-2" />
Cluster Status
</h2>
<div className="space-y-4 flex-1">
<div className="flex items-center justify-between">
<div className="flex items-center text-slate-600">
<Box size={16} className="mr-2 text-blue-500" />
<span className="text-sm">Active Nodes</span>
</div>
<span className="text-sm font-medium text-slate-800">{aliveNodes} / {totalNodes || 0}</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center text-slate-600">
<Cpu size={16} className="mr-2 text-indigo-500" />
<span className="text-sm">Cluster CPU</span>
</div>
<span className="text-sm font-medium text-slate-800">{cpuPercent.toFixed(1)}%</span>
</div>
<div className="w-full bg-slate-100 rounded-full h-1.5">
<div className="bg-indigo-500 h-1.5 rounded-full" style={{ width: `${cpuPercent}%` }}></div>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center text-slate-600">
<HardDrive size={16} className="mr-2 text-green-500" />
<span className="text-sm">Cluster RAM</span>
</div>
<span className="text-sm font-medium text-slate-800">
{(totalMemory > 0 ? usedMemory / (1024 ** 3) : 0).toFixed(1)} GB
</span>
</div>
<div className="w-full bg-slate-100 rounded-full h-1.5">
<div className="bg-green-500 h-1.5 rounded-full" style={{ width: `${memPercent}%` }}></div>
</div>
</div>
</div>
{/* Bottom: Tabs for Workflows & Basic Chats */}
<div className="flex-1 flex flex-col overflow-hidden">
<div className="flex border-b border-slate-100">
<button
onClick={() => setActiveTab('chats')}
className={`flex-1 py-3 text-xs font-medium text-center uppercase tracking-wider transition-colors ${activeTab === 'chats' ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50/50' : 'text-slate-500 hover:bg-slate-50'}`}
>
<MessageCircle size={14} className="inline mr-1.5 -mt-0.5" />
Chats
</button>
<button
onClick={() => setActiveTab('workflows')}
className={`flex-1 py-3 text-xs font-medium text-center uppercase tracking-wider transition-colors ${activeTab === 'workflows' ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50/50' : 'text-slate-500 hover:bg-slate-50'}`}
>
<List size={14} className="inline mr-1.5 -mt-0.5" />
Workflows
</button>
</div>
<div className="flex-1 p-4 overflow-y-auto">
{activeTab === 'workflows' && (
<div className="space-y-2">
{loadingWorkflows ? (
<div className="text-center text-slate-400 text-sm py-4">Loading workflows...</div>
) : workflows.length === 0 ? (
<div className="text-center text-slate-400 text-sm py-4"></div>
) : (
workflows.map((wf) => (
<div
key={wf.event_id}
onClick={() => setSelectedWorkflow(wf.event_id)}
className={`p-3 rounded-lg border cursor-pointer transition-all ${selectedWorkflow === wf.event_id ? 'border-blue-200 bg-blue-50 shadow-sm' : 'border-slate-100 hover:border-blue-200 hover:bg-slate-50'}`}
>
<div className="flex justify-between items-center mb-1">
<span className={`font-medium text-sm ${selectedWorkflow === wf.event_id ? 'text-blue-700' : 'text-slate-700'}`}>{wf.workflow_title || 'Unnamed Workflow'}</span>
<span className={`flex h-2 w-2 rounded-full ${wf.status === 'llm_working' || wf.status === 'tool_working' ? 'bg-green-400 animate-pulse' : wf.status === 'failed' ? 'bg-red-400' : 'bg-slate-300'}`}></span>
</div>
<p className="text-xs text-slate-500 font-mono line-clamp-1">ID: {wf.event_id}</p>
</div>
))
)}
</div>
)}
{activeTab === 'chats' && (
<div className="space-y-2">
</div>
)}
</div>
</div>
</div>
);
}
+206
View File
@@ -0,0 +1,206 @@
import { useState, useEffect, useRef } from 'react';
import { Terminal, Activity, RefreshCw, CheckCircle2, Circle, XCircle, Clock, Loader2 } from 'lucide-react';
import apiClient from '../../api/client';
import type { WorkflowDetail, WorkflowStep } from '../../types';
interface RightPanelProps {
selectedWorkflow: string | null;
}
function stepStatusIcon(status: string) {
switch (status) {
case 'completed':
return <CheckCircle2 size={14} className="text-green-500" />;
case 'running':
return <Loader2 size={14} className="text-blue-500 animate-spin" />;
case 'failed':
return <XCircle size={14} className="text-red-500" />;
default:
return <Circle size={14} className="text-slate-300" />;
}
}
export function RightPanel({ selectedWorkflow }: RightPanelProps) {
const [detail, setDetail] = useState<WorkflowDetail | null>(null);
const [loading, setLoading] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const [sseConnected, setSseConnected] = useState(false);
const eventSourceRef = useRef<EventSource | null>(null);
const fetchDetail = async (traceId: string) => {
setLoading(true);
setLogs([]);
try {
const response = await apiClient.get(`/api/v1/workflow/${traceId}`);
setDetail(response.data);
} catch {
setDetail(null);
} finally {
setLoading(false);
}
};
useEffect(() => {
if (!selectedWorkflow) {
setDetail(null);
setLogs([]);
return;
}
fetchDetail(selectedWorkflow);
const protocol = window.location.protocol;
const host = window.location.host;
const apiBase = import.meta.env.VITE_API_BASE_URL || `${protocol}//${host}`;
const es = new EventSource(`${apiBase}/api/v1/workflow/sse/${selectedWorkflow}`);
eventSourceRef.current = es;
es.onopen = () => {
setSseConnected(true);
};
es.onmessage = (event) => {
setLogs(prev => [...prev, event.data]);
};
es.onerror = () => {
setSseConnected(false);
};
const interval = setInterval(() => {
fetchDetail(selectedWorkflow);
}, 3000);
return () => {
es.close();
eventSourceRef.current = null;
clearInterval(interval);
};
}, [selectedWorkflow]);
const isActive = detail?.status === 'llm_working' || detail?.status === 'tool_working';
if (!selectedWorkflow) {
return (
<div className="w-80 bg-white border-l border-slate-200 flex flex-col z-0 justify-center items-center p-6 text-center">
<Activity size={32} className="text-slate-300 mb-4" />
<h3 className="text-sm font-semibold text-slate-600">No Workflow Selected</h3>
<p className="text-xs text-slate-400 mt-2">Select a workflow from the left panel to view its details.</p>
</div>
);
}
return (
<div className="w-80 bg-white border-l border-slate-200 flex flex-col z-0">
<div className="h-14 border-b border-slate-100 flex items-center px-4 justify-between bg-slate-50/50">
<h2 className="font-semibold text-slate-800 text-sm flex items-center">
<Terminal size={16} className="mr-2 text-slate-500" />
Workflow Detail
</h2>
<div className="flex items-center gap-2">
<span className={`px-2 py-1 text-xs rounded-md font-medium border ${sseConnected ? 'bg-green-100 text-green-700 border-green-200' : 'bg-slate-100 text-slate-500 border-slate-200'}`}>
{sseConnected ? 'Live' : '--'}
</span>
<button
onClick={() => selectedWorkflow && fetchDetail(selectedWorkflow)}
className="p-1 text-slate-400 hover:text-blue-600 rounded transition-colors"
title="Refresh"
>
<RefreshCw size={14} />
</button>
</div>
</div>
<div className="flex-1 p-4 overflow-y-auto">
{loading && !detail ? (
<div className="text-center text-slate-400 text-sm py-8">
<Loader2 size={24} className="animate-spin mx-auto mb-2" />
Loading...
</div>
) : !detail ? (
<div className="text-center text-slate-400 text-sm py-8">Failed to load workflow details</div>
) : (
<>
{/* Header */}
<div className="mb-4">
<h3 className="text-base font-bold text-slate-800">
{detail.workflow_title || 'Workflow'}
</h3>
<p className="text-xs text-slate-500 font-mono mt-1">ID: {detail.event_id}</p>
{detail.command && (
<p className="text-xs text-slate-500 mt-1 truncate">Command: {detail.command}</p>
)}
<div className="flex items-center gap-2 mt-2">
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
detail.status === 'failed' ? 'bg-red-100 text-red-700' :
isActive ? 'bg-blue-100 text-blue-700' :
detail.status === 'waiting_llm_working' || detail.status === 'waiting_tool_working' ? 'bg-yellow-100 text-yellow-700' :
'bg-green-100 text-green-700'
}`}>
{detail.status}
</span>
<span className="text-xs text-slate-400">
Step {detail.current_step}/{detail.steps.length}
</span>
</div>
</div>
{/* Steps */}
{detail.steps.length > 0 && (
<div className="mb-4">
<h4 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Steps</h4>
<div className="space-y-1.5">
{detail.steps.map((step: WorkflowStep) => (
<div
key={step.step}
className={`flex items-center gap-2 px-2.5 py-1.5 rounded-md text-xs border ${
step.step === detail.current_step && isActive
? 'border-blue-200 bg-blue-50'
: step.status === 'completed'
? 'border-green-100 bg-green-50/50'
: step.status === 'failed'
? 'border-red-100 bg-red-50/50'
: 'border-slate-100 bg-white'
}`}
>
{stepStatusIcon(step.status)}
<span className="font-medium text-slate-700 w-5 text-right">{step.step}</span>
<span className="text-slate-600 truncate flex-1">{step.name}</span>
<span className="text-slate-400 text-[10px]">{step.node}</span>
</div>
))}
</div>
</div>
)}
{detail.steps.length === 0 && (
<div className="text-center py-4">
<Clock size={24} className="text-slate-300 mx-auto mb-2" />
<p className="text-xs text-slate-400">Workflow is being generated...</p>
</div>
)}
{/* SSE Logs */}
{logs.length > 0 && (
<div>
<h4 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Live Logs</h4>
<div className="relative border-l-2 border-slate-200 ml-3 pl-5 space-y-3">
{logs.map((msg, idx) => (
<div key={idx} className="relative">
<div className={`absolute -left-[27px] top-1 w-3 h-3 rounded-full border-2 border-white shadow-sm ${idx === logs.length - 1 && sseConnected ? 'bg-blue-500 animate-pulse' : 'bg-green-500'}`} />
<p className="text-[11px] font-mono text-slate-600 leading-relaxed break-all">{msg}</p>
</div>
))}
</div>
</div>
)}
{logs.length === 0 && sseConnected && isActive && (
<div className="text-xs text-slate-400 italic mt-2">Waiting for live events...</div>
)}
</>
)}
</div>
</div>
);
}
@@ -0,0 +1,51 @@
import { Activity, MessageSquare, Settings, Bot, Box } from 'lucide-react';
interface SidebarProps {
currentView: string;
setCurrentView: (view: string) => void;
}
export function Sidebar({ currentView, setCurrentView }: SidebarProps) {
return (
<div className="w-12 bg-white border-r border-slate-200 flex flex-col items-center py-4 space-y-6 shadow-sm z-10 shrink-0">
<div
className="w-8 h-8 bg-blue-600 rounded-xl flex items-center justify-center text-white shadow-md shadow-blue-200 cursor-pointer hover:bg-blue-700 transition-colors"
onClick={() => setCurrentView('dashboard')}
>
<Activity size={18} />
</div>
<div className="flex flex-col space-y-4 flex-1 mt-8">
<button
onClick={() => setCurrentView('dashboard')}
className={`p-1.5 rounded-lg transition-colors ${currentView === 'dashboard' ? 'text-blue-600 bg-blue-50' : 'text-slate-400 hover:text-blue-500 hover:bg-blue-50'}`}
title="Chat"
>
<MessageSquare size={18} />
</button>
<button
onClick={() => setCurrentView('agent')}
className={`p-1.5 rounded-lg transition-colors ${currentView === 'agent' ? 'text-blue-600 bg-blue-50' : 'text-slate-400 hover:text-blue-500 hover:bg-blue-50'}`}
title="Agents"
>
<Bot size={18} />
</button>
<button
onClick={() => setCurrentView('resource')}
className={`p-1.5 rounded-lg transition-colors ${currentView === 'resource' ? 'text-blue-600 bg-blue-50' : 'text-slate-400 hover:text-blue-500 hover:bg-blue-50'}`}
title="Resources"
>
<Box size={18} />
</button>
<button
onClick={() => setCurrentView('settings')}
className={`p-1.5 rounded-lg transition-colors ${currentView === 'settings' ? 'text-blue-600 bg-blue-50' : 'text-slate-400 hover:text-blue-500 hover:bg-blue-50'}`}
title="Settings"
>
<Settings size={18} />
</button>
</div>
</div>
);
}
@@ -0,0 +1,52 @@
import { Wrench, Database, FileCode } from 'lucide-react';
import { SkillSettings } from './SkillSettings';
import { ToolSettings } from './ToolSettings';
import { WorkflowTemplateSettings } from './WorkflowTemplateSettings';
interface ResourceLayoutProps {
resourceTab: string;
setResourceTab: (tab: string) => void;
}
export function ResourceLayout({ resourceTab, setResourceTab }: ResourceLayoutProps) {
return (
<div className="flex-1 flex bg-slate-50 overflow-hidden">
{/* Resource Inner Sidebar */}
<div className="w-64 bg-white border-r border-slate-200 flex flex-col z-0">
<div className="p-6 border-b border-slate-100">
<h2 className="text-lg font-semibold text-slate-800">Resources</h2>
</div>
<div className="flex-1 p-4 space-y-2 overflow-y-auto">
<button
onClick={() => setResourceTab('skill')}
className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all ${resourceTab === 'skill' ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}
>
<Wrench size={18} className="mr-3" />
Skills
</button>
<button
onClick={() => setResourceTab('workflow_template')}
className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all ${resourceTab === 'workflow_template' ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}
>
<FileCode size={18} className="mr-3" />
Workflow Templates
</button>
<button
onClick={() => setResourceTab('tool')}
className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all ${resourceTab === 'tool' ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}
>
<Database size={18} className="mr-3" />
Tools
</button>
</div>
</div>
{/* Resource Main Content */}
<div className="flex-1 overflow-y-auto p-8">
{resourceTab === 'skill' && <SkillSettings />}
{resourceTab === 'workflow_template' && <WorkflowTemplateSettings />}
{resourceTab === 'tool' && <ToolSettings />}
</div>
</div>
);
}
@@ -0,0 +1,167 @@
import { useState, useEffect } from 'react';
import apiClient from '../../api/client';
import { Download, Trash2, Plus, Box } from 'lucide-react';
export function SkillSettings() {
const [skills, setSkills] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [repoUrl, setRepoUrl] = useState('');
const [path, setPath] = useState('');
const [installing, setInstalling] = useState(false);
const [message, setMessage] = useState('');
const [error, setError] = useState('');
const fetchSkills = async () => {
setLoading(true);
try {
const response = await apiClient.get('/api/v1/resource/skill');
const skillsData = response.data.skills || {};
// skillsData might be an object mapping skill names to their details, or it might be an array in some versions.
// We ensure it is an array of strings (skill names)
if (Array.isArray(skillsData)) {
setSkills(skillsData);
} else {
setSkills(Object.keys(skillsData));
}
} catch (err) {
console.error('Failed to fetch skills:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchSkills();
}, []);
const handleInstall = async (e: React.FormEvent) => {
e.preventDefault();
if (!repoUrl) return;
setInstalling(true);
setMessage('');
setError('');
try {
await apiClient.post('/api/v1/resource/skill', {
repo_url: repoUrl,
path: path || null
});
setMessage('Skill installed successfully');
setRepoUrl('');
setPath('');
fetchSkills();
} catch (err: any) {
console.error(err);
setError(err.response?.data?.message || 'Failed to install skill');
} finally {
setInstalling(false);
}
};
const handleDelete = async (skillName: string) => {
if (!confirm(`Are you sure you want to delete ${skillName}?`)) return;
try {
await apiClient.delete(`/api/v1/resource/skill/${skillName}`);
fetchSkills();
} catch (err: any) {
console.error('Failed to delete skill:', err);
alert('Failed to delete skill');
}
};
return (
<div className="max-w-4xl space-y-6">
<div className="mb-8">
<h1 className="text-2xl font-bold text-slate-800">Skill Management</h1>
<p className="text-slate-500 mt-1">Manage agent skills and functions.</p>
</div>
<div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
<div className="p-6 border-b border-slate-100 flex items-center space-x-3">
<div className="w-10 h-10 bg-indigo-50 text-indigo-600 rounded-lg flex items-center justify-center">
<Download size={20} />
</div>
<div>
<h2 className="text-lg font-semibold text-slate-800">Install Skill</h2>
<p className="text-sm text-slate-500">Install a new skill from a repository.</p>
</div>
</div>
<div className="p-6">
<form onSubmit={handleInstall} className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Repository URL</label>
<input
type="text"
required
value={repoUrl}
onChange={(e) => setRepoUrl(e.target.value)}
placeholder="https://github.com/user/repo"
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Path (Optional)</label>
<input
type="text"
value={path}
onChange={(e) => setPath(e.target.value)}
placeholder="e.g. subfolder/path"
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
</div>
{message && <div className="text-green-600 text-sm">{message}</div>}
{error && <div className="text-red-600 text-sm">{error}</div>}
<div className="flex justify-end">
<button
type="submit"
disabled={installing}
className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50"
>
<Plus size={16} className="mr-2" />
{installing ? 'Installing...' : 'Install'}
</button>
</div>
</form>
</div>
</div>
<div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
<div className="p-6 border-b border-slate-100">
<h2 className="text-lg font-semibold text-slate-800">Installed Skills</h2>
</div>
<div className="p-6">
{loading ? (
<div className="text-slate-500 text-sm">Loading skills...</div>
) : skills.length === 0 ? (
<div className="text-slate-500 text-sm">No skills installed yet.</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{skills.map((skill) => (
<div key={skill} className="p-4 border border-slate-200 rounded-xl flex items-center justify-between hover:shadow-sm transition-shadow">
<div className="flex items-center space-x-3">
<div className="w-8 h-8 rounded-lg bg-slate-100 flex items-center justify-center text-slate-500">
<Box size={16} />
</div>
<span className="font-medium text-slate-800">{skill}</span>
</div>
<button
onClick={() => handleDelete(skill)}
className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
title="Delete Skill"
>
<Trash2 size={16} />
</button>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,64 @@
import { useState, useEffect } from 'react';
import { Package } from 'lucide-react';
import apiClient from '../../api/client';
export function ToolSettings() {
const [tools, setTools] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchTools();
}, []);
const fetchTools = async () => {
try {
setLoading(true);
const response = await apiClient.get('/api/v1/resource/tool');
const toolsData = response.data.tools || [];
setTools(toolsData);
} catch (err) {
console.error('Failed to fetch tools:', err);
} finally {
setLoading(false);
}
};
return (
<div className="max-w-4xl space-y-6">
<div>
<h3 className="text-xl font-semibold text-slate-800">Installed Tools</h3>
<p className="text-slate-500 mt-1">Manage agent tools and functions.</p>
</div>
<div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
<div className="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
<div>
<h4 className="font-medium text-slate-800">Available Tools</h4>
<p className="text-sm text-slate-500">List of installed tools available for agents.</p>
</div>
</div>
<div className="p-6">
{loading ? (
<div className="text-slate-500 text-sm">Loading tools...</div>
) : tools.length === 0 ? (
<div className="text-slate-500 text-sm">No tools installed yet.</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{tools.map((tool) => (
<div key={tool} className="p-4 border border-slate-200 rounded-xl flex items-center justify-between hover:shadow-sm transition-shadow">
<div className="flex items-center">
<div className="w-10 h-10 bg-purple-50 rounded-lg flex items-center justify-center mr-3">
<Package size={20} className="text-purple-600" />
</div>
<span className="font-medium text-slate-800">{tool}</span>
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,163 @@
import { useState, useEffect } from 'react';
import apiClient from '../../api/client';
import { FileCode, Trash2, Plus, LayoutTemplate } from 'lucide-react';
import type { WorkflowTemplate as ParsedWorkflowTemplate } from '../../types';
export function WorkflowTemplateSettings() {
const [templates, setTemplates] = useState<Record<string, ParsedWorkflowTemplate>>({});
const [loading, setLoading] = useState(true);
const [templateJson, setTemplateJson] = useState('{\n "name": "my_template",\n "steps": [\n {\n "name": "step1",\n "actor": "actor_name"\n }\n ]\n}');
const [creating, setCreating] = useState(false);
const [message, setMessage] = useState('');
const [error, setError] = useState('');
const validateTemplate = (data: any): data is ParsedWorkflowTemplate => {
if (!data || typeof data !== 'object') return false;
if (typeof data.name !== 'string') return false;
if (!Array.isArray(data.steps)) return false;
for (const step of data.steps) {
if (typeof step.name !== 'string') return false;
if (typeof step.actor !== 'string') return false;
}
return true;
};
const fetchTemplates = async () => {
setLoading(true);
try {
const response = await apiClient.get('/api/v1/resource/workflow_template');
setTemplates(response.data.templates || {});
} catch (err) {
console.error('Failed to fetch templates:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchTemplates();
}, []);
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
setCreating(true);
setMessage('');
setError('');
try {
const parsedJson = JSON.parse(templateJson);
if (!validateTemplate(parsedJson)) {
throw new Error('JSON structure does not match WorkflowTemplate schema (requires name and steps array with name and actor).');
}
await apiClient.post('/api/v1/resource/workflow_template', parsedJson);
setMessage('Workflow template created successfully');
setTemplateJson('{\n "name": "my_template",\n "steps": []\n}');
fetchTemplates();
} catch (err: any) {
console.error(err);
if (err instanceof SyntaxError) {
setError('Invalid JSON format');
} else {
setError(err.message || err.response?.data?.message || 'Failed to create workflow template');
}
} finally {
setCreating(false);
}
};
const handleDelete = async (templateName: string) => {
if (!confirm(`Are you sure you want to delete ${templateName}?`)) return;
try {
await apiClient.delete(`/api/v1/resource/workflow_template/${templateName}`);
fetchTemplates();
} catch (err: any) {
console.error('Failed to delete template:', err);
alert('Failed to delete template');
}
};
return (
<div className="max-w-4xl space-y-6">
<div className="mb-8">
<h1 className="text-2xl font-bold text-slate-800">Workflow Templates</h1>
<p className="text-slate-500 mt-1">Manage and create reusable workflow templates.</p>
</div>
<div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
<div className="p-6 border-b border-slate-100 flex items-center space-x-3">
<div className="w-10 h-10 bg-indigo-50 text-indigo-600 rounded-lg flex items-center justify-center">
<FileCode size={20} />
</div>
<div>
<h2 className="text-lg font-semibold text-slate-800">Create Template</h2>
<p className="text-sm text-slate-500">Provide the JSON definition for a new workflow template.</p>
</div>
</div>
<div className="p-6">
<form onSubmit={handleCreate} className="space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Template JSON Definition</label>
<textarea
required
rows={8}
value={templateJson}
onChange={(e) => setTemplateJson(e.target.value)}
className="w-full px-4 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 font-mono text-sm"
/>
</div>
{message && <div className="text-green-600 text-sm">{message}</div>}
{error && <div className="text-red-600 text-sm">{error}</div>}
<div className="flex justify-end">
<button
type="submit"
disabled={creating}
className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50"
>
<Plus size={16} className="mr-2" />
{creating ? 'Creating...' : 'Create Template'}
</button>
</div>
</form>
</div>
</div>
<div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
<div className="p-6 border-b border-slate-100">
<h2 className="text-lg font-semibold text-slate-800">Available Templates</h2>
</div>
<div className="p-6">
{loading ? (
<div className="text-slate-500 text-sm">Loading templates...</div>
) : Object.keys(templates).length === 0 ? (
<div className="text-slate-500 text-sm">No workflow templates created yet.</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{Object.keys(templates).map((name) => (
<div key={name} className="p-4 border border-slate-200 rounded-xl flex items-center justify-between hover:shadow-sm transition-shadow">
<div className="flex items-center space-x-3">
<div className="w-8 h-8 rounded-lg bg-slate-100 flex items-center justify-center text-slate-500">
<LayoutTemplate size={16} />
</div>
<span className="font-medium text-slate-800">{name}</span>
</div>
<button
onClick={() => handleDelete(name)}
className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
title="Delete Template"
>
<Trash2 size={16} />
</button>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,44 @@
import { Users, Sliders } from 'lucide-react';
import { UsersSettings } from './UsersSettings';
import { SystemSettings } from './SystemSettings';
interface SettingsLayoutProps {
settingsTab: string;
setSettingsTab: (tab: string) => void;
}
export function SettingsLayout({ settingsTab, setSettingsTab }: SettingsLayoutProps) {
return (
<div className="flex-1 flex bg-slate-50 overflow-hidden">
{/* Settings Inner Sidebar */}
<div className="w-64 bg-white border-r border-slate-200 flex flex-col z-0">
<div className="p-6 border-b border-slate-100">
<h2 className="text-lg font-semibold text-slate-800">Settings</h2>
</div>
<div className="flex-1 p-4 space-y-2 overflow-y-auto">
<button
onClick={() => setSettingsTab('users')}
className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all ${settingsTab === 'users' ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}
>
<Users size={18} className="mr-3" />
User Management
</button>
<button
onClick={() => setSettingsTab('system')}
className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all ${settingsTab === 'system' ? 'bg-blue-50 text-blue-600' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}
>
<Sliders size={18} className="mr-3" />
System Settings
</button>
</div>
</div>
{/* Settings Main Content */}
<div className="flex-1 overflow-y-auto p-8">
{settingsTab === 'users' && <UsersSettings />}
{settingsTab === 'system' && <SystemSettings />}
</div>
</div>
);
}
@@ -0,0 +1,107 @@
import { useState, useEffect } from 'react';
import { Globe, Server, Save } from 'lucide-react';
export function SystemSettings() {
const [language, setLanguage] = useState(localStorage.getItem('language') || 'English');
const [theme, setTheme] = useState(localStorage.getItem('theme') || 'Light');
const [debugMode, setDebugMode] = useState(true);
const handleSave = () => {
localStorage.setItem('language', language);
localStorage.setItem('theme', theme);
// Apply theme
if (theme === 'Dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
// In a real app, you would dispatch a language change event or context update here
alert(`Settings saved!\nLanguage: ${language}\nTheme: ${theme}`);
};
// Initialize theme on mount if needed
useEffect(() => {
if (theme === 'Dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [theme]);
return (
<div className="max-w-4xl mx-auto">
<div className="mb-6">
<h3 className="text-xl font-semibold text-slate-800">System Settings</h3>
<p className="text-sm text-slate-500 mt-1">Global platform configurations.</p>
</div>
<div className="space-y-6">
<div className="bg-white border border-slate-200 rounded-xl shadow-sm p-6">
<h4 className="text-sm font-semibold text-slate-800 mb-4 flex items-center">
<Globe size={16} className="mr-2 text-slate-500" />
General
</h4>
<div className="space-y-4 max-w-md">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">System Language</label>
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
className="w-full bg-slate-50 border border-slate-200 text-sm rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
>
<option value="English">English</option>
<option value="简体中文"></option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Theme</label>
<select
value={theme}
onChange={(e) => setTheme(e.target.value)}
className="w-full bg-slate-50 border border-slate-200 text-sm rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
>
<option value="Light">Light</option>
<option value="Dark">Dark</option>
<option value="System Default">System Default</option>
</select>
</div>
</div>
</div>
<div className="bg-white border border-slate-200 rounded-xl shadow-sm p-6">
<h4 className="text-sm font-semibold text-slate-800 mb-4 flex items-center">
<Server size={16} className="mr-2 text-slate-500" />
Cluster & Runtime
</h4>
<div className="space-y-4 max-w-md">
<div className="flex items-center mt-4">
<input
type="checkbox"
id="debug_mode"
checked={debugMode}
onChange={(e) => setDebugMode(e.target.checked)}
className="w-4 h-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500"
/>
<label htmlFor="debug_mode" className="ml-2 block text-sm text-slate-700">
Enable debug logging
</label>
</div>
</div>
</div>
<div className="flex justify-end">
<button
onClick={handleSave}
className="flex items-center px-6 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium transition-colors shadow-sm cursor-pointer"
>
<Save size={16} className="mr-2" />
Save Changes
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,295 @@
import { useEffect } from 'react';
import { useState } from 'react';
import { Plus, Edit2, Trash2, X } from 'lucide-react';
import type { User } from '../../types';
import apiClient from '../../api/client';
export function UsersSettings() {
const [users, setUsers] = useState<User[]>([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [editingUser, setEditingUser] = useState<User | null>(null);
const [editRole, setEditRole] = useState('User');
const fetchUsers = async () => {
try {
const response = await apiClient.get('/api/v1/auth/list');
setUsers(response.data.users || []);
} catch (err) {
console.error('Failed to fetch users', err);
}
};
useEffect(() => {
fetchUsers();
}, []);
const [formData, setFormData] = useState({
username: '',
password: ''
});
const [submitLoading, setSubmitLoading] = useState(false);
const [error, setError] = useState('');
const handleOpenModal = () => {
setFormData({ username: '', password: '' });
setError('');
setIsModalOpen(true);
};
const handleCloseModal = () => {
setIsModalOpen(false);
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.username || !formData.password) {
setError('Please fill in both username and password.');
return;
}
setSubmitLoading(true);
setError('');
try {
await apiClient.post('/api/v1/auth/register', {
user_name: formData.username,
password: formData.password
});
await fetchUsers();
handleCloseModal();
} catch (err) {
console.error("Failed to register user", err);
setError('Registration failed. Please try again.');
} finally {
setSubmitLoading(false);
}
};
const handleDeleteUser = async (userId: string | undefined) => {
if (!userId) return;
if (!confirm('Are you sure you want to delete this user?')) return;
try {
await apiClient.delete(`/api/v1/auth/${userId}`);
await fetchUsers();
} catch (err) {
console.error("Failed to delete user", err);
alert("Failed to delete user");
}
};
const handleEditClick = (user: User) => {
setEditingUser(user);
setEditRole(user.role || 'User');
setIsEditModalOpen(true);
};
const handleEditSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!editingUser?.user_id) return;
setSubmitLoading(true);
try {
await apiClient.put('/api/v1/auth/authority', {
user_id: editingUser.user_id,
new_authority: editRole
});
await fetchUsers();
setIsEditModalOpen(false);
} catch (err) {
console.error("Failed to update user role", err);
alert("Failed to update user role");
} finally {
setSubmitLoading(false);
}
};
return (
<div className="max-w-4xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h3 className="text-xl font-semibold text-slate-800">User Management</h3>
<p className="text-sm text-slate-500 mt-1">Manage system users and their roles.</p>
</div>
<button
onClick={handleOpenModal}
className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium transition-colors shadow-sm cursor-pointer"
>
<Plus size={16} className="mr-2" />
Add User
</button>
</div>
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
<table className="w-full text-left text-sm">
<thead className="bg-slate-50 border-b border-slate-200 text-slate-500">
<tr>
<th className="px-6 py-4 font-medium">Username</th>
<th className="px-6 py-4 font-medium">Role</th>
<th className="px-6 py-4 font-medium">Status</th>
<th className="px-6 py-4 font-medium text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{users.map((user, i) => (
<tr key={i} className="hover:bg-slate-50 transition-colors">
<td className="px-6 py-4 font-medium text-slate-800">{user.user_name}</td>
<td className="px-6 py-4 text-slate-600">{user.role || 'User'}</td>
<td className="px-6 py-4">
<span className={`px-2.5 py-1 rounded-full text-xs font-medium ${user.status === 'Active' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-slate-100 text-slate-600 border border-slate-200'}`}>
{user.status || 'Active'}
</span>
</td>
<td className="px-6 py-4 text-right">
<button onClick={() => handleEditClick(user)} className="text-slate-400 hover:text-blue-600 mr-3 transition-colors cursor-pointer" title="Edit"><Edit2 size={16} /></button>
<button onClick={() => handleDeleteUser(user.user_id)} className="text-slate-400 hover:text-red-600 transition-colors cursor-pointer" title="Delete"><Trash2 size={16} /></button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Add User Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in-95 duration-200">
<div className="flex justify-between items-center p-5 border-b border-slate-100">
<h3 className="text-lg font-semibold text-slate-800">Add New User</h3>
<button
onClick={handleCloseModal}
className="text-slate-400 hover:text-slate-600 p-1 rounded-md transition-colors cursor-pointer"
>
<X size={20} />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-4">
{error && (
<div className="p-3 bg-red-50 text-red-600 text-sm rounded-lg border border-red-100">
{error}
</div>
)}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">Username</label>
<input
type="text"
name="username"
placeholder="e.g. jsmith"
value={formData.username}
onChange={handleChange}
className="w-full bg-white border border-slate-200 text-sm rounded-lg px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">Password</label>
<input
type="password"
name="password"
placeholder="Enter secure password"
value={formData.password}
onChange={handleChange}
className="w-full bg-white border border-slate-200 text-sm rounded-lg px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400"
/>
</div>
<div className="pt-4 flex justify-end space-x-3">
<button
type="button"
onClick={handleCloseModal}
className="px-4 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors cursor-pointer"
>
Cancel
</button>
<button
type="submit"
disabled={submitLoading}
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer disabled:opacity-70 flex items-center"
>
{submitLoading ? (
<span className="flex items-center">
<svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Creating...
</span>
) : (
'Add User'
)}
</button>
</div>
</form>
</div>
</div>
)}
{/* Edit User Role Modal */}
{isEditModalOpen && editingUser && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in-95 duration-200">
<div className="flex justify-between items-center p-5 border-b border-slate-100">
<h3 className="text-lg font-semibold text-slate-800">Edit User Role</h3>
<button
onClick={() => setIsEditModalOpen(false)}
className="text-slate-400 hover:text-slate-600 p-1 rounded-md transition-colors cursor-pointer"
>
<X size={20} />
</button>
</div>
<form onSubmit={handleEditSubmit} className="p-6 space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">Username</label>
<input
type="text"
disabled
value={editingUser.user_name}
className="w-full bg-slate-50 border border-slate-200 text-sm rounded-lg px-3 py-2.5 text-slate-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">Role</label>
<select
value={editRole}
onChange={(e) => setEditRole(e.target.value)}
className="w-full bg-white border border-slate-200 text-sm rounded-lg px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all cursor-pointer"
>
<option value="User">User</option>
<option value="Administrator">Administrator</option>
<option value="SuperAdministrator">SuperAdministrator</option>
</select>
</div>
<div className="pt-4 flex justify-end space-x-3">
<button
type="button"
onClick={() => setIsEditModalOpen(false)}
className="px-4 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors cursor-pointer"
>
Cancel
</button>
<button
type="submit"
disabled={submitLoading}
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer disabled:opacity-70 flex items-center"
>
{submitLoading ? 'Saving...' : 'Save Changes'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}
+66
View File
@@ -0,0 +1,66 @@
import { useState, useEffect } from 'react';
import type { ClusterNode } from '../types';
export function useClusterState() {
const [nodes, setNodes] = useState<ClusterNode[]>([]);
const [isConnected, setIsConnected] = useState(false);
useEffect(() => {
let ws: WebSocket | null = null;
let reconnectTimeout: ReturnType<typeof setTimeout>;
let retryCount = 0;
const maxRetryCount = 10;
const baseDelay = 1000;
const connect = () => {
// Determine WS URL based on API base URL or window location
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
const wsBase = import.meta.env.VITE_API_BASE_URL
? import.meta.env.VITE_API_BASE_URL.replace(/^http/, 'ws')
: `${protocol}//${host}`;
ws = new WebSocket(`${wsBase}/api/v1/cluster/ws/state`);
ws.onopen = () => {
setIsConnected(true);
retryCount = 0; // Reset retry count on successful connection
};
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (Array.isArray(data)) {
setNodes(data);
}
} catch (e) {
console.error("Error parsing cluster state websocket message", e);
}
};
ws.onclose = () => {
setIsConnected(false);
if (retryCount < maxRetryCount) {
const delay = baseDelay * Math.pow(2, retryCount);
retryCount++;
console.log(`WebSocket closed. Reconnecting in ${delay}ms... (Attempt ${retryCount})`);
reconnectTimeout = setTimeout(connect, delay);
} else {
console.error("Max WebSocket reconnect attempts reached.");
}
};
};
connect();
return () => {
clearTimeout(reconnectTimeout);
if (ws) {
ws.close();
}
};
}, []);
return { nodes, isConnected };
}
+1
View File
@@ -0,0 +1 @@
@import "tailwindcss";
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+105
View File
@@ -0,0 +1,105 @@
// General types
export interface TokenData {
user_id: string;
user_name: string;
}
export interface User {
user_id?: string;
user_name: string;
role?: string;
status?: string;
}
// Provider types
export interface Provider {
provider_type: 'openai' | 'claude' | 'local' | 'deepseek';
provider_title: string;
provider_url?: string;
provider_owner?: string;
provider_models?: string[];
// Based on your UI needs we might infer some local status fields
status?: string;
model?: string;
}
export interface ProviderRegisterRequest {
provider_type: 'openai' | 'claude' | 'local' | 'deepseek';
provider_title: string;
provider_url: string;
provider_apikey: string;
}
export interface ProviderListResponse {
provider_list: Record<string, Provider>;
}
// Cluster types (Websocket response)
export interface ClusterResources {
CPU?: number;
memory?: number;
GPU?: number;
[key: string]: number | undefined;
}
export interface ClusterNode {
node_id: string;
node_name: string;
alive: boolean;
resources: ClusterResources;
remaining: ClusterResources;
}
// Chat types
export interface ChatMessageRequest {
message: string;
}
export interface ChatMessageResponse {
message: string; // Either event_id or text
}
// Workflow types
export interface Workflow {
event_id: string;
workflow_title: string;
status?: string;
}
export interface WorkflowStep {
step: number;
name: string;
node: string;
action: string;
desc: string;
status: string;
agent_id?: string;
}
export interface WorkflowDetail {
event_id: string;
workflow_title: string | null;
status: string;
command?: string;
current_step: number;
user_name: string;
message: string;
create_time: string;
steps: WorkflowStep[];
}
// Workflow Template Validation
export interface WorkStep {
name: string;
desc?: string;
actor: string; // the name of the worker individual
inputs?: string[];
outputs?: string[];
}
export interface WorkflowTemplate {
name: string;
desc?: string;
steps: WorkStep[];
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
})