# 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 ### 默认登录 - 访问密码: `admin123` ⚠️ **重要**: 生产环境请务必修改默认密码! ## 项目架构 ### 整体架构设计 CC Cloud 采用前后端分离架构,遵循 RESTful API 设计原则。 ``` ┌─────────────────────────────────────────────────────────────┐ │ 客户端层 │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Vue 3 SPA │ │ 浏览器应用 │ │ 移动端(未来) │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ └─────────┼──────────────────┼──────────────────┼─────────────┘ │ │ │ └──────────────────┼──────────────────┘ │ HTTP/WebSocket ┌──────────────────┼──────────────────┐ │ │ │ ┌─────────┼──────────────────┼──────────────────┼─────────────┐ │ ↓ ↓ ↓ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ API 网关层 (Express) │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ CORS 中间件 │ │ 认证中间件 │ │ 错误处理 │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ └───────────────────────┬──────────────────────────────┘ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ 业务逻辑层 (Services) │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐│ │ │ │ │实例管理服务 │ │ PM2服务 │ │ 交互服务 ││ │ │ │ │日志服务 │ │ 监控服务 │ │ 认证服务 ││ │ │ │ └──────────────┘ └──────────────┘ └─────────────┘│ │ │ └───────────────────────┬──────────────────────────────┘ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ 数据访问层 (Storage) │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐│ │ │ │ │ 文件存储 │ │ PM2进程 │ │ 内存缓存 ││ │ │ │ └──────────────┘ └──────────────┘ └─────────────┘│ │ │ └──────────────────────────────────────────────────────┘ │ │ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ Claude Code 实例层 │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐│ │ │ │ │ 实例1(4000) │ │ 实例2(4001) │ │ 实例3(...) ││ │ │ │ └──────────────┘ └──────────────┘ └─────────────┘│ │ │ └──────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ### 架构特点 1. **前后端分离** - 前端负责展示和用户交互 - 后端提供 RESTful API - 通过 HTTP/WebSocket 通信 2. **分层设计** - **表现层**: Vue 3 组件 - **业务逻辑层**: Services - **数据访问层**: Storage Utils - **进程管理层**: PM2/child_process 3. **模块化** - 每个功能模块独立 - 低耦合,高内聚 - 易于维护和扩展 4. **可扩展性** - 支持多种进程管理模式(PM2/child_process) - 可替换存储层(文件 → 数据库) - 插件化架构设计 ### 数据流设计 ``` 用户操作 → Vue组件 → API调用(request工具) → Express路由 ↓ 控制器(Controller) → 业务逻辑(Service) → 数据访问(Storage) ↓ 返回响应 ← Service处理 ← 数据操作 ← 进程管理(PM2) ``` ### 状态管理设计 **后端状态管理**: - **实例状态**: 存储在文件系统 (`data/instances/*.json`) - **运行状态**: PM2 进程状态 + 内存缓存 - **日志数据**: 文件存储 + 内存缓存(最近1000行) **前端状态管理**: - **认证状态**: Pinia Store (`auth.ts`) - **实例状态**: Pinia Store (`instance.ts`) - **本地状态**: 组件内部 `ref`/`reactive` ## 技术框架 ### 前端技术栈 | 技术 | 版本 | 用途 | 说明 | |------|------|------|------| | **Vue** | 3.x | 渐进式框架 | 采用 Composition API | | **TypeScript** | 5.x | 类型系统 | 提供类型安全 | | **Vite** | 5.x | 构建工具 | 快速热更新 | | **Element Plus** | Latest | UI 组件库 | 企业级组件 | | **Vue Router** | 4.x | 路由管理 | 单页应用路由 | | **Pinia** | 2.x | 状态管理 | 官方推荐状态管理 | | **Axios** | 1.x | HTTP 客户端 | 封装为 request 工具 | ### 后端技术栈 | 技术 | 版本 | 用途 | 说明 | |------|------|------|------| | **Node.js** | 18+ | 运行时 | LTS 版本 | | **Express** | 4.x | Web 框架 | 轻量级、灵活 | | **TypeScript** | 5.x | 类型系统 | 类型安全 | | **Socket.IO** | 4.x | WebSocket | 实时通信 | | **PM2** | Latest | 进程管理 | 生产环境进程管理 | | **JWT** | - | 认证 | Token 认证 | | **Zod** | 3.x | 数据验证 | 运行时类型验证 | | **Winston** | 3.x | 日志 | 结构化日志 | ### 开发工具 | 工具 | 用途 | |------|------| | **ESLint** | 代码检查 | | **Prettier** | 代码格式化 | | **tsx** | TypeScript 执行 | | **nodemon** | 开发热更新 | | **Playwright** | E2E 测试 | ## 项目结构 ``` 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/ # 文档 ``` ## 组件设计规范 ### 前端组件规范 #### 1. 组件命名 **文件命名**: - 使用 PascalCase - 多个单词组合,描述性强 - 示例: `InstanceList.vue`, `CreateInstanceDialog.vue` **组件名称**: ```vue ``` #### 2. 组件结构 ```vue ``` #### 3. Props 定义规范 ```typescript // ✅ 推荐:使用 TypeScript 接口 interface Props { instanceId: string model?: string maxMemory?: number } const props = withDefaults(defineProps(), { model: 'claude-sonnet-4-5', maxMemory: 512 }) // ❌ 避免:使用简单的数组 defineProps(['instanceId', 'model']) ``` #### 4. 组件通信 **父传子 (Props)**: ```vue ``` **子传父 (Emits)**: ```vue ``` **跨组件通信 (Pinia)**: ```typescript // stores/instance.ts export const useInstanceStore = defineStore('instance', () => { const instances = ref([]) const fetchInstances = async () => { // ... } return { instances, fetchInstances } }) ``` #### 5. 组合式函数 (Composables) ```typescript // composables/useInstance.ts export function useInstance(instanceId: string) { const instance = ref(null) const loading = ref(false) const error = ref(null) const fetch = async () => { loading.value = true try { instance.value = await getInstance(instanceId) } catch (e) { error.value = e as Error } finally { loading.value = false } } return { instance, loading, error, fetch } } ``` ### 后端服务规范 #### 1. 服务层结构 ```typescript // services/example.service.ts import logger from '../utils/logger' // 1. 类型定义 interface ServiceInput { id: string data: Record } interface ServiceOutput { success: boolean data?: unknown } // 2. 私有函数 function privateHelper(input: string): string { return input.toUpperCase() } // 3. 公共函数 export async function publicService(input: ServiceInput): Promise { try { // 业务逻辑 const result = privateHelper(input.id) logger.info('操作成功', { id: input.id }) return { success: true, data: result } } catch (error) { logger.error('操作失败', error) throw error } } ``` #### 2. 控制器规范 ```typescript // controllers/example.controller.ts import { Request, Response } from 'express' import { z } from 'zod' import { publicService } from '../services/example.service' import logger from '../utils/logger' // 1. 验证 Schema const exampleSchema = z.object({ body: z.object({ id: z.string().uuid('无效的ID'), data: z.record(z.unknown()) }) }) // 2. 处理函数 export async function exampleHandler(req: Request, res: Response): Promise { try { const { id, data } = req.body logger.info('处理请求', { id }) const result = await publicService({ id, data }) res.json(result) } catch (error: any) { logger.error('请求处理失败', error) res.status(500).json({ error: error.message || '操作失败' }) } } export { exampleSchema } ``` #### 3. 错误处理 ```typescript // ✅ 推荐:详细错误处理 export async function safeOperation(): Promise { try { // 业务逻辑 } catch (error) { logger.error('操作失败', { context: 'safeOperation', error }) // 返回用户友好的错误信息 if (error instanceof ValidationError) { throw new Error('验证失败:' + error.message) } else if (error instanceof NotFoundError) { throw new Error('资源不存在') } // 未知错误 throw new Error('操作失败,请稍后重试') } } // ❌ 避免:简单抛出 export async function unsafeOperation(): Promise { throw error // 用户看不懂错误信息 } ``` ## 开发流程 ### 开发工作流 ``` 1. 需求分析 ├─ 阅读 PRD/用户需求 ├─ 明确功能边界 └─ 识别依赖关系 2. 技术设计 ├─ 进入 Plan Mode (使用 Claude Code) ├─ 设计数据模型 ├─ 设计 API 接口 ├─ 设计组件结构 └─ 创建设计文档 3. 编码实现 ├─ 创建任务列表 (TodoWrite) ├─ 按设计实现功能 ├─ 遵循代码规范 └─ 更新任务状态 4. 代码审查 ├─ 自我检查 ├─ 类型检查 (npm run typecheck) ├─ 代码检查 (npm run lint) └─ 功能测试 5. 测试验证 ├─ 单元测试 ├─ 集成测试 ├─ E2E 测试 └─ 手动测试 6. 文档更新 ├─ 更新 API 文档 ├─ 更新组件文档 ├─ 更新 CHANGELOG └─ 更新开发指南 7. 提交代码 ├─ Git commit ├─ Pull Request └─ Code Review ``` ### 功能开发步骤 #### 步骤 1: 需求分析 ```markdown ## 功能需求 **功能名称**: [功能名称] **用户故事**: 作为[角色],我想要[功能],以便[价值] **验收标准**: - [ ] 标准1 - [ ] 标准2 - [ ] 标准3 **依赖关系**: - 前置依赖: [其他功能] - 后续影响: [其他模块] ``` #### 步骤 2: 技术设计 使用 Claude Code 的 EnterPlanMode: ``` 请帮我设计 [功能名称] 的实现方案 需求: - ... 请分析: 1. 需要修改/创建哪些文件? 2. 数据结构如何设计? 3. API 接口如何设计? 4. 前端组件如何划分? 5. 有哪些技术难点? ``` #### 步骤 3: 创建任务列表 ```typescript // 使用 TodoWrite 工具 TodoWrite({ todos: [ { content: "创建数据模型", status: "pending", activeForm: "正在创建数据模型" }, { content: "实现后端 API", status: "pending", activeForm: "正在实现后端API" }, { content: "实现前端组件", status: "pending", activeForm: "正在实现前端组件" }, { content: "编写测试", status: "pending", activeForm: "正在编写测试" }, { content: "更新文档", status: "pending", activeForm: "正在更新文档" } ] }) ``` #### 步骤 4: 编码实现 **编码顺序**: 1. **类型定义** (`types/index.ts`) 2. **数据访问层** (`services/`) 3. **API 层** (`controllers/`, `routes/`) 4. **前端状态管理** (`stores/`) 5. **前端组件** (`views/`, `components/`) 6. **样式调整** (`style`) #### 步骤 5: 测试验证 ```bash # 1. 类型检查 npm run typecheck # 2. 代码检查 npm run lint # 3. 单元测试 npm run test # 4. E2E 测试 npm run test:e2e # 5. 手动测试 # - 启动开发服务器 # - 访问功能页面 # - 验证所有交互 ``` #### 步骤 6: 文档更新 ```markdown # 更新清单 - [ ] API.md - 添加新接口文档 - [ ] CHANGELOG.md - 记录变更 - [ ] DEVELOPMENT_GUIDE.md - 更新开发指南(如需要) - [ ] 组件注释 - 添加 JSDoc/Vue Comments ``` #### 步骤 7: 代码提交 ```bash # 提交格式 git commit -m "feat: 添加实例批量操作功能 - 实现批量启动功能 - 实现批量停止功能 - 添加进度提示 Closes #123" # 提交类型 feat: 新功能 fix: 修复 bug refactor: 重构 docs: 文档更新 style: 代码格式调整 test: 测试相关 chore: 构建/工具相关 ``` ## 测试规范 ### 测试金字塔 ``` /\ / \ E2E 测试 (10%) / \ - 关键用户流程 /------\ - 集成测试 / \ - Playwright /----------\ / 集成测试 \ (30%) / (Integration)\ - Service 测试 /________________\ - API 测试 / 单元测试 \ (60%) / (Unit Tests) \ - 函数测试 /__________________\ - 组件测试 ``` ### 单元测试 #### 后端单元测试 ```typescript // services/__tests__/instance.service.test.ts import { describe, it, expect, beforeEach } from '@jest/globals' import { createInstance } from '../instance.service' describe('InstanceService', () => { beforeEach(() => { // 清理测试数据 }) describe('createInstance', () => { it('should create instance with valid data', async () => { const data = { name: '测试实例', config: { model: 'claude-sonnet-4-5', workingDir: '/tmp/test' } } const instance = await createInstance(data) expect(instance).toBeDefined() expect(instance.name).toBe('测试实例') expect(instance.status).toBe('stopped') }) it('should throw error with invalid working directory', async () => { const data = { name: '测试实例', config: { model: 'claude-sonnet-4-5', workingDir: '/invalid/path' } } await expect(createInstance(data)).rejects.toThrow() }) }) }) ``` #### 前端单元测试 ```typescript // components/__tests__/InstanceCard.test.ts import { describe, it, expect } from 'vitest' import { mount } from '@vue/test-utils' import InstanceCard from '../InstanceCard.vue' describe('InstanceCard', () => { it('renders instance name', () => { const wrapper = mount(InstanceCard, { props: { instance: { name: '测试实例', status: 'running' } } }) expect(wrapper.text()).toContain('测试实例') }) it('emits start event when button clicked', async () => { const wrapper = mount(InstanceCard, { props: { instance: { id: '123', name: '测试实例', status: 'stopped' } } }) await wrapper.find('.start-button').trigger('click') expect(wrapper.emitted('start')).toBeTruthy() expect(wrapper.emitted('start')[0]).toEqual(['123']) }) }) ``` ### 集成测试 #### API 测试 ```typescript // api/__tests__/instances.test.ts import request from 'supertest' import app from '../app' describe('POST /api/instances', () => { it('should create instance', async () => { const response = await request(app) .post('/api/instances') .set('Authorization', 'Bearer valid-token') .send({ name: '测试实例', config: { model: 'claude-sonnet-4-5', workingDir: '/tmp/test' } }) expect(response.status).toBe(200) expect(response.body.instance).toBeDefined() expect(response.body.instance.name).toBe('测试实例') }) it('should return 401 without token', async () => { const response = await request(app) .post('/api/instances') .send({}) expect(response.status).toBe(401) }) }) ``` ### E2E 测试 ```typescript // e2e/instance-management.spec.ts import { test, expect } from '@playwright/test' test.describe('实例管理', () => { test.beforeEach(async ({ page }) => { // 登录 await page.goto('http://localhost:5173/login') await page.fill('input[name="password"]', 'admin123') await page.click('button[type="submit"]') await page.waitForURL('**/dashboard') }) test('创建实例', async ({ page }) => { await page.goto('http://localhost:5173/instances') // 点击创建按钮 await page.click('button:has-text("创建实例")') // 填写表单 await page.fill('input[name="name"]', 'E2E测试实例') await page.fill('input[name="workingDir"]', '/tmp/e2e-test') // 提交 await page.click('button:has-text("创建")') // 验证 await expect(page.locator('text=E2E测试实例')).toBeVisible() }) test('启动实例', async ({ page }) => { await page.goto('http://localhost:5173/instances') // 点击启动按钮 await page.click('.instance-list .instance-item:first-child button:has-text("启动")') // 验证状态变化 await expect(page.locator('.instance-list .instance-item:first-child .status')).toHaveText(/运行中/) }) }) ``` ### 测试最佳实践 1. **AAA 模式** (Arrange-Act-Assert) ```typescript it('should do something', () => { // Arrange: 准备测试数据 const input = { value: 1 } // Act: 执行操作 const result = doSomething(input) // Assert: 验证结果 expect(result).toBe(2) }) ``` 2. **测试独立性** - 每个测试独立运行 - 使用 `beforeEach` 清理状态 - 避免测试间依赖 3. **覆盖率要求** - 核心业务逻辑: 80%+ - 工具函数: 90%+ - 组件: 70%+ 4. **命名规范** ```typescript // ✅ 好的命名 it('should return empty array when no instances exist') it('should throw error when working directory is invalid') // ❌ 不好的命名 it('test1') it('works') ``` ## 代码规范 ### 命名规范 #### 1. 文件命名 ``` 前端组件: PascalCase ├── InstanceList.vue └── CreateUserDialog.vue 前端工具: kebab-case ├── request.ts └── format-date.ts 后端服务: kebab-case ├── instance.service.ts └── pm2.service.ts 后端控制器: kebab-case + .controller ├── instance.controller.ts └── auth.controller.ts 类型定义: 清晰描述 ├── types/index.ts └── interfaces/instance.ts ``` #### 2. 变量命名 ```typescript // ✅ 推荐 const instanceList = [] // camelCase const isLoading = false // 布尔值用 is/has/can const MAX_INSTANCES = 10 // 常量用 UPPER_SNAKE_CASE interface InstanceConfig {} // 接口用 PascalCase class InstanceManager {} // 类用 PascalCase // ❌ 避免 const list = [] // 不够具体 const flag = false // flag 含义不明 const max = 10 // max 什么? ``` #### 3. 函数命名 ```typescript // ✅ 推荐:动词开头,描述清晰 async function createInstance(data: CreateInstanceRequest): Promise function getInstanceStatus(instanceId: string): InstanceStatus function validateInput(input: string): boolean async function fetchUserById(userId: string): Promise // ❌ 避免:含义模糊 function process(data: any): any function handle(item: any): void ``` ### 代码风格 #### 1. TypeScript 规范 ```typescript // ✅ 推荐:明确类型 interface Instance { id: string name: string status: 'running' | 'stopped' | 'errored' config: InstanceConfig } function createInstance(data: Instance): Instance { return { ...data } } // ❌ 避免:使用 any function createInstance(data: any): any { return data } ``` #### 2. 异步处理 ```typescript // ✅ 推荐:使用 async/await async function fetchInstances(): Promise { try { const instances = await listInstances() return instances } catch (error) { logger.error('获取实例失败', error) return [] } } // ❌ 避免:回调地狱 function fetchInstances(callback: Function) { listInstances((err: Error, data: any) => { if (err) { callback(err) } else { callback(null, data) } }) } ``` #### 3. 错误处理 ```typescript // ✅ 推荐:具体错误处理 async function startInstance(instanceId: string): Promise { try { await launchProcess(instanceId) } catch (error: any) { if (error.code === 'ENOENT') { throw new Error('CLI未安装') } else if (error.code === 'EACCES') { throw new Error('权限不足') } throw error } } // ❌ 避免:忽略错误 async function startInstance(instanceId: string): Promise { try { await launchProcess(instanceId) } catch (error) { // 什么都不做 } } ``` ### 注释规范 #### 1. 文件注释 ```typescript /** * 实例管理服务 * * 提供实例的创建、启动、停止、删除等功能 * 支持 PM2 和 child_process 两种模式 * * @module instance.service */ ``` #### 2. 函数注释 ```typescript /** * 创建新的 Claude Code 实例 * * @param data - 实例创建请求数据 * @param data.name - 实例名称 * @param data.config - 实例配置 * @returns 创建的实例对象 * @throws {Error} 当工作目录不存在时 * * @example * ```typescript * const instance = await createInstance({ * name: '我的实例', * config: { * model: 'claude-sonnet-4-5', * workingDir: '/path/to/project' * } * }) * ``` */ export async function createInstance(data: CreateInstanceRequest): Promise ``` #### 3. 行内注释 ```typescript // ✅ 推荐:解释"为什么" // 使用 PM2 模式以获得更好的进程管理 if (config.usePM2) { await startProcess(options) } // ❌ 避免:重复代码 // 创建实例 const instance = createInstance(data) ``` ### Git 提交规范 #### Commit Message 格式 ``` ():