feat: 初始化 Claude Code 管理平台项目
实现了基于 Web 的 Claude Code 实例管理功能: ## 功能特性 - 🔐 用户认证:JWT 登录验证 - 🚀 实例管理:创建、启动、停止、删除 Claude Code 实例 - 📊 实时监控:CPU、内存、运行时间统计 - 📝 日志管理:Winston 日志系统 - 🔌 PM2 集成:稳定的进程管理 - 🌐 Web 界面:Vue 3 + Element Plus ## 技术栈 - 后端:Node.js + Express + TypeScript + PM2 - 前端:Vue 3 + TypeScript + Vite + Element Plus - 认证:JWT - 存储:文件系统(JSON) ## 项目结构 - Monorepo 结构,前后端分离 - 完整的类型定义 - 模块化设计 - 详细的开发文档 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
commit
ed626e74dc
46 files changed
+11882
No files matched your search
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npm install:*)",
|
||||
"Bash(git init:*)",
|
||||
"Bash(git add:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# 服务器配置
|
||||
PORT=3000
|
||||
NODE_ENV=development
|
||||
|
||||
# JWT 密钥(请修改为随机字符串)
|
||||
JWT_SECRET=your-secret-key-change-this
|
||||
|
||||
# 用户认证
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=admin123
|
||||
|
||||
# PM2 配置
|
||||
PM2_HOME=~/.pm2
|
||||
|
||||
# 实例配置
|
||||
INSTANCE_PORT_RANGE_START=4000
|
||||
INSTANCE_PORT_RANGE_END=4999
|
||||
MAX_INSTANCES=10
|
||||
|
||||
# 日志配置
|
||||
LOG_LEVEL=info
|
||||
LOG_DIR=data/logs
|
||||
|
||||
# 数据存储
|
||||
DATA_DIR=data
|
||||
INSTANCE_CONFIG_DIR=data/instances
|
||||
|
||||
# CORS 配置
|
||||
CORS_ORIGIN=http://localhost:5173
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# 依赖
|
||||
node_modules/
|
||||
.pnp
|
||||
.pnp.js
|
||||
|
||||
# 环境变量
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# 构建输出
|
||||
dist/
|
||||
build/
|
||||
*.tsbuildinfo
|
||||
|
||||
# 日志
|
||||
logs/
|
||||
*.log
|
||||
data/logs/
|
||||
|
||||
# 数据存储(保留目录结构但忽略内容)
|
||||
data/instances/*.json
|
||||
!data/instances/.gitkeep
|
||||
|
||||
# 编辑器
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
|
||||
# 测试覆盖率
|
||||
coverage/
|
||||
.nyc_output/
|
||||
|
||||
# 临时文件
|
||||
*.tmp
|
||||
.cache/
|
||||
@@ -0,0 +1,192 @@
|
||||
# CC Cloud - Claude Code 管理平台
|
||||
|
||||
一个基于 Web 的 Claude Code 实例管理平台,支持启动、停止、交互、监控和配置管理。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- 🚀 **实例管理**: 启动、停止、删除 Claude Code 实例
|
||||
- 💬 **交互界面**: 通过 Web 界面与 Claude Code 实例交互
|
||||
- 📊 **实时监控**: CPU、内存、运行时间等监控数据
|
||||
- 📝 **日志查看**: 实时查看实例运行日志
|
||||
- ⚙️ **配置管理**: 灵活的实例配置(模型、API Key、工作目录等)
|
||||
- 🔐 **认证保护**: 简单的用户名密码认证
|
||||
|
||||
## 技术栈
|
||||
|
||||
### 后端
|
||||
- Node.js + Express + TypeScript
|
||||
- PM2 进程管理
|
||||
- Socket.IO (WebSocket)
|
||||
- JWT 认证
|
||||
- Winston 日志
|
||||
|
||||
### 前端
|
||||
- Vue 3 + TypeScript + Vite
|
||||
- Element Plus UI
|
||||
- Pinia 状态管理
|
||||
- Axios HTTP 客户端
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Node.js >= 18
|
||||
- npm >= 9
|
||||
- PM2 (`npm install -g pm2`)
|
||||
- Claude Code CLI
|
||||
|
||||
### 安装
|
||||
|
||||
```bash
|
||||
# 克隆项目
|
||||
git clone <repository-url>
|
||||
cd cc-cloud
|
||||
|
||||
# 安装所有依赖
|
||||
npm run install:all
|
||||
```
|
||||
|
||||
### 配置
|
||||
|
||||
```bash
|
||||
# 复制环境变量模板
|
||||
cp .env.example .env
|
||||
|
||||
# 编辑 .env 文件,设置必要的配置
|
||||
# 至少需要设置:
|
||||
# - JWT_SECRET: 随机字符串
|
||||
# - ADMIN_USERNAME: 管理员用户名
|
||||
# - ADMIN_PASSWORD: 管理员密码
|
||||
```
|
||||
|
||||
### 开发
|
||||
|
||||
```bash
|
||||
# 同时启动前后端开发服务器
|
||||
npm run dev
|
||||
|
||||
# 或者分别启动
|
||||
npm run dev:backend # 后端: http://localhost:3000
|
||||
npm run dev:frontend # 前端: http://localhost:5173
|
||||
```
|
||||
|
||||
### 生产部署
|
||||
|
||||
```bash
|
||||
# 构建前后端
|
||||
npm run build
|
||||
|
||||
# 使用 PM2 启动后端
|
||||
pm2 start backend/dist/app.js --name cc-cloud-backend
|
||||
|
||||
# 部署前端到 Nginx
|
||||
# 将 frontend/dist/ 目录部署到 Nginx 静态文件目录
|
||||
```
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
cc-cloud/
|
||||
├── backend/ # 后端代码
|
||||
├── frontend/ # 前端代码
|
||||
├── data/ # 数据目录
|
||||
│ ├── instances/ # 实例配置
|
||||
│ └── logs/ # 日志文件
|
||||
├── .env.example # 环境变量模板
|
||||
└── README.md # 项目文档
|
||||
```
|
||||
|
||||
## API 文档
|
||||
|
||||
详细的 API 文档请查看 [docs/API.md](docs/API.md)
|
||||
|
||||
### 主要接口
|
||||
|
||||
- `POST /api/auth/login` - 用户登录
|
||||
- `GET /api/instances` - 获取实例列表
|
||||
- `POST /api/instances/start` - 启动实例
|
||||
- `POST /api/instances/:id/stop` - 停止实例
|
||||
- `DELETE /api/instances/:id` - 删除实例
|
||||
- `POST /api/interactions/:id/chat` - 与实例交互
|
||||
- `GET /api/monitor/:id` - 获取监控数据
|
||||
|
||||
## 配置说明
|
||||
|
||||
### 环境变量
|
||||
|
||||
| 变量名 | 说明 | 默认值 |
|
||||
|--------|------|--------|
|
||||
| PORT | 后端服务端口 | 3000 |
|
||||
| JWT_SECRET | JWT 密钥 | - |
|
||||
| ADMIN_USERNAME | 管理员用户名 | admin |
|
||||
| ADMIN_PASSWORD | 管理员密码 | admin123 |
|
||||
| INSTANCE_PORT_RANGE_START | 实例端口范围起始 | 4000 |
|
||||
| INSTANCE_PORT_RANGE_END | 实例端口范围结束 | 4999 |
|
||||
| MAX_INSTANCES | 最大实例数量 | 10 |
|
||||
|
||||
### 实例配置
|
||||
|
||||
每个实例可以配置:
|
||||
- **模型**: Claude 模型名称(如 claude-sonnet-4-5)
|
||||
- **API Key**: Anthropic API Key(可选)
|
||||
- **工作目录**: 实例运行的工作目录
|
||||
- **端口**: HTTP 服务端口(可选,自动分配)
|
||||
- **环境变量**: 自定义环境变量
|
||||
|
||||
## 开发指南
|
||||
|
||||
详细的开发指南请查看 [docs/DEVELOPMENT_GUIDE.md](docs/DEVELOPMENT_GUIDE.md)
|
||||
|
||||
### 代码规范
|
||||
|
||||
```bash
|
||||
# 运行代码检查
|
||||
npm run lint
|
||||
|
||||
# 格式化代码
|
||||
npm run format
|
||||
```
|
||||
|
||||
### 测试
|
||||
|
||||
```bash
|
||||
# 运行测试
|
||||
npm test
|
||||
|
||||
# 测试覆盖率
|
||||
npm run test:coverage
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 1. 如何查看实例日志?
|
||||
|
||||
在 Web 界面的"日志"页面可以实时查看实例日志,也可以直接访问 `data/logs/` 目录查看日志文件。
|
||||
|
||||
### 2. 实例无法启动?
|
||||
|
||||
检查以下项目:
|
||||
- Claude Code CLI 是否已安装
|
||||
- 工作目录是否存在且有读写权限
|
||||
- API Key 是否正确
|
||||
- 端口是否已被占用
|
||||
|
||||
### 3. 如何重置管理员密码?
|
||||
|
||||
编辑 `.env` 文件,修改 `ADMIN_PASSWORD` 变量,然后重启后端服务。
|
||||
|
||||
## 安全建议
|
||||
|
||||
- 修改默认的管理员密码
|
||||
- 使用强 JWT_SECRET
|
||||
- 在生产环境启用 HTTPS
|
||||
- 限制工作目录访问范围
|
||||
- 定期更新依赖包
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT
|
||||
|
||||
## 贡献
|
||||
|
||||
欢迎提交 Issue 和 Pull Request!
|
||||
@@ -0,0 +1,22 @@
|
||||
module.exports = {
|
||||
parser: '@typescript-eslint/parser',
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
],
|
||||
plugins: ['@typescript-eslint'],
|
||||
env: {
|
||||
node: true,
|
||||
es6: true,
|
||||
},
|
||||
parserOptions: {
|
||||
ecmaVersion: 2022,
|
||||
sourceType: 'module',
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
||||
'no-console': 'off',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.log
|
||||
.env
|
||||
.DS_Store
|
||||
*.tsbuildinfo
|
||||
coverage/
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "cc-cloud-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "CC Cloud 后端服务",
|
||||
"main": "dist/app.js",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/app.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/app.js",
|
||||
"lint": "eslint src --ext .ts",
|
||||
"lint:fix": "eslint src --ext .ts --fix",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"bcrypt": "^5.1.1",
|
||||
"pm2": "^5.3.0",
|
||||
"socket.io": "^4.6.1",
|
||||
"ws": "^8.16.0",
|
||||
"axios": "^1.6.5",
|
||||
"winston": "^3.11.0",
|
||||
"winston-daily-rotate-file": "^4.7.1",
|
||||
"detect-port": "^2.0.0",
|
||||
"uuid": "^9.0.1",
|
||||
"zod": "^3.22.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/jsonwebtoken": "^9.0.5",
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/node": "^20.11.5",
|
||||
"@types/ws": "^8.5.10",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@typescript-eslint/eslint-plugin": "^6.19.1",
|
||||
"@typescript-eslint/parser": "^6.19.1",
|
||||
"eslint": "^8.56.0",
|
||||
"tsx": "^4.7.0",
|
||||
"typescript": "^5.3.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import { createServer } from 'http';
|
||||
import { Server as SocketIOServer } from 'socket.io';
|
||||
import { config } from './config';
|
||||
import logger from './utils/logger';
|
||||
import { initStorage } from './utils/storage';
|
||||
import { initDefaultUser } from './controllers/auth.controller';
|
||||
import { initInstanceService } from './services/instance.service';
|
||||
import { authMiddleware, optionalAuth } from './middleware/auth.middleware';
|
||||
import { errorMiddleware, notFoundMiddleware } from './middleware/error.middleware';
|
||||
import {
|
||||
login,
|
||||
verifyToken,
|
||||
} from './controllers/auth.controller';
|
||||
import {
|
||||
createInstanceHandler,
|
||||
startInstanceHandler,
|
||||
stopInstanceHandler,
|
||||
deleteInstanceHandler,
|
||||
listInstancesHandler,
|
||||
getInstanceHandler,
|
||||
getInstanceStatusHandler,
|
||||
createInstanceSchema,
|
||||
} from './controllers/instance.controller';
|
||||
import { validate } from './middleware/validate.middleware';
|
||||
|
||||
// 创建 Express 应用
|
||||
const app = express();
|
||||
const httpServer = createServer(app);
|
||||
|
||||
// 创建 Socket.IO 服务器
|
||||
const io = new SocketIOServer(httpServer, {
|
||||
cors: {
|
||||
origin: config.corsOrigin,
|
||||
credentials: true,
|
||||
},
|
||||
});
|
||||
|
||||
// 中间件
|
||||
app.use(cors({
|
||||
origin: config.corsOrigin,
|
||||
credentials: true,
|
||||
}));
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// 请求日志
|
||||
app.use((req, res, next) => {
|
||||
logger.info(`${req.method} ${req.path}`);
|
||||
next();
|
||||
});
|
||||
|
||||
// 认证路由(不需要认证)
|
||||
app.post('/api/auth/login', login);
|
||||
app.get('/api/auth/verify', authMiddleware, verifyToken);
|
||||
|
||||
// 实例路由(需要认证)
|
||||
app.post('/api/instances/start', authMiddleware, validate(createInstanceSchema), createInstanceHandler);
|
||||
app.get('/api/instances', authMiddleware, listInstancesHandler);
|
||||
app.get('/api/instances/:instanceId', authMiddleware, getInstanceHandler);
|
||||
app.post('/api/instances/:instanceId/start', authMiddleware, startInstanceHandler);
|
||||
app.post('/api/instances/:instanceId/stop', authMiddleware, stopInstanceHandler);
|
||||
app.delete('/api/instances/:instanceId', authMiddleware, deleteInstanceHandler);
|
||||
app.get('/api/instances/:instanceId/status', authMiddleware, getInstanceStatusHandler);
|
||||
|
||||
// Socket.IO 认证中间件
|
||||
io.use((socket, next) => {
|
||||
const token = socket.handshake.auth.token;
|
||||
|
||||
if (!token) {
|
||||
return next(new Error('认证失败'));
|
||||
}
|
||||
|
||||
try {
|
||||
const jwt = require('jsonwebtoken');
|
||||
const decoded = jwt.verify(token, config.jwtSecret);
|
||||
socket.data.user = decoded;
|
||||
next();
|
||||
} catch (error) {
|
||||
next(new Error('无效的认证令牌'));
|
||||
}
|
||||
});
|
||||
|
||||
// Socket.IO 连接处理
|
||||
io.on('connection', (socket) => {
|
||||
logger.info('WebSocket 连接已建立', { socketId: socket.id });
|
||||
|
||||
socket.on('join-instance', (instanceId: string) => {
|
||||
socket.join(`instance:${instanceId}`);
|
||||
logger.info('加入实例房间', { socketId: socket.id, instanceId });
|
||||
});
|
||||
|
||||
socket.on('leave-instance', (instanceId: string) => {
|
||||
socket.leave(`instance:${instanceId}`);
|
||||
logger.info('离开实例房间', { socketId: socket.id, instanceId });
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
logger.info('WebSocket 连接已断开', { socketId: socket.id });
|
||||
});
|
||||
});
|
||||
|
||||
// 导出 io 实例供其他模块使用
|
||||
export { io };
|
||||
|
||||
// 404 处理
|
||||
app.use(notFoundMiddleware);
|
||||
|
||||
// 错误处理
|
||||
app.use(errorMiddleware);
|
||||
|
||||
// 初始化函数
|
||||
export async function initialize() {
|
||||
try {
|
||||
// 初始化存储
|
||||
await initStorage();
|
||||
logger.info('存储初始化完成');
|
||||
|
||||
// 初始化默认用户
|
||||
await initDefaultUser();
|
||||
logger.info('默认用户初始化完成');
|
||||
|
||||
// 初始化实例服务
|
||||
await initInstanceService();
|
||||
logger.info('实例服务初始化完成');
|
||||
} catch (error) {
|
||||
logger.error('初始化失败', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 启动服务器
|
||||
export async function startServer() {
|
||||
await initialize();
|
||||
|
||||
httpServer.listen(config.port, () => {
|
||||
logger.info(`服务器已启动`, {
|
||||
port: config.port,
|
||||
env: config.nodeEnv,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 如果直接运行此文件
|
||||
if (require.main === module) {
|
||||
startServer().catch((error) => {
|
||||
logger.error('服务器启动失败', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
export default app;
|
||||
@@ -0,0 +1,38 @@
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export const config = {
|
||||
// 服务器配置
|
||||
port: parseInt(process.env.PORT || '3000'),
|
||||
nodeEnv: process.env.NODE_ENV || 'development',
|
||||
|
||||
// JWT 配置
|
||||
jwtSecret: process.env.JWT_SECRET || 'your-secret-key-change-this',
|
||||
jwtExpiresIn: '7d',
|
||||
|
||||
// 用户认证
|
||||
adminUsername: process.env.ADMIN_USERNAME || 'admin',
|
||||
adminPassword: process.env.ADMIN_PASSWORD || 'admin123',
|
||||
|
||||
// PM2 配置
|
||||
pm2Home: process.env.PM2_HOME || path.join(process.env.HOME || '', '.pm2'),
|
||||
|
||||
// 实例配置
|
||||
instancePortRangeStart: parseInt(process.env.INSTANCE_PORT_RANGE_START || '4000'),
|
||||
instancePortRangeEnd: parseInt(process.env.INSTANCE_PORT_RANGE_END || '4999'),
|
||||
maxInstances: parseInt(process.env.MAX_INSTANCES || '10'),
|
||||
|
||||
// 日志配置
|
||||
logLevel: process.env.LOG_LEVEL || 'info',
|
||||
logDir: process.env.LOG_DIR || path.join(process.cwd(), 'data', 'logs'),
|
||||
|
||||
// 数据存储
|
||||
dataDir: process.env.DATA_DIR || path.join(process.cwd(), 'data'),
|
||||
instanceConfigDir: process.env.INSTANCE_CONFIG_DIR ||
|
||||
path.join(process.cwd(), 'data', 'instances'),
|
||||
|
||||
// CORS 配置
|
||||
corsOrigin: process.env.CORS_ORIGIN || 'http://localhost:5173',
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Request, Response } from 'express';
|
||||
import bcrypt from 'bcrypt';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { config } from '../config';
|
||||
import type { User, LoginRequest, LoginResponse, JwtPayload } from '../types';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// 模拟用户存储(实际项目中应该使用数据库)
|
||||
const users: Map<string, User> = new Map();
|
||||
|
||||
// 初始化默认管理员用户
|
||||
export async function initDefaultUser() {
|
||||
const userId = uuidv4();
|
||||
const passwordHash = await bcrypt.hash(config.adminPassword, 10);
|
||||
|
||||
const defaultUser: User = {
|
||||
id: userId,
|
||||
username: config.adminUsername,
|
||||
passwordHash,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
users.set(userId, defaultUser);
|
||||
logger.info('默认管理员用户已创建', { username: config.adminUsername });
|
||||
}
|
||||
|
||||
export async function login(req: Request, res: Response) {
|
||||
try {
|
||||
const { username, password }: LoginRequest = req.body;
|
||||
|
||||
// 查找用户
|
||||
const user = Array.from(users.values()).find(u => u.username === username);
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: '用户名或密码错误' });
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
const isValid = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!isValid) {
|
||||
return res.status(401).json({ error: '用户名或密码错误' });
|
||||
}
|
||||
|
||||
// 生成 JWT
|
||||
const payload: JwtPayload = {
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
};
|
||||
|
||||
const token = jwt.sign(payload, config.jwtSecret, {
|
||||
expiresIn: config.jwtExpiresIn,
|
||||
});
|
||||
|
||||
const response: LoginResponse = {
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
createdAt: user.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
logger.info('用户登录成功', { username });
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
logger.error('登录失败', error);
|
||||
res.status(500).json({ error: '登录失败' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyToken(req: Request, res: Response) {
|
||||
// 如果能到达这里,说明 token 已经被 authMiddleware 验证过
|
||||
res.json({
|
||||
valid: true,
|
||||
user: req.user,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
createInstance,
|
||||
startInstance,
|
||||
stopInstance,
|
||||
removeInstance,
|
||||
getAllInstances,
|
||||
getInstance,
|
||||
} from '../services/instance.service';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// 验证 schema
|
||||
const createInstanceSchema = z.object({
|
||||
body: z.object({
|
||||
name: z.string().min(1, '实例名称不能为空'),
|
||||
config: z.object({
|
||||
model: z.string().min(1, '模型不能为空'),
|
||||
apiKey: z.string().optional(),
|
||||
workingDir: z.string().min(1, '工作目录不能为空'),
|
||||
port: z.number().int().min(1).max(65535).optional(),
|
||||
maxMemory: z.number().int().positive().optional(),
|
||||
env: z.record(z.string()).optional(),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
export async function createInstanceHandler(req: Request, res: Response) {
|
||||
try {
|
||||
const instance = await createInstance(req.body);
|
||||
res.status(201).json({ instance });
|
||||
} catch (error: any) {
|
||||
logger.error('创建实例失败', error);
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function startInstanceHandler(req: Request, res: Response) {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
await startInstance(instanceId);
|
||||
res.json({ success: true, message: '实例启动成功' });
|
||||
} catch (error: any) {
|
||||
logger.error('启动实例失败', error);
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopInstanceHandler(req: Request, res: Response) {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
await stopInstance(instanceId);
|
||||
res.json({ success: true, message: '实例停止成功' });
|
||||
} catch (error: any) {
|
||||
logger.error('停止实例失败', error);
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteInstanceHandler(req: Request, res: Response) {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
await removeInstance(instanceId);
|
||||
res.json({ success: true, message: '实例删除成功' });
|
||||
} catch (error: any) {
|
||||
logger.error('删除实例失败', error);
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listInstancesHandler(req: Request, res: Response) {
|
||||
try {
|
||||
const instances = await getAllInstances();
|
||||
res.json({ instances });
|
||||
} catch (error: any) {
|
||||
logger.error('获取实例列表失败', error);
|
||||
res.status(500).json({ error: '获取实例列表失败' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInstanceHandler(req: Request, res: Response) {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
const instance = await getInstance(instanceId);
|
||||
|
||||
if (!instance) {
|
||||
return res.status(404).json({ error: '实例不存在' });
|
||||
}
|
||||
|
||||
res.json({ instance });
|
||||
} catch (error: any) {
|
||||
logger.error('获取实例失败', error);
|
||||
res.status(500).json({ error: '获取实例失败' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInstanceStatusHandler(req: Request, res: Response) {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
const instance = await getInstance(instanceId);
|
||||
|
||||
if (!instance) {
|
||||
return res.status(404).json({ error: '实例不存在' });
|
||||
}
|
||||
|
||||
res.json({
|
||||
status: instance.status,
|
||||
stats: instance.stats,
|
||||
});
|
||||
} catch (error: any) {
|
||||
logger.error('获取实例状态失败', error);
|
||||
res.status(500).json({ error: '获取实例状态失败' });
|
||||
}
|
||||
}
|
||||
|
||||
export { createInstanceSchema };
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { config } from '../config';
|
||||
import type { JwtPayload } from '../types';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// 扩展 Express Request 类型
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
user?: JwtPayload;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function authMiddleware(req: Request, res: Response, next: NextFunction) {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
return res.status(401).json({ error: '未提供认证令牌' });
|
||||
}
|
||||
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, config.jwtSecret) as JwtPayload;
|
||||
req.user = decoded;
|
||||
next();
|
||||
} catch (error: any) {
|
||||
logger.error('Token 验证失败', error);
|
||||
return res.status(401).json({ error: '无效的认证令牌' });
|
||||
}
|
||||
}
|
||||
|
||||
// 可选认证(不强制要求登录)
|
||||
export function optionalAuth(req: Request, res: Response, next: NextFunction) {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, config.jwtSecret) as JwtPayload;
|
||||
req.user = decoded;
|
||||
} catch (error) {
|
||||
// 忽略错误,继续处理请求
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export function errorMiddleware(
|
||||
error: Error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
logger.error('请求处理错误', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
});
|
||||
|
||||
res.status(500).json({
|
||||
error: '服务器内部错误',
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
export function notFoundMiddleware(req: Request, res: Response) {
|
||||
res.status(404).json({
|
||||
error: '未找到',
|
||||
message: `路径 ${req.path} 不存在`,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { AnyZodObject, ZodError } from 'zod';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export function validate(schema: AnyZodObject) {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
await schema.parseAsync({
|
||||
body: req.body,
|
||||
query: req.query,
|
||||
params: req.params,
|
||||
});
|
||||
next();
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
logger.error('验证失败', { errors: error.errors });
|
||||
return res.status(400).json({
|
||||
error: '请求数据验证失败',
|
||||
details: error.errors,
|
||||
});
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { Instance, CreateInstanceRequest, InstanceStats } from '../types';
|
||||
import { readInstance, writeInstance, deleteInstance, listInstances, instanceExists } from '../utils/storage';
|
||||
import { allocatePort, releasePort, initPortAllocations } from '../utils/port-manager';
|
||||
import { startProcess, stopProcess, deleteProcess, isProcessRunning, describeProcess } from './pm2.service';
|
||||
import logger from '../utils/logger';
|
||||
import fs from 'fs/promises';
|
||||
|
||||
// 初始化端口分配
|
||||
export async function initInstanceService() {
|
||||
const instances = await listInstances();
|
||||
const ports = instances
|
||||
.filter(i => i.config.port)
|
||||
.map(i => i.config.port!);
|
||||
initPortAllocations(ports);
|
||||
logger.info('实例服务已初始化', { instanceCount: instances.length });
|
||||
}
|
||||
|
||||
// 创建实例
|
||||
export async function createInstance(data: CreateInstanceRequest): Promise<Instance> {
|
||||
const { name, config } = data;
|
||||
|
||||
// 验证工作目录
|
||||
try {
|
||||
await fs.access(config.workingDir);
|
||||
} catch {
|
||||
throw new Error('工作目录不存在或无权访问');
|
||||
}
|
||||
|
||||
// 分配端口
|
||||
const port = config.port ? await allocatePort(config.port) : await allocatePort();
|
||||
|
||||
const instance: Instance = {
|
||||
id: uuidv4(),
|
||||
name,
|
||||
status: 'stopped',
|
||||
config: {
|
||||
...config,
|
||||
port,
|
||||
},
|
||||
stats: {
|
||||
memory: 0,
|
||||
cpu: 0,
|
||||
restarts: 0,
|
||||
status: 'offline',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
await writeInstance(instance);
|
||||
logger.info('实例已创建', { instanceId: instance.id, name, port });
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
// 启动实例
|
||||
export async function startInstance(instanceId: string): Promise<void> {
|
||||
const instance = await readInstance(instanceId);
|
||||
if (!instance) {
|
||||
throw new Error('实例不存在');
|
||||
}
|
||||
|
||||
if (instance.status === 'running') {
|
||||
throw new Error('实例已在运行中');
|
||||
}
|
||||
|
||||
const { config, id } = instance;
|
||||
|
||||
try {
|
||||
// PM2 启动选项
|
||||
const pm2Options = {
|
||||
name: id,
|
||||
script: 'npx',
|
||||
args: ['@anthropic-ai/claude-code', 'serve', '--port', config.port!.toString()],
|
||||
cwd: config.workingDir,
|
||||
env: {
|
||||
...config.env,
|
||||
ANTHROPIC_API_KEY: config.apiKey || process.env.ANTHROPIC_API_KEY,
|
||||
PORT: config.port!.toString(),
|
||||
},
|
||||
error_file: `data/logs/${id}-error.log`,
|
||||
out_file: `data/logs/${id}-out.log`,
|
||||
max_memory_restart: config.maxMemory ? `${config.maxMemory}M` : undefined,
|
||||
};
|
||||
|
||||
await startProcess(pm2Options);
|
||||
|
||||
// 更新实例状态
|
||||
instance.status = 'running';
|
||||
instance.lastStarted = new Date();
|
||||
instance.stats.port = config.port;
|
||||
await writeInstance(instance);
|
||||
|
||||
logger.info('实例已启动', { instanceId, port: config.port });
|
||||
} catch (error) {
|
||||
instance.status = 'errored';
|
||||
await writeInstance(instance);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 停止实例
|
||||
export async function stopInstance(instanceId: string): Promise<void> {
|
||||
const instance = await readInstance(instanceId);
|
||||
if (!instance) {
|
||||
throw new Error('实例不存在');
|
||||
}
|
||||
|
||||
if (instance.status === 'stopped') {
|
||||
throw new Error('实例未运行');
|
||||
}
|
||||
|
||||
try {
|
||||
await stopProcess(instanceId);
|
||||
|
||||
instance.status = 'stopped';
|
||||
instance.stats.pid = undefined;
|
||||
instance.stats.uptime = undefined;
|
||||
instance.stats.status = 'offline';
|
||||
await writeInstance(instance);
|
||||
|
||||
logger.info('实例已停止', { instanceId });
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 删除实例
|
||||
export async function removeInstance(instanceId: string): Promise<void> {
|
||||
const instance = await readInstance(instanceId);
|
||||
if (!instance) {
|
||||
throw new Error('实例不存在');
|
||||
}
|
||||
|
||||
// 如果实例在运行,先停止
|
||||
if (instance.status === 'running') {
|
||||
await stopInstance(instanceId);
|
||||
}
|
||||
|
||||
// 删除 PM2 进程
|
||||
try {
|
||||
await deleteProcess(instanceId);
|
||||
} catch (error) {
|
||||
// 忽略删除进程的错误
|
||||
}
|
||||
|
||||
// 释放端口
|
||||
if (instance.config.port) {
|
||||
releasePort(instance.config.port);
|
||||
}
|
||||
|
||||
// 删除实例配置
|
||||
await deleteInstance(instanceId);
|
||||
|
||||
logger.info('实例已删除', { instanceId });
|
||||
}
|
||||
|
||||
// 获取实例状态
|
||||
export async function getInstanceStatus(instanceId: string): Promise<InstanceStats> {
|
||||
const instance = await readInstance(instanceId);
|
||||
if (!instance) {
|
||||
throw new Error('实例不存在');
|
||||
}
|
||||
|
||||
const process = await describeProcess(instanceId);
|
||||
|
||||
if (process) {
|
||||
const isRunning = process.pm2_env.status === 'online';
|
||||
|
||||
instance.stats = {
|
||||
pid: process.pid,
|
||||
port: instance.config.port,
|
||||
uptime: process.pm2_env.uptime,
|
||||
memory: process.monit.memory,
|
||||
cpu: process.monit.cpu,
|
||||
restarts: process.pm2_env.restart_time,
|
||||
status: isRunning ? 'online' : 'offline',
|
||||
};
|
||||
|
||||
// 更新状态
|
||||
instance.status = isRunning ? 'running' : 'stopped';
|
||||
await writeInstance(instance);
|
||||
} else {
|
||||
instance.stats.status = 'offline';
|
||||
instance.status = 'stopped';
|
||||
}
|
||||
|
||||
return instance.stats;
|
||||
}
|
||||
|
||||
// 获取所有实例
|
||||
export async function getAllInstances(): Promise<Instance[]> {
|
||||
const instances = await listInstances();
|
||||
|
||||
// 更新所有实例的状态
|
||||
for (const instance of instances) {
|
||||
try {
|
||||
await getInstanceStatus(instance.id);
|
||||
} catch (error) {
|
||||
logger.error(`更新实例状态失败: ${instance.id}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 重新读取最新的实例数据
|
||||
return await listInstances();
|
||||
}
|
||||
|
||||
// 获取单个实例
|
||||
export async function getInstance(instanceId: string): Promise<Instance | null> {
|
||||
await getInstanceStatus(instanceId);
|
||||
return await readInstance(instanceId);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import pm2 from 'pm2';
|
||||
import { promisify } from 'util';
|
||||
import type { PM2Process } from '../types';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// Promisify PM2 方法
|
||||
const pm2Connect = promisify(pm2.connect);
|
||||
const pm2Start = promisify(pm2.start);
|
||||
const pm2Stop = promisify(pm2.stop);
|
||||
const pm2Delete = promisify(pm2.delete);
|
||||
const pm2Describe = promisify(pm2.describe);
|
||||
const pm2List = promisify(pm2.list);
|
||||
const pm2Restart = promisify(pm2.restart);
|
||||
const pm2Disconnect = promisify(pm2.disconnect);
|
||||
|
||||
// PM2 连接状态
|
||||
let connected = false;
|
||||
|
||||
// 确保 PM2 已连接
|
||||
export async function ensureConnection() {
|
||||
if (!connected) {
|
||||
try {
|
||||
await pm2Connect();
|
||||
connected = true;
|
||||
logger.info('PM2 已连接');
|
||||
} catch (error) {
|
||||
logger.error('PM2 连接失败', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 启动进程
|
||||
export async function startProcess(options: any): Promise<void> {
|
||||
await ensureConnection();
|
||||
|
||||
try {
|
||||
await pm2Start(options);
|
||||
logger.info(`PM2 进程已启动: ${options.name}`);
|
||||
} catch (error) {
|
||||
logger.error(`PM2 启动进程失败: ${options.name}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 停止进程
|
||||
export async function stopProcess(processName: string): Promise<void> {
|
||||
await ensureConnection();
|
||||
|
||||
try {
|
||||
await pm2Stop(processName);
|
||||
logger.info(`PM2 进程已停止: ${processName}`);
|
||||
} catch (error) {
|
||||
logger.error(`PM2 停止进程失败: ${processName}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 删除进程
|
||||
export async function deleteProcess(processName: string): Promise<void> {
|
||||
await ensureConnection();
|
||||
|
||||
try {
|
||||
await pm2Delete(processName);
|
||||
logger.info(`PM2 进程已删除: ${processName}`);
|
||||
} catch (error) {
|
||||
logger.error(`PM2 删除进程失败: ${processName}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 重启进程
|
||||
export async function restartProcess(processName: string): Promise<void> {
|
||||
await ensureConnection();
|
||||
|
||||
try {
|
||||
await pm2Restart(processName);
|
||||
logger.info(`PM2 进程已重启: ${processName}`);
|
||||
} catch (error) {
|
||||
logger.error(`PM2 重启进程失败: ${processName}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取进程信息
|
||||
export async function describeProcess(processName: string): Promise<PM2Process | undefined> {
|
||||
await ensureConnection();
|
||||
|
||||
try {
|
||||
const processes = await pm2Describe(processName) as PM2Process[];
|
||||
return processes[0];
|
||||
} catch (error) {
|
||||
logger.error(`PM2 获取进程信息失败: ${processName}`, error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// 列出所有进程
|
||||
export async function listProcesses(): Promise<PM2Process[]> {
|
||||
await ensureConnection();
|
||||
|
||||
try {
|
||||
const processes = await pm2List() as PM2Process[];
|
||||
return processes;
|
||||
} catch (error) {
|
||||
logger.error('PM2 列出进程失败', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// 检查进程是否在运行
|
||||
export async function isProcessRunning(processName: string): Promise<boolean> {
|
||||
const process = await describeProcess(processName);
|
||||
if (!process) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const status = process.pm2_env.status;
|
||||
return status === 'online';
|
||||
}
|
||||
|
||||
// 断开 PM2 连接
|
||||
export async function disconnect() {
|
||||
if (connected) {
|
||||
try {
|
||||
await pm2Disconnect();
|
||||
connected = false;
|
||||
logger.info('PM2 已断开连接');
|
||||
} catch (error) {
|
||||
logger.error('PM2 断开连接失败', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 进程退出时断开连接
|
||||
process.on('exit', () => {
|
||||
disconnect();
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
// 通用类型定义
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface InstanceConfig {
|
||||
model: string;
|
||||
apiKey?: string;
|
||||
workingDir: string;
|
||||
port?: number;
|
||||
maxMemory?: number;
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface InstanceStats {
|
||||
pid?: number;
|
||||
port?: number;
|
||||
uptime?: number;
|
||||
memory: number;
|
||||
cpu: number;
|
||||
restarts: number;
|
||||
status: 'online' | 'offline';
|
||||
}
|
||||
|
||||
export interface Instance {
|
||||
id: string;
|
||||
name: string;
|
||||
status: 'running' | 'stopped' | 'errored' | 'offline';
|
||||
config: InstanceConfig;
|
||||
stats: InstanceStats;
|
||||
createdAt: Date;
|
||||
lastStarted?: Date;
|
||||
}
|
||||
|
||||
export interface CreateInstanceRequest {
|
||||
name: string;
|
||||
config: InstanceConfig;
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string;
|
||||
user: Omit<User, 'passwordHash'>;
|
||||
}
|
||||
|
||||
export interface PM2Process {
|
||||
name: string;
|
||||
pid: number;
|
||||
pm2_env: {
|
||||
status: string;
|
||||
uptime: number;
|
||||
restart_time: number;
|
||||
pm_out_log_path: string;
|
||||
pm_err_log_path: string;
|
||||
};
|
||||
monit: {
|
||||
memory: number;
|
||||
cpu: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface JwtPayload {
|
||||
userId: string;
|
||||
username: string;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import winston from 'winston';
|
||||
import DailyRotateFile from 'winston-daily-rotate-file';
|
||||
import path from 'path';
|
||||
import { config } from '../config';
|
||||
|
||||
const logDir = config.logDir;
|
||||
|
||||
// 自定义日志格式
|
||||
const logFormat = winston.format.combine(
|
||||
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||
winston.format.errors({ stack: true }),
|
||||
winston.format.printf(({ timestamp, level, message, stack }) => {
|
||||
if (stack) {
|
||||
return `${timestamp} [${level.toUpperCase()}]: ${message}\n${stack}`;
|
||||
}
|
||||
return `${timestamp} [${level.toUpperCase()}]: ${message}`;
|
||||
})
|
||||
);
|
||||
|
||||
// 创建日志传输器
|
||||
const transports: winston.transport[] = [
|
||||
// 控制台输出
|
||||
new winston.transports.Console({
|
||||
format: winston.format.combine(
|
||||
winston.format.colorize(),
|
||||
logFormat
|
||||
),
|
||||
}),
|
||||
];
|
||||
|
||||
// 文件日志(每日轮转)
|
||||
if (config.nodeEnv === 'production') {
|
||||
transports.push(
|
||||
// 所有日志
|
||||
new DailyRotateFile({
|
||||
dirname: logDir,
|
||||
filename: 'application-%DATE%.log',
|
||||
datePattern: 'YYYY-MM-DD',
|
||||
maxSize: '20m',
|
||||
maxFiles: '14d',
|
||||
format: logFormat,
|
||||
}),
|
||||
// 错误日志
|
||||
new DailyRotateFile({
|
||||
dirname: logDir,
|
||||
filename: 'error-%DATE%.log',
|
||||
datePattern: 'YYYY-MM-DD',
|
||||
level: 'error',
|
||||
maxSize: '20m',
|
||||
maxFiles: '30d',
|
||||
format: logFormat,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// 创建 logger
|
||||
export const logger = winston.createLogger({
|
||||
level: config.logLevel,
|
||||
transports,
|
||||
});
|
||||
|
||||
export default logger;
|
||||
@@ -0,0 +1,55 @@
|
||||
import detectPort from 'detect-port';
|
||||
import { config } from '../config';
|
||||
import logger from './logger';
|
||||
|
||||
// 已分配的端口缓存
|
||||
const allocatedPorts = new Set<number>();
|
||||
|
||||
// 初始化已分配端口
|
||||
export function initPortAllocations(ports: number[]) {
|
||||
ports.forEach(port => allocatedPorts.add(port));
|
||||
}
|
||||
|
||||
// 分配端口
|
||||
export async function allocatePort(preferredPort?: number): Promise<number> {
|
||||
// 如果指定了首选端口
|
||||
if (preferredPort) {
|
||||
const port = await detectPort(preferredPort);
|
||||
if (port === preferredPort) {
|
||||
allocatedPorts.add(port);
|
||||
logger.info(`分配端口: ${port}`);
|
||||
return port;
|
||||
}
|
||||
logger.warn(`首选端口 ${preferredPort} 已被占用,自动分配其他端口`);
|
||||
}
|
||||
|
||||
// 自动分配可用端口
|
||||
const startPort = config.instancePortRangeStart;
|
||||
const endPort = config.instancePortRangeEnd;
|
||||
|
||||
for (let port = startPort; port <= endPort; port++) {
|
||||
if (allocatedPorts.has(port)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const availablePort = await detectPort(port);
|
||||
if (availablePort === port) {
|
||||
allocatedPorts.add(port);
|
||||
logger.info(`自动分配端口: ${port}`);
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('没有可用的端口');
|
||||
}
|
||||
|
||||
// 释放端口
|
||||
export function releasePort(port: number) {
|
||||
allocatedPorts.delete(port);
|
||||
logger.info(`释放端口: ${port}`);
|
||||
}
|
||||
|
||||
// 获取所有已分配端口
|
||||
export function getAllocatedPorts(): number[] {
|
||||
return Array.from(allocatedPorts);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import { config } from '../config';
|
||||
import type { Instance } from '../types';
|
||||
import logger from './logger';
|
||||
|
||||
const instancesDir = config.instanceConfigDir;
|
||||
|
||||
// 确保目录存在
|
||||
export async function ensureDir(dir: string) {
|
||||
try {
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
} catch (error) {
|
||||
logger.error(`创建目录失败: ${dir}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化存储
|
||||
export async function initStorage() {
|
||||
await ensureDir(config.dataDir);
|
||||
await ensureDir(instancesDir);
|
||||
await ensureDir(config.logDir);
|
||||
}
|
||||
|
||||
// 读取实例配置
|
||||
export async function readInstance(instanceId: string): Promise<Instance | null> {
|
||||
try {
|
||||
const filePath = path.join(instancesDir, `${instanceId}.json`);
|
||||
const data = await fs.readFile(filePath, 'utf-8');
|
||||
const instance = JSON.parse(data);
|
||||
// 转换日期
|
||||
instance.createdAt = new Date(instance.createdAt);
|
||||
if (instance.lastStarted) {
|
||||
instance.lastStarted = new Date(instance.lastStarted);
|
||||
}
|
||||
return instance;
|
||||
} catch (error: any) {
|
||||
if (error.code === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
logger.error(`读取实例配置失败: ${instanceId}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 写入实例配置
|
||||
export async function writeInstance(instance: Instance): Promise<void> {
|
||||
try {
|
||||
await ensureDir(instancesDir);
|
||||
const filePath = path.join(instancesDir, `${instance.id}.json`);
|
||||
await fs.writeFile(filePath, JSON.stringify(instance, null, 2));
|
||||
} catch (error) {
|
||||
logger.error(`写入实例配置失败: ${instance.id}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 删除实例配置
|
||||
export async function deleteInstance(instanceId: string): Promise<void> {
|
||||
try {
|
||||
const filePath = path.join(instancesDir, `${instanceId}.json`);
|
||||
await fs.unlink(filePath);
|
||||
} catch (error: any) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
logger.error(`删除实例配置失败: ${instanceId}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 列出所有实例
|
||||
export async function listInstances(): Promise<Instance[]> {
|
||||
try {
|
||||
await ensureDir(instancesDir);
|
||||
const files = await fs.readdir(instancesDir);
|
||||
const instanceFiles = files.filter(f => f.endsWith('.json'));
|
||||
|
||||
const instances: Instance[] = [];
|
||||
for (const file of instanceFiles) {
|
||||
try {
|
||||
const instanceId = path.basename(file, '.json');
|
||||
const instance = await readInstance(instanceId);
|
||||
if (instance) {
|
||||
instances.push(instance);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`读取实例文件失败: ${file}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return instances;
|
||||
} catch (error) {
|
||||
logger.error('列出实例失败', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 检查实例是否存在
|
||||
export async function instanceExists(instanceId: string): Promise<boolean> {
|
||||
const filePath = path.join(instancesDir, `${instanceId}.json`);
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
# 此文件用于保留目录结构
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
# CC Cloud API 文档
|
||||
|
||||
本文档详细描述 CC Cloud 后端 API 接口。
|
||||
|
||||
## 基础信息
|
||||
|
||||
- **Base URL**: `http://localhost:3000/api`
|
||||
- **认证方式**: JWT Bearer Token
|
||||
- **Content-Type**: `application/json`
|
||||
|
||||
## 认证
|
||||
|
||||
### 登录
|
||||
|
||||
获取访问令牌。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
POST /auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "string",
|
||||
"password": "string"
|
||||
}
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||
"user": {
|
||||
"id": "string",
|
||||
"username": "string",
|
||||
"createdAt": "2024-01-01T00:00:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 验证 Token
|
||||
|
||||
验证当前 Token 是否有效。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
GET /auth/verify
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"valid": true,
|
||||
"user": {
|
||||
"userId": "string",
|
||||
"username": "string"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 实例管理
|
||||
|
||||
### 创建实例
|
||||
|
||||
创建新的 Claude Code 实例。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
POST /instances/start
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "string", // 实例名称
|
||||
"config": {
|
||||
"model": "string", // Claude 模型名称
|
||||
"apiKey": "string", // API Key(可选)
|
||||
"workingDir": "string", // 工作目录路径
|
||||
"port": 4000, // 端口(可选,自动分配)
|
||||
"maxMemory": 512, // 最大内存(MB,可选)
|
||||
"env": { // 环境变量(可选)
|
||||
"KEY": "value"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"instance": {
|
||||
"id": "string",
|
||||
"name": "string",
|
||||
"status": "stopped",
|
||||
"config": { ... },
|
||||
"stats": {
|
||||
"memory": 0,
|
||||
"cpu": 0,
|
||||
"restarts": 0,
|
||||
"status": "offline"
|
||||
},
|
||||
"createdAt": "2024-01-01T00:00:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 列出所有实例
|
||||
|
||||
获取所有实例列表。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
GET /instances
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"instances": [
|
||||
{
|
||||
"id": "string",
|
||||
"name": "string",
|
||||
"status": "running",
|
||||
"config": { ... },
|
||||
"stats": { ... },
|
||||
"createdAt": "2024-01-01T00:00:00.000Z",
|
||||
"lastStarted": "2024-01-01T01:00:00.000Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 获取实例详情
|
||||
|
||||
获取指定实例的详细信息。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
GET /instances/:instanceId
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"instance": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
### 启动实例
|
||||
|
||||
启动已停止的实例。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
POST /instances/:instanceId/start
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "实例启动成功"
|
||||
}
|
||||
```
|
||||
|
||||
### 停止实例
|
||||
|
||||
停止正在运行的实例。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
POST /instances/:instanceId/stop
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "实例停止成功"
|
||||
}
|
||||
```
|
||||
|
||||
### 删除实例
|
||||
|
||||
删除指定实例(会先停止实例)。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
DELETE /instances/:instanceId
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "实例删除成功"
|
||||
}
|
||||
```
|
||||
|
||||
### 获取实例状态
|
||||
|
||||
获取实例的实时状态信息。
|
||||
|
||||
**请求**
|
||||
```http
|
||||
GET /instances/:instanceId/status
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
"status": "running",
|
||||
"stats": {
|
||||
"pid": 12345,
|
||||
"port": 4000,
|
||||
"uptime": 3600,
|
||||
"memory": 134217728,
|
||||
"cpu": 5.2,
|
||||
"restarts": 0,
|
||||
"status": "online"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 数据模型
|
||||
|
||||
### Instance
|
||||
|
||||
实例对象结构:
|
||||
|
||||
```typescript
|
||||
interface Instance {
|
||||
id: string; // 实例 ID (UUID)
|
||||
name: string; // 实例名称
|
||||
status: 'running' | 'stopped' | 'errored' | 'offline';
|
||||
config: InstanceConfig; // 实例配置
|
||||
stats: InstanceStats; // 实时统计
|
||||
createdAt: Date; // 创建时间
|
||||
lastStarted?: Date; // 最后启动时间
|
||||
}
|
||||
```
|
||||
|
||||
### InstanceConfig
|
||||
|
||||
实例配置:
|
||||
|
||||
```typescript
|
||||
interface InstanceConfig {
|
||||
model: string; // Claude 模型名称
|
||||
apiKey?: string; // Anthropic API Key(可选)
|
||||
workingDir: string; // 工作目录路径
|
||||
port?: number; // HTTP 服务端口
|
||||
maxMemory?: number; // 最大内存限制(MB)
|
||||
env?: Record<string, string>; // 环境变量
|
||||
}
|
||||
```
|
||||
|
||||
### InstanceStats
|
||||
|
||||
实例统计信息:
|
||||
|
||||
```typescript
|
||||
interface InstanceStats {
|
||||
pid?: number; // 进程 ID
|
||||
port?: number; // HTTP 服务端口
|
||||
uptime?: number; // 运行时长(秒)
|
||||
memory: number; // 内存使用(字节)
|
||||
cpu: number; // CPU 使用率(%)
|
||||
restarts: number; // 重启次数
|
||||
status: 'online' | 'offline'; // 进程状态
|
||||
}
|
||||
```
|
||||
|
||||
## 错误响应
|
||||
|
||||
所有错误响应遵循统一格式:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "错误描述",
|
||||
"message": "详细错误信息(可选)"
|
||||
}
|
||||
```
|
||||
|
||||
### HTTP 状态码
|
||||
|
||||
- `200` - 成功
|
||||
- `201` - 创建成功
|
||||
- `400` - 请求错误
|
||||
- `401` - 未授权
|
||||
- `404` - 资源不存在
|
||||
- `500` - 服务器错误
|
||||
|
||||
## WebSocket 事件
|
||||
|
||||
### 连接
|
||||
|
||||
```javascript
|
||||
import { io } from 'socket.io-client';
|
||||
|
||||
const socket = io('http://localhost:3000', {
|
||||
auth: {
|
||||
token: 'your-jwt-token'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 加入实例房间
|
||||
|
||||
```javascript
|
||||
socket.emit('join-instance', 'instance-id');
|
||||
```
|
||||
|
||||
### 离开实例房间
|
||||
|
||||
```javascript
|
||||
socket.emit('leave-instance', 'instance-id');
|
||||
```
|
||||
|
||||
### 监听事件(待实现)
|
||||
|
||||
```javascript
|
||||
// 实例状态变化
|
||||
socket.on('instance-status-changed', (data) => {
|
||||
console.log('Status:', data.status);
|
||||
});
|
||||
|
||||
// 日志更新
|
||||
socket.on('log-update', (data) => {
|
||||
console.log('Log:', data.log);
|
||||
});
|
||||
|
||||
// 监控数据更新
|
||||
socket.on('monitor-update', (data) => {
|
||||
console.log('Stats:', data.stats);
|
||||
});
|
||||
```
|
||||
|
||||
## 使用示例
|
||||
|
||||
### 创建并启动实例
|
||||
|
||||
```bash
|
||||
# 1. 登录获取 token
|
||||
TOKEN=$(curl -X POST http://localhost:3000/api/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"admin","password":"admin123"}' \
|
||||
| jq -r '.token')
|
||||
|
||||
# 2. 创建实例
|
||||
INSTANCE=$(curl -X POST http://localhost:3000/api/instances/start \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "My Instance",
|
||||
"config": {
|
||||
"model": "claude-sonnet-4-5",
|
||||
"workingDir": "/path/to/project"
|
||||
}
|
||||
}' | jq -r '.instance.id')
|
||||
|
||||
# 3. 启动实例
|
||||
curl -X POST http://localhost:3000/api/instances/$INSTANCE/start \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
|
||||
# 4. 查看状态
|
||||
curl http://localhost:3000/api/instances/$INSTANCE/status \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
### JavaScript 示例
|
||||
|
||||
```javascript
|
||||
import axios from 'axios';
|
||||
|
||||
const API = 'http://localhost:3000/api';
|
||||
let token = '';
|
||||
|
||||
// 登录
|
||||
async function login(username, password) {
|
||||
const response = await axios.post(`${API}/auth/login`, {
|
||||
username,
|
||||
password
|
||||
});
|
||||
token = response.data.token;
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// 创建实例
|
||||
async function createInstance(name, config) {
|
||||
const response = await axios.post(`${API}/instances/start`, {
|
||||
name,
|
||||
config
|
||||
}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
return response.data.instance;
|
||||
}
|
||||
|
||||
// 启动实例
|
||||
async function startInstance(instanceId) {
|
||||
const response = await axios.post(`${API}/instances/${instanceId}/start`, {}, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
await login('admin', 'admin123');
|
||||
const instance = await createInstance('My Instance', {
|
||||
model: 'claude-sonnet-4-5',
|
||||
workingDir: '/path/to/project'
|
||||
});
|
||||
await startInstance(instance.id);
|
||||
```
|
||||
@@ -0,0 +1,513 @@
|
||||
# CC Cloud 开发指南
|
||||
|
||||
本文档提供 CC Cloud 项目的详细开发指南。
|
||||
|
||||
## 目录
|
||||
|
||||
- [快速开始](#快速开始)
|
||||
- [项目结构](#项目结构)
|
||||
- [开发环境设置](#开发环境设置)
|
||||
- [API 文档](#api-文档)
|
||||
- [核心功能说明](#核心功能说明)
|
||||
- [调试技巧](#调试技巧)
|
||||
- [常见问题](#常见问题)
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Node.js >= 18
|
||||
- npm >= 9
|
||||
- PM2 (`npm install -g pm2`)
|
||||
- Claude Code CLI(在服务器上安装)
|
||||
|
||||
### 安装和启动
|
||||
|
||||
```bash
|
||||
# 1. 安装依赖
|
||||
npm run install:all
|
||||
|
||||
# 2. 配置环境变量
|
||||
cp .env.example backend/.env
|
||||
# 编辑 backend/.env 设置必要的配置
|
||||
|
||||
# 3. 启动开发服务器
|
||||
npm run dev
|
||||
```
|
||||
|
||||
这将同时启动:
|
||||
- 后端: http://localhost:3000
|
||||
- 前端: http://localhost:5173
|
||||
|
||||
### 默认登录
|
||||
|
||||
- 用户名: `admin`
|
||||
- 密码: `admin123`
|
||||
|
||||
⚠️ **重要**: 生产环境请务必修改默认密码!
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
cc-cloud/
|
||||
├── backend/ # 后端代码
|
||||
│ ├── src/
|
||||
│ │ ├── config/ # 配置文件
|
||||
│ │ │ └── index.ts # 集中配置管理
|
||||
│ │ ├── controllers/ # 控制器(处理 HTTP 请求)
|
||||
│ │ │ ├── auth.controller.ts
|
||||
│ │ │ └── instance.controller.ts
|
||||
│ │ ├── services/ # 业务逻辑
|
||||
│ │ │ ├── pm2.service.ts # PM2 进程管理
|
||||
│ │ │ └── instance.service.ts # 实例管理
|
||||
│ │ ├── middleware/ # 中间件
|
||||
│ │ │ ├── auth.middleware.ts # JWT 认证
|
||||
│ │ │ ├── error.middleware.ts # 错误处理
|
||||
│ │ │ └── validate.middleware.ts # 请求验证
|
||||
│ │ ├── types/ # TypeScript 类型定义
|
||||
│ │ │ └── index.ts
|
||||
│ │ ├── utils/ # 工具函数
|
||||
│ │ │ ├── logger.ts # 日志工具
|
||||
│ │ │ ├── storage.ts # 文件存储
|
||||
│ │ │ └── port-manager.ts # 端口管理
|
||||
│ │ └── app.ts # 应用入口
|
||||
│ ├── package.json
|
||||
│ └── tsconfig.json
|
||||
│
|
||||
├── frontend/ # 前端代码
|
||||
│ ├── src/
|
||||
│ │ ├── api/ # API 调用
|
||||
│ │ ├── components/ # Vue 组件
|
||||
│ │ ├── views/ # 页面视图
|
||||
│ │ │ ├── Login.vue
|
||||
│ │ │ ├── Layout.vue
|
||||
│ │ │ ├── Dashboard.vue
|
||||
│ │ │ ├── Instances.vue
|
||||
│ │ │ └── InstanceDetail.vue
|
||||
│ │ ├── stores/ # Pinia 状态管理
|
||||
│ │ │ ├── auth.ts
|
||||
│ │ │ └── instance.ts
|
||||
│ │ ├── router/ # Vue Router 路由
|
||||
│ │ ├── types/ # TypeScript 类型
|
||||
│ │ └── utils/ # 工具函数
|
||||
│ │ └── request.ts # Axios 封装
|
||||
│ ├── package.json
|
||||
│ └── vite.config.ts
|
||||
│
|
||||
├── data/ # 数据目录
|
||||
│ ├── instances/ # 实例配置(JSON 文件)
|
||||
│ └── logs/ # 日志文件
|
||||
│
|
||||
└── docs/ # 文档
|
||||
```
|
||||
|
||||
## 开发环境设置
|
||||
|
||||
### 后端开发
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run dev # 启动开发服务器(tsx watch)
|
||||
npm run build # 编译 TypeScript
|
||||
npm run start # 运行编译后的代码
|
||||
npm run lint # 代码检查
|
||||
npm run typecheck # 类型检查
|
||||
```
|
||||
|
||||
### 前端开发
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run dev # 启动开发服务器(Vite)
|
||||
npm run build # 构建生产版本
|
||||
npm run preview # 预览构建结果
|
||||
npm run lint # 代码检查
|
||||
npm run typecheck # 类型检查
|
||||
```
|
||||
|
||||
### 环境变量配置
|
||||
|
||||
编辑 `backend/.env` 文件:
|
||||
|
||||
```env
|
||||
# 服务器配置
|
||||
PORT=3000
|
||||
NODE_ENV=development
|
||||
|
||||
# JWT 密钥(生产环境请使用强密码)
|
||||
JWT_SECRET=your-secret-key
|
||||
|
||||
# 管理员账号
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=admin123
|
||||
|
||||
# 实例端口范围
|
||||
INSTANCE_PORT_RANGE_START=4000
|
||||
INSTANCE_PORT_RANGE_END=4999
|
||||
MAX_INSTANCES=10
|
||||
|
||||
# 日志级别
|
||||
LOG_LEVEL=info
|
||||
```
|
||||
|
||||
## API 文档
|
||||
|
||||
### 认证接口
|
||||
|
||||
#### 登录
|
||||
```http
|
||||
POST /api/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "admin",
|
||||
"password": "admin123"
|
||||
}
|
||||
|
||||
Response:
|
||||
{
|
||||
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||
"user": {
|
||||
"id": "uuid",
|
||||
"username": "admin",
|
||||
"createdAt": "2024-01-01T00:00:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证 Token
|
||||
```http
|
||||
GET /api/auth/verify
|
||||
Authorization: Bearer <token>
|
||||
|
||||
Response:
|
||||
{
|
||||
"valid": true,
|
||||
"user": {
|
||||
"userId": "uuid",
|
||||
"username": "admin"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 实例管理接口
|
||||
|
||||
#### 创建实例
|
||||
```http
|
||||
POST /api/instances/start
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "我的实例",
|
||||
"config": {
|
||||
"model": "claude-sonnet-4-5",
|
||||
"workingDir": "/path/to/project",
|
||||
"apiKey": "sk-ant-...",
|
||||
"maxMemory": 512
|
||||
}
|
||||
}
|
||||
|
||||
Response:
|
||||
{
|
||||
"instance": {
|
||||
"id": "uuid",
|
||||
"name": "我的实例",
|
||||
"status": "stopped",
|
||||
"config": { ... },
|
||||
"stats": { ... },
|
||||
"createdAt": "2024-01-01T00:00:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 列出所有实例
|
||||
```http
|
||||
GET /api/instances
|
||||
Authorization: Bearer <token>
|
||||
|
||||
Response:
|
||||
{
|
||||
"instances": [ ... ]
|
||||
}
|
||||
```
|
||||
|
||||
#### 获取实例详情
|
||||
```http
|
||||
GET /api/instances/:instanceId
|
||||
Authorization: Bearer <token>
|
||||
|
||||
Response:
|
||||
{
|
||||
"instance": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
#### 启动实例
|
||||
```http
|
||||
POST /api/instances/:instanceId/start
|
||||
Authorization: Bearer <token>
|
||||
|
||||
Response:
|
||||
{
|
||||
"success": true,
|
||||
"message": "实例启动成功"
|
||||
}
|
||||
```
|
||||
|
||||
#### 停止实例
|
||||
```http
|
||||
POST /api/instances/:instanceId/stop
|
||||
Authorization: Bearer <token>
|
||||
|
||||
Response:
|
||||
{
|
||||
"success": true,
|
||||
"message": "实例停止成功"
|
||||
}
|
||||
```
|
||||
|
||||
#### 删除实例
|
||||
```http
|
||||
DELETE /api/instances/:instanceId
|
||||
Authorization: Bearer <token>
|
||||
|
||||
Response:
|
||||
{
|
||||
"success": true,
|
||||
"message": "实例删除成功"
|
||||
}
|
||||
```
|
||||
|
||||
#### 获取实例状态
|
||||
```http
|
||||
GET /api/instances/:instanceId/status
|
||||
Authorization: Bearer <token>
|
||||
|
||||
Response:
|
||||
{
|
||||
"status": "running",
|
||||
"stats": {
|
||||
"pid": 12345,
|
||||
"port": 4000,
|
||||
"uptime": 3600,
|
||||
"memory": 134217728,
|
||||
"cpu": 5.2,
|
||||
"restarts": 0,
|
||||
"status": "online"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 核心功能说明
|
||||
|
||||
### 1. 实例管理
|
||||
|
||||
每个 Claude Code 实例通过 PM2 独立管理,具有:
|
||||
|
||||
- **独立端口**: 自动分配 4000-4999 范围内的可用端口
|
||||
- **独立工作目录**: 每个实例在指定的工作目录中运行
|
||||
- **资源限制**: 可设置最大内存限制
|
||||
- **日志文件**: 标准输出和错误输出分别记录到文件
|
||||
|
||||
### 2. 端口管理
|
||||
|
||||
系统自动管理端口分配:
|
||||
|
||||
- 启动时自动分配可用端口
|
||||
- 停止时释放端口
|
||||
- 防止端口冲突
|
||||
|
||||
### 3. 认证机制
|
||||
|
||||
- 使用 JWT 进行身份验证
|
||||
- 所有 API(除登录外)都需要认证
|
||||
- Token 有效期 7 天(可配置)
|
||||
|
||||
### 4. 数据存储
|
||||
|
||||
当前使用文件系统存储:
|
||||
|
||||
- 实例配置: `data/instances/*.json`
|
||||
- 日志文件: `data/logs/*.log`
|
||||
|
||||
未来可扩展为数据库存储。
|
||||
|
||||
## 调试技巧
|
||||
|
||||
### 查看后端日志
|
||||
|
||||
```bash
|
||||
# 开发环境日志直接输出到控制台
|
||||
cd backend
|
||||
npm run dev
|
||||
|
||||
# 生产环境日志
|
||||
tail -f data/logs/application-*.log
|
||||
tail -f data/logs/error-*.log
|
||||
```
|
||||
|
||||
### 查看实例日志
|
||||
|
||||
```bash
|
||||
# 查看特定实例的日志
|
||||
tail -f data/logs/<instance-id>-out.log
|
||||
tail -f data/logs/<instance-id>-error.log
|
||||
|
||||
# 使用 PM2 查看日志
|
||||
pm2 logs <instance-id>
|
||||
```
|
||||
|
||||
### PM2 进程管理
|
||||
|
||||
```bash
|
||||
# 列出所有 PM2 进程
|
||||
pm2 list
|
||||
|
||||
# 查看进程详情
|
||||
pm2 describe <instance-id>
|
||||
|
||||
# 查看进程日志
|
||||
pm2 logs <instance-id>
|
||||
|
||||
# 重启进程
|
||||
pm2 restart <instance-id>
|
||||
|
||||
# 停止进程
|
||||
pm2 stop <instance-id>
|
||||
|
||||
# 删除进程
|
||||
pm2 delete <instance-id>
|
||||
```
|
||||
|
||||
### 前端调试
|
||||
|
||||
- 使用浏览器开发者工具(F12)
|
||||
- Vue DevTools 扩展
|
||||
- Network 面板查看 API 请求
|
||||
- Console 查看错误信息
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 实例启动失败?
|
||||
|
||||
**可能原因**:
|
||||
1. Claude Code CLI 未安装
|
||||
2. 工作目录不存在或无权限
|
||||
3. API Key 无效
|
||||
4. 端口已被占用
|
||||
|
||||
**解决方法**:
|
||||
1. 安装 Claude Code: `npm install -g @anthropic-ai/claude-code`
|
||||
2. 检查工作目录权限
|
||||
3. 验证 API Key 有效性
|
||||
4. 查看日志: `tail -f data/logs/<instance-id>-error.log`
|
||||
|
||||
### Q: 无法连接到后端 API?
|
||||
|
||||
**检查项**:
|
||||
1. 后端是否正在运行: `http://localhost:3000`
|
||||
2. 前端代理配置是否正确(`vite.config.ts`)
|
||||
3. CORS 配置是否正确
|
||||
4. Token 是否有效
|
||||
|
||||
### Q: 前端页面空白?
|
||||
|
||||
**可能原因**:
|
||||
1. 前端开发服务器未启动
|
||||
2. 路由配置错误
|
||||
3. API 请求失败
|
||||
|
||||
**解决方法**:
|
||||
1. 检查 `http://localhost:5173` 是否可访问
|
||||
2. 查看浏览器控制台错误信息
|
||||
3. 检查 Network 面板查看 API 请求状态
|
||||
|
||||
### Q: PM2 连接失败?
|
||||
|
||||
**解决方法**:
|
||||
```bash
|
||||
# 清理 PM2 进程
|
||||
pm2 delete all
|
||||
|
||||
# 重启 PM2 守护进程
|
||||
pm2 kill
|
||||
pm2 resurrect
|
||||
```
|
||||
|
||||
### Q: 如何重置管理员密码?
|
||||
|
||||
编辑 `backend/.env` 文件,修改 `ADMIN_PASSWORD` 变量,然后重启后端服务。
|
||||
|
||||
## 生产部署
|
||||
|
||||
### 构建项目
|
||||
|
||||
```bash
|
||||
# 构建前后端
|
||||
npm run build
|
||||
```
|
||||
|
||||
### 部署后端
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run build
|
||||
pm2 start dist/app.js --name cc-cloud-backend
|
||||
```
|
||||
|
||||
### 部署前端
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run build
|
||||
# 将 dist/ 目录部署到 Nginx 或其他静态服务器
|
||||
```
|
||||
|
||||
### Nginx 配置示例
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name your-domain.com;
|
||||
|
||||
# 前端静态文件
|
||||
location / {
|
||||
root /path/to/frontend/dist;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# 后端 API 代理
|
||||
location /api {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
|
||||
# WebSocket 代理
|
||||
location /socket {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 贡献指南
|
||||
|
||||
欢迎贡献代码!请遵循以下规范:
|
||||
|
||||
1. 遵循现有的代码风格
|
||||
2. 添加必要的类型定义
|
||||
3. 编写清晰的提交信息
|
||||
4. 确保代码通过类型检查和 Lint 检查
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,21 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: {
|
||||
node: true,
|
||||
browser: true,
|
||||
es6: true,
|
||||
},
|
||||
extends: [
|
||||
'plugin:vue/vue3-essential',
|
||||
'eslint:recommended',
|
||||
'@vue/typescript/recommended',
|
||||
],
|
||||
parserOptions: {
|
||||
ecmaVersion: 2022,
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'vue/multi-word-component-names': 'off',
|
||||
'no-console': 'off',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-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?
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>CC Cloud - Claude Code 管理平台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "cc-cloud-frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
|
||||
"typecheck": "vue-tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.4.15",
|
||||
"vue-router": "^4.2.5",
|
||||
"pinia": "^2.1.7",
|
||||
"axios": "^1.6.5",
|
||||
"socket.io-client": "^4.6.1",
|
||||
"element-plus": "^2.5.4",
|
||||
"@element-plus/icons-vue": "^2.3.1",
|
||||
"dayjs": "^1.11.10",
|
||||
"echarts": "^5.4.3",
|
||||
"vue-echarts": "^6.6.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.0.3",
|
||||
"@vue/eslint-config-typescript": "^12.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^6.19.1",
|
||||
"@typescript-eslint/parser": "^6.19.1",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-plugin-vue": "^9.20.1",
|
||||
"typescript": "^5.3.3",
|
||||
"vite": "^5.0.12",
|
||||
"vue-tsc": "^1.8.27",
|
||||
"unplugin-vue-components": "^0.26.0",
|
||||
"unplugin-auto-import": "^0.17.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// App 根组件
|
||||
</script>
|
||||
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
#app {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createApp } from 'vue';
|
||||
import { createPinia } from 'pinia';
|
||||
import ElementPlus from 'element-plus';
|
||||
import 'element-plus/dist/index.css';
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
|
||||
import router from './router';
|
||||
import App from './App.vue';
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
// 注册 Element Plus 图标
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component);
|
||||
}
|
||||
|
||||
app.use(createPinia());
|
||||
app.use(router);
|
||||
app.use(ElementPlus);
|
||||
|
||||
app.mount('#app');
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/login',
|
||||
name: 'Login',
|
||||
component: () => import('@/views/Login.vue'),
|
||||
meta: { requiresAuth: false },
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
component: () => import('@/views/Layout.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
redirect: '/dashboard',
|
||||
children: [
|
||||
{
|
||||
path: 'dashboard',
|
||||
name: 'Dashboard',
|
||||
component: () => import('@/views/Dashboard.vue'),
|
||||
},
|
||||
{
|
||||
path: 'instances',
|
||||
name: 'Instances',
|
||||
component: () => import('@/views/Instances.vue'),
|
||||
},
|
||||
{
|
||||
path: 'instances/:id',
|
||||
name: 'InstanceDetail',
|
||||
component: () => import('@/views/InstanceDetail.vue'),
|
||||
},
|
||||
{
|
||||
path: 'settings',
|
||||
name: 'Settings',
|
||||
component: () => import('@/views/Settings.vue'),
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
});
|
||||
|
||||
// 路由守卫
|
||||
router.beforeEach((to, from, next) => {
|
||||
const token = localStorage.getItem('token');
|
||||
const requiresAuth = to.meta.requiresAuth !== false;
|
||||
|
||||
if (requiresAuth && !token) {
|
||||
next('/login');
|
||||
} else if (to.path === '/login' && token) {
|
||||
next('/');
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import request from '@/utils/request';
|
||||
import type { User, LoginRequest } from '@/types';
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const user = ref<User | null>(null);
|
||||
const token = ref<string | null>(localStorage.getItem('token'));
|
||||
|
||||
const login = async (credentials: LoginRequest) => {
|
||||
const response = await request.post<any>('/auth/login', credentials);
|
||||
token.value = response.token;
|
||||
user.value = response.user;
|
||||
localStorage.setItem('token', response.token);
|
||||
localStorage.setItem('user', JSON.stringify(response.user));
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
token.value = null;
|
||||
user.value = null;
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
};
|
||||
|
||||
// 初始化时从 localStorage 恢复用户信息
|
||||
const initAuth = () => {
|
||||
const userStr = localStorage.getItem('user');
|
||||
if (userStr) {
|
||||
try {
|
||||
user.value = JSON.parse(userStr);
|
||||
} catch (error) {
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
initAuth();
|
||||
|
||||
return {
|
||||
user,
|
||||
token,
|
||||
login,
|
||||
logout,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import request from '@/utils/request';
|
||||
import type { Instance } from '@/types';
|
||||
|
||||
export const useInstanceStore = defineStore('instance', () => {
|
||||
const instances = ref<Instance[]>([]);
|
||||
|
||||
const fetchInstances = async () => {
|
||||
const response = await request.get<{ instances: Instance[] }>('/instances');
|
||||
instances.value = response.instances;
|
||||
};
|
||||
|
||||
const createInstance = async (data: any) => {
|
||||
await request.post('/instances/start', data);
|
||||
};
|
||||
|
||||
const startInstance = async (id: string) => {
|
||||
await request.post(`/instances/${id}/start`);
|
||||
};
|
||||
|
||||
const stopInstance = async (id: string) => {
|
||||
await request.post(`/instances/${id}/stop`);
|
||||
};
|
||||
|
||||
const deleteInstance = async (id: string) => {
|
||||
await request.delete(`/instances/${id}`);
|
||||
};
|
||||
|
||||
return {
|
||||
instances,
|
||||
fetchInstances,
|
||||
createInstance,
|
||||
startInstance,
|
||||
stopInstance,
|
||||
deleteInstance,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
// 通用类型定义
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface InstanceConfig {
|
||||
model: string;
|
||||
apiKey?: string;
|
||||
workingDir: string;
|
||||
port?: number;
|
||||
maxMemory?: number;
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface InstanceStats {
|
||||
pid?: number;
|
||||
port?: number;
|
||||
uptime?: number;
|
||||
memory: number;
|
||||
cpu: number;
|
||||
restarts: number;
|
||||
}
|
||||
|
||||
export interface Instance {
|
||||
id: string;
|
||||
name: string;
|
||||
status: 'running' | 'stopped' | 'errored' | 'offline';
|
||||
config: InstanceConfig;
|
||||
stats: InstanceStats;
|
||||
createdAt: Date;
|
||||
lastStarted?: Date;
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
message?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface ChatRequest {
|
||||
messages: ChatMessage[];
|
||||
stream?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import axios, { AxiosInstance, AxiosRequestConfig, AxiosError } from 'axios';
|
||||
import { ElMessage } from 'element-plus';
|
||||
|
||||
// 创建 axios 实例
|
||||
const request: AxiosInstance = axios.create({
|
||||
baseURL: '/api',
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// 请求拦截器
|
||||
request.interceptors.request.use(
|
||||
(config) => {
|
||||
// 从 localStorage 获取 token
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// 响应拦截器
|
||||
request.interceptors.response.use(
|
||||
(response) => {
|
||||
return response.data;
|
||||
},
|
||||
(error: AxiosError<any>) => {
|
||||
const message = error.response?.data?.message || error.message || '请求失败';
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
// Token 过期,清除本地存储并跳转到登录页
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
window.location.href = '/login';
|
||||
ElMessage.error('登录已过期,请重新登录');
|
||||
} else {
|
||||
ElMessage.error(message);
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default request;
|
||||
@@ -0,0 +1,110 @@
|
||||
<template>
|
||||
<div class="dashboard">
|
||||
<h1>仪表盘</h1>
|
||||
<el-row :gutter="20">
|
||||
<el-col :span="6">
|
||||
<el-card>
|
||||
<div class="stat-card">
|
||||
<el-icon class="stat-icon" color="#409eff"><Server /></el-icon>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">{{ stats.totalInstances }}</div>
|
||||
<div class="stat-label">总实例数</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
<el-col :span="6">
|
||||
<el-card>
|
||||
<div class="stat-card">
|
||||
<el-icon class="stat-icon" color="#67c23a"><CircleCheck /></el-icon>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">{{ stats.runningInstances }}</div>
|
||||
<div class="stat-label">运行中</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
<el-col :span="6">
|
||||
<el-card>
|
||||
<div class="stat-card">
|
||||
<el-icon class="stat-icon" color="#e6a23c"><VideoPause /></el-icon>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">{{ stats.stoppedInstances }}</div>
|
||||
<div class="stat-label">已停止</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
<el-col :span="6">
|
||||
<el-card>
|
||||
<div class="stat-card">
|
||||
<el-icon class="stat-icon" color="#f56c6c"><Warning /></el-icon>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value">{{ stats.erroredInstances }}</div>
|
||||
<div class="stat-label">异常</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useInstanceStore } from '@/stores/instance';
|
||||
|
||||
const instanceStore = useInstanceStore();
|
||||
|
||||
const stats = ref({
|
||||
totalInstances: 0,
|
||||
runningInstances: 0,
|
||||
stoppedInstances: 0,
|
||||
erroredInstances: 0,
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await instanceStore.fetchInstances();
|
||||
const instances = instanceStore.instances;
|
||||
|
||||
stats.value = {
|
||||
totalInstances: instances.length,
|
||||
runningInstances: instances.filter((i) => i.status === 'running').length,
|
||||
stoppedInstances: instances.filter((i) => i.status === 'stopped').length,
|
||||
erroredInstances: instances.filter((i) => i.status === 'errored').length,
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dashboard h1 {
|
||||
margin-bottom: 20px;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
font-size: 48px;
|
||||
}
|
||||
|
||||
.stat-content {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 32px;
|
||||
font-weight: bold;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
margin-top: 8px;
|
||||
font-size: 14px;
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,205 @@
|
||||
<template>
|
||||
<div class="instance-detail">
|
||||
<h1>实例详情</h1>
|
||||
<p>实例 ID: {{ $route.params.id }}</p>
|
||||
<el-tabs>
|
||||
<el-tab-pane label="交互">
|
||||
<div class="interaction-panel">
|
||||
<el-input
|
||||
v-model="userMessage"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
placeholder="输入消息..."
|
||||
@keydown.ctrl.enter="handleSend"
|
||||
/>
|
||||
<el-button type="primary" @click="handleSend" :loading="sending">
|
||||
发送 (Ctrl+Enter)
|
||||
</el-button>
|
||||
<div v-if="messages.length" class="messages">
|
||||
<div v-for="(msg, index) in messages" :key="index" class="message" :class="msg.role">
|
||||
<div class="message-role">{{ msg.role === 'user' ? '用户' : 'Claude' }}</div>
|
||||
<div class="message-content">{{ msg.content }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="日志">
|
||||
<div class="log-viewer">
|
||||
<pre>{{ logs }}</pre>
|
||||
</div>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="监控">
|
||||
<div class="monitor-panel">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="CPU">{{ monitorData.cpu }}%</el-descriptions-item>
|
||||
<el-descriptions-item label="内存">{{ formatMemory(monitorData.memory) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="运行时间">{{ formatUptime(monitorData.uptime) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="重启次数">{{ monitorData.restarts }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</div>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import axios from 'axios';
|
||||
|
||||
const route = useRoute();
|
||||
const instanceId = route.params.id as string;
|
||||
|
||||
const userMessage = ref('');
|
||||
const sending = ref(false);
|
||||
const messages = ref<Array<{ role: string; content: string }>>([]);
|
||||
const logs = ref('暂无日志');
|
||||
const monitorData = ref({
|
||||
cpu: 0,
|
||||
memory: 0,
|
||||
uptime: 0,
|
||||
restarts: 0,
|
||||
});
|
||||
|
||||
let logInterval: NodeJS.Timeout;
|
||||
let monitorInterval: NodeJS.Timeout;
|
||||
|
||||
onMounted(() => {
|
||||
// 启动日志轮询
|
||||
logInterval = setInterval(fetchLogs, 2000);
|
||||
// 启动监控轮询
|
||||
monitorInterval = setInterval(fetchMonitor, 3000);
|
||||
|
||||
fetchLogs();
|
||||
fetchMonitor();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
clearInterval(logInterval);
|
||||
clearInterval(monitorInterval);
|
||||
});
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!userMessage.value.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
sending.value = true;
|
||||
try {
|
||||
// 添加用户消息
|
||||
messages.value.push({
|
||||
role: 'user',
|
||||
content: userMessage.value,
|
||||
});
|
||||
|
||||
// 发送到后端
|
||||
const response = await axios.post(`/api/interactions/${instanceId}/chat`, {
|
||||
messages: messages.value,
|
||||
});
|
||||
|
||||
// 添加 AI 响应
|
||||
messages.value.push({
|
||||
role: 'assistant',
|
||||
content: response.data.content,
|
||||
});
|
||||
|
||||
userMessage.value = '';
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '发送失败');
|
||||
} finally {
|
||||
sending.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const fetchLogs = async () => {
|
||||
try {
|
||||
const response = await axios.get(`/api/logs/${instanceId}`);
|
||||
logs.value = response.data.logs.join('\n');
|
||||
} catch (error) {
|
||||
// 静默失败
|
||||
}
|
||||
};
|
||||
|
||||
const fetchMonitor = async () => {
|
||||
try {
|
||||
const response = await axios.get(`/api/monitor/${instanceId}`);
|
||||
monitorData.value = response.data;
|
||||
} catch (error) {
|
||||
// 静默失败
|
||||
}
|
||||
};
|
||||
|
||||
const formatMemory = (bytes: number) => {
|
||||
return (bytes / 1024 / 1024).toFixed(2) + ' MB';
|
||||
};
|
||||
|
||||
const formatUptime = (seconds: number) => {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
return `${hours}h ${minutes}m`;
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.instance-detail h1 {
|
||||
margin-bottom: 20px;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.interaction-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.messages {
|
||||
border: 1px solid #e6e6e6;
|
||||
border-radius: 4px;
|
||||
padding: 16px;
|
||||
max-height: 500px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 16px;
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.message.user {
|
||||
background-color: #f0f9ff;
|
||||
}
|
||||
|
||||
.message.assistant {
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.message-role {
|
||||
font-weight: bold;
|
||||
margin-bottom: 8px;
|
||||
font-size: 14px;
|
||||
color: #606266;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.log-viewer {
|
||||
background-color: #1e1e1e;
|
||||
color: #d4d4d4;
|
||||
padding: 16px;
|
||||
border-radius: 4px;
|
||||
max-height: 600px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.log-viewer pre {
|
||||
margin: 0;
|
||||
font-family: 'Consolas', 'Monaco', monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,200 @@
|
||||
<template>
|
||||
<div class="instances">
|
||||
<div class="page-header">
|
||||
<h1>实例管理</h1>
|
||||
<el-button type="primary" @click="showCreateDialog = true">
|
||||
<el-icon><Plus /></el-icon>
|
||||
创建实例
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<el-card>
|
||||
<el-table :data="instances" v-loading="loading">
|
||||
<el-table-column prop="name" label="实例名称" />
|
||||
<el-table-column prop="status" label="状态">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="getStatusType(row.status)">
|
||||
{{ getStatusText(row.status) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="config.workingDir" label="工作目录" />
|
||||
<el-table-column prop="stats.port" label="端口" />
|
||||
<el-table-column label="操作" width="300">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-if="row.status === 'stopped'"
|
||||
type="success"
|
||||
size="small"
|
||||
@click="handleStart(row.id)"
|
||||
>
|
||||
启动
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="row.status === 'running'"
|
||||
type="warning"
|
||||
size="small"
|
||||
@click="handleStop(row.id)"
|
||||
>
|
||||
停止
|
||||
</el-button>
|
||||
<el-button type="primary" size="small" @click="handleView(row.id)">
|
||||
查看
|
||||
</el-button>
|
||||
<el-button type="danger" size="small" @click="handleDelete(row.id)">
|
||||
删除
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
<!-- 创建实例对话框 -->
|
||||
<el-dialog v-model="showCreateDialog" title="创建实例" width="600px">
|
||||
<el-form :model="createForm" label-width="120px">
|
||||
<el-form-item label="实例名称">
|
||||
<el-input v-model="createForm.name" placeholder="请输入实例名称" />
|
||||
</el-form-item>
|
||||
<el-form-item label="工作目录">
|
||||
<el-input v-model="createForm.workingDir" placeholder="请输入工作目录路径" />
|
||||
</el-form-item>
|
||||
<el-form-item label="模型">
|
||||
<el-select v-model="createForm.model" placeholder="请选择模型">
|
||||
<el-option label="Claude Sonnet 4.5" value="claude-sonnet-4-5" />
|
||||
<el-option label="Claude Opus 4.5" value="claude-opus-4-5" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="API Key">
|
||||
<el-input v-model="createForm.apiKey" type="password" placeholder="可选,留空使用默认" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="showCreateDialog = false">取消</el-button>
|
||||
<el-button type="primary" @click="handleCreate">创建</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { useInstanceStore } from '@/stores/instance';
|
||||
|
||||
const router = useRouter();
|
||||
const instanceStore = useInstanceStore();
|
||||
|
||||
const loading = ref(false);
|
||||
const showCreateDialog = ref(false);
|
||||
const instances = ref(instanceStore.instances);
|
||||
|
||||
const createForm = ref({
|
||||
name: '',
|
||||
workingDir: '',
|
||||
model: 'claude-sonnet-4-5',
|
||||
apiKey: '',
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
await instanceStore.fetchInstances();
|
||||
instances.value = instanceStore.instances;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
const getStatusType = (status: string) => {
|
||||
const map: Record<string, any> = {
|
||||
running: 'success',
|
||||
stopped: 'info',
|
||||
errored: 'danger',
|
||||
offline: 'warning',
|
||||
};
|
||||
return map[status] || 'info';
|
||||
};
|
||||
|
||||
const getStatusText = (status: string) => {
|
||||
const map: Record<string, string> = {
|
||||
running: '运行中',
|
||||
stopped: '已停止',
|
||||
errored: '异常',
|
||||
offline: '离线',
|
||||
};
|
||||
return map[status] || status;
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
try {
|
||||
await instanceStore.createInstance(createForm.value);
|
||||
ElMessage.success('创建成功');
|
||||
showCreateDialog.value = false;
|
||||
await instanceStore.fetchInstances();
|
||||
instances.value = instanceStore.instances;
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '创建失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleStart = async (id: string) => {
|
||||
try {
|
||||
await instanceStore.startInstance(id);
|
||||
ElMessage.success('启动成功');
|
||||
await instanceStore.fetchInstances();
|
||||
instances.value = instanceStore.instances;
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '启动失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleStop = async (id: string) => {
|
||||
try {
|
||||
await instanceStore.stopInstance(id);
|
||||
ElMessage.success('停止成功');
|
||||
await instanceStore.fetchInstances();
|
||||
instances.value = instanceStore.instances;
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '停止失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
try {
|
||||
await ElMessageBox.confirm('确定要删除这个实例吗?', '提示', {
|
||||
type: 'warning',
|
||||
});
|
||||
await instanceStore.deleteInstance(id);
|
||||
ElMessage.success('删除成功');
|
||||
await instanceStore.fetchInstances();
|
||||
instances.value = instanceStore.instances;
|
||||
} catch (error: any) {
|
||||
if (error !== 'cancel') {
|
||||
ElMessage.error(error.message || '删除失败');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleView = (id: string) => {
|
||||
router.push(`/instances/${id}`);
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.instances {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.page-header h1 {
|
||||
margin: 0;
|
||||
color: #303133;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,126 @@
|
||||
<template>
|
||||
<el-container class="layout-container">
|
||||
<el-aside width="200px">
|
||||
<div class="logo">
|
||||
<h2>CC Cloud</h2>
|
||||
</div>
|
||||
<el-menu
|
||||
:default-active="currentRoute"
|
||||
router
|
||||
background-color="#545c64"
|
||||
text-color="#fff"
|
||||
active-text-color="#ffd04b"
|
||||
>
|
||||
<el-menu-item index="/dashboard">
|
||||
<el-icon><Monitor /></el-icon>
|
||||
<span>仪表盘</span>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/instances">
|
||||
<el-icon><List /></el-icon>
|
||||
<span>实例管理</span>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/settings">
|
||||
<el-icon><Setting /></el-icon>
|
||||
<span>设置</span>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</el-aside>
|
||||
|
||||
<el-container>
|
||||
<el-header>
|
||||
<div class="header-content">
|
||||
<span>{{ currentTitle }}</span>
|
||||
<el-dropdown @command="handleCommand">
|
||||
<span class="user-dropdown">
|
||||
<el-icon><User /></el-icon>
|
||||
{{ username }}
|
||||
</span>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="logout">退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</div>
|
||||
</el-header>
|
||||
|
||||
<el-main>
|
||||
<router-view />
|
||||
</el-main>
|
||||
</el-container>
|
||||
</el-container>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const username = computed(() => authStore.user?.username || '');
|
||||
const currentRoute = computed(() => route.path);
|
||||
const currentTitle = computed(() => route.meta.title || 'CC Cloud');
|
||||
|
||||
const handleCommand = (command: string) => {
|
||||
if (command === 'logout') {
|
||||
authStore.logout();
|
||||
ElMessage.success('已退出登录');
|
||||
router.push('/login');
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.layout-container {
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.el-aside {
|
||||
background-color: #545c64;
|
||||
}
|
||||
|
||||
.logo {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.logo h2 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.el-header {
|
||||
background-color: #fff;
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.user-dropdown {
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.el-main {
|
||||
background-color: #f5f5f5;
|
||||
padding: 20px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,114 @@
|
||||
<template>
|
||||
<div class="login-container">
|
||||
<el-card class="login-card">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<h2>CC Cloud</h2>
|
||||
<p>Claude Code 管理平台</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-form :model="loginForm" :rules="rules" ref="formRef" @submit.prevent="handleLogin">
|
||||
<el-form-item prop="username">
|
||||
<el-input
|
||||
v-model="loginForm.username"
|
||||
placeholder="用户名"
|
||||
prefix-icon="User"
|
||||
size="large"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="password">
|
||||
<el-input
|
||||
v-model="loginForm.password"
|
||||
type="password"
|
||||
placeholder="密码"
|
||||
prefix-icon="Lock"
|
||||
size="large"
|
||||
@keyup.enter="handleLogin"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" size="large" style="width: 100%" :loading="loading" @click="handleLogin">
|
||||
登录
|
||||
</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import type { FormInstance, FormRules } from 'element-plus';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
|
||||
const router = useRouter();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const formRef = ref<FormInstance>();
|
||||
const loading = ref(false);
|
||||
|
||||
const loginForm = reactive({
|
||||
username: '',
|
||||
password: '',
|
||||
});
|
||||
|
||||
const rules: FormRules = {
|
||||
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!formRef.value) return;
|
||||
|
||||
await formRef.value.validate(async (valid) => {
|
||||
if (!valid) return;
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
await authStore.login(loginForm);
|
||||
ElMessage.success('登录成功');
|
||||
router.push('/');
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '登录失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 400px;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.card-header h2 {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.card-header p {
|
||||
margin: 8px 0 0;
|
||||
font-size: 14px;
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,33 @@
|
||||
<template>
|
||||
<div class="settings">
|
||||
<h1>设置</h1>
|
||||
<el-card>
|
||||
<el-form label-width="120px">
|
||||
<el-form-item label="用户名">
|
||||
<el-input :value="username" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="API 端点">
|
||||
<el-input value="/api" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="WebSocket">
|
||||
<el-input value="/socket" disabled />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const username = computed(() => authStore.user?.username || '');
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.settings h1 {
|
||||
margin-bottom: 20px;
|
||||
color: #303133;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "preserve",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import AutoImport from 'unplugin-auto-import/vite';
|
||||
import Components from 'unplugin-vue-components/vite';
|
||||
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
|
||||
import { fileURLToPath, URL } from 'node:url';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
AutoImport({
|
||||
resolvers: [ElementPlusResolver()],
|
||||
imports: ['vue', 'vue-router', 'pinia'],
|
||||
dts: 'src/auto-imports.d.ts',
|
||||
}),
|
||||
Components({
|
||||
resolvers: [ElementPlusResolver()],
|
||||
dts: 'src/components.d.ts',
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/socket': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Generated
+8144
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "cc-cloud",
|
||||
"version": "1.0.0",
|
||||
"description": "Claude Code 管理平台 - Web 界面管理 Claude Code 实例",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"backend",
|
||||
"frontend"
|
||||
],
|
||||
"scripts": {
|
||||
"install:all": "npm install && cd backend && npm install && cd ../frontend && npm install",
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
"dev:frontend": "cd frontend && npm run dev",
|
||||
"dev": "concurrently \"npm run dev:backend\" \"npm run dev:frontend\"",
|
||||
"build:backend": "cd backend && npm run build",
|
||||
"build:frontend": "cd frontend && npm run build",
|
||||
"build": "npm run build:backend && npm run build:frontend",
|
||||
"lint": "npm run lint:backend && npm run lint:frontend",
|
||||
"lint:backend": "cd backend && npm run lint",
|
||||
"lint:frontend": "cd frontend && npm run lint"
|
||||
},
|
||||
"keywords": [
|
||||
"claude-code",
|
||||
"claude",
|
||||
"management",
|
||||
"web"
|
||||
],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"concurrently": "^8.2.2"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user