From 455dd1f4cdcd5ca3eda14760eede77c5ad9306f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=92=E5=AF=92?= <2596194220@qq.com> Date: Sun, 25 Jan 2026 03:30:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E2=9C=A8=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E4=B8=80=E4=BA=9B=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 实现任务暂停功能 2. 实现页面的国际化功能 3.优化项目的结构以及BUG 4. 优化系统架构 5. 实现一大堆的功能 --- .trae/documents/plan_20260124_170009.md | 175 +++ .trae/documents/plan_20260124_172544.md | 183 +++ .trae/documents/优化任务列表和添加技术文档.md | 380 +++++ .trae/documents/项目优化计划.md | 98 ++ .trae/skills/debugging/README.md | 50 + .trae/skills/debugging/SKILL.md | 553 +++++++ .../references/debugging-workflows.md | 617 ++++++++ .../incident-postmortem.template.md | 206 +++ .trae/skills/debugging/scripts/parse-logs.py | 124 ++ .trae/skills/frontend-design/README.md | 50 + .trae/skills/frontend-design/SKILL.md | 491 ++++++ .trae/skills/mcp-builder/LICENSE.txt | 202 +++ .trae/skills/mcp-builder/README.md | 50 + .trae/skills/mcp-builder/SKILL.md | 235 +++ .../mcp-builder/reference/evaluation.md | 602 +++++++ .../reference/mcp_best_practices.md | 249 +++ .../mcp-builder/reference/node_mcp_server.md | 970 ++++++++++++ .../reference/python_mcp_server.md | 719 +++++++++ .../skills/mcp-builder/scripts/connections.py | 151 ++ .../skills/mcp-builder/scripts/evaluation.py | 373 +++++ .../scripts/example_evaluation.xml | 22 + .../mcp-builder/scripts/requirements.txt | 2 + .trae/skills/project-planner/README.md | 150 ++ .trae/skills/project-planner/SKILL.md | 856 ++++++++++ .trae/skills/project-planner/SKILLSTORE.md | 50 + .../assets/requirements-template.md | 83 + .trae/skills/project-planner/plugin.json | 13 + .../references/domain-templates.md | 1379 +++++++++++++++++ .../scripts/generate_project_docs.py | 801 ++++++++++ .../scripts/validate_documents.py | 325 ++++ .trae/skills/prompt-optimize/README.md | 50 + .trae/skills/prompt-optimize/SKILL.md | 243 +++ Task.md | 69 +- db.sqlite | Bin 180224 -> 180224 bytes package.json | 1 + pnpm-lock.yaml | 55 + src/main/db/data-source.ts | 20 +- .../db/entities/ReadingReflectionTaskBatch.ts | 12 + .../db/entities/ReadingReflectionTaskItem.ts | 8 +- src/main/index.ts | 9 + .../manager/readingReflectionsTaskManager.ts | 164 +- src/main/manager/taskExecutor.ts | 187 +++ src/main/manager/taskStatusManager.ts | 88 ++ src/main/services/ai/{ => core}/llmService.ts | 9 +- .../ai/nodes/readingReflectionContent.ts | 2 +- .../ai/nodes/readingReflectionSummary.ts | 2 +- src/main/services/configService.ts | 173 +++ src/main/services/notificationService.ts | 56 + src/main/utils/concurrencyManager.ts | 61 + src/main/utils/errorHandler.ts | 76 + src/main/utils/errors/aiError.ts | 46 + src/main/utils/errors/baseError.ts | 25 + src/main/utils/errors/databaseError.ts | 46 + src/renderer/components.d.ts | 1 + src/renderer/src/App.vue | 17 +- src/renderer/src/common/taskStatus.ts | 31 +- src/renderer/src/locales/en.json | 282 ++++ src/renderer/src/locales/es.json | 282 ++++ src/renderer/src/locales/ja.json | 277 ++++ src/renderer/src/locales/ko.json | 282 ++++ src/renderer/src/locales/zh.json | 282 ++++ src/renderer/src/main.ts | 3 +- src/renderer/src/pages/about/index.vue | 34 +- src/renderer/src/pages/faq/data/faqData.ts | 83 +- src/renderer/src/pages/faq/index.vue | 26 +- .../src/pages/menus/data/MenusData.ts | 119 +- src/renderer/src/pages/menus/index.vue | 3 +- .../src/pages/menus/views/Developing.vue | 9 +- .../src/pages/menus/views/search/index.vue | 16 +- .../components/ContributionWall.vue | 3 +- .../pages/menus/views/userPersona/index.vue | 58 +- src/renderer/src/pages/reflection/index.vue | 76 +- .../pages/reflection/views/export/index.vue | 27 +- .../pages/reflection/views/poster/index.vue | 4 +- .../setting/components/LanguageSetting.vue | 80 + .../components/NotificationSetting.vue | 35 +- src/renderer/src/pages/setting/index.vue | 17 +- .../src/pages/task/components/TaskList.vue | 49 +- src/renderer/src/pages/task/create.vue | 52 +- src/renderer/src/pages/task/index.vue | 96 +- src/renderer/src/pages/task/list.vue | 20 +- src/renderer/src/plugins/i18n.ts | 22 + src/rpc/router/config.router.ts | 39 +- src/rpc/router/notice.router.ts | 32 +- src/rpc/router/task.router.ts | 93 ++ src/shared/types/IConfig.ts | 14 + src/shared/types/IReadingReflectionTask.ts | 6 +- tsconfig.node.json | 1 - 88 files changed, 13451 insertions(+), 581 deletions(-) create mode 100644 .trae/documents/plan_20260124_170009.md create mode 100644 .trae/documents/plan_20260124_172544.md create mode 100644 .trae/documents/优化任务列表和添加技术文档.md create mode 100644 .trae/documents/项目优化计划.md create mode 100644 .trae/skills/debugging/README.md create mode 100644 .trae/skills/debugging/SKILL.md create mode 100644 .trae/skills/debugging/references/debugging-workflows.md create mode 100644 .trae/skills/debugging/references/incident-postmortem.template.md create mode 100644 .trae/skills/debugging/scripts/parse-logs.py create mode 100644 .trae/skills/frontend-design/README.md create mode 100644 .trae/skills/frontend-design/SKILL.md create mode 100644 .trae/skills/mcp-builder/LICENSE.txt create mode 100644 .trae/skills/mcp-builder/README.md create mode 100644 .trae/skills/mcp-builder/SKILL.md create mode 100644 .trae/skills/mcp-builder/reference/evaluation.md create mode 100644 .trae/skills/mcp-builder/reference/mcp_best_practices.md create mode 100644 .trae/skills/mcp-builder/reference/node_mcp_server.md create mode 100644 .trae/skills/mcp-builder/reference/python_mcp_server.md create mode 100644 .trae/skills/mcp-builder/scripts/connections.py create mode 100644 .trae/skills/mcp-builder/scripts/evaluation.py create mode 100644 .trae/skills/mcp-builder/scripts/example_evaluation.xml create mode 100644 .trae/skills/mcp-builder/scripts/requirements.txt create mode 100644 .trae/skills/project-planner/README.md create mode 100644 .trae/skills/project-planner/SKILL.md create mode 100644 .trae/skills/project-planner/SKILLSTORE.md create mode 100644 .trae/skills/project-planner/assets/requirements-template.md create mode 100644 .trae/skills/project-planner/plugin.json create mode 100644 .trae/skills/project-planner/references/domain-templates.md create mode 100644 .trae/skills/project-planner/scripts/generate_project_docs.py create mode 100644 .trae/skills/project-planner/scripts/validate_documents.py create mode 100644 .trae/skills/prompt-optimize/README.md create mode 100644 .trae/skills/prompt-optimize/SKILL.md create mode 100644 src/main/manager/taskExecutor.ts create mode 100644 src/main/manager/taskStatusManager.ts rename src/main/services/ai/{ => core}/llmService.ts (67%) create mode 100644 src/main/services/configService.ts create mode 100644 src/main/services/notificationService.ts create mode 100644 src/main/utils/concurrencyManager.ts create mode 100644 src/main/utils/errorHandler.ts create mode 100644 src/main/utils/errors/aiError.ts create mode 100644 src/main/utils/errors/baseError.ts create mode 100644 src/main/utils/errors/databaseError.ts create mode 100644 src/renderer/src/locales/en.json create mode 100644 src/renderer/src/locales/es.json create mode 100644 src/renderer/src/locales/ja.json create mode 100644 src/renderer/src/locales/ko.json create mode 100644 src/renderer/src/locales/zh.json create mode 100644 src/renderer/src/pages/setting/components/LanguageSetting.vue create mode 100644 src/renderer/src/plugins/i18n.ts diff --git a/.trae/documents/plan_20260124_170009.md b/.trae/documents/plan_20260124_170009.md new file mode 100644 index 0000000..ec89b16 --- /dev/null +++ b/.trae/documents/plan_20260124_170009.md @@ -0,0 +1,175 @@ +# i18n集成和语言配置功能实现计划 + +## 1. 依赖安装 + +| 任务ID | 任务名称 | 技术栈 | 详细描述 | +|--------|----------|--------|----------| +| I18N-001 | 安装Vue I18n依赖 | Vue I18n | 使用pnpm安装Vue I18n库 | + +## 2. 配置服务扩展 + +| 任务ID | 任务名称 | 技术栈 | 详细描述 | +|--------|----------|--------|----------| +| I18N-002 | 更新配置类型定义 | TypeScript | 在IConfig.ts中添加语言配置类型 | +| I18N-003 | 扩展配置服务 | TypeScript | 在ConfigService中添加语言配置的读写方法 | + +## 3. i18n配置实现 + +| 任务ID | 任务名称 | 技术栈 | 详细描述 | +|--------|----------|--------|----------| +| I18N-004 | 创建i18n配置文件 | Vue I18n | 创建i18n配置文件和初始化逻辑 | +| I18N-005 | 创建语言包 | JSON | 创建中英文语言包文件 | +| I18N-006 | 集成i18n到Vue应用 | Vue 3 | 在main.ts中注册i18n插件 | + +## 4. 语言设置页面实现 + +| 任务ID | 任务名称 | 技术栈 | 详细描述 | +|--------|----------|--------|----------| +| I18N-007 | 添加语言设置组件 | Vue 3 | 在setting页面添加语言选择组件 | +| I18N-008 | 实现语言切换逻辑 | Vue 3 | 实现语言切换功能和配置保存 | + +## 5. 前端页面i18n集成 + +| 任务ID | 任务名称 | 技术栈 | 详细描述 | +|--------|----------|--------|----------| +| I18N-009 | 翻译任务管理页面 | Vue I18n | 将任务管理页面的文本替换为i18n翻译 | +| I18N-010 | 翻译阅读心得页面 | Vue I18n | 将阅读心得页面的文本替换为i18n翻译 | +| I18N-011 | 翻译设置页面 | Vue I18n | 将设置页面的文本替换为i18n翻译 | +| I18N-012 | 翻译其他页面 | Vue I18n | 将其他页面的文本替换为i18n翻译 | + +## 6. 测试和优化 + +| 任务ID | 任务名称 | 技术栈 | 详细描述 | +|--------|----------|--------|----------| +| I18N-013 | 测试语言切换功能 | Vue I18n | 测试语言切换是否正常工作 | +| I18N-014 | 测试配置持久化 | Electron Store | 测试语言配置是否持久化保存 | +| I18N-015 | 优化i18n性能 | Vue I18n | 优化i18n加载性能和使用体验 | + +## 技术实现细节 + +### 1. 配置服务扩展 + +1. **更新IConfig.ts**: + - 添加语言配置类型定义 + - 添加语言配置Schema验证 + +2. **扩展ConfigService**: + - 添加LANGUAGE_KEY常量 + - 添加getLanguageConfig方法 + - 添加saveLanguageConfig方法 + - 在schema中添加语言配置定义 + +### 2. i18n配置实现 + +1. **创建i18n配置文件**: + ```typescript + // src/renderer/plugins/i18n.ts + import { createI18n } from 'vue-i18n' + import zh from '@renderer/locales/zh.json' + import en from '@renderer/locales/en.json' + + const i18n = createI18n({ + legacy: false, + locale: 'zh', + messages: { + zh, + en + } + }) + + export default i18n + ``` + +2. **创建语言包**: + - src/renderer/locales/zh.json(中文语言包) + - src/renderer/locales/en.json(英文语言包) + +3. **集成到Vue应用**: + ```typescript + // src/renderer/main.ts + import i18n from '@renderer/plugins/i18n' + + app.use(i18n) + ``` + +### 3. 语言设置页面实现 + +1. **添加语言设置组件**: + ```vue + + + ``` + +2. **实现语言切换逻辑**: + ```typescript + // src/renderer/src/pages/setting/components/LanguageSetting.vue + + ``` + +### 4. 前端页面i18n集成 + +1. **在组件中使用i18n**: + ```vue + + + + ``` + +2. **批量替换文本**: + - 逐个页面替换硬编码文本为i18n翻译 + - 确保所有动态文本都能正确翻译 + - 添加必要的语言包条目 + +## 预期效果 + +1. **语言切换功能**:用户可以在设置页面切换中文和英文 +2. **配置持久化**:语言设置会保存到electron-store中,应用重启后保持不变 +3. **全页面翻译**:所有前端页面的文本都会根据当前语言显示对应的翻译 +4. **平滑切换**:语言切换时页面会实时更新,无需刷新 + +## 技术栈 + +- Vue 3 +- Vue I18n +- TypeScript +- Electron Store +- tRPC + +## 实现时间 + +计划在1-2小时内完成所有任务,包括依赖安装、配置扩展、i18n集成和页面翻译。 \ No newline at end of file diff --git a/.trae/documents/plan_20260124_172544.md b/.trae/documents/plan_20260124_172544.md new file mode 100644 index 0000000..8127395 --- /dev/null +++ b/.trae/documents/plan_20260124_172544.md @@ -0,0 +1,183 @@ +# 任务暂停功能实现计划 + +## 1. 实现顺序 + +按照Task.md中的优先级顺序,我将按以下步骤实现任务暂停功能: + +### 1.1 数据库模型扩展 (PAUSE-001) +- 检查ReadingReflectionTaskBatch实体当前定义 +- 添加isPaused和pausedAt字段 +- 运行数据库迁移 + +### 1.2 实现暂停/恢复API (PAUSE-002) +- 在task.router.ts中添加pauseBatch和resumeBatch方法 +- 实现暂停和恢复任务的业务逻辑 + +### 1.3 任务执行器改进 (PAUSE-003) +- 在TaskExecutor中添加任务状态检查 +- 实现任务执行的中断和恢复机制 +- 确保任务执行过程中能响应暂停命令 + +### 1.4 前端暂停按钮功能 (PAUSE-004) +- 为暂停按钮添加点击事件处理 +- 实现暂停/恢复状态的切换逻辑 +- 调用后端API实现暂停和恢复操作 + +### 1.5 暂停状态视觉反馈 (PAUSE-005) +- 添加暂停状态的视觉提示 +- 实现按钮样式和文字的动态变化 +- 显示暂停原因和预计恢复时间 + +### 1.6 任务队列管理 (PAUSE-006) +- 实现任务队列管理系统 +- 支持暂停/恢复整个队列 +- 处理队列中任务的状态管理 + +### 1.7 持久化暂停状态 (PAUSE-007) +- 确保暂停状态能持久化保存 +- 应用重启后恢复暂停状态 +- 处理断电等异常情况 + +## 2. 技术实现细节 + +### 2.1 数据库模型扩展 + +```typescript +// src/main/db/entities/ReadingReflectionTaskBatch.ts +@Entity('reading_reflection_task_batches') +export class ReadingReflectionTaskBatch { + // 现有字段... + + @Column({ type: 'boolean', default: false }) + isPaused!: boolean + + @CreateDateColumn({ type: 'datetime', nullable: true }) + pausedAt!: Date | null +} +``` + +### 2.2 实现暂停/恢复API + +```typescript +// src/rpc/router/task.router.ts +export const taskRouter = router({ + // 现有方法... + + /** + * 暂停任务批次 + */ + pauseBatch: publicProcedure + .input(z.object({ batchId: z.string() })) + .mutation(async ({ input }) => { + // 暂停任务逻辑 + }), + + /** + * 恢复任务批次 + */ + resumeBatch: publicProcedure + .input(z.object({ batchId: z.string() })) + .mutation(async ({ input }) => { + // 恢复任务逻辑 + }) +}) +``` + +### 2.3 任务执行器改进 + +```typescript +// src/main/manager/taskExecutor.ts +export class TaskExecutor { + // 现有方法... + + private async checkPauseStatus(taskId: string): Promise { + // 检查任务是否被暂停 + } + + private async executeSubTask(taskId: string, subTaskId: string, task: any, index: number, total: number): Promise { + // 执行子任务,定期检查暂停状态 + } +} +``` + +### 2.4 前端暂停按钮功能 + +```vue + + +``` + +## 3. 预期效果 + +1. **暂停功能**:用户可以通过暂停按钮暂停正在执行的任务 +2. **恢复功能**:用户可以恢复被暂停的任务 +3. **状态反馈**:界面会显示当前任务的暂停状态 +4. **持久化**:任务暂停状态会被持久化保存 +5. **队列管理**:支持暂停/恢复整个任务队列 + +## 4. 测试计划 + +1. **功能测试**: + - 验证暂停按钮能正常触发暂停操作 + - 验证恢复按钮能正常恢复任务 + - 验证暂停状态能正确显示 + +2. **边界测试**: + - 测试同时暂停多个任务 + - 测试应用重启后暂停状态是否保持 + - 测试暂停状态下的任务进度更新 + +3. **性能测试**: + - 测试大量任务时的暂停/恢复响应时间 + - 验证暂停状态下的系统资源占用 + +## 5. 风险评估 + +1. **任务中断风险**:任务执行过程中中断可能导致数据不一致 +2. **性能影响**:频繁检查暂停状态可能影响性能 +3. **并发冲突**:多个任务同时暂停/恢复可能导致冲突 +4. **持久化失败**:断电等异常情况可能导致暂停状态丢失 + +## 6. 解决方案 + +1. **任务中断处理**:实现事务机制,确保任务中断时数据一致性 +2. **性能优化**:合理设置暂停状态检查频率,避免频繁查询数据库 +3. **并发控制**:使用锁机制确保任务状态更新的原子性 +4. **持久化保障**:使用事务确保暂停状态能可靠保存 + +## 7. 代码规范 + +- 遵循项目现有的代码风格和命名规范 +- 确保类型安全,使用TypeScript严格模式 +- 添加必要的注释和文档 +- 编写单元测试确保功能正确性 + +## 8. 交付标准 + +1. 所有暂停功能按优先级实现完成 +2. 代码通过TypeScript类型检查 +3. 没有语法错误和运行时错误 +4. 功能测试通过 +5. 代码符合项目的质量标准 + +## 9. 后续优化 + +1. 添加任务暂停的原因记录 +2. 实现自动恢复功能 +3. 支持基于时间的暂停计划 +4. 添加暂停状态的日志记录 +5. 优化暂停状态的查询性能 + +现在我将按照这个计划开始实现任务暂停功能,首先检查数据库模型。 \ No newline at end of file diff --git a/.trae/documents/优化任务列表和添加技术文档.md b/.trae/documents/优化任务列表和添加技术文档.md new file mode 100644 index 0000000..01d762e --- /dev/null +++ b/.trae/documents/优化任务列表和添加技术文档.md @@ -0,0 +1,380 @@ +# 优化任务列表和技术实现文档 + +## 1. 任务列表优化 + +### 1.1 国际化支持优化 + +| 任务ID | 任务名称 | 优先级 | 技术栈 | 详细描述 | +|--------|----------|--------|--------|----------| +| I18N-001 | 选择并集成i18n库 | P1 | Vue I18n | 选择合适的i18n库并集成到项目中,配置基本的国际化环境 | +| I18N-002 | 提取前端文本资源 | P1 | Vue I18n | 将所有前端组件中的硬编码文本提取到国际化资源文件中 | +| I18N-003 | 实现语言切换功能 | P2 | Vue I18n | 添加语言切换组件,支持中英文切换 | +| I18N-004 | 优化i18n性能 | P3 | Vue I18n | 实现按需加载语言包,优化国际化性能 | + +### 1.2 暂停功能优化 + +| 任务ID | 任务名称 | 优先级 | 技术栈 | 详细描述 | +|--------|----------|--------|--------|----------| +| PAUSE-001 | 数据库模型扩展 | P0 | TypeORM | 为ReadingReflectionTaskBatch添加isPaused和pausedAt字段 | +| PAUSE-002 | 实现暂停/恢复API | P0 | tRPC | 添加暂停和恢复任务的RPC方法 | +| PAUSE-003 | 任务执行器改进 | P0 | TypeScript | 在TaskExecutor中实现任务状态检查和暂停逻辑 | +| PAUSE-004 | 前端暂停按钮功能 | P0 | Vue 3 | 为暂停按钮添加点击事件和状态切换逻辑 | +| PAUSE-005 | 暂停状态视觉反馈 | P1 | Vue 3 | 添加暂停状态的视觉提示,包括按钮样式变化和状态文字 | +| PAUSE-006 | 任务队列管理 | P1 | TypeScript | 实现任务队列管理,支持暂停/恢复整个队列 | +| PAUSE-007 | 持久化暂停状态 | P2 | TypeORM | 确保任务暂停状态在应用重启后保持 | + +## 2. 技术实现文档 + +### 2.1 国际化支持实现指南 + +#### 2.1.1 集成Vue I18n + +1. **安装依赖** + ```bash + npm install vue-i18n@next + ``` + +2. **创建i18n配置文件** + ```typescript + // src/renderer/plugins/i18n.ts + import { createI18n } from 'vue-i18n' + import zh from '@renderer/locales/zh.json' + import en from '@renderer/locales/en.json' + + const i18n = createI18n({ + legacy: false, + locale: 'zh', + messages: { + zh, + en + } + }) + + export default i18n + ``` + +3. **在main.ts中注册** + ```typescript + // src/renderer/main.ts + import i18n from '@renderer/plugins/i18n' + + app.use(i18n) + ``` + +#### 2.1.2 提取文本资源 + +1. **创建语言包文件** + ```json + // src/renderer/locales/zh.json + { + "task": { + "title": "任务管理", + "status": { + "pending": "任务排队中", + "writing": "运行中", + "completed": "任务完成", + "failed": "任务失败" + } + } + } + ``` + +2. **在组件中使用** + ```vue + + + + ``` + +### 2.2 暂停功能实现指南 + +#### 2.2.1 数据库模型扩展 + +1. **修改实体类** + ```typescript + // src/main/db/entities/ReadingReflectionTaskBatch.ts + import { Column, CreateDateColumn, Entity, OneToMany, PrimaryColumn } from 'typeorm' + + @Entity('reading_reflection_task_batches') + export class ReadingReflectionTaskBatch { + // 现有字段... + + @Column({ type: 'boolean', default: false }) + isPaused!: boolean + + @CreateDateColumn({ type: 'datetime', nullable: true }) + pausedAt!: Date | null + } + ``` + +2. **运行数据库迁移** + ```bash + npm run typeorm migration:generate -- -n AddPauseFields + npm run typeorm migration:run + ``` + +#### 2.2.2 实现暂停/恢复API + +1. **添加RPC方法** + ```typescript + // src/rpc/router/task.router.ts + export const taskRouter = router({ + // 现有方法... + + /** + * 暂停任务批次 + */ + pauseBatch: publicProcedure + .input(z.object({ batchId: z.string() })) + .mutation(async ({ input }) => { + const batchRepo = AppDataSource.getRepository(ReadingReflectionTaskBatch) + await batchRepo.update(input.batchId, { + isPaused: true, + pausedAt: new Date() + }) + return { success: true } + }), + + /** + * 恢复任务批次 + */ + resumeBatch: publicProcedure + .input(z.object({ batchId: z.string() })) + .mutation(async ({ input }) => { + const batchRepo = AppDataSource.getRepository(ReadingReflectionTaskBatch) + await batchRepo.update(input.batchId, { + isPaused: false, + pausedAt: null + }) + return { success: true } + }) + }) + ``` + +#### 2.2.3 任务执行器改进 + +1. **添加暂停检查逻辑** + ```typescript + // src/main/manager/taskExecutor.ts + export class TaskExecutor { + // 现有方法... + + private async checkPauseStatus(taskId: string): Promise { + const batch = await this.batchRepo.findOne({ where: { id: taskId } }) + return batch?.isPaused || false + } + + private async executeSubTask(taskId: string, subTaskId: string, task: any, index: number, total: number): Promise { + // 现有代码... + + for await (const chunk of stream) { + // 检查暂停状态 + if (await this.checkPauseStatus(taskId)) { + await this.itemRepo.update(subTaskId, { + status: 'PAUSED' + }) + await this.taskStatusManager.updateBatchStatus(taskId) + return // 退出执行 + } + + // 现有处理逻辑... + } + } + } + ``` + +#### 2.2.4 前端暂停按钮功能 + +1. **添加按钮点击事件** + ```vue + + + + + ``` + +## 3. 学习资源 + +### 3.1 国际化支持学习 + +1. **Vue I18n官方文档** + - 地址:https://vue-i18n.intlify.dev/ + - 内容:详细的API文档和使用示例 + +2. **国际化最佳实践** + - 地址:https://www.smashingmagazine.com/2018/09/internationalization-vue-apps/) + - 内容:国际化的设计原则和最佳实践 + +### 3.2 暂停功能学习 + +1. **TypeORM官方文档** + - 地址:https://typeorm.io/ + - 内容:数据库模型设计和迁移 + +2. **tRPC官方文档** + - 地址:https://trpc.io/ + - 内容:API设计和实现 + +3. **任务队列管理** + - 地址:https://www.alexdebrie.com/posts/nodejs-task-queues/) + - 内容:任务队列的设计和实现 + +## 4. 测试指南 + +### 4.1 国际化支持测试 + +1. **功能测试** + - 验证所有文本都能正确显示 + - 验证语言切换功能正常 + - 验证动态文本(如任务状态)能正确翻译 + +2. **性能测试** + - 检查语言切换时的页面响应时间 + - 验证语言包加载性能 + +### 4.2 暂停功能测试 + +1. **功能测试** + - 验证暂停按钮能正常触发暂停操作 + - 验证恢复按钮能正常恢复任务 + - 验证暂停状态能正确持久化 + - 验证任务执行过程中能被暂停 + +2. **边界测试** + - 测试同时暂停多个任务 + - 测试应用重启后暂停状态是否保持 + - 测试暂停状态下的任务进度更新 + +3. **性能测试** + - 测试大量任务时的暂停/恢复响应时间 + - 验证暂停状态下的系统资源占用 + +## 5. 部署指南 + +### 5.1 国际化支持部署 + +1. **构建生产版本** + ```bash + npm run build:renderer + ``` + +2. **验证构建产物** + - 检查语言包是否正确包含在构建产物中 + - 验证国际化功能在生产环境中正常工作 + +### 5.2 暂停功能部署 + +1. **数据库迁移** + - 在生产环境运行数据库迁移 + - 验证数据库字段添加成功 + +2. **部署应用** + ```bash + npm run build:main + npm run build:renderer + npm run package + ``` + +3. **验证部署** + - 验证暂停/恢复功能在生产环境中正常工作 + - 监控系统性能和稳定性 + +## 6. 维护指南 + +### 6.1 国际化支持维护 + +1. **添加新语言** + - 复制现有语言包文件 + - 翻译所有文本 + - 在i18n配置中添加新语言 + +2. **更新文本** + - 修改对应语言包中的文本 + - 重新构建应用 + +### 6.2 暂停功能维护 + +1. **监控暂停状态** + - 添加暂停状态的日志记录 + - 监控长时间暂停的任务 + +2. **优化暂停逻辑** + - 根据实际使用情况调整暂停检查频率 + - 优化暂停状态的数据库查询性能 + +3. **添加新功能** + - 支持批量暂停/恢复 + - 添加暂停原因记录 + - 实现自动恢复功能 + +## 7. 总结 + +通过本技术文档,您可以学习到: + +1. **国际化支持的完整实现流程** + - 从库的选择到最终部署 + - 最佳实践和性能优化 + +2. **暂停功能的设计和实现** + - 数据库模型扩展 + - API设计和实现 + - 前端交互逻辑 + - 任务执行器改进 + +3. **完整的技术文档编写规范** + - 任务列表优化 + - 实现指南 + - 学习资源 + - 测试指南 + - 部署和维护指南 + +希望本技术文档能够帮助您学习和掌握相关技术,顺利完成项目优化任务。 \ No newline at end of file diff --git a/.trae/documents/项目优化计划.md b/.trae/documents/项目优化计划.md new file mode 100644 index 0000000..82d1cd9 --- /dev/null +++ b/.trae/documents/项目优化计划.md @@ -0,0 +1,98 @@ +# 项目优化计划 + +根据 `d:\working\tools\read_book\Task.md` 文件中的优化建议,我将按照以下计划逐步优化项目: + +## 1. 代码结构与组织优化 + +### 1.1 目录结构优化(进行中) +- ✅ 创建了 `src/main/services/ai/core` 和 `src/main/services/ai/utils` 目录 +- ✅ 将 `llmService.ts` 移动到了 `core` 目录中 +- ✅ 更新了相关文件的导入路径 + +### 1.2 模块拆分 +- **目标**:将 `readingReflectionsTaskManager.ts` 拆分为多个小类 +- **实施步骤**: + - 创建 `NotificationService` 类,负责处理通知逻辑 + - 创建 `TaskStatusManager` 类,负责管理任务状态 + - 创建 `TaskExecutor` 类,负责执行任务 + - 重构 `TaskManager` 类,使其成为协调器 + +## 2. 错误处理改进 + +### 2.1 实现完善的错误处理机制 +- **目标**:改进当前简单的错误处理方式 +- **实施步骤**: + - 创建自定义错误类,如 `DatabaseError`、`AIError` 等 + - 实现统一的错误处理中间件 + - 添加详细的日志记录 + - 为关键操作添加重试机制 + +## 3. 数据库操作优化 + +### 3.1 使用批量更新和批量查询 +- **目标**:减少数据库交互次数,提高性能 +- **实施步骤**: + - 优化 `updateBatchStatus` 方法,使用聚合查询替代多次查询 + - 实现批量更新任务状态的功能 + - 优化 `startBatchTask` 方法中的数据库操作 + +### 3.2 添加数据库索引 +- **目标**:提高查询性能 +- **实施步骤**: + - 为 `ReadingReflectionTaskItem` 的 `batchId` 字段添加索引 + - 为常用查询字段添加索引 + +## 4. 异步操作优化 + +### 4.1 改进并发控制策略 +- **目标**:提高异步操作的效率和可靠性 +- **实施步骤**: + - 实现动态调整并发数的机制 + - 改进 `startBatchTask` 方法中的并发处理 + - 优化异步流处理逻辑 + +## 5. 安全性增强 + +### 5.1 改进数据加密方式 +- **目标**:提高数据安全性 +- **实施步骤**: + - 改进 `electron-store` 的加密方式 + - 实现更安全的密钥管理策略 + +### 5.2 实现严格的输入验证 +- **目标**:防止恶意输入和安全漏洞 +- **实施步骤**: + - 使用 Zod 库实现严格的输入验证 + - 为所有外部输入添加验证逻辑 + - 实现 API 调用的验证机制 + +## 6. 功能改进 + +### 6.1 实现配置管理系统 +- **目标**:提高配置的灵活性和可维护性 +- **实施步骤**: + - 实现配置管理服务 + - 支持不同环境的配置 + - 提供配置界面 + +## 7. 技术栈升级 + +### 7.1 更新依赖版本 +- **目标**:保持技术的先进性,获取最新的功能和安全修复 +- **实施步骤**: + - 更新 `p-limit` 等依赖到最新版本 + - 测试更新后的依赖兼容性 + +## 实施顺序 + +按照优先级和实施难度,我将按照以下顺序实施优化: + +1. **代码结构优化**:重新组织目录结构和拆分大型模块 +2. **错误处理改进**:实现完善的错误处理机制 +3. **数据库操作优化**:使用批量更新和批量查询,添加数据库索引 +4. **异步操作优化**:改进并发控制策略 +5. **安全性增强**:改进数据加密方式,实现严格的输入验证 +6. **功能改进**:实现配置管理系统 +7. **技术栈升级**:更新依赖版本 + +现在,我将开始实施第一个优化任务:拆分 `readingReflectionsTaskManager.ts` 模块。 \ No newline at end of file diff --git a/.trae/skills/debugging/README.md b/.trae/skills/debugging/README.md new file mode 100644 index 0000000..9c59999 --- /dev/null +++ b/.trae/skills/debugging/README.md @@ -0,0 +1,50 @@ +# debugging + +Comprehensive debugging specialist for errors, test failures, log analysis, and system problems. Use when encountering issues, analyzing error logs, investigating system anomalies, debugging production issues, analyzing stack traces, or identifying root causes. Combines general debugging workflows with error pattern detection and log analysis. + +--- + +## 📦 Downloaded from [Skillstore.io](https://skillstore.io) + +This skill was downloaded from **AI Skillstore** — the official marketplace for Claude Code, Codex, and Claude skills. + +🔗 **Skill Page**: [skillstore.io/skills/x-89jobrien-debugging](https://skillstore.io/skills/x-89jobrien-debugging) + +## 🚀 Installation + +### Via Claude Code Plugin System + +``` +/plugin marketplace add aiskillstore/marketplace +/plugin install x-89jobrien-debugging@aiskillstore +``` + +### Manual Installation + +Copy the contents of this folder to your project's `.claude/skills/` directory. + +## 📋 Skill Info + +| Property | Value | +|----------|-------| +| **Name** | debugging | +| **Version** | 1.0.1 | +| **Author** | Joseph OBrien | + +### Supported Tools + +- claude +- codex +- claude-code + +## 🌐 Discover More Skills + +Browse thousands of AI skills at **[skillstore.io](https://skillstore.io)**: + +- 🔍 Search by category, tool, or keyword +- ⭐ Find verified, security-audited skills +- 📤 Submit your own skills to share with the community + +--- + +*From [skillstore.io](https://skillstore.io) — AI Skills Marketplace* diff --git a/.trae/skills/debugging/SKILL.md b/.trae/skills/debugging/SKILL.md new file mode 100644 index 0000000..d165bfc --- /dev/null +++ b/.trae/skills/debugging/SKILL.md @@ -0,0 +1,553 @@ +--- +name: debugging +description: Comprehensive debugging specialist for errors, test failures, log analysis, +--- + +# Debugging + +This skill provides comprehensive debugging capabilities for identifying and fixing errors, test failures, unexpected behavior, and production issues. It combines general debugging workflows with specialized error analysis, log parsing, and pattern recognition. + +## When to Use This Skill + +- When encountering errors or exceptions in code +- When tests are failing and you need to understand why +- When investigating unexpected behavior or bugs +- When analyzing stack traces and error messages +- When debugging production issues +- When fixing issues reported by users or QA +- When analyzing error logs and stack traces +- When investigating performance issues or anomalies +- When correlating errors across multiple services +- When identifying recurring error patterns +- When setting up error monitoring and alerting +- When conducting post-mortem analysis of incidents + +## What This Skill Does + +1. **Error Analysis**: Captures and analyzes error messages and stack traces +2. **Log Parsing**: Extracts errors from logs using regex patterns and structured parsing +3. **Stack Trace Analysis**: Analyzes stack traces across multiple programming languages +4. **Error Correlation**: Identifies relationships between errors across distributed systems +5. **Pattern Recognition**: Detects common error patterns and anti-patterns +6. **Reproduction**: Identifies steps to reproduce the issue +7. **Isolation**: Locates the exact failure point in code +8. **Root Cause Analysis**: Works backward from symptoms to identify underlying causes +9. **Minimal Fix**: Implements the smallest change that resolves the issue +10. **Verification**: Confirms the solution works and doesn't introduce new issues +11. **Monitoring Setup**: Creates queries and alerts for error detection + +## Helper Scripts + +This skill includes Python helper scripts in `scripts/`: + +- **`parse_logs.py`**: Parses log files and extracts errors, exceptions, and stack traces. Outputs JSON with error analysis and pattern detection. + + ```bash + python scripts/parse_logs.py /var/log/app.log + ``` + +## How to Use + +### Debug an Error + +``` +Debug this error: TypeError: Cannot read property 'x' of undefined +``` + +``` +Investigate why the test is failing in test_user_service.js +``` + +### Analyze Error Logs + +``` +Analyze the error logs in /var/log/app.log and identify the root cause +``` + +``` +Investigate why the API is returning 500 errors +``` + +### Pattern Detection + +``` +Find patterns in these error logs from the past 24 hours +``` + +``` +Correlate errors between the API service and database +``` + +## Debugging Process + +### 1. Capture Error Information + +**Error Message:** + +- Read the full error message +- Note the error type (TypeError, ReferenceError, etc.) +- Identify the error location (file and line number) + +**Stack Trace:** + +- Analyze the call stack +- Identify the sequence of function calls +- Find where the error originated + +**Context:** + +- Check recent code changes +- Review related code files +- Understand the execution flow + +### 2. Error Extraction (Log Analysis) + +**Using Helper Script:** + +The skill includes a Python helper script for parsing logs: + +```bash +# Parse log file and extract errors +python scripts/parse_logs.py /var/log/app.log +``` + +**Manual Log Parsing Patterns:** + +```bash +# Extract errors from logs +grep -i "error\|exception\|fatal\|critical" /var/log/app.log + +# Extract stack traces +grep -A 20 "Exception\|Error\|Traceback" /var/log/app.log + +# Extract specific error types +grep "TypeError\|ReferenceError\|SyntaxError" /var/log/app.log +``` + +**Structured Log Parsing:** + +```javascript +// Parse JSON logs +const errors = logs + .filter(log => log.level === 'error' || log.level === 'critical') + .map(log => ({ + timestamp: log.timestamp, + message: log.message, + stack: log.stack, + context: log.context + })); +``` + +### 3. Stack Trace Analysis + +**Common Patterns:** + +**JavaScript/Node.js:** + +``` +Error: Cannot read property 'x' of undefined + at FunctionName (file.js:123:45) + at AnotherFunction (file.js:456:78) +``` + +**Python:** + +``` +Traceback (most recent call last): + File "app.py", line 123, in function_name + result = process(data) + File "utils.py", line 45, in process + return data['key'] +KeyError: 'key' +``` + +**Java:** + +``` +java.lang.NullPointerException + at com.example.Class.method(Class.java:123) + at com.example.AnotherClass.call(AnotherClass.java:456) +``` + +### 4. Error Correlation + +**Timeline Analysis:** + +- Group errors by timestamp +- Identify error spikes and patterns +- Correlate with deployments or changes +- Check for cascading failures + +**Service Correlation:** + +- Map errors across service boundaries +- Identify upstream/downstream relationships +- Track error propagation paths +- Find common failure points + +### 5. Pattern Recognition + +**Common Error Patterns:** + +**N+1 Query Problem:** + +``` +Multiple database queries in loop +Pattern: SELECT * FROM users; SELECT * FROM posts WHERE user_id = ? +``` + +**Memory Leaks:** + +``` +Gradually increasing memory usage +Pattern: Memory growth over time without release +``` + +**Race Conditions:** + +``` +Intermittent failures under load +Pattern: Errors only occur with concurrent requests +``` + +**Timeout Issues:** + +``` +Requests timing out +Pattern: Errors after specific duration (e.g., 30s) +``` + +### 6. Reproduce the Issue + +**Reproduction Steps:** + +1. Identify the exact conditions that trigger the error +2. Create a minimal test case that reproduces the issue +3. Verify the issue is consistent and reproducible +4. Document the steps clearly + +**Example:** + +```markdown +## Reproduction Steps + +1. Navigate to `/users/123` +2. Click "Edit Profile" +3. Submit form without filling required fields +4. Error occurs: "Cannot read property 'validate' of undefined" +``` + +### 7. Isolate the Failure Location + +**Code Analysis:** + +- Read the code around the error location +- Trace the execution path +- Identify where the assumption breaks +- Check variable states and values + +**Debugging Techniques:** + +- Add strategic logging to track execution +- Use debugger breakpoints +- Inspect variable states +- Check function return values +- Verify data structures + +### 8. Form and Test Hypotheses + +**Hypothesis Formation:** + +- What could cause this error? +- What assumptions might be wrong? +- What edge cases weren't considered? +- What dependencies might be missing? + +**Testing Hypotheses:** + +- Add logging to verify assumptions +- Test edge cases +- Check input validation +- Verify dependencies are available +- Test with different data + +### 9. Root Cause Analysis + +**Investigation Steps:** + +1. **Start with Symptoms**: What error is occurring? +2. **Work Backward**: What changed before the error? +3. **Check Patterns**: Is this recurring or isolated? +4. **Correlate Events**: What else happened at the same time? +5. **Identify Cause**: What is the underlying issue? + +**Analysis Framework:** + +```markdown +## Error Analysis + +**Error**: [Description] +**Frequency**: [How often] +**Timeline**: [When it started] +**Affected Services**: [Which services] +**User Impact**: [How many users affected] + +**Root Cause Hypothesis**: +- [Primary hypothesis with evidence] +- [Alternative hypotheses] + +**Evidence**: +- [Log entries supporting hypothesis] +- [Error patterns observed] +- [Correlation with other events] + +**Recommended Actions**: +- [Immediate fix] +- [Long-term prevention] +``` + +### 10. Implement Minimal Fix + +**Fix Principles:** + +- Fix the root cause, not just symptoms +- Make the smallest change possible +- Preserve existing functionality +- Don't introduce new complexity +- Add appropriate error handling + +**Fix Verification:** + +- Test the fix with the reproduction case +- Verify no regressions +- Check edge cases +- Ensure error handling is appropriate +- Confirm the fix is complete + +### 11. Document the Solution + +**Documentation Should Include:** + +- Root cause explanation +- Evidence supporting the diagnosis +- Specific code fix +- Testing approach +- Prevention recommendations + +## Examples + +### Example 1: Null Reference Error + +**Input**: Error: `TypeError: Cannot read property 'name' of undefined` + +**Output**: + +```markdown +## Debugging Analysis + +### Error Information +- **Type**: TypeError +- **Location**: `src/services/user.js:45` +- **Message**: Cannot read property 'name' of undefined + +### Root Cause +The `getUser()` function returns `undefined` when a user is not found, but the code assumes it always returns a user object. + +### Code Location +```javascript +// src/services/user.js:45 +const user = getUser(userId); +console.log(user.name); // ❌ Error: user is undefined +``` + +### Fix + +```javascript +// Add null check +const user = getUser(userId); +if (!user) { + throw new Error(`User ${userId} not found`); +} +console.log(user.name); // ✅ Safe +``` + +### Prevention + +- Always validate return values from functions that might return null/undefined +- Use optional chaining: `user?.name` +- Add TypeScript types to catch these issues at compile time + +``` + +### Example 2: Database Connection Errors (Log Analysis) + +**Input**: Error logs showing database connection failures + +**Output**: + +```markdown +## Error Analysis: Database Connection Failures + +### Pattern Detected + +**Error**: `ECONNREFUSED` errors from PostgreSQL +**Frequency**: 15 errors/minute, started 2 hours ago +**Timeline**: Errors began after deployment at 14:30 + +### Root Cause Analysis + +**Hypothesis**: Connection pool exhaustion + +**Evidence**: +- Errors correlate with high traffic period (14:30-16:30) +- Connection pool size: 10, concurrent requests: 50+ +- No connection cleanup in error handlers +- Errors spike during peak usage + +**Code Location**: `src/db/connection.js:45` + +**Fix**: +```javascript +// Add connection cleanup +try { + const result = await query(sql); + return result; +} catch (error) { + // Ensure connection is released + await releaseConnection(); + throw error; +} +``` + +**Monitoring Query**: + +```sql +SELECT count(*) FROM pg_stat_activity WHERE state = 'active'; +``` + +``` + +## Reference Files + +For detailed debugging workflows, error patterns, and techniques, load reference files as needed: + +- **`references/debugging_workflows.md`** - Common debugging workflows by issue type, language-specific debugging, debugging techniques, debugging checklists, and common error patterns (database errors, memory leaks, race conditions, timeouts, authentication errors, network errors, application errors, performance errors) +- **`references/INCIDENT_POSTMORTEM.template.md`** - Incident postmortem template with timeline, root cause analysis, and action items + +When debugging specific types of issues or analyzing error patterns, load `references/debugging_workflows.md` and refer to the relevant section. + +## Best Practices + +### Debugging Approach + +1. **Start with Symptoms**: Understand what's wrong before jumping to solutions +2. **Work Backward**: Trace from error to cause +3. **Test Hypotheses**: Don't assume, verify +4. **Minimal Changes**: Fix only what's necessary +5. **Verify Fixes**: Always test that the fix works + +### Log Analysis Techniques + +1. **Use Structured Logging**: JSON logs are easier to parse and analyze +2. **Include Context**: Add request IDs, user IDs, timestamps to all logs +3. **Log Levels**: Use appropriate levels (error, warn, info, debug) +4. **Correlation IDs**: Use request IDs to trace errors across services +5. **Error Grouping**: Group similar errors to identify patterns + +### Error Pattern Recognition + +**Time-Based Patterns:** +- Errors at specific times (deployment windows, peak hours) +- Errors after specific duration (timeouts, memory leaks) +- Errors during specific events (database migrations, cache clears) + +**Frequency Patterns:** +- Sudden spikes (deployment issues, traffic spikes) +- Gradual increases (memory leaks, resource exhaustion) +- Intermittent (race conditions, timing issues) + +**Correlation Patterns:** +- Errors in multiple services simultaneously (infrastructure issues) +- Errors after specific user actions (application bugs) +- Errors correlated with external services (dependency issues) + +### Common Debugging Patterns + +**Null/Undefined Checks:** +```javascript +// Always check for null/undefined +if (!value) { + // Handle missing value +} +``` + +**Error Handling:** + +```javascript +try { + // Risky operation +} catch (error) { + // Log error with context + console.error('Operation failed:', error); + // Handle gracefully +} +``` + +**Logging:** + +```javascript +// Strategic logging +console.log('Before operation:', { userId, data }); +const result = await operation(); +console.log('After operation:', { result }); +``` + +**Type Checking:** + +```javascript +// Verify types +if (typeof value !== 'string') { + throw new TypeError('Expected string'); +} +``` + +### Monitoring Setup + +**Error Rate Monitoring:** + +```javascript +// Track error rate over time +const errorRate = errors.length / totalRequests; +if (errorRate > 0.01) { // 1% error rate threshold + alert('High error rate detected'); +} +``` + +**Error Alerting:** + +- Alert on error rate spikes (> 5% increase) +- Alert on new error types +- Alert on critical error patterns +- Alert on error correlation across services + +### Prevention Strategies + +1. **Input Validation**: Validate all inputs at boundaries +2. **Type Safety**: Use TypeScript or type checking +3. **Error Boundaries**: Catch errors at appropriate levels +4. **Testing**: Write tests for edge cases +5. **Code Review**: Review code for common pitfalls + +## Related Use Cases + +- Fixing production bugs +- Debugging test failures +- Investigating user-reported issues +- Analyzing error logs +- Root cause analysis +- Performance debugging +- Production incident investigation +- System reliability analysis +- Error monitoring setup +- Post-mortem analysis +- Debugging distributed systems \ No newline at end of file diff --git a/.trae/skills/debugging/references/debugging-workflows.md b/.trae/skills/debugging/references/debugging-workflows.md new file mode 100644 index 0000000..567f189 --- /dev/null +++ b/.trae/skills/debugging/references/debugging-workflows.md @@ -0,0 +1,617 @@ +--- +author: Joseph OBrien +status: unpublished +updated: '2025-12-23' +version: 1.0.1 +tag: skill +type: reference +parent: debugging +--- + +# Debugging Workflows + +Reference guide for common debugging workflows and techniques across different scenarios. + +## Debugging Workflows by Issue Type + +### Production Errors + +**Workflow:** + +1. Capture error message and stack trace +2. Check error logs for context +3. Identify when error started (deployment, traffic spike, etc.) +4. Reproduce in staging environment +5. Add logging to trace execution path +6. Identify root cause +7. Implement fix with tests +8. Deploy and monitor + +**Tools:** + +- Error tracking (Sentry, Rollbar) +- Log aggregation (ELK, Datadog) +- APM tools (New Relic, AppDynamics) + +### Test Failures + +**Workflow:** + +1. Read test failure message +2. Understand what the test expects +3. Run test in isolation +4. Check test data and setup +5. Trace through code execution +6. Identify why test fails +7. Fix code or test as appropriate +8. Verify test passes + +**Tools:** + +- Test runner debug mode +- IDE debugger +- Test coverage tools + +### Performance Issues + +**Workflow:** + +1. Measure current performance +2. Identify slow operations +3. Profile to find bottlenecks +4. Analyze profiling data +5. Optimize identified bottlenecks +6. Measure improvement +7. Verify no regressions + +**Tools:** + +- Profilers (Chrome DevTools, py-spy) +- APM tools +- Performance monitoring + +## Language-Specific Debugging + +### JavaScript/Node.js + +**Debugging Tools:** + +- Chrome DevTools +- Node.js debugger +- console.log (strategic logging) +- debugger statement + +**Common Issues:** + +- Undefined variables +- Async/await errors +- Promise rejections +- Scope issues +- Type coercion + +**Techniques:** + +- Use debugger breakpoints +- Log variable states +- Check call stack +- Inspect closures +- Monitor event loop + +### Python + +**Debugging Tools:** + +- pdb (Python debugger) +- ipdb (enhanced debugger) +- print() statements +- logging module + +**Common Issues:** + +- AttributeError +- TypeError +- IndentationError +- Import errors +- NameError + +**Techniques:** + +- Use pdb.set_trace() +- Check variable types +- Verify imports +- Check indentation +- Use type hints + +### Java + +**Debugging Tools:** + +- IntelliJ debugger +- Eclipse debugger +- jdb (command line) +- Logging frameworks + +**Common Issues:** + +- NullPointerException +- ClassCastException +- OutOfMemoryError +- StackOverflowError + +**Techniques:** + +- Set breakpoints +- Inspect variables +- Check exception stack traces +- Monitor memory usage +- Use profilers + +## Debugging Techniques + +### Binary Search + +**When to Use:** + +- Large codebase +- Unclear where issue is +- Many potential causes + +**Process:** + +1. Divide code in half +2. Test which half has issue +3. Repeat on problematic half +4. Narrow down to specific location + +### Rubber Duck Debugging + +**Process:** + +1. Explain code to "rubber duck" (or yourself) +2. Walk through execution step by step +3. Identify assumptions +4. Find where logic breaks + +### Logging Strategy + +**What to Log:** + +- Function entry/exit +- Variable values at key points +- Decision points (if/else branches) +- Error conditions +- Performance metrics + +**Log Levels:** + +- DEBUG: Detailed diagnostic info +- INFO: General informational messages +- WARN: Warning messages +- ERROR: Error conditions +- CRITICAL: Critical failures + +### Reproducing Issues + +**Steps:** + +1. Identify exact conditions that trigger issue +2. Document steps to reproduce +3. Create minimal test case +4. Verify issue reproduces consistently +5. Isolate variables + +**Common Challenges:** + +- Intermittent issues +- Race conditions +- Environment-specific +- Data-dependent + +## Debugging Checklist + +### Before Starting + +- [ ] Understand what should happen +- [ ] Understand what's actually happening +- [ ] Have reproduction steps +- [ ] Have access to logs/debugger + +### During Debugging + +- [ ] Form hypotheses +- [ ] Test hypotheses systematically +- [ ] Document findings +- [ ] Check assumptions +- [ ] Look for patterns + +### After Finding Root Cause + +- [ ] Verify root cause is correct +- [ ] Understand why it happened +- [ ] Implement fix +- [ ] Test fix thoroughly +- [ ] Check for similar issues +- [ ] Document solution + +## Common Error Patterns + +Reference guide for identifying and resolving common error patterns across different systems and languages. + +### Database Errors + +#### Connection Pool Exhaustion + +**Symptoms:** + +- `ECONNREFUSED` errors +- Errors spike during high traffic +- Connection pool size is smaller than concurrent requests + +**Pattern:** + +``` +Error: ECONNREFUSED +Connection pool exhausted +Too many connections +``` + +**Root Causes:** + +- Connection pool size too small +- Connections not being released +- Long-running transactions holding connections +- Missing connection cleanup in error handlers + +**Solutions:** + +- Increase connection pool size +- Ensure connections are released in finally blocks +- Add connection timeout +- Implement connection retry logic + +#### N+1 Query Problem + +**Symptoms:** + +- Slow response times +- Many database queries for single operation +- Queries increase linearly with data size + +**Pattern:** + +``` +SELECT * FROM users; +SELECT * FROM posts WHERE user_id = 1; +SELECT * FROM posts WHERE user_id = 2; +SELECT * FROM posts WHERE user_id = 3; +... +``` + +**Solutions:** + +- Use eager loading (JOINs) +- Batch queries +- Use data loaders +- Implement query result caching + +### Memory Leaks + +#### Event Listener Leaks + +**Symptoms:** + +- Memory usage grows over time +- No decrease after component/page unload +- Correlates with user interactions + +**Pattern:** + +```javascript +// Problem: Listeners registered but never removed +window.addEventListener('resize', handler); +// Missing: window.removeEventListener('resize', handler); +``` + +**Solutions:** + +- Always remove event listeners +- Use cleanup functions in React useEffect +- Use WeakMap for automatic cleanup +- Monitor listener count + +#### Closure Leaks + +**Symptoms:** + +- Memory growth in long-running applications +- Large objects retained in closures +- Circular references + +**Pattern:** + +```javascript +// Problem: Large object retained in closure +function createHandler(largeData) { + return function() { + // largeData retained even if not used + }; +} +``` + +**Solutions:** + +- Avoid retaining large objects in closures +- Use WeakMap/WeakSet when possible +- Clear references when done +- Use memory profilers to identify leaks + +### Race Conditions + +#### Concurrent Modification + +**Symptoms:** + +- Intermittent failures +- Data inconsistency +- Errors only under load + +**Pattern:** + +``` +Thread 1: Read value (100) +Thread 2: Read value (100) +Thread 1: Write value (101) +Thread 2: Write value (101) // Lost update +``` + +**Solutions:** + +- Use locks/mutexes +- Implement optimistic locking +- Use atomic operations +- Add request queuing + +#### Async Race Conditions + +**Symptoms:** + +- Results arrive out of order +- Stale data displayed +- Race between multiple async operations + +**Pattern:** + +```javascript +// Problem: Race between requests +fetch('/api/users/1').then(setUser1); +fetch('/api/users/2').then(setUser2); +// Results may arrive in wrong order +``` + +**Solutions:** + +- Use Promise.all for parallel operations +- Cancel previous requests +- Use request IDs to match responses +- Implement request deduplication + +### Timeout Issues + +#### Request Timeouts + +**Symptoms:** + +- Requests fail after specific duration +- Timeout errors in logs +- Slow external dependencies + +**Pattern:** + +``` +Error: Request timeout after 30000ms +ETIMEDOUT +``` + +**Solutions:** + +- Increase timeout for slow operations +- Implement retry with exponential backoff +- Add timeout configuration +- Optimize slow operations + +#### Database Query Timeouts + +**Symptoms:** + +- Queries fail after timeout period +- Slow query logs show long-running queries +- Timeouts during peak load + +**Solutions:** + +- Optimize slow queries +- Add appropriate indexes +- Increase query timeout +- Implement query cancellation + +### Authentication Errors + +#### Token Expiration + +**Symptoms:** + +- 401 Unauthorized errors +- Errors after specific time period +- Token refresh needed + +**Pattern:** + +``` +401 Unauthorized +Token expired +Invalid token +``` + +**Solutions:** + +- Implement token refresh logic +- Handle token expiration gracefully +- Add token expiration checks +- Use refresh tokens + +#### Session Expiration + +**Symptoms:** + +- Users logged out unexpectedly +- Session errors after inactivity +- Cookie expiration issues + +**Solutions:** + +- Extend session on activity +- Implement session refresh +- Handle expiration gracefully +- Clear expired sessions + +### Network Errors + +#### Connection Refused + +**Symptoms:** + +- Service unavailable errors +- Connection refused errors +- Service not running + +**Pattern:** + +``` +ECONNREFUSED +Connection refused +Service unavailable +``` + +**Solutions:** + +- Check if service is running +- Verify port configuration +- Check firewall rules +- Implement health checks + +#### DNS Resolution Failures + +**Symptoms:** + +- Cannot resolve hostname +- DNS lookup failures +- Network configuration issues + +**Pattern:** + +``` +ENOTFOUND +DNS resolution failed +getaddrinfo failed +``` + +**Solutions:** + +- Verify DNS configuration +- Check hostname spelling +- Use IP addresses as fallback +- Implement DNS caching + +### Application Errors + +#### Null Reference Errors + +**Symptoms:** + +- NullPointerException (Java) +- TypeError: Cannot read property (JavaScript) +- AttributeError (Python) + +**Pattern:** + +``` +TypeError: Cannot read property 'x' of undefined +NullPointerException +AttributeError: 'NoneType' object has no attribute +``` + +**Solutions:** + +- Add null checks +- Use optional chaining +- Provide default values +- Validate inputs + +#### Type Errors + +**Symptoms:** + +- Type mismatch errors +- Invalid type errors +- Casting failures + +**Pattern:** + +``` +TypeError: expected string, got number +InvalidCastException +Type mismatch +``` + +**Solutions:** + +- Add type validation +- Use type guards +- Implement proper type checking +- Handle type conversions + +### Performance Errors + +#### Out of Memory + +**Symptoms:** + +- Application crashes +- Memory limit exceeded +- Heap out of memory + +**Pattern:** + +``` +OutOfMemoryError +Heap out of memory +Memory limit exceeded +``` + +**Solutions:** + +- Increase memory limits +- Optimize memory usage +- Implement pagination +- Use streaming for large data + +#### CPU Exhaustion + +**Symptoms:** + +- Slow response times +- High CPU usage +- Application freezing + +**Pattern:** + +- High CPU utilization (90%+) +- Slow processing +- Event loop blocking + +**Solutions:** + +- Optimize algorithms +- Use worker threads +- Implement caching +- Break up long-running tasks diff --git a/.trae/skills/debugging/references/incident-postmortem.template.md b/.trae/skills/debugging/references/incident-postmortem.template.md new file mode 100644 index 0000000..6e0b968 --- /dev/null +++ b/.trae/skills/debugging/references/incident-postmortem.template.md @@ -0,0 +1,206 @@ +--- +author: Joseph OBrien +status: unpublished +updated: '2025-12-23' +version: 1.0.1 +tag: skill +type: reference +parent: debugging +--- + +# Incident Postmortem: {{INCIDENT_TITLE}} + +**Incident ID:** {{INC-XXXX}} +**Date:** {{YYYY-MM-DD}} +**Duration:** {{START_TIME}} - {{END_TIME}} ({{DURATION}}) +**Severity:** {{SEV1|SEV2|SEV3|SEV4}} +**Status:** {{RESOLVED|MONITORING}} + +--- + +## Summary + +{{ONE_PARAGRAPH_SUMMARY}} + +### Impact + +| Metric | Value | +|--------|-------| +| Users Affected | {{N}} | +| Revenue Impact | ${{N}} | +| Requests Failed | {{N}} | +| Error Rate | {{N}}% | +| Downtime | {{DURATION}} | + +--- + +## Timeline + +| Time (UTC) | Event | +|------------|-------| +| {{HH:MM}} | {{TRIGGER_EVENT}} | +| {{HH:MM}} | Alert fired: {{ALERT_NAME}} | +| {{HH:MM}} | On-call paged | +| {{HH:MM}} | Investigation started | +| {{HH:MM}} | Root cause identified | +| {{HH:MM}} | Mitigation applied | +| {{HH:MM}} | Service recovered | +| {{HH:MM}} | Incident closed | + +--- + +## Root Cause + +{{DETAILED_ROOT_CAUSE_ANALYSIS}} + +### Contributing Factors + +1. {{FACTOR_1}} +2. {{FACTOR_2}} +3. {{FACTOR_3}} + +### What Failed + +- **Detection:** {{HOW_WAS_IT_DETECTED}} +- **Prevention:** {{WHY_WASNT_IT_PREVENTED}} +- **Response:** {{RESPONSE_GAPS}} + +--- + +## Resolution + +### Immediate Actions + +1. {{ACTION_1}} +2. {{ACTION_2}} + +### Mitigation Steps + +```bash +{{COMMANDS_OR_STEPS_TAKEN}} +``` + +### Verification + +- [ ] Service health restored +- [ ] Error rates normalized +- [ ] No recurring alerts + +--- + +## Lessons Learned + +### What Went Well + +- {{POSITIVE_1}} +- {{POSITIVE_2}} + +### What Went Wrong + +- {{NEGATIVE_1}} +- {{NEGATIVE_2}} + +### Where We Got Lucky + +- {{LUCKY_1}} + +--- + +## Action Items + +| ID | Action | Owner | Priority | Due Date | Status | +|----|--------|-------|----------|----------|--------| +| 1 | {{ACTION}} | {{OWNER}} | {{P1-4}} | {{DATE}} | {{STATUS}} | +| 2 | {{ACTION}} | {{OWNER}} | {{P1-4}} | {{DATE}} | {{STATUS}} | +| 3 | {{ACTION}} | {{OWNER}} | {{P1-4}} | {{DATE}} | {{STATUS}} | + +### Prevention + +- [ ] {{PREVENTIVE_MEASURE_1}} +- [ ] {{PREVENTIVE_MEASURE_2}} + +### Detection + +- [ ] {{DETECTION_IMPROVEMENT_1}} +- [ ] {{DETECTION_IMPROVEMENT_2}} + +### Response + +- [ ] {{RESPONSE_IMPROVEMENT_1}} +- [ ] {{RESPONSE_IMPROVEMENT_2}} + +--- + +## Technical Details + +### Affected Systems + +| System | Impact | Recovery | +|--------|--------|----------| +| {{SYSTEM}} | {{DESCRIPTION}} | {{TIME}} | + +### Metrics During Incident + +| Metric | Normal | During Incident | Peak | +|--------|--------|-----------------|------| +| Latency (p99) | {{MS}} | {{MS}} | {{MS}} | +| Error Rate | {{N}}% | {{N}}% | {{N}}% | +| CPU Usage | {{N}}% | {{N}}% | {{N}}% | +| Memory | {{N}}GB | {{N}}GB | {{N}}GB | + +### Logs + +``` +{{RELEVANT_LOG_SNIPPETS}} +``` + +--- + +## Communication + +### Internal + +| Time | Channel | Message | +|------|---------|---------| +| {{TIME}} | {{SLACK/EMAIL}} | {{SUMMARY}} | + +### External + +| Time | Channel | Audience | Message | +|------|---------|----------|---------| +| {{TIME}} | Status Page | Customers | {{MESSAGE}} | + +--- + +## Related Incidents + +| ID | Date | Similarity | +|----|------|------------| +| {{INC-XXXX}} | {{DATE}} | {{DESCRIPTION}} | + +--- + +## Appendix + +### A. Alert Configuration + +```yaml +{{ALERT_CONFIG}} +``` + +### B. Runbook Updates Needed + +- {{RUNBOOK_UPDATE_1}} +- {{RUNBOOK_UPDATE_2}} + +--- + +## Quality Checklist + +- [ ] Timeline is complete and accurate +- [ ] Root cause clearly identified +- [ ] Impact quantified +- [ ] Action items have owners and due dates +- [ ] Lessons learned documented +- [ ] Prevention measures identified +- [ ] Related incidents linked diff --git a/.trae/skills/debugging/scripts/parse-logs.py b/.trae/skills/debugging/scripts/parse-logs.py new file mode 100644 index 0000000..960b9c2 --- /dev/null +++ b/.trae/skills/debugging/scripts/parse-logs.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Error log parser for debugging skill. +Extracts errors, exceptions, and stack traces from log files. +""" + +import json +import re +import sys +from pathlib import Path + + +def extract_errors(log_content: str) -> list[dict]: + """Extract errors and exceptions from log content.""" + errors = [] + + patterns = { + "error": re.compile(r"(?i)(error|ERROR):\s*(.+?)(?:\n|$)"), + "exception": re.compile(r"(?i)(exception|Exception|EXCEPTION):\s*(.+?)(?:\n|$)"), + "fatal": re.compile(r"(?i)(fatal|FATAL):\s*(.+?)(?:\n|$)"), + "critical": re.compile(r"(?i)(critical|CRITICAL):\s*(.+?)(?:\n|$)"), + "traceback": re.compile(r"Traceback \(most recent call last\):(.+?)(?=\n\w|\Z)", re.DOTALL), + } + + lines = log_content.split("\n") + for i, line in enumerate(lines): + for error_type, pattern in patterns.items(): + match = pattern.search(line) + if match: + error = { + "type": error_type, + "message": (match.group(2) if len(match.groups()) > 1 else match.group(0)), + "line_number": i + 1, + "line_content": line, + "timestamp": extract_timestamp(line), + } + + if error_type == "traceback": + error["stack_trace"] = match.group(1).strip() + + errors.append(error) + + return errors + + +def extract_timestamp(line: str) -> str | None: + """Extract timestamp from log line if present.""" + timestamp_patterns = [ + r"(\d{4}-\d{2}-\d{2}[\sT]\d{2}:\d{2}:\d{2})", + r"(\d{2}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2})", + r"\[(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\]", + ] + + for pattern in timestamp_patterns: + match = re.search(pattern, line) + if match: + return match.group(1) + + return None + + +def group_errors_by_type(errors: list[dict]) -> dict[str, list[dict]]: + """Group errors by type.""" + grouped: dict[str, list[dict]] = {} + for error in errors: + error_type = error["type"] + if error_type not in grouped: + grouped[error_type] = [] + grouped[error_type].append(error) + return grouped + + +def analyze_error_patterns(errors: list[dict]) -> dict: + """Analyze error patterns and provide insights.""" + if not errors: + return {} + + type_counts: dict[str, int] = {} + for error in errors: + error_type = error["type"] + type_counts[error_type] = type_counts.get(error_type, 0) + 1 + + message_counts: dict[str, int] = {} + for error in errors: + message = error.get("message", "")[:100] + message_counts[message] = message_counts.get(message, 0) + 1 + + most_common = sorted(message_counts.items(), key=lambda x: x[1], reverse=True)[:5] + + return { + "total_errors": len(errors), + "by_type": type_counts, + "most_common_errors": [{"message": msg, "count": count} for msg, count in most_common], + } + + +def main(): + """Main entry point.""" + if len(sys.argv) < 2: + print("Usage: parse_logs.py ") + sys.exit(1) + + log_file = Path(sys.argv[1]) + if not log_file.exists(): + print(f"Error: File not found: {log_file}") + sys.exit(1) + + log_content = log_file.read_text() + + errors = extract_errors(log_content) + + analysis = analyze_error_patterns(errors) + + output = { + "file": str(log_file), + "errors": errors, + "analysis": analysis, + "grouped_by_type": group_errors_by_type(errors), + } + + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/.trae/skills/frontend-design/README.md b/.trae/skills/frontend-design/README.md new file mode 100644 index 0000000..9009ff8 --- /dev/null +++ b/.trae/skills/frontend-design/README.md @@ -0,0 +1,50 @@ +# frontend-design + +Creates unique, production-grade frontend interfaces with exceptional design quality. Use when user asks to build web components, pages, materials, posters, or applications (e.g., websites, landing pages, dashboards, React components, HTML/CSS layouts, or styling/beautifying any web UI). Generates creative, polished code and UI designs that avoid mediocre AI aesthetics. + +--- + +## 📦 Downloaded from [Skillstore.io](https://skillstore.io) + +This skill was downloaded from **AI Skillstore** — the official marketplace for Claude Code, Codex, and Claude skills. + +🔗 **Skill Page**: [skillstore.io/skills/yyh211-frontend-design](https://skillstore.io/skills/yyh211-frontend-design) + +## 🚀 Installation + +### Via Claude Code Plugin System + +``` +/plugin marketplace add aiskillstore/marketplace +/plugin install yyh211-frontend-design@aiskillstore +``` + +### Manual Installation + +Copy the contents of this folder to your project's `.claude/skills/` directory. + +## 📋 Skill Info + +| Property | Value | +|----------|-------| +| **Name** | frontend-design | +| **Version** | 1.0.0 | +| **Author** | YYH211 | + +### Supported Tools + +- claude +- codex +- claude-code + +## 🌐 Discover More Skills + +Browse thousands of AI skills at **[skillstore.io](https://skillstore.io)**: + +- 🔍 Search by category, tool, or keyword +- ⭐ Find verified, security-audited skills +- 📤 Submit your own skills to share with the community + +--- + +*From [skillstore.io](https://skillstore.io) — AI Skills Marketplace* diff --git a/.trae/skills/frontend-design/SKILL.md b/.trae/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..0ff06dd --- /dev/null +++ b/.trae/skills/frontend-design/SKILL.md @@ -0,0 +1,491 @@ +--- +name: frontend-design +description: Creates unique, production-grade frontend interfaces with exceptional design quality. Use when user asks to build web components, pages, materials, posters, or applications (e.g., websites, landing pages, dashboards, React components, HTML/CSS layouts, or styling/beautifying any web UI). Generates creative, polished code and UI designs that avoid mediocre AI aesthetics. +--- + +# Frontend Design Skill + +此技能指导创建独特的生产级前端界面,避免平庸的"AI 粗糙"美学。实现真正可用的代码,并高度关注美学细节和创意选择。 + +## When to Use This Skill + +使用此技能当用户请求: +- 构建 Web 组件、页面或完整应用程序 +- 创建着陆页、仪表盘或营销页面 +- 设计 React、Vue 或原生 HTML/CSS 界面 +- 美化或重新设计现有的 Web UI +- 创建海报、素材或视觉设计元素(用于 Web) +- 需要高设计品质和独特美学的任何前端项目 + +**关键触发词**: Web 组件、页面、应用、网站、着陆页、仪表盘、React 组件、HTML/CSS、UI 设计、美化、前端 + +## 核心原则 + +在编写代码之前,必须进行深入的设计思考。每个界面都应该是独特的、有意图的、令人难忘的。 + +### 设计思维流程 + +在实现任何代码之前,回答以下问题: + +#### 1. 目的 (Purpose) +- **问题**: 此界面解决什么问题? +- **用户**: 谁使用它?在什么情境下使用? +- **目标**: 用户需要完成什么任务? + +#### 2. 风格方向 (Style Direction) +选择一个**明确且大胆**的美学方向。不要选择"现代简约"这样的通用描述,而是选择极致的风格: + +**风格选项**(但不限于这些): +- **极简主义**: 极度克制,大量留白,精准排版 +- **极致混乱**: 密集布局,重叠元素,视觉冲击 +- **复古未来主义**: 80年代霓虹色,网格,合成波风格 +- **有机/自然**: 流动形状,自然色调,柔和曲线 +- **奢华/精致**: 优雅字体,金色点缀,精细细节 +- **俏皮/玩具感**: 明亮色彩,圆角,趣味动画 +- **编辑/杂志风格**: 大胆排版,网格系统,黑白为主 +- **粗犷/原始**: 单色,硬边,实用主义 +- **装饰艺术/几何**: 对称图案,几何形状,高对比度 +- **柔和/粉彩**: 温和色彩,渐变,梦幻感 +- **工业/实用**: 系统字体,单色,功能优先 +- **新拟态**: 柔和阴影,浮雕效果,微妙深度 +- **玻璃态**: 模糊背景,透明度,光感 + +**关键**: 选择清晰的概念方向并精准执行。大胆的极致主义和精致的极简主义都有效——关键在于**意图**,而不是强度。 + +#### 3. 技术限制 (Constraints) +- 使用什么框架?(React, Vue, 原生 HTML/CSS) +- 性能要求?(动画复杂度,文件大小) +- 可访问性要求?(ARIA 标签,键盘导航,色彩对比度) +- 浏览器兼容性? + +#### 4. 差异化 (Differentiation) +- **记忆点**: 是什么让它令人难忘? +- **独特性**: 用户会记住哪一个细节? +- **惊喜**: 哪里会让用户眼前一亮? + +## 前端美学指南 + +### 1. 排版 (Typography) + +**原则**: 字体选择是设计的灵魂。 + +**Do**: +- ✅ 选择**独特且有个性**的字体 +- ✅ 标题使用引人注目的字体,正文使用易读字体 +- ✅ 尝试意想不到的字体配对 +- ✅ 使用字体变体(font-weight, font-style)创造层次 +- ✅ 精确控制字间距(letter-spacing)和行高(line-height) + +**Don't**: +- ❌ 使用通用字体:Arial, Helvetica, Inter, Roboto, 系统字体 +- ❌ 所有文本使用相同的字体和大小 +- ❌ 忽略字体加载性能(使用 font-display: swap) + +**推荐字体来源**: +- Google Fonts (选择小众、独特的字体) +- 自定义字体(如果项目允许) + +**示例字体组合**: +```css +/* 极简编辑风格 */ +--font-heading: 'Playfair Display', serif; +--font-body: 'Source Sans Pro', sans-serif; + +/* 现代科技风格 */ +--font-heading: 'Space Mono', monospace; +--font-body: 'DM Sans', sans-serif; + +/* 优雅奢华风格 */ +--font-heading: 'Cormorant Garamond', serif; +--font-body: 'Lato', sans-serif; +``` + +### 2. 颜色与主题 (Color & Theme) + +**原则**: 颜色定义情绪和品牌。 + +**Do**: +- ✅ 使用 CSS 变量保持一致性 +- ✅ 主色调 + 鲜明点缀色的组合 +- ✅ 考虑色彩心理学(蓝色=信任,红色=紧迫,绿色=成功) +- ✅ 使用渐变营造深度(但要有品味) +- ✅ 保持色彩对比度(WCAG AA 标准:至少 4.5:1) + +**Don't**: +- ❌ 俗套配色:白色背景 + 紫色渐变 +- ❌ 过多颜色(3-5 个主色已足够) +- ❌ 忽略可访问性 + +**示例主题**: +```css +:root { + /* 极简黑白 */ + --color-primary: #000000; + --color-secondary: #ffffff; + --color-accent: #ff3366; + + /* 复古未来 */ + --color-primary: #1a1a2e; + --color-secondary: #16213e; + --color-accent: #00fff5; + --color-highlight: #ff006e; + + /* 自然有机 */ + --color-primary: #2d6a4f; + --color-secondary: #52b788; + --color-accent: #ffc857; +} +``` + +### 3. 动效 (Animation & Motion) + +**原则**: 动画应该增强体验,而不是分散注意力。 + +**Do**: +- ✅ 优先使用 CSS 动画(性能更好) +- ✅ 设计页面加载动画(首次印象) +- ✅ 使用 `animation-delay` 实现元素逐个显示 +- ✅ 悬停状态添加微妙过渡 +- ✅ 滚动触发动画(Intersection Observer) +- ✅ 对于 React,使用 Framer Motion 或 React Spring + +**Don't**: +- ❌ 过度使用动画(每个元素都在动) +- ❌ 动画持续时间过长(> 500ms 会让人不耐烦) +- ❌ 忽略 `prefers-reduced-motion` 媒体查询 + +**示例动画**: +```css +/* 页面加载 - 元素逐个淡入 */ +.fade-in-up { + animation: fadeInUp 0.6s ease-out forwards; + opacity: 0; +} + +.fade-in-up:nth-child(1) { animation-delay: 0.1s; } +.fade-in-up:nth-child(2) { animation-delay: 0.2s; } +.fade-in-up:nth-child(3) { animation-delay: 0.3s; } + +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(30px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +/* 悬停效果 */ +.card { + transition: transform 0.3s ease, box-shadow 0.3s ease; +} + +.card:hover { + transform: translateY(-8px); + box-shadow: 0 20px 40px rgba(0,0,0,0.15); +} +``` + +### 4. 空间构成 (Spatial Composition) + +**原则**: 布局应该引导视线,创造视觉节奏。 + +**Do**: +- ✅ 尝试不对称布局 +- ✅ 使用重叠元素创造深度 +- ✅ 对角线流程引导视线 +- ✅ 打破网格的元素(但有意图) +- ✅ 宽敞的留白或精心控制的密度 +- ✅ 使用 Grid 和 Flexbox 创造复杂布局 + +**Don't**: +- ❌ 所有元素居中对齐 +- ❌ 均匀分布的网格(无聊) +- ❌ 忽略响应式设计 + +**示例布局技巧**: +```css +/* 不对称网格 */ +.grid-asymmetric { + display: grid; + grid-template-columns: 2fr 1fr; + gap: 40px; +} + +/* 重叠效果 */ +.overlap-container { + position: relative; +} + +.overlap-item { + position: absolute; + z-index: 2; + transform: translate(-20%, -20%); +} + +/* 对角线流程 */ +.diagonal-section { + transform: skewY(-3deg); + padding: 100px 0; +} + +.diagonal-section > * { + transform: skewY(3deg); +} +``` + +### 5. 背景和视觉细节 (Background & Visual Details) + +**原则**: 背景营造氛围和深度。 + +**Do**: +- ✅ 渐变网格 +- ✅ 噪点纹理 +- ✅ 几何图案 +- ✅ 分层透明度 +- ✅ 戏剧性阴影 +- ✅ 装饰性边框 +- ✅ 自定义光标(如果适合风格) +- ✅ 颗粒叠加效果 + +**Don't**: +- ❌ 纯色背景(除非极简风格) +- ❌ 低质量或不相关的库存图片 +- ❌ 过度使用阴影(box-shadow 污染) + +**示例背景效果**: +```css +/* 渐变网格背景 */ +.gradient-grid { + background: + linear-gradient(90deg, rgba(255,255,255,0.05) 1px, transparent 1px), + linear-gradient(rgba(255,255,255,0.05) 1px, transparent 1px), + linear-gradient(135deg, #667eea 0%, #764ba2 100%); + background-size: 50px 50px, 50px 50px, 100% 100%; +} + +/* 噪点纹理 */ +.noise-texture { + position: relative; +} + +.noise-texture::before { + content: ''; + position: absolute; + inset: 0; + background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' /%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.05'/%3E%3C/svg%3E"); + pointer-events: none; +} + +/* 玻璃态效果 */ +.glass-card { + background: rgba(255, 255, 255, 0.1); + backdrop-filter: blur(10px); + border: 1px solid rgba(255, 255, 255, 0.2); + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); +} +``` + +## 避免通用 AI 美学 + +**绝对禁止的元素**: +- ❌ 过度使用的字体:Inter, Roboto, Arial, 系统字体 +- ❌ 俗套配色:白色背景 + 紫色渐变 +- ❌ 可预测的布局模式(居中卡片网格) +- ❌ 缺乏特定上下文特征的千篇一律设计 + +**如何避免**: +- ✅ 为每个项目选择**不同**的字体 +- ✅ 在浅色/深色主题之间变化 +- ✅ 尝试不同的布局结构 +- ✅ 添加独特的品牌元素和个性 + +## 实现复杂性与美学匹配 + +**关键原则**: 代码复杂度应与设计愿景相匹配。 + +### 极繁主义设计 → 复杂代码 +- 大量动画和过渡效果 +- 多层叠加元素 +- 复杂的交互状态 +- 详细的视觉效果(粒子、渐变、纹理) + +```jsx +// 示例:复杂的动画卡片 + + {/* 复杂内容 */} + +``` + +### 极简主义设计 → 精准代码 +- 克制的动画(仅在关键时刻) +- 精确的间距和排版 +- 细微的过渡效果 +- 关注细节而非数量 + +```css +/* 示例:精致的极简主义 */ +.minimal-card { + padding: 60px; + background: #ffffff; + border: 1px solid rgba(0,0,0,0.08); + transition: border-color 0.3s ease; +} + +.minimal-card:hover { + border-color: rgba(0,0,0,0.2); +} + +.minimal-card h2 { + font-family: 'Cormorant Garamond', serif; + font-size: 2.5rem; + font-weight: 300; + letter-spacing: -0.02em; + line-height: 1.2; + margin: 0 0 20px 0; +} +``` + +## 工作流程 + +### 第 1 步:理解需求 +- 阅读用户请求,提取关键信息 +- 确定项目类型(组件、页面、完整应用) +- 识别技术栈(React、Vue、原生 HTML/CSS) + +### 第 2 步:设计思考 +- 回答设计思维流程中的 4 个问题 +- 选择明确的美学方向 +- 在心中可视化最终效果 + +### 第 3 步:技术决策 +- 选择框架和工具 +- 决定动画库(Framer Motion、CSS、React Spring) +- 确定字体来源 + +### 第 4 步:实现 +- 编写语义化 HTML 结构 +- 实现 CSS 样式(使用 CSS 变量) +- 添加交互和动画 +- 确保响应式设计 + +### 第 5 步:精细化 +- 调整间距和排版 +- 优化动画时间 +- 测试不同屏幕尺寸 +- 确保可访问性(ARIA、键盘导航) + +## 示例场景 + +### 场景 1: 创建着陆页 + +**用户请求**: "帮我创建一个 SaaS 产品的着陆页" + +**设计思考**: +- 目的:展示产品价值,吸引用户注册 +- 风格:现代科技 + 编辑风格,使用 Space Grotesk 字体,黑白 + 蓝色点缀 +- 布局:不对称,英雄区域占据 70% 屏幕,对角线流程 +- 差异化:独特的字体配对,大胆的排版层次 + +**实现重点**: +- Hero section 使用大字号标题(4-6rem) +- 滚动触发的淡入动画 +- 玻璃态 CTA 按钮 +- 响应式网格展示功能 + +### 场景 2: 设计仪表盘 + +**用户请求**: "创建一个数据分析仪表盘" + +**设计思考**: +- 目的:清晰展示数据,支持快速决策 +- 风格:实用主义 + 精致,使用 IBM Plex Sans,深色主题 +- 布局:网格系统,卡片式布局,数据可视化优先 +- 差异化:微妙的动画过渡,悬停显示详细信息 + +**实现重点**: +- 深色背景减少眼睛疲劳 +- 卡片使用柔和阴影和边框 +- 图表使用鲜明的点缀色 +- 加载状态使用骨架屏 + +### 场景 3: React 组件库 + +**用户请求**: "创建一套自定义按钮组件" + +**设计思考**: +- 目的:可复用、可定制的按钮系统 +- 风格:灵活,支持多种变体 +- 技术:使用 styled-components 或 CSS modules +- 差异化:独特的悬停效果和加载状态 + +**实现重点**: +- 主按钮、次要按钮、文本按钮变体 +- 大小变体(small, medium, large) +- 加载和禁用状态 +- 平滑的过渡动画 + +## 代码质量标准 + +### 必须遵守: +- ✅ 语义化 HTML(`
`, `