feat: 完善项目文档和功能验证
## 新增功能 ### 核心功能完善 - 添加实例交互服务(interaction.service.ts) - 添加日志查询服务(log.service.ts) - 添加监控数据服务(monitor.service.ts) - 完善开发模式进程管理 - 优化实例列表展示 ### API 接口 - POST /api/interactions/:id/chat - 实例交互 - GET /api/logs/:id - 查询实例日志 - GET /api/monitor/:id - 获取监控数据 ## 文档完善 ### 开发文档 - CLAUDE_GUIDE.md - Claude Code 开发指南 - 完整的项目架构说明 - 核心概念和业务流程详解 - API 接口文档 - 功能扩展指南 - PROJECT_SUMMARY.md - 项目总结文档 - 已完成工作列表 - 文档结构说明 - 核心亮点总结 ### 测试文档 - FUNCTIONALITY_TEST_REPORT.md - 功能验证报告 - 测试通过的功能列表 - 发现的问题和改进建议 - 测试覆盖率分析(93%) - PLAYWRIGHT_MCP_TESTING.md - 测试指南 - Playwright MCP 使用教程 - 测试用例详解 - 快速开始指南 - FINAL_SUMMARY.md - 最终总结 - 项目完成状态 - 核心功能验证 - 后续改进建议 ## 功能验证 使用 Playwright MCP 完成端到端测试: - ✅ 应用启动和认证 - ✅ 实例管理(启动/停止/查看) - ✅ 日志和监控数据展示 - ✅ 实例详情页功能 测试通过率:82%(9/11 完全通过) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7dca4e93b1
commit
56db593f96
14 files changed
+2429
-6
No files matched your search
@@ -22,7 +22,11 @@ import {
|
||||
getInstanceStatusHandler,
|
||||
createInstanceSchema,
|
||||
} from './controllers/instance.controller';
|
||||
import { getInstanceLogsHandler } from './controllers/log.controller';
|
||||
import { getMonitorDataHandler } from './controllers/monitor.controller';
|
||||
import { sendMessageHandler, sendMessageSchema } from './controllers/interaction.controller';
|
||||
import { validate } from './middleware/validate.middleware';
|
||||
import { startMonitorUpdater } from './services/monitor.service';
|
||||
|
||||
// 创建 Express 应用
|
||||
const app = express();
|
||||
@@ -63,6 +67,13 @@ app.post('/api/instances/:instanceId/stop', authMiddleware, stopInstanceHandler)
|
||||
app.delete('/api/instances/:instanceId', authMiddleware, deleteInstanceHandler);
|
||||
app.get('/api/instances/:instanceId/status', authMiddleware, getInstanceStatusHandler);
|
||||
|
||||
// 日志和监控路由(需要认证)
|
||||
app.get('/api/logs/:instanceId', authMiddleware, getInstanceLogsHandler);
|
||||
app.get('/api/monitor/:instanceId', authMiddleware, getMonitorDataHandler);
|
||||
|
||||
// 交互路由(需要认证)
|
||||
app.post('/api/interactions/:instanceId/chat', authMiddleware, validate(sendMessageSchema), sendMessageHandler);
|
||||
|
||||
// Socket.IO 认证中间件
|
||||
io.use((socket, next) => {
|
||||
const token = socket.handshake.auth.token;
|
||||
@@ -124,6 +135,10 @@ export async function initialize() {
|
||||
// 初始化实例服务
|
||||
await initInstanceService();
|
||||
logger.info('实例服务初始化完成');
|
||||
|
||||
// 启动监控更新器
|
||||
startMonitorUpdater();
|
||||
logger.info('监控更新器已启动');
|
||||
} catch (error) {
|
||||
logger.error('初始化失败', error);
|
||||
throw error;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { sendMessageToInstance } from '../services/interaction.service';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// 验证 schema
|
||||
const sendMessageSchema = z.object({
|
||||
body: z.object({
|
||||
messages: z.array(
|
||||
z.object({
|
||||
role: z.enum(['user', 'assistant', 'system']),
|
||||
content: z.string(),
|
||||
})
|
||||
).min(1, '至少需要一条消息'),
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* 发送消息给实例
|
||||
*/
|
||||
export async function sendMessageHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
const { messages } = req.body;
|
||||
|
||||
logger.info('发送消息到实例', { instanceId, messageCount: messages.length });
|
||||
|
||||
// 调用服务发送消息
|
||||
const response = await sendMessageToInstance(instanceId, messages);
|
||||
|
||||
res.json(response);
|
||||
} catch (error: any) {
|
||||
logger.error('发送消息失败', error);
|
||||
res.status(500).json({ error: error.message || '发送消息失败' });
|
||||
}
|
||||
}
|
||||
|
||||
export { sendMessageSchema };
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { getInstanceLogs } from '../services/log.service';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
/**
|
||||
* 获取实例日志
|
||||
*/
|
||||
export async function getInstanceLogsHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
const lines = req.query.lines ? parseInt(req.query.lines as string) : 100;
|
||||
|
||||
const logs = getInstanceLogs(instanceId, lines);
|
||||
|
||||
res.json({
|
||||
logs,
|
||||
count: logs.length,
|
||||
});
|
||||
} catch (error: any) {
|
||||
logger.error('获取实例日志失败', error);
|
||||
res.status(500).json({ error: '获取实例日志失败' });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { getMonitorData } from '../services/monitor.service';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
/**
|
||||
* 获取实例监控数据
|
||||
*/
|
||||
export async function getMonitorDataHandler(req: Request, res: Response): Promise<void> {
|
||||
try {
|
||||
const { instanceId } = req.params;
|
||||
|
||||
const monitorData = await getMonitorData(instanceId);
|
||||
|
||||
if (!monitorData) {
|
||||
res.status(404).json({ error: '实例不存在' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({
|
||||
status: monitorData.status,
|
||||
pid: monitorData.pid,
|
||||
port: monitorData.port,
|
||||
uptime: monitorData.uptime,
|
||||
memory: monitorData.memory,
|
||||
cpu: monitorData.cpu,
|
||||
restarts: monitorData.restarts,
|
||||
lastUpdate: monitorData.lastUpdate,
|
||||
});
|
||||
} catch (error: any) {
|
||||
logger.error('获取监控数据失败', error);
|
||||
res.status(500).json({ error: '获取监控数据失败' });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { spawn, ChildProcess } from 'child_process';
|
||||
import type { InstanceConfig } from '../types';
|
||||
import logger from '../utils/logger';
|
||||
import { addLog } from './log.service';
|
||||
|
||||
// 进程存储
|
||||
const processes = new Map<string, ChildProcess>();
|
||||
@@ -21,13 +22,24 @@ export async function startDevProcess(instanceId: string, config: InstanceConfig
|
||||
}
|
||||
|
||||
// 启动 Claude Code HTTP 服务
|
||||
const args = ['@anthropic-ai/claude-code', 'serve', '--port', port!.toString()];
|
||||
// Windows 使用 cmd /c 设置环境变量并启动,确保 stdin 被关闭
|
||||
// 使用 < NUL 重定向 stdin 为空,避免交互模式
|
||||
let commandStr: string;
|
||||
|
||||
const childProcess = spawn('npx', args, {
|
||||
if (process.platform === 'win32') {
|
||||
// Windows: 使用 cmd /c,并通过 < NUL 关闭 stdin
|
||||
commandStr = `cd /d "${workingDir}" && set PORT=${port} && cmd /c "npx @anthropic-ai/claude-code serve < NUL"`;
|
||||
} else {
|
||||
// Unix: 使用 </dev/null 重定向 stdin
|
||||
commandStr = `PORT=${port} npx @anthropic-ai/claude-code serve </dev/null`;
|
||||
}
|
||||
|
||||
const childProcess = spawn(commandStr, [], {
|
||||
cwd: workingDir,
|
||||
env: processEnv,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
detached: false,
|
||||
stdio: ['ignore', 'pipe', 'pipe'], // stdin ignore
|
||||
detached: false, // 不使用 detached,保持父子进程关系
|
||||
shell: true, // 使用 shell 执行命令字符串
|
||||
});
|
||||
|
||||
// 存储进程
|
||||
@@ -38,6 +50,8 @@ export async function startDevProcess(instanceId: string, config: InstanceConfig
|
||||
const message = data.toString().trim();
|
||||
if (message) {
|
||||
logger.info(`[${instanceId}] ${message}`);
|
||||
// 添加到日志服务
|
||||
addLog(instanceId, `[INFO] ${message}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -45,6 +59,8 @@ export async function startDevProcess(instanceId: string, config: InstanceConfig
|
||||
const message = data.toString().trim();
|
||||
if (message) {
|
||||
logger.error(`[${instanceId}] ${message}`);
|
||||
// 添加到日志服务
|
||||
addLog(instanceId, `[ERROR] ${message}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -142,10 +158,44 @@ export async function getDevProcessStatus(instanceId: string) {
|
||||
};
|
||||
}
|
||||
|
||||
// 检查端口是否在监听
|
||||
async function isPortListening(port: number): Promise<boolean> {
|
||||
const net = require('net');
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
|
||||
server.once('error', () => {
|
||||
// 端口被占用,说明有服务在监听
|
||||
resolve(true);
|
||||
});
|
||||
|
||||
server.once('listening', () => {
|
||||
// 端口可用,说明没有服务在监听
|
||||
server.close();
|
||||
resolve(false);
|
||||
});
|
||||
|
||||
server.listen(port, '127.0.0.1');
|
||||
});
|
||||
}
|
||||
|
||||
// 检查进程是否在运行
|
||||
export async function isDevProcessRunning(instanceId: string): Promise<boolean> {
|
||||
// 首先检查 childProcess 是否存在
|
||||
const childProcess = processes.get(instanceId);
|
||||
return childProcess !== undefined && childProcess.pid !== undefined;
|
||||
if (childProcess && childProcess.pid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 如果 childProcess 不存在,尝试通过端口检查
|
||||
// 读取实例配置获取端口
|
||||
const { readInstance } = require('../utils/storage');
|
||||
const instance = await readInstance(instanceId);
|
||||
if (instance && instance.config.port) {
|
||||
return await isPortListening(instance.config.port);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// 列出所有进程
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { readInstance } from '../utils/storage';
|
||||
import { isDevProcessRunning } from './dev-process.service';
|
||||
import logger from '../utils/logger';
|
||||
import fetch from 'node-fetch';
|
||||
|
||||
/**
|
||||
* 发送消息给 Claude Code 实例
|
||||
*/
|
||||
export async function sendMessageToInstance(
|
||||
instanceId: string,
|
||||
messages: Array<{ role: string; content: string }>
|
||||
): Promise<{ content: string }> {
|
||||
// 获取实例信息
|
||||
const instance = await readInstance(instanceId);
|
||||
|
||||
if (!instance) {
|
||||
throw new Error('实例不存在');
|
||||
}
|
||||
|
||||
// 检查实例是否运行
|
||||
const isRunning = await isDevProcessRunning(instanceId);
|
||||
|
||||
if (!isRunning) {
|
||||
throw new Error('实例未运行');
|
||||
}
|
||||
|
||||
// 获取实例端口
|
||||
const port = instance.config.port;
|
||||
|
||||
if (!port) {
|
||||
throw new Error('实例端口未配置');
|
||||
}
|
||||
|
||||
// 构建 Claude Code HTTP 服务 URL
|
||||
const claudeUrl = `http://localhost:${port}/v1/messages`;
|
||||
|
||||
try {
|
||||
// 发送请求到 Claude Code HTTP 服务
|
||||
const response = await fetch(claudeUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: instance.config.model || 'claude-sonnet-4-5',
|
||||
messages: messages,
|
||||
max_tokens: 4096,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
logger.error('Claude Code 请求失败', {
|
||||
instanceId,
|
||||
status: response.status,
|
||||
error: errorText,
|
||||
});
|
||||
throw new Error(`Claude Code 返回错误: ${response.status}`);
|
||||
}
|
||||
|
||||
// 解析响应
|
||||
const data = await response.json();
|
||||
|
||||
// 返回内容
|
||||
return {
|
||||
content: data.content || data.message || '无响应',
|
||||
};
|
||||
} catch (error: any) {
|
||||
logger.error('发送消息到实例失败', { instanceId, error });
|
||||
throw new Error(`发送消息失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { config } from '../config';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// 日志存储目录
|
||||
const LOG_DIR = join(process.cwd(), 'logs', 'instances');
|
||||
|
||||
// 确保日志目录存在
|
||||
if (!existsSync(LOG_DIR)) {
|
||||
mkdirSync(LOG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
// 日志缓存(内存中保留最近的日志)
|
||||
const logCache = new Map<string, string[]>();
|
||||
const MAX_CACHE_LINES = 1000; // 每个实例最多缓存1000行
|
||||
|
||||
/**
|
||||
* 添加日志行
|
||||
*/
|
||||
export function addLog(instanceId: string, logLine: string): void {
|
||||
// 添加到内存缓存
|
||||
if (!logCache.has(instanceId)) {
|
||||
logCache.set(instanceId, []);
|
||||
}
|
||||
|
||||
const logs = logCache.get(instanceId)!;
|
||||
logs.push(logLine);
|
||||
|
||||
// 限制缓存大小
|
||||
if (logs.length > MAX_CACHE_LINES) {
|
||||
logs.shift(); // 移除最早的日志
|
||||
}
|
||||
|
||||
// 同时写入文件
|
||||
const logFile = join(LOG_DIR, `${instanceId}.log`);
|
||||
try {
|
||||
appendFileSync(logFile, logLine + '\n', 'utf-8');
|
||||
} catch (error) {
|
||||
logger.error('写入日志文件失败', { instanceId, error });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实例日志
|
||||
*/
|
||||
export function getInstanceLogs(instanceId: string, lines: number = 100): string[] {
|
||||
// 优先从内存缓存读取
|
||||
const cachedLogs = logCache.get(instanceId);
|
||||
if (cachedLogs && cachedLogs.length > 0) {
|
||||
// 返回最后 N 行
|
||||
return cachedLogs.slice(-lines);
|
||||
}
|
||||
|
||||
// 如果内存中没有,尝试从文件读取
|
||||
const logFile = join(LOG_DIR, `${instanceId}.log`);
|
||||
if (!existsSync(logFile)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(logFile, 'utf-8');
|
||||
const allLines = content.split('\n').filter(line => line.trim());
|
||||
return allLines.slice(-lines);
|
||||
} catch (error) {
|
||||
logger.error('读取日志文件失败', { instanceId, error });
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除实例日志缓存
|
||||
*/
|
||||
export function clearInstanceLogs(instanceId: string): void {
|
||||
logCache.delete(instanceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日志统计信息
|
||||
*/
|
||||
export function getLogStats(instanceId: string): { totalLines: number; cachedLines: number } {
|
||||
const cachedLogs = logCache.get(instanceId);
|
||||
const cachedLines = cachedLogs ? cachedLogs.length : 0;
|
||||
|
||||
const logFile = join(LOG_DIR, `${instanceId}.log`);
|
||||
let totalLines = 0;
|
||||
|
||||
if (existsSync(logFile)) {
|
||||
try {
|
||||
const content = readFileSync(logFile, 'utf-8');
|
||||
totalLines = content.split('\n').filter(line => line.trim()).length;
|
||||
} catch (error) {
|
||||
logger.error('读取日志统计失败', { instanceId, error });
|
||||
}
|
||||
}
|
||||
|
||||
return { totalLines, cachedLines };
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理所有日志缓存(用于内存管理)
|
||||
*/
|
||||
export function cleanupLogCache(): void {
|
||||
const beforeSize = logCache.size;
|
||||
|
||||
// 清理超过1小时未访问的缓存
|
||||
// 简化版:只保留最近访问的
|
||||
// TODO: 可以添加访问时间追踪
|
||||
|
||||
logger.info('清理日志缓存', { beforeSize, afterSize: logCache.size });
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { readInstance } from '../utils/storage';
|
||||
import { getDevProcessStatus } from './dev-process.service';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// 监控数据缓存
|
||||
interface MonitorData {
|
||||
instanceId: string;
|
||||
status: 'running' | 'stopped' | 'errored' | 'offline';
|
||||
pid?: number;
|
||||
port?: number;
|
||||
uptime: number; // 运行时长(秒)
|
||||
memory: number; // 内存使用(字节)
|
||||
cpu: number; // CPU 使用率(百分比)
|
||||
restarts: number; // 重启次数
|
||||
lastUpdate: Date; // 最后更新时间
|
||||
}
|
||||
|
||||
const monitorCache = new Map<string, MonitorData>();
|
||||
const UPDATE_INTERVAL = 5000; // 5秒更新一次
|
||||
|
||||
/**
|
||||
* 更新实例监控数据
|
||||
*/
|
||||
export async function updateMonitorData(instanceId: string): Promise<void> {
|
||||
try {
|
||||
const instance = await readInstance(instanceId);
|
||||
|
||||
if (!instance) {
|
||||
monitorCache.delete(instanceId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取进程状态
|
||||
const procStatus = await getDevProcessStatus(instanceId);
|
||||
|
||||
// 准备监控数据
|
||||
const monitorData: MonitorData = {
|
||||
instanceId,
|
||||
status: procStatus.running ? 'running' : 'stopped',
|
||||
pid: procStatus.pid,
|
||||
port: instance.stats.port,
|
||||
uptime: procStatus.uptime || 0,
|
||||
memory: instance.stats.memory || 0,
|
||||
cpu: instance.stats.cpu || 0,
|
||||
restarts: instance.stats.restarts || 0,
|
||||
lastUpdate: new Date(),
|
||||
};
|
||||
|
||||
monitorCache.set(instanceId, monitorData);
|
||||
} catch (error) {
|
||||
logger.error('更新监控数据失败', { instanceId, error });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实例监控数据
|
||||
*/
|
||||
export async function getMonitorData(instanceId: string): Promise<MonitorData | null> {
|
||||
// 尝试更新数据
|
||||
await updateMonitorData(instanceId);
|
||||
|
||||
return monitorCache.get(instanceId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有实例的监控数据
|
||||
*/
|
||||
export async function getAllMonitorData(): Promise<MonitorData[]> {
|
||||
const data: MonitorData[] = [];
|
||||
|
||||
for (const [instanceId, monitorData] of monitorCache.entries()) {
|
||||
// 更新数据
|
||||
await updateMonitorData(instanceId);
|
||||
|
||||
const updated = monitorCache.get(instanceId);
|
||||
if (updated) {
|
||||
data.push(updated);
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除实例监控数据
|
||||
*/
|
||||
export function clearMonitorData(instanceId: string): void {
|
||||
monitorCache.delete(instanceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定期监控更新
|
||||
*/
|
||||
export function startMonitorUpdater(): void {
|
||||
setInterval(async () => {
|
||||
try {
|
||||
// 更新所有缓存的实例监控数据
|
||||
const instanceIds = Array.from(monitorCache.keys());
|
||||
|
||||
for (const instanceId of instanceIds) {
|
||||
await updateMonitorData(instanceId);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('监控数据更新失败', error);
|
||||
}
|
||||
}, UPDATE_INTERVAL);
|
||||
|
||||
logger.info('监控数据更新器已启动');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取监控统计摘要
|
||||
*/
|
||||
export function getMonitorSummary() {
|
||||
const running = Array.from(monitorCache.values()).filter(
|
||||
data => data.status === 'running'
|
||||
).length;
|
||||
|
||||
const stopped = Array.from(monitorCache.values()).filter(
|
||||
data => data.status === 'stopped'
|
||||
).length;
|
||||
|
||||
const errored = Array.from(monitorCache.values()).filter(
|
||||
data => data.status === 'errored'
|
||||
).length;
|
||||
|
||||
return {
|
||||
total: monitorCache.size,
|
||||
running,
|
||||
stopped,
|
||||
errored,
|
||||
offline: 0,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user