Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3ed61d87da | |||
| 45919e6db8 | |||
| 01b411cbc3 |
@@ -1,183 +0,0 @@
|
||||
---
|
||||
description: Complete guide for adding a new AI provider documentation to LobeChat
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Adding New AI Provider Documentation
|
||||
|
||||
This document provides a step-by-step guide for adding documentation for a new AI provider to LobeChat, based on the complete workflow used for adding providers like BFL (Black Forest Labs) and FAL.
|
||||
|
||||
## Overview
|
||||
|
||||
Adding a new provider requires creating both user-facing documentation and technical configuration files. The process involves:
|
||||
|
||||
1. Creating usage documentation (EN + CN)
|
||||
2. Adding environment variable documentation (EN + CN)
|
||||
3. Updating Docker configuration files
|
||||
4. Updating .env.example file
|
||||
5. Preparing image resources
|
||||
|
||||
## Step 1: Create Provider Usage Documentation
|
||||
|
||||
Create user-facing documentation that explains how to use the new provider.
|
||||
|
||||
### Required Files
|
||||
|
||||
Create both English and Chinese versions:
|
||||
- `docs/usage/providers/{provider-name}.mdx` (English)
|
||||
- `docs/usage/providers/{provider-name}.zh-CN.mdx` (Chinese)
|
||||
|
||||
### Documentation Structure
|
||||
|
||||
Follow the structure and format used in existing provider documentation. For reference, see:
|
||||
- `docs/usage/providers/fal.mdx` (English template)
|
||||
- `docs/usage/providers/fal.zh-CN.mdx` (Chinese template)
|
||||
|
||||
### Key Requirements
|
||||
|
||||
- **Images**: Prepare 5-6 screenshots showing the process
|
||||
- **Cover Image**: Create or obtain a cover image for the provider
|
||||
- **Accurate URLs**: Use real registration and dashboard URLs
|
||||
- **Service Type**: Specify whether it's for image generation, text generation, etc.
|
||||
- **Pricing Warning**: Include pricing information callout
|
||||
|
||||
### Important Notes
|
||||
|
||||
- **🔒 API Key Security**: Never include real API keys in documentation. Always use placeholder format (e.g., `bfl-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)
|
||||
- **🖼️ Image Hosting**: Use LobeHub's CDN for all images: `hub-apac-1.lobeobjects.space`
|
||||
|
||||
## Step 2: Update Environment Variables Documentation
|
||||
|
||||
Add the new provider's environment variables to the self-hosting documentation.
|
||||
|
||||
### Files to Update
|
||||
|
||||
- `docs/self-hosting/environment-variables/model-provider.mdx` (English)
|
||||
- `docs/self-hosting/environment-variables/model-provider.zh-CN.mdx` (Chinese)
|
||||
|
||||
### Content to Add
|
||||
|
||||
Add two sections for each provider:
|
||||
|
||||
```markdown
|
||||
### `{PROVIDER}_API_KEY`
|
||||
|
||||
- Type: Required
|
||||
- Description: This is the API key you applied for in the {Provider Name} service.
|
||||
- Default: -
|
||||
- Example: `{api-key-format-example}`
|
||||
|
||||
### `{PROVIDER}_MODEL_LIST`
|
||||
|
||||
- Type: Optional
|
||||
- Description: Used to control the {Provider Name} model list. Use `+` to add a model, `-` to hide a model, and `model_name=display_name` to customize the display name of a model. Separate multiple entries with commas. The definition syntax follows the same rules as other providers' model lists.
|
||||
- Default: `-`
|
||||
- Example: `-all,+{model-id-1},+{model-id-2}={display-name}`
|
||||
|
||||
The above example disables all models first, then enables `{model-id-1}` and `{model-id-2}` (displayed as `{display-name}`).
|
||||
|
||||
[model-list]: /docs/self-hosting/advanced/model-list
|
||||
```
|
||||
|
||||
### Important Notes
|
||||
|
||||
- **API Key Format**: Use proper UUID format for examples (e.g., `12345678-1234-1234-1234-123456789abc`)
|
||||
- **Real Model IDs**: Use actual model IDs from the codebase, not placeholders
|
||||
- **Consistent Naming**: Follow the pattern `{PROVIDER}_API_KEY` and `{PROVIDER}_MODEL_LIST`
|
||||
|
||||
## Step 3: Update Docker Configuration Files
|
||||
|
||||
Add environment variables to all Docker configuration files to ensure the provider works in containerized deployments.
|
||||
|
||||
### Files to Update
|
||||
|
||||
All Dockerfile variants must be updated:
|
||||
- `Dockerfile`
|
||||
- `Dockerfile.database`
|
||||
- `Dockerfile.pglite`
|
||||
|
||||
### Changes Required
|
||||
|
||||
Add the new provider's environment variables at the **end** of the ENV section, just before the final line:
|
||||
|
||||
```dockerfile
|
||||
# Previous providers...
|
||||
# 302.AI
|
||||
AI302_API_KEY="" AI302_MODEL_LIST="" \
|
||||
# {New Provider 1}
|
||||
{PROVIDER1}_API_KEY="" {PROVIDER1}_MODEL_LIST="" \
|
||||
# {New Provider 2}
|
||||
{PROVIDER2}_API_KEY="" {PROVIDER2}_MODEL_LIST=""
|
||||
```
|
||||
|
||||
### Important Rules
|
||||
|
||||
- **Position**: Add new providers at the **end** of the list
|
||||
- **Ordering**: When adding multiple providers, use alphabetical order (e.g., FAL before BFL)
|
||||
- **Consistency**: Maintain identical ordering across all Dockerfile variants
|
||||
- **Format**: Follow the pattern `{PROVIDER}_API_KEY="" {PROVIDER}_MODEL_LIST="" \`
|
||||
|
||||
## Step 4: Update .env.example File
|
||||
|
||||
Add example configuration entries to help users understand how to configure the provider locally.
|
||||
|
||||
### File to Update
|
||||
|
||||
- `.env.example`
|
||||
|
||||
### Content to Add
|
||||
|
||||
Add new sections before the "Market Service" section:
|
||||
|
||||
```bash
|
||||
### {Provider Name} ###
|
||||
|
||||
# {PROVIDER}_API_KEY={provider-prefix}-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
### Format Guidelines
|
||||
|
||||
- **Section Header**: Use `### {Provider Name} ###` format
|
||||
- **Commented Example**: Use `#` to comment out the example
|
||||
- **Key Format**: Use appropriate prefix for the provider (e.g., `bfl-`, `fal-`, `sk-`)
|
||||
- **Position**: Add before the Market Service section
|
||||
- **Spacing**: Maintain consistent spacing with existing entries
|
||||
|
||||
## Step 5: Image Resources
|
||||
|
||||
Prepare all necessary image resources for the documentation.
|
||||
|
||||
### Required Images
|
||||
|
||||
1. **Cover Image**: Provider logo or branded image
|
||||
2. **API Dashboard Screenshots**: 3-4 screenshots showing API key creation process
|
||||
3. **LobeChat Configuration Screenshots**: 2-3 screenshots showing provider setup in LobeChat
|
||||
|
||||
### Image Guidelines
|
||||
|
||||
- **Quality**: Use high-resolution screenshots
|
||||
- **Consistency**: Maintain consistent styling across all screenshots
|
||||
- **Privacy**: Remove or blur any sensitive information
|
||||
- **Format**: Use PNG format for screenshots
|
||||
- **Hosting**: Use LobeHub's CDN (`hub-apac-1.lobeobjects.space`) for all images
|
||||
|
||||
## Checklist
|
||||
|
||||
Before submitting your provider documentation:
|
||||
|
||||
- [ ] Created both English and Chinese usage documentation
|
||||
- [ ] Added environment variable documentation (EN + CN)
|
||||
- [ ] Updated all 3 Dockerfile variants with consistent ordering
|
||||
- [ ] Updated .env.example with proper key format
|
||||
- [ ] Prepared all required screenshots and images
|
||||
- [ ] Used actual model IDs from the codebase
|
||||
- [ ] Verified no real API keys are included in documentation
|
||||
- [ ] Used LobeHub CDN for all image hosting
|
||||
- [ ] Tested the documentation for clarity and accuracy
|
||||
|
||||
## Reference
|
||||
|
||||
This guide was created based on the implementation of BFL (Black Forest Labs) provider documentation. For a complete example, refer to:
|
||||
- Commits: `d2da03e1a` (documentation) and `6a2e95868` (environment variables)
|
||||
- Files: `docs/usage/providers/bfl.mdx`, `docs/usage/providers/bfl.zh-CN.mdx`
|
||||
- PR: Current branch `tj/feat/bfl-docs`
|
||||
@@ -1,9 +1,8 @@
|
||||
---
|
||||
description:
|
||||
description:
|
||||
globs: src/services/**/*,src/database/**/*,src/server/**/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# LobeChat 后端技术架构指南
|
||||
|
||||
本指南旨在阐述 LobeChat 项目的后端分层架构,重点介绍各核心目录的职责以及它们之间的协作方式。
|
||||
@@ -30,21 +29,24 @@ LobeChat 的后端设计注重模块化、可测试性和灵活性,以适应
|
||||
其主要分层如下:
|
||||
|
||||
1. 客户端服务层 (`src/services`):
|
||||
|
||||
- 位于 src/services/。
|
||||
- 这是客户端业务逻辑的核心层,负责封装各种业务操作和数据处理逻辑。
|
||||
- 环境适配: 根据不同的运行环境,服务层会选择合适的数据访问方式:
|
||||
- 本地数据库模式: 直接调用 `Model` 层进行数据操作,适用于浏览器 PGLite 和本地 Electron 应用。
|
||||
- 远程数据库模式: 通过 `tRPC` 客户端调用服务端 API,适用于需要云同步的场景。
|
||||
- 本地数据库模式: 直接调用 `Model` 层进行数据操作,适用于浏览器 PGLite 和本地 Electron 应用。
|
||||
- 远程数据库模式: 通过 `tRPC` 客户端调用服务端 API,适用于需要云同步的场景。
|
||||
- 类型转换: 对于简单的数据类型转换,直接在此层进行类型断言,如 `this.pluginModel.query() as Promise<LobeTool[]>`
|
||||
- 每个服务模块通常包含 `client.ts`(本地模式)、`server.ts`(远程模式)和 `type.ts`(接口定义)文件,在实现时应该确保本地模式和远程模式业务逻辑实现一致,只是数据库不同。
|
||||
|
||||
2. API 接口层 (`TRPC`):
|
||||
|
||||
- 位于 src/server/routers/
|
||||
- 使用 `tRPC` 构建类型安全的 API。Router 根据运行时环境(如 Edge Functions, Node.js Lambda)进行组织。
|
||||
- 负责接收客户端请求,并将其路由到相应的 `Service` 层进行处理。
|
||||
- 新建 lambda 端点时可以参考 src/server/routers/lambda/\_template.ts
|
||||
|
||||
3. 仓库层 (`Repositories`):
|
||||
|
||||
- 位于 src/database/repositories/。
|
||||
- 主要处理复杂的跨表查询和数据聚合逻辑,特别是当需要从多个 `Model` 获取数据并进行组合时。
|
||||
- 与 `Model` 层不同,`Repository` 层专注于复杂的业务查询场景,而不涉及简单的领域模型转换。
|
||||
@@ -52,6 +54,7 @@ LobeChat 的后端设计注重模块化、可测试性和灵活性,以适应
|
||||
- 如果数据操作简单(仅涉及单个 `Model`),则通常直接在 `src/services` 层调用 `Model` 并进行简单的类型断言。
|
||||
|
||||
4. 模型层 (`Models`):
|
||||
|
||||
- 位于 src/database/models/ (例如 src/database/models/plugin.ts 和 src/database/models/document.ts)。
|
||||
- 提供对数据库中各个表(由 src/database/schemas/ 中的 Drizzle ORM schema 定义)的基本 CRUD (创建、读取、更新、删除) 操作和简单的查询能力。
|
||||
- `Model` 类专注于单个数据表的直接操作,不涉及复杂的领域模型转换,这些转换通常在上层的 `src/services` 中通过类型断言完成。
|
||||
@@ -62,11 +65,11 @@ LobeChat 的后端设计注重模块化、可测试性和灵活性,以适应
|
||||
- 客户端模式 (浏览器/PWA): 使用 PGLite (基于 WASM 的 PostgreSQL),数据存储在用户浏览器本地。
|
||||
- 服务端模式 (云部署): 使用远程 PostgreSQL 数据库。
|
||||
- Electron 桌面应用:
|
||||
- Electron 客户端会启动一个本地 Node.js 服务。
|
||||
- 本地服务通过 `tRPC` 与 Electron 的渲染进程通信。
|
||||
- 数据库选择依赖于是否开启云同步功能:
|
||||
- 云同步开启: 连接到远程 PostgreSQL 数据库。
|
||||
- 云同步关闭: 使用 PGLite (通过 Node.js 的 WASM 实现) 在本地存储数据。
|
||||
- Electron 客户端会启动一个本地 Node.js 服务。
|
||||
- 本地服务通过 `tRPC` 与 Electron 的渲染进程通信。
|
||||
- 数据库选择依赖于是否开启云同步功能:
|
||||
- 云同步开启: 连接到远程 PostgreSQL 数据库。
|
||||
- 云同步关闭: 使用 PGLite (通过 Node.js 的 WASM 实现) 在本地存储数据。
|
||||
|
||||
## 数据流向说明
|
||||
|
||||
@@ -90,87 +93,8 @@ UI (Electron Renderer) → Zustand action → Client Service -> TRPC Client →
|
||||
|
||||
## 服务层 (Server Services)
|
||||
|
||||
- 位于 src/server/services/。
|
||||
- 核心职责是封装独立的、可复用的业务逻辑单元。这些服务应易于测试。
|
||||
- 平台差异抽象: 一个关键特性是通过其内部的 `impls` 子目录(例如 src/server/services/file/impls 包含 s3.ts 和 local.ts)来抹平不同运行环境带来的差异(例如云端使用 S3 存储,桌面版使用本地文件系统)。这使得上层(如 `tRPC` routers)无需关心底层具体实现。
|
||||
- 目标是使 `tRPC` router 层的逻辑尽可能纯粹,专注于请求处理和业务流程编排。
|
||||
- 服务可能会调用 `Repository` 层或直接调用 `Model` 层进行数据持久化和检索,也可能调用其他服务。
|
||||
|
||||
## 最佳实践 (Best Practices)
|
||||
|
||||
### 数据库操作封装原则
|
||||
|
||||
**连续的数据库操作应该封装到 Model 层**
|
||||
|
||||
当业务逻辑涉及多个相关的数据库操作时,建议将这些操作封装到 Model 层中,而不是在上层(Service 或 Router 层)中进行多次数据库调用。
|
||||
|
||||
**优势:**
|
||||
|
||||
- **代码复用**: Client DB 环境的 service 实现和 Server DB 的 lambda 层实现可以复用相同的 Model 方法
|
||||
- **事务一致性**: 相关的数据库操作可以在同一个方法中管理,便于维护数据一致性
|
||||
- **性能优化**: 减少数据库连接次数,提高查询效率
|
||||
- **职责清晰**: Model 层专注数据访问,上层专注业务协调
|
||||
|
||||
**示例:**
|
||||
|
||||
```typescript
|
||||
// ✅ 推荐:在 Model 层封装连续的数据库操作
|
||||
class GenerationBatchModel {
|
||||
async delete(id: string): Promise<{ deletedBatch: BatchItem; thumbnailUrls: string[] }> {
|
||||
// 1. 查询相关数据
|
||||
const batchWithGenerations = await this.db.query.generationBatches.findFirst({...});
|
||||
|
||||
// 2. 收集需要处理的数据
|
||||
const thumbnailUrls = [...];
|
||||
|
||||
// 3. 执行删除操作
|
||||
const [deletedBatch] = await this.db.delete(generationBatches)...;
|
||||
|
||||
return { deletedBatch, thumbnailUrls };
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ 上层使用简洁
|
||||
const { thumbnailUrls } = await model.delete(id);
|
||||
await fileService.deleteFiles(thumbnailUrls);
|
||||
```
|
||||
|
||||
### 文件操作与数据库操作的执行顺序
|
||||
|
||||
**删除操作原则:数据库删除在前,文件删除在后**
|
||||
|
||||
当业务逻辑同时涉及数据库记录和文件系统操作时,应该遵循"数据库优先"的原则。
|
||||
|
||||
**原因:**
|
||||
|
||||
- **用户体验优先**: 如果先删除文件再删除数据库记录,可能出现文件已删除但数据库记录仍存在的情况,用户访问时会遇到文件不存在的错误
|
||||
- **影响程度较小**: 如果先删除数据库记录再删除文件,即使文件删除失败,用户也看不到这个记录,只是造成一些存储空间浪费,对用户体验影响更小
|
||||
- **数据一致性**: 数据库记录是业务逻辑的核心,应该优先保证其一致性
|
||||
|
||||
**示例:**
|
||||
|
||||
```typescript
|
||||
// ✅ 推荐:先删除数据库记录,再删除文件
|
||||
async deleteGeneration(id: string) {
|
||||
// 1. 先删除数据库记录
|
||||
const deletedGeneration = await generationModel.delete(id);
|
||||
|
||||
// 2. 再删除相关文件
|
||||
if (deletedGeneration.asset?.thumbnailUrl) {
|
||||
await fileService.deleteFile(deletedGeneration.asset.thumbnailUrl);
|
||||
}
|
||||
}
|
||||
|
||||
// ❌ 不推荐:先删除文件
|
||||
async deleteGeneration(id: string) {
|
||||
const generation = await generationModel.findById(id);
|
||||
|
||||
// 如果这里删除成功,但后面数据库删除失败,用户会遇到访问错误
|
||||
await fileService.deleteFile(generation.asset.thumbnailUrl);
|
||||
await generationModel.delete(id); // 可能失败
|
||||
}
|
||||
```
|
||||
|
||||
**创建操作原则:数据库创建在前,文件操作在后**
|
||||
|
||||
创建操作同样应该优先处理数据库记录,确保数据的一致性和完整性。
|
||||
- 位于 src/server/services/。
|
||||
- 核心职责是封装独立的、可复用的业务逻辑单元。这些服务应易于测试。
|
||||
- 平台差异抽象: 一个关键特性是通过其内部的 `impls` 子目录(例如 src/server/services/file/impls 包含 s3.ts 和 local.ts)来抹平不同运行环境带来的差异(例如云端使用 S3 存储,桌面版使用本地文件系统)。这使得上层(如 `tRPC` routers)无需关心底层具体实现。
|
||||
- 目标是使 `tRPC` router 层的逻辑尽可能纯粹,专注于请求处理和业务流程编排。
|
||||
- 服务可能会调用 `Repository` 层或直接调用 `Model` 层进行数据持久化和检索,也可能调用其他服务。
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
---
|
||||
description: How to code review
|
||||
globs:
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Role Description
|
||||
|
||||
- You are a senior full-stack engineer skilled in performance optimization, security, and design systems.
|
||||
- You excel at reviewing code and providing constructive feedback.
|
||||
- Your task is to review submitted Git diffs **in Chinese** and return a structured review report.
|
||||
- You are a senior full-stack engineer skilled in performance optimization, security, and design systems.
|
||||
- You excel at reviewing code and providing constructive feedback.
|
||||
- Your task is to review submitted Git diffs **in Chinese** and return a structured review report.
|
||||
- Review style: concise, direct, focused on what matters most, with actionable suggestions.
|
||||
|
||||
## Before the Review
|
||||
@@ -17,42 +16,54 @@ Gather the modified code and context. Please strictly follow the process below:
|
||||
|
||||
1. Use `read_file` to read [package.json](mdc:package.json)
|
||||
2. Use terminal to run command `git diff HEAD | cat` to obtain the diff and list the changed files. If you recieived empty result, run the same command once more.
|
||||
3. Use `read_file` to open each changed file.
|
||||
4. Use `read_file` to read [rules-attach.mdc](mdc:.cursor/rules/rules-attach.mdc). Even if you think it's unnecessary, you must read it.
|
||||
5. combine changed files, step3 and `agent_requestable_workspace_rules`, list the rules which need to read
|
||||
3. Use `read_file` to open each changed file.
|
||||
4. Use `read_file` to read [rules-attach.mdc](mdc:.cursor/rules/rules-attach.mdc). Even if you think it's unnecessary, you must read it.
|
||||
5. combine changed files, step3 and `agent_requestable_workspace_rules`, list the rules which need to read
|
||||
6. Use `read_file` to read the rules list in step 5
|
||||
|
||||
## Review
|
||||
|
||||
### Code Style
|
||||
|
||||
read [typescript.mdc](mdc:.cursor/rules/typescript.mdc) for the consolidated project code style and optimization rules.
|
||||
- Ensure JSDoc comments accurately reflect the implementation; update them when needed.
|
||||
- Look for opportunities to simplify or modernize code with the latest JavaScript/TypeScript features.
|
||||
- Prefer `async`/`await` over callbacks or chained `.then` promises.
|
||||
- Use consistent, descriptive naming—avoid obscure abbreviations.
|
||||
- Replace magic numbers or strings with well-named constants.
|
||||
- Use semantically meaningful variable, function, and class names.
|
||||
- Ignore purely formatting issues and other autofixable lint problems.
|
||||
|
||||
### Code Optimization
|
||||
|
||||
The optimization checklist has been consolidated into [typescript.mdc](mdc:.cursor/rules/typescript.mdc): loops, debouncing/throttling, design system components, theming tokens, concurrency with `Promise.*`, minimal DB column selection, and package reuse.
|
||||
- Prefer `for…of` loops to index-based `for` loops when feasible.
|
||||
- Decide whether callbacks should be **debounced** or **throttled**.
|
||||
- Use components from `@lobehub/ui`, Ant Design, or the existing design system instead of raw HTML tags (e.g., `Button` vs. `button`).
|
||||
- reuse npm packages already installed (e.g., `lodash/omit`) rather than reinventing the wheel.
|
||||
- Design for dark mode and mobile responsiveness:
|
||||
- Use the `antd-style` token system instead of hard-coded colors.
|
||||
- Select the proper component variants.
|
||||
- Performance considerations:
|
||||
- Where safe, convert sequential async flows to concurrent ones with `Promise.all`, `Promise.race`, etc.
|
||||
- Query only the required columns from a database rather than selecting entire rows.
|
||||
|
||||
### Obvious Bugs
|
||||
|
||||
- Do not silently swallow errors in `catch` blocks; at minimum, log them.
|
||||
- Revert temporary code used only for testing (e.g., debug logs, temporary configs).
|
||||
- Remove empty handlers (e.g., an empty `onClick`).
|
||||
- Do not silently swallow errors in `catch` blocks; at minimum, log them.
|
||||
- Revert temporary code used only for testing (e.g., debug logs, temporary configs).
|
||||
- Remove empty handlers (e.g., an empty `onClick`).
|
||||
- Confirm the UI degrades gracefully for unauthenticated users.
|
||||
- Don't leave any debug logs in the code (except when using the `debug` module properly).
|
||||
- When using the `debug` module, avoid `import { log } from 'debug'` as it logs directly to console. Use proper debug namespaces instead.
|
||||
- Check logs for sensitive information like api key, etc
|
||||
|
||||
## After the Review: output
|
||||
|
||||
1. Summary
|
||||
- Start with a brief explanation of what the change set does.
|
||||
- Summarize the changes for each modified file (or logical group).
|
||||
- Start with a brief explanation of what the change set does.
|
||||
- Summarize the changes for each modified file (or logical group).
|
||||
2. Comments Issues
|
||||
- List the most critical issues first.
|
||||
- Use an ordered list, which will be convenient for me to reference later.
|
||||
- For each issue:
|
||||
- Mark severity tag (`❌ Must fix`, `⚠️ Should fix`, `💅 Nitpick`)
|
||||
- Provode file path to the relevant file.
|
||||
- Provide recommended fix
|
||||
- End with a **git commit** command, instruct the author to run it.
|
||||
- We use gitmoji to label commit messages, format: [emoji] <type>(<scope>): <subject>
|
||||
- List the most critical issues first.
|
||||
- Use an ordered list, which will be convenient for me to reference later.
|
||||
- For each issue:
|
||||
- Mark severity tag (`❌ Must fix`, `⚠️ Should fix`, `💅 Nitpick`)
|
||||
- Provode file path to the relevant file.
|
||||
- Provide recommended fix
|
||||
- End with a **git commit** command, instruct the author to run it.
|
||||
- We use gitmoji to label commit messages, format: [emoji] <type>(<scope>): <subject>
|
||||
@@ -1,25 +1,21 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Guide to Optimize Output(Response) Rendering
|
||||
|
||||
## File Path and Code Symbol Rendering
|
||||
|
||||
- When rendering file paths, use backtick wrapping instead of markdown links so they can be parsed as clickable links in Cursor IDE.
|
||||
- Good: `src/components/Button.tsx`
|
||||
- Bad: [src/components/Button.tsx](src/components/Button.tsx)
|
||||
|
||||
- Don't use line and column number in file path, this will make file path not clickable in Cursor IDE.
|
||||
- Good: `src/components/Button.tsx` `10:20` (add a space between the file path and the line and column number)
|
||||
- Bad: `src/components/Button.tsx:10:20`
|
||||
- Good: `src/components/Button.tsx`
|
||||
- Bad: [src/components/Button.tsx](mdc:src/components/Button.tsx)
|
||||
|
||||
- When rendering functions, variables, or other code symbols, use backtick wrapping so they can be parsed as navigable links in Cursor IDE
|
||||
- Good: The `useState` hook in `MyComponent`
|
||||
- Bad: The useState hook in MyComponent
|
||||
|
||||
- Good: The `useState` hook in `MyComponent`
|
||||
- Bad: The useState hook in MyComponent
|
||||
|
||||
## Markdown Render
|
||||
|
||||
- don't use br tag to wrap in table cell
|
||||
@@ -27,6 +23,72 @@ alwaysApply: true
|
||||
## Terminal Command Output
|
||||
|
||||
- If terminal commands don't produce output, it's likely due to paging issues. Try piping the command to `cat` to ensure full output is displayed.
|
||||
- Good: `git show commit_hash -- file.txt | cat`
|
||||
- Good: `git log --oneline | cat`
|
||||
- Reason: Some git commands use pagers by default, which may prevent output from being captured properly
|
||||
- Good: `git show commit_hash -- file.txt | cat`
|
||||
- Good: `git log --oneline | cat`
|
||||
- Reason: Some git commands use pagers by default, which may prevent output from being captured properly
|
||||
|
||||
## Mermaid Diagram Generation: Strict Syntax Validation Checklist
|
||||
|
||||
Before producing any Mermaid diagram, you **must** compare your final code line-by-line against every rule in the following checklist to ensure 100% compliance. **This is a hard requirement and takes precedence over other stylistic suggestions.** Please follow these action steps:
|
||||
|
||||
1. Plan the Mermaid diagram logic in your mind.
|
||||
2. Write the Mermaid code.
|
||||
3. **Carefully review your code line-by-line against the entire checklist below.**
|
||||
4. Fix any aspect of your code that doesn't comply.
|
||||
5. Use the `validateMermaid` tool to check your code for syntax errors. Only proceed if validation passes.
|
||||
6. Output the final, compliant, and copy-ready Mermaid code block.
|
||||
7. Immediately after the Mermaid code block, output:
|
||||
I have checked that the Mermaid syntax fully complies with the validation checklist.
|
||||
|
||||
---
|
||||
|
||||
### Checklist Details
|
||||
|
||||
#### Rule 1: Edge Labels – Must Be Plain Text Only
|
||||
> **Essence:** Anything inside `|...|` must contain pure, unformatted text. Absolutely NO Markdown, list markers, or parentheses/brackets allowed—these often cause rendering failures.
|
||||
|
||||
- **✅ Do:** `A -->|Process plain text data| B`
|
||||
- **❌ Don't:** `A -->|1. Ordered list item| B` (No numbered lists)
|
||||
- **❌ Don't:** `CC --"1. fetch('/api/...')"--> API` (No square brackets)
|
||||
- **❌ Don't:** `A -->|- Unordered list item| B` (No hyphen lists)
|
||||
- **❌ Don't:** `A -->|Transform (important)| B` (No parentheses)
|
||||
- **❌ Don't:** `A -->|Transform [important]| B` (No square brackets)
|
||||
|
||||
#### Rule 2: Node Definition – Handle Special Characters with Care
|
||||
> **Essence:** When node text or subgraph titles contain special characters like `()` or `[]`, wrap the text in quotes to avoid conflicts with Mermaid shape syntax.
|
||||
|
||||
- **When your node text includes parentheses (e.g., 'React (JSX)'):**
|
||||
- **✅ Do:** `I_REACT["<b>React component (JSX)</b>"]` (Quotes wrap all text)
|
||||
- **❌ Don't:** `I_REACT(<b>React component (JSX)</b>)` (Wrong, Mermaid parses this as a shape)
|
||||
- **❌ Don't:** `subgraph Plugin Features (Plugins)` (Wrong, subgraph titles with parentheses must also be wrapped in quotes)
|
||||
|
||||
#### Rule 3: Double Quotes in Text – Must Be Escaped
|
||||
> **Essence:** Use `"` for double quotes **inside node text**.
|
||||
|
||||
- **✅ Do:** `A[This node contains "quotes"]`
|
||||
- **❌ Don't:** `A[This node contains "quotes"]`
|
||||
|
||||
#### Rule 4: All Formatting Must Use HTML Tags (NOT Markdown!)
|
||||
> **Essence:** For newlines, bold, and other text formatting in nodes, use HTML tags only. Markdown is not supported.
|
||||
|
||||
- **✅ Do (robust):** `A["<b>Bold</b> and <code>code</code><br>This is a new line"]`
|
||||
- **❌ Don't (not rendered):** `C["# This is a heading"]`
|
||||
- **❌ Don't (not rendered):** ``C["`const` means constant"]``
|
||||
- **⚠️ Warning (unreliable):** `B["Markdown **bold** might sometimes work but DON'T rely on it"]`
|
||||
|
||||
#### Rule 5: No HTML Tags for Participants and Message Labels (Sequence Diagrams)
|
||||
> **Important Addition:**
|
||||
> In Mermaid sequence diagrams, you MUST NOT use any HTML tags (such as `<b>`, `<code>`, etc.) in:
|
||||
> - `participant` display names (`as` part)
|
||||
> - Message labels (the text after `:` in diagram flows)
|
||||
>
|
||||
> These tags are generally not rendered—they may appear as-is or cause compatibility issues.
|
||||
|
||||
- **✅ Do:** `participant A as Client`
|
||||
- **❌ Don't:** `participant A as <b>Client</b>`
|
||||
- **✅ Do:** `A->>B: 1. Establish connection`
|
||||
- **❌ Don't:** `A->>B: 1. <code>Establish connection</code>`
|
||||
|
||||
---
|
||||
|
||||
**Validate each Mermaid code block by running it through the `validateMermaid` tool before delivering your output!**
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
---
|
||||
description: Debug 调试指南
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
# Debug 调试指南
|
||||
|
||||
## 💡 调试流程概览
|
||||
|
||||
当遇到问题时,请按照以下优先级进行处理:
|
||||
|
||||
1. **快速判断** - 对于熟悉的错误,直接提供解决方案
|
||||
2. **信息收集** - 使用工具搜索相关代码和配置
|
||||
3. **网络搜索** - 查找现有解决方案
|
||||
4. **定位调试** - 添加日志进行问题定位
|
||||
5. **临时方案** - 如果找不到根本解决方案,提供临时解决方案
|
||||
6. **解决实施** - 提供可维护的最终解决方案
|
||||
|
||||
## 🔍 错误信息分析
|
||||
|
||||
### 错误来源识别
|
||||
|
||||
错误信息可能来自:
|
||||
|
||||
- **Terminal 输出** - 构建、运行时错误
|
||||
- **浏览器控制台** - 前端 JavaScript 错误
|
||||
- **开发工具** - ESLint、TypeScript、测试框架等
|
||||
- **服务器日志** - API、数据库连接等后端错误
|
||||
- **截图或文本** - 用户直接提供的错误信息
|
||||
|
||||
## 🛠️ 信息收集工具
|
||||
|
||||
### 代码搜索工具
|
||||
|
||||
使用以下工具收集相关信息,并根据场景选择最合适的工具:
|
||||
|
||||
- **`codebase_search` (语义搜索)**
|
||||
- **何时使用**: 当你不确定具体的代码实现,想要寻找相关概念、功能或逻辑时。
|
||||
- **示例**: `查询"文件上传"功能的实现`
|
||||
- **`grep_search` (精确/正则搜索)**
|
||||
- **何时使用**: 当你知道要查找的确切字符串、函数名、变量名或一个特定的模式时。
|
||||
- **示例**: `查找所有使用了 'useState' 的地方`
|
||||
- **`file_search` (文件搜索)**
|
||||
- **何时使用**: 当你知道文件名的一部分,需要快速定位文件时。
|
||||
- **示例**: `查找 'Button.tsx' 组件`
|
||||
- **`read_file` (内容读取)**
|
||||
- **何时使用**: 在定位到具体文件后,用于查看其完整内容和上下文。
|
||||
- **`web_search` (网络搜索)**
|
||||
- **何时使用**: 当错误信息可能与第三方库、API 或常见问题相关时,用于获取外部信息。
|
||||
|
||||
### 环境与依赖检查
|
||||
|
||||
- **检查 `package.json`**: 查看 `scripts` 了解项目如何运行、构建和测试。查看 `dependencies` 和 `devDependencies` 确认库版本,版本冲突有时是问题的根源。
|
||||
- **运行测试**: 使用 `ni vitest` 运行单元测试和集成测试,这可以快速定位功能回归或组件错误。
|
||||
|
||||
### 项目特定搜索目标
|
||||
|
||||
针对 lobe-chat 项目,重点关注:
|
||||
|
||||
- **配置文件**: [package.json](mdc:package.json), [next.config.mjs](mdc:next.config.mjs)
|
||||
- **核心功能**: `src/features/` 下的相关模块
|
||||
- **状态管理**: `src/store/` 下的 Zustand stores
|
||||
- **数据库**: `src/database/` 和 `src/migrations/`
|
||||
- **类型定义**: `src/types/` 下的类型文件
|
||||
- **服务层**: `src/services/` 下的 API 服务
|
||||
- **启动流程**: [apps/desktop/src/main/core/App.ts](mdc:apps/desktop/src/main/core/App.ts) - 了解应用启动流程
|
||||
|
||||
## 🌐 网络搜索策略
|
||||
|
||||
### 搜索顺序优先级
|
||||
|
||||
1. **和问题相关的项目的 github issue**
|
||||
|
||||
2. **技术社区**
|
||||
- Stack Overflow
|
||||
- GitHub Discussions
|
||||
- Reddit
|
||||
|
||||
3. **官方文档**
|
||||
- 使用 `mcp_context7_resolve-library-id` 和 `mcp_context7_get-library-docs` 工具
|
||||
- 查阅官方文档网站
|
||||
|
||||
### 搜索关键词策略
|
||||
|
||||
- **错误信息**: 完整的错误消息
|
||||
- **技术栈**: "Next.js 15" + "error message"
|
||||
- **上下文**: 添加功能相关的关键词
|
||||
|
||||
## 🔧 问题定位与结构化思考
|
||||
|
||||
如果问题比较复杂,我们要按照先定位问题,再解决问题的大方向进行。
|
||||
|
||||
### 结构化思考工具
|
||||
|
||||
对于复杂或多步骤的调试任务,使用 `mcp_sequential-thinking_sequentialthinking` 工具来结构化思考过程。这有助于:
|
||||
|
||||
- **分解问题**: 将大问题拆解成可管理的小步骤。
|
||||
- **清晰追踪**: 记录每一步的发现和决策,避免遗漏。
|
||||
- **自我修正**: 在过程中评估和调整调试路径。
|
||||
|
||||
### 日志调试
|
||||
|
||||
在问题产生的路径上添加日志,可以简单使用 `console.log` 或者参考 [debug-usage.mdc](mdc:.cursor/rules/debug-usage.mdc) 使用 `debug` 模块。添加完日志后,请求我运行相关的代码并提供关键输出和错误信息。
|
||||
|
||||
### 引导式交互调试
|
||||
|
||||
虽然我无法直接操作浏览器开发者工具,但我可以引导你进行交互式调试:
|
||||
|
||||
1. **设置断点**: 我会告诉你可以在哪些关键代码行设置断点。
|
||||
2. **检查变量**: 我会请你在断点处检查特定变量的值或 `props`/`state`。
|
||||
3. **分析调用栈**: 我会请你提供调用栈信息,以帮助理解代码执行流程。
|
||||
|
||||
## 💡 临时解决方案策略
|
||||
|
||||
当无法找到根本解决方案时,提供临时解决方案:
|
||||
|
||||
### 临时方案准则
|
||||
|
||||
- **快速修复** - 优先让功能可用
|
||||
- **最小修改** - 减少对现有代码的影响
|
||||
- **清晰标记** - 明确标注这是临时方案
|
||||
- **后续计划** - 说明后续如何找到更好的解决方案
|
||||
|
||||
### 临时方案模板
|
||||
|
||||
```markdown
|
||||
## 临时解决方案 ⚠️
|
||||
|
||||
**问题**: [简要描述问题]
|
||||
|
||||
**临时修复**:
|
||||
[具体的临时修复步骤]
|
||||
|
||||
**风险说明**:
|
||||
|
||||
- [可能的副作用或限制]
|
||||
- [需要注意的事项]
|
||||
|
||||
**后续计划**:
|
||||
|
||||
- [ ] 深入调研根本原因
|
||||
- [ ] 寻找更优雅的解决方案
|
||||
- [ ] 监控是否有其他影响
|
||||
```
|
||||
|
||||
## ✅ 解决方案准则
|
||||
|
||||
### 方案质量标准
|
||||
|
||||
提供的解决方案应该:
|
||||
|
||||
- **✅ 低侵入性** - 最小化对现有代码的修改
|
||||
- **✅ 可维护性** - 易于理解和后续维护
|
||||
- **✅ 类型安全** - 符合 TypeScript 规范
|
||||
- **✅ 最佳实践** - 遵循项目的编码规范
|
||||
- **✅ 测试友好** - 便于编写和运行测试
|
||||
- **❌ 避免长期 Hack** - 临时方案可以 hack,但要明确标注
|
||||
|
||||
### 解决方案模板
|
||||
|
||||
```markdown
|
||||
## 问题原因
|
||||
|
||||
[简要说明问题产生的根本原因]
|
||||
|
||||
## 解决方案
|
||||
|
||||
[详细的解决步骤]
|
||||
|
||||
## 代码修改
|
||||
|
||||
[具体的代码变更]
|
||||
|
||||
## 验证方法
|
||||
|
||||
[如何验证问题已解决]
|
||||
|
||||
## 预防措施
|
||||
|
||||
[如何避免类似问题再次发生]
|
||||
```
|
||||
|
||||
## 🔄 迭代调试流程
|
||||
|
||||
如果初次解决方案无效:
|
||||
|
||||
1. **重新收集信息** - 基于新的错误信息搜索
|
||||
2. **深入代码分析** - 查看更多相关代码文件
|
||||
3. **运行相关测试** - 编写或运行一个失败的测试来稳定复现问题。
|
||||
4. **扩大搜索范围** - 搜索更广泛的相关问题
|
||||
5. **请求更多日志** - 添加更详细的调试信息
|
||||
6. **提供临时方案** - 如果根本解决方案复杂,先提供临时修复
|
||||
7. **分解问题** - 将复杂问题拆解为更小的子问题
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
description:
|
||||
globs: src/locales/**/*
|
||||
alwaysApply: false
|
||||
---
|
||||
read [i18n.mdc](mdc:.cursor/rules/i18n/i18n.mdc)
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
globs: *.tsx
|
||||
description: i18n workflow and troubleshooting
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
# LobeChat 国际化指南
|
||||
@@ -1,16 +1,19 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
## Project Description
|
||||
|
||||
You are developing an open-source, modern-design AI chat framework: lobe chat.
|
||||
You are developing an open-source, modern-design AI chat framework: lobe chat.
|
||||
|
||||
Emoji logo: 🤯
|
||||
|
||||
Emoji logo: 🤯
|
||||
|
||||
## Project Technologies Stack
|
||||
|
||||
read [package.json](mdc:package.json) to know all npm packages you can use.
|
||||
read [folder-structure.mdx](mdc:docs/development/basic/folder-structure.mdx) to learn project structure.
|
||||
|
||||
The project uses the following technologies:
|
||||
|
||||
|
||||
@@ -1,239 +0,0 @@
|
||||
---
|
||||
description: Project directory structure overview
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# LobeChat Project Structure
|
||||
|
||||
## Directory Structure
|
||||
|
||||
note: some files are not shown for simplicity.
|
||||
|
||||
```plaintext
|
||||
lobe-chat/
|
||||
├── apps/ # Applications directory
|
||||
│ └── desktop/ # Electron desktop application
|
||||
│ ├── src/ # Desktop app source code
|
||||
│ └── resources/ # Desktop app resources
|
||||
├── docs/ # Project documentation
|
||||
│ ├── development/ # Development docs
|
||||
│ ├── self-hosting/ # Self-hosting docs
|
||||
│ └── usage/ # Usage guides
|
||||
├── locales/ # Internationalization files (multiple locales)
|
||||
│ ├── en-US/ # English (example)
|
||||
│ └── zh-CN/ # Simplified Chinese (example)
|
||||
├── packages/ # Monorepo packages directory
|
||||
│ ├── const/ # Constants definition package
|
||||
│ ├── database/ # Database related package
|
||||
│ ├── electron-client-ipc/ # Electron renderer ↔ main IPC client
|
||||
│ ├── electron-server-ipc/ # Electron main process IPC server
|
||||
│ ├── model-bank/ # Built-in model presets/catalog exports
|
||||
│ ├── model-runtime/ # AI model runtime package
|
||||
│ ├── types/ # TypeScript type definitions
|
||||
│ ├── utils/ # Utility functions package
|
||||
│ ├── file-loaders/ # File processing packages
|
||||
│ ├── prompts/ # AI prompt management
|
||||
│ └── web-crawler/ # Web crawling functionality
|
||||
├── public/ # Static assets
|
||||
│ ├── icons/ # Application icons
|
||||
│ ├── images/ # Image resources
|
||||
│ └── screenshots/ # Application screenshots
|
||||
├── scripts/ # Build and tool scripts
|
||||
├── src/ # Main application source code (see below)
|
||||
├── .cursor/ # Cursor AI configuration
|
||||
├── docker-compose/ # Docker configuration
|
||||
├── package.json # Project dependencies
|
||||
├── pnpm-workspace.yaml # pnpm monorepo configuration
|
||||
├── next.config.ts # Next.js configuration
|
||||
├── drizzle.config.ts # Drizzle ORM configuration
|
||||
└── tsconfig.json # TypeScript configuration
|
||||
```
|
||||
|
||||
## Core Source Directory (`src/`)
|
||||
|
||||
```plaintext
|
||||
src/
|
||||
├── app/ # Next.js App Router routes
|
||||
│ ├── (backend)/ # Backend API routes
|
||||
│ │ ├── api/ # REST API endpoints
|
||||
│ │ │ ├── auth/ # Authentication endpoints
|
||||
│ │ │ └── webhooks/ # Webhook handlers for various auth providers
|
||||
│ │ ├── middleware/ # Request middleware
|
||||
│ │ ├── oidc/ # OpenID Connect endpoints
|
||||
│ │ ├── trpc/ # tRPC API routes
|
||||
│ │ │ ├── async/ # Async tRPC endpoints
|
||||
│ │ │ ├── desktop/ # Desktop runtime endpoints
|
||||
│ │ │ ├── edge/ # Edge runtime endpoints
|
||||
│ │ │ ├── lambda/ # Lambda runtime endpoints
|
||||
│ │ │ └── tools/ # Tools-specific endpoints
|
||||
│ │ └── webapi/ # Web API endpoints
|
||||
│ │ ├── chat/ # Chat-related APIs for various providers
|
||||
│ │ ├── models/ # Model management APIs
|
||||
│ │ ├── plugin/ # Plugin system APIs
|
||||
│ │ ├── stt/ # Speech-to-text APIs
|
||||
│ │ ├── text-to-image/ # Image generation APIs
|
||||
│ │ └── tts/ # Text-to-speech APIs
|
||||
│ ├── [variants]/ # Page route variants
|
||||
│ │ ├── (main)/ # Main application routes
|
||||
│ │ │ ├── chat/ # Chat interface and workspace
|
||||
│ │ │ ├── discover/ # Discover page (assistants, models, providers)
|
||||
│ │ │ ├── files/ # File management interface
|
||||
│ │ │ ├── image/ # Image generation interface
|
||||
│ │ │ ├── profile/ # User profile and stats
|
||||
│ │ │ ├── repos/ # Knowledge base repositories
|
||||
│ │ │ └── settings/ # Application settings
|
||||
│ │ └── @modal/ # Modal routes
|
||||
│ └── manifest.ts # PWA configuration
|
||||
├── components/ # Global shared components
|
||||
│ ├── Analytics/ # Analytics tracking components
|
||||
│ ├── Error/ # Error handling components
|
||||
│ └── Loading/ # Loading state components
|
||||
├── config/ # Application configuration
|
||||
│ ├── featureFlags/ # Feature flags & experiments
|
||||
│ └── modelProviders/ # Model provider configurations
|
||||
├── features/ # Feature components (UI Layer)
|
||||
│ ├── AgentSetting/ # Agent configuration and management
|
||||
│ ├── ChatInput/ # Chat input with file upload and tools
|
||||
│ ├── Conversation/ # Message display and interaction
|
||||
│ ├── FileManager/ # File upload and knowledge base
|
||||
│ └── PluginStore/ # Plugin marketplace and management
|
||||
├── hooks/ # Custom React hooks
|
||||
├── layout/ # Global layout components
|
||||
│ ├── AuthProvider/ # Authentication provider
|
||||
│ └── GlobalProvider/ # Global state provider
|
||||
├── libs/ # External library integrations
|
||||
│ ├── analytics/ # Analytics services integration
|
||||
│ ├── next-auth/ # NextAuth.js configuration
|
||||
│ └── oidc-provider/ # OIDC provider implementation
|
||||
├── locales/ # Internationalization resources
|
||||
│ └── default/ # Default language definitions
|
||||
├── migrations/ # Client-side data migrations
|
||||
├── server/ # Server-side code
|
||||
│ ├── modules/ # Server modules
|
||||
│ ├── routers/ # tRPC routers
|
||||
│ └── services/ # Server services
|
||||
├── services/ # Service layer (per-domain, client/server split)
|
||||
│ ├── user/ # User services
|
||||
│ │ ├── client.ts # Client DB (PGLite) implementation
|
||||
│ │ └── server.ts # Server DB implementation (via tRPC)
|
||||
│ ├── aiModel/ # AI model services
|
||||
│ ├── session/ # Session services
|
||||
│ └── message/ # Message services
|
||||
├── store/ # Zustand state management
|
||||
│ ├── agent/ # Agent state
|
||||
│ ├── chat/ # Chat state
|
||||
│ └── user/ # User state
|
||||
├── styles/ # Global styles
|
||||
├── tools/ # Built-in tool system
|
||||
│ ├── artifacts/ # Code artifacts and preview
|
||||
│ └── web-browsing/ # Web search and browsing
|
||||
├── types/ # TypeScript type definitions
|
||||
└── utils/ # Utility functions
|
||||
├── client/ # Client-side utilities
|
||||
└── server/ # Server-side utilities
|
||||
```
|
||||
|
||||
## Key Monorepo Packages
|
||||
|
||||
```plaintext
|
||||
packages/
|
||||
├── const/ # Global constants and configurations
|
||||
├── database/ # Database schemas and models
|
||||
│ ├── src/models/ # Data models (CRUD operations)
|
||||
│ ├── src/schemas/ # Drizzle database schemas
|
||||
│ ├── src/repositories/ # Complex query layer
|
||||
│ └── migrations/ # Database migration files
|
||||
├── model-runtime/ # AI model runtime
|
||||
│ └── src/
|
||||
│ ├── openai/ # OpenAI provider integration
|
||||
│ ├── anthropic/ # Anthropic provider integration
|
||||
│ ├── google/ # Google AI provider integration
|
||||
│ ├── ollama/ # Ollama local model integration
|
||||
│ ├── types/ # Runtime type definitions
|
||||
│ └── utils/ # Runtime utilities
|
||||
├── types/ # Shared TypeScript type definitions
|
||||
│ └── src/
|
||||
│ ├── agent/ # Agent-related types
|
||||
│ ├── message/ # Message and chat types
|
||||
│ ├── user/ # User and session types
|
||||
│ └── tool/ # Tool and plugin types
|
||||
├── utils/ # Shared utility functions
|
||||
│ └── src/
|
||||
│ ├── client/ # Client-side utilities
|
||||
│ ├── server/ # Server-side utilities
|
||||
│ ├── fetch/ # HTTP request utilities
|
||||
│ └── tokenizer/ # Token counting utilities
|
||||
├── file-loaders/ # File loaders (PDF, DOCX, etc.)
|
||||
├── prompts/ # AI prompt management
|
||||
└── web-crawler/ # Web crawling functionality
|
||||
```
|
||||
|
||||
## Architecture Map
|
||||
|
||||
- Presentation: `src/features`, `src/components`, `src/layout` — UI composition, global providers
|
||||
- State: `src/store` — Zustand slices, selectors, middleware
|
||||
- Client Services: `src/services/<domain>/{client|server}.ts` — client: PGLite; server: tRPC bridge
|
||||
- API Routers: `src/app/(backend)/webapi` (REST), `src/app/(backend)/trpc/{edge|lambda|async|desktop|tools}`; Lambda router triggers Async router for long-running tasks (e.g., image)
|
||||
- Server Services: `src/server/services` (business logic), `src/server/modules` (infra adapters)
|
||||
- Data Access: `packages/database/src/{schemas,models,repositories}` — Schema (Drizzle), Model (CRUD), Repository (complex queries)
|
||||
- Integrations: `src/libs` — analytics, auth, trpc, logging, runtime helpers
|
||||
|
||||
## Data Flow Architecture
|
||||
|
||||
### Unified Flow Pattern
|
||||
|
||||
```
|
||||
UI Layer → State Management → Client Service → [Environment Branch] → Database
|
||||
↓ ↓ ↓ ↓ ↓
|
||||
React Zustand Environment Local/Remote PGLite/
|
||||
Components Store Adaptation Routing PostgreSQL
|
||||
```
|
||||
|
||||
### Environment-Specific Routing
|
||||
|
||||
| Mode | UI | Service Route | Database |
|
||||
| --------------- | -------- | ---------------------- | ------------------- |
|
||||
| **Browser/PWA** | React | Direct Model Access | PGLite (Local) |
|
||||
| **Server** | React | tRPC → Server Services | PostgreSQL (Remote) |
|
||||
| **Desktop** | Electron | tRPC → Local Node.js | PGLite/PostgreSQL\* |
|
||||
|
||||
_\*Depends on cloud sync configuration_
|
||||
|
||||
### Key Characteristics
|
||||
|
||||
- **Type Safety**: End-to-end type safety via tRPC and Drizzle ORM
|
||||
- **Local/Remote Dual Mode**: PGLite enables user data ownership and local control
|
||||
|
||||
## Quick Map
|
||||
|
||||
- App Routes: `src/app` — UI routes (App Router) and backend routes under `(backend)`
|
||||
- Web API: `src/app/(backend)/webapi` — REST-like endpoints
|
||||
- tRPC Routers: `src/server/routers` — typed RPC endpoints by runtime
|
||||
- Client Services: `src/services` — environment-adaptive client-side business logic
|
||||
- Server Services: `src/server/services` — platform-agnostic business logic
|
||||
- Database: `packages/database` — schemas/models/repositories/migrations
|
||||
- State: `src/store` — Zustand stores and slices
|
||||
- Integrations: `src/libs` — analytics/auth/trpc/logging/runtime helpers
|
||||
- Tools: `src/tools` — built-in tool system
|
||||
|
||||
## Common Tasks
|
||||
|
||||
- Add Web API route: `src/app/(backend)/webapi/<module>/route.ts`
|
||||
- Add tRPC endpoint: `src/server/routers/{edge|lambda|desktop}/...`
|
||||
- Add client/server service: `src/services/<domain>/{client|server}.ts` (client: PGLite; server: tRPC)
|
||||
- Add server service: `src/server/services/<domain>`
|
||||
- Add a new model/provider: `src/config/modelProviders/<provider>.ts` + `packages/model-bank/src/aiModels/<provider>.ts` + `packages/model-runtime/src/<provider>/index.ts`
|
||||
- Add DB schema/model/repository: `packages/database/src/{schemas|models|repositories}`
|
||||
- Add Zustand slice: `src/store/<domain>/slices`
|
||||
|
||||
## Env Modes
|
||||
|
||||
- `NEXT_PUBLIC_CLIENT_DB`: selects client DB mode (e.g., `pglite`) vs server-backed
|
||||
- `NEXT_PUBLIC_IS_DESKTOP_APP`: enables desktop-specific routes and behavior
|
||||
- `NEXT_PUBLIC_SERVICE_MODE`: controls service routing preference (client/server)
|
||||
|
||||
## Boundaries
|
||||
|
||||
- Keep client logic in `src/services`; server-only logic stays in `src/server/services`
|
||||
- Don’t mix Web API (`webapi/`) with tRPC (`src/server/routers/`)
|
||||
- Place business UI under `src/features`, global reusable UI under `src/components`
|
||||
@@ -3,7 +3,6 @@ description:
|
||||
globs: *.tsx
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# react component 编写指南
|
||||
|
||||
- 如果要写复杂样式的话用 antd-style ,简单的话可以用 style 属性直接写内联样式
|
||||
@@ -21,20 +20,18 @@ import { useTheme } from 'antd-style';
|
||||
|
||||
const MyComponent = () => {
|
||||
const theme = useTheme();
|
||||
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
color: theme.colorPrimary,
|
||||
backgroundColor: theme.colorBgContainer,
|
||||
padding: theme.padding,
|
||||
borderRadius: theme.borderRadius,
|
||||
}}
|
||||
>
|
||||
<div style={{
|
||||
color: theme.colorPrimary,
|
||||
backgroundColor: theme.colorBgContainer,
|
||||
padding: theme.padding,
|
||||
borderRadius: theme.borderRadius
|
||||
}}>
|
||||
使用主题 token 的组件
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
#### 使用 antd-style 的 createStyles
|
||||
@@ -56,13 +53,13 @@ const useStyles = createStyles(({ css, token }) => {
|
||||
content: css`
|
||||
font-size: ${token.fontSize}px;
|
||||
line-height: ${token.lineHeight};
|
||||
`,
|
||||
`
|
||||
};
|
||||
});
|
||||
|
||||
const Card: FC<CardProps> = ({ title, content }) => {
|
||||
const { styles } = useStyles();
|
||||
|
||||
|
||||
return (
|
||||
<Flexbox className={styles.container}>
|
||||
<div className={styles.title}>{title}</div>
|
||||
@@ -77,96 +74,80 @@ const Card: FC<CardProps> = ({ title, content }) => {
|
||||
请注意使用下面的 token 而不是 css 字面值。可以访问 https://ant.design/docs/react/customize-theme-cn 了解所有 token
|
||||
|
||||
- 动画类
|
||||
- token.motionDurationMid
|
||||
- token.motionEaseInOut
|
||||
- token.motionDurationMid
|
||||
- token.motionEaseInOut
|
||||
- 包围盒属性
|
||||
- token.paddingSM
|
||||
- token.marginLG
|
||||
- token.paddingSM
|
||||
- token.marginLG
|
||||
|
||||
|
||||
## Lobe UI 包含的组件
|
||||
|
||||
- 不知道 @lobehub/ui 的组件怎么用,有哪些属性,就自己搜下这个项目其它地方怎么用的,不要瞎猜,大部分组件都是在 antd 的基础上扩展了属性
|
||||
- 具体用法不懂可以联网搜索,例如 ActionIcon 就爬取 https://ui.lobehub.com/components/action-icon
|
||||
- 可以阅读 node_modules/@lobehub/ui/es/index.js 了解有哪些组件,每个组件的属性是什么
|
||||
|
||||
- General
|
||||
- ActionIcon
|
||||
- ActionIconGroup
|
||||
- Block
|
||||
- Button
|
||||
- DownloadButton
|
||||
- Icon
|
||||
ActionIcon
|
||||
ActionIconGroup
|
||||
Block
|
||||
Button
|
||||
Icon
|
||||
- Data Display
|
||||
- Avatar
|
||||
- AvatarGroup
|
||||
- GroupAvatar
|
||||
- Collapse
|
||||
- FileTypeIcon
|
||||
- FluentEmoji
|
||||
- GuideCard
|
||||
- Highlighter
|
||||
- Hotkey
|
||||
- Image
|
||||
- List
|
||||
- Markdown
|
||||
- SearchResultCards
|
||||
- MaterialFileTypeIcon
|
||||
- Mermaid
|
||||
- Typography
|
||||
- Text
|
||||
- Segmented
|
||||
- Snippet
|
||||
- SortableList
|
||||
- Tag
|
||||
- Tooltip
|
||||
- Video
|
||||
Avatar
|
||||
Collapse
|
||||
FileTypeIcon
|
||||
FluentEmoji
|
||||
GuideCard
|
||||
Highlighter
|
||||
Hotkey
|
||||
Image
|
||||
List
|
||||
Markdown
|
||||
MaterialFileTypeIcon
|
||||
Mermaid
|
||||
Segmented
|
||||
Snippet
|
||||
SortableList
|
||||
Tag
|
||||
Tooltip
|
||||
Video
|
||||
- Data Entry
|
||||
- AutoComplete
|
||||
- CodeEditor
|
||||
- ColorSwatches
|
||||
- CopyButton
|
||||
- DatePicker
|
||||
- EditableText
|
||||
- EmojiPicker
|
||||
- Form
|
||||
- FormModal
|
||||
- HotkeyInput
|
||||
- ImageSelect
|
||||
- Input
|
||||
- SearchBar
|
||||
- Select
|
||||
- SliderWithInput
|
||||
- ThemeSwitch
|
||||
AutoComplete
|
||||
CodeEditor
|
||||
ColorSwatches
|
||||
CopyButton
|
||||
DatePicker
|
||||
EditableText
|
||||
EmojiPicker
|
||||
Form
|
||||
FormModal
|
||||
HotkeyInput
|
||||
ImageSelect
|
||||
Input
|
||||
SearchBar
|
||||
Select
|
||||
SliderWithInput
|
||||
ThemeSwitch
|
||||
- Feedback
|
||||
- Alert
|
||||
- Drawer
|
||||
- Modal
|
||||
Alert
|
||||
Drawer
|
||||
Modal
|
||||
- Layout
|
||||
- DraggablePanel
|
||||
- DraggablePanelBody
|
||||
- DraggablePanelContainer
|
||||
- DraggablePanelFooter
|
||||
- DraggablePanelHeader
|
||||
- Footer
|
||||
- Grid
|
||||
- Header
|
||||
- Layout
|
||||
- LayoutFooter
|
||||
- LayoutHeader
|
||||
- LayoutMain
|
||||
- LayoutSidebar
|
||||
- LayoutSidebarInner
|
||||
- LayoutToc
|
||||
- MaskShadow
|
||||
- ScrollShadow
|
||||
DraggablePanel
|
||||
Footer
|
||||
Grid
|
||||
Header
|
||||
Layout
|
||||
MaskShadow
|
||||
ScrollShadow
|
||||
- Navigation
|
||||
- Burger
|
||||
- Dropdown
|
||||
- Menu
|
||||
- SideNav
|
||||
- Tabs
|
||||
- Toc
|
||||
Burger
|
||||
Dropdown
|
||||
Menu
|
||||
SideNav
|
||||
Tabs
|
||||
Toc
|
||||
- Theme
|
||||
- ConfigProvider
|
||||
- FontLoader
|
||||
- ThemeProvider
|
||||
ConfigProvider
|
||||
FontLoader
|
||||
ThemeProvider
|
||||
@@ -1,52 +1,76 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
# LobeChat Cursor Rules System Guide
|
||||
|
||||
# 📋 Available Rules Index
|
||||
This document explains how the LobeChat project's Cursor rules system works and serves as an index for manually accessible rules.
|
||||
|
||||
## 🎯 Core Principle
|
||||
|
||||
**All rules are equal** - there are no priorities or "recommendations" between different rule sources. You should follow all applicable rules simultaneously.
|
||||
|
||||
## 📚 Four Ways to Access Rules
|
||||
|
||||
### 1. **Always Applied Rules** - `always_applied_workspace_rules`
|
||||
- **What**: Core project guidelines that are always active
|
||||
- **Content**: Project tech stack, basic coding standards, output formatting rules
|
||||
- **Access**: No tools needed - automatically provided in every conversation
|
||||
|
||||
### 2. **Dynamic Context Rules** - `cursor_rules_context`
|
||||
- **What**: Rules automatically matched based on files referenced in the conversation
|
||||
- **Trigger**: Only when user **explicitly @ mentions files** or **opens files in Cursor**
|
||||
- **Content**: May include brief descriptions or full rule content, depending on relevance
|
||||
- **Access**: No tools needed - automatically updated when files are referenced
|
||||
|
||||
### 3. **Agent Requestable Rules** - `agent_requestable_workspace_rules`
|
||||
- **What**: Detailed operational guides that can be requested on-demand
|
||||
- **Access**: Use `fetch_rules` tool with rule names
|
||||
- **Examples**: `debug`, `i18n/i18n`, `code-review`
|
||||
|
||||
### 4. **Manual Rules Index** - This file + `read_file`
|
||||
- **What**: Additional rules not covered by the above mechanisms
|
||||
- **Why needed**: Cursor's rule system only supports "agent request" or "auto attach" modes
|
||||
- **Access**: Use `read_file` tool to read specific `.mdc` files
|
||||
|
||||
## 🔧 When to Use `read_file` for Rules
|
||||
|
||||
Use `read_file` to access rules from the index below when:
|
||||
|
||||
1. **Gap identification**: You determine a rule is needed for the current task
|
||||
2. **No auto-trigger**: The rule isn't provided in `cursor_rules_context` (because relevant files weren't @ mentioned)
|
||||
3. **Not agent-requestable**: The rule isn't available via `fetch_rules`
|
||||
|
||||
## 📋 Available Rules Index
|
||||
|
||||
The following rules are available via `read_file` from the `.cursor/rules/` directory:
|
||||
|
||||
## General
|
||||
|
||||
- `project-introduce.mdc` – Project description and tech stack
|
||||
- `cursor-rules.mdc` – Cursor rules authoring and optimization guide
|
||||
- `code-review.mdc` – How to code review
|
||||
|
||||
## Backend
|
||||
|
||||
- `backend-architecture.mdc` – Backend layer architecture and design guidelines
|
||||
- `define-database-model.mdc` – Database model definition guidelines
|
||||
- `drizzle-schema-style-guide.mdc` – Style guide for defining Drizzle ORM schemas
|
||||
|
||||
## Frontend
|
||||
|
||||
- `react-component.mdc` – React component style guide and conventions
|
||||
- `i18n.mdc` – Internationalization guide using react-i18next
|
||||
- `typescript.mdc` – TypeScript code style guide
|
||||
- `packages/react-layout-kit.mdc` – Usage guide for react-layout-kit
|
||||
|
||||
## State Management
|
||||
|
||||
- `zustand-action-patterns.mdc` – Recommended patterns for organizing Zustand actions
|
||||
- `zustand-slice-organization.mdc` – Best practices for structuring Zustand slices
|
||||
- `drizzle-schema-style-guide.mdc` – Style guide for defining Drizzle ORM schemas
|
||||
- `react-component.mdc` – React component style guide and conventions
|
||||
|
||||
## Desktop (Electron)
|
||||
## ❌ Common Misunderstandings to Avoid
|
||||
|
||||
- `desktop-feature-implementation.mdc` – Implementing new Electron desktop features
|
||||
- `desktop-controller-tests.mdc` – Desktop controller unit testing guide
|
||||
- `desktop-local-tools-implement.mdc` – Workflow to add new desktop local tools
|
||||
- `desktop-menu-configuration.mdc` – Desktop menu configuration guide
|
||||
- `desktop-window-management.mdc` – Desktop window management guide
|
||||
1. **"Priority confusion"**: There's no hierarchy between rule sources - they're complementary, not competitive
|
||||
2. **"Dynamic expectations"**: `cursor_rules_context` only updates when you @ files - it won't automatically include rules for tasks you're thinking about
|
||||
3. **"Tool redundancy"**: Each access method serves a different purpose - they're not alternatives to choose from
|
||||
|
||||
## Debugging
|
||||
## 🛠️ Practical Workflow
|
||||
|
||||
- `debug.mdc` – General debugging guide
|
||||
- `debug-usage.mdc` – Using the debug package and namespace conventions
|
||||
```
|
||||
1. Start with always_applied_workspace_rules (automatic)
|
||||
2. Check cursor_rules_context for auto-matched rules (automatic)
|
||||
3. If you need specific guides: fetch_rules (manual)
|
||||
4. If you identify gaps: consult this index → read_file (manual)
|
||||
```
|
||||
|
||||
## Testing
|
||||
## Example Decision Flow
|
||||
|
||||
- `testing-guide/testing-guide.mdc` – Comprehensive testing guide for Vitest
|
||||
- `testing-guide/electron-ipc-test.mdc` – Electron IPC interface testing strategy
|
||||
- `testing-guide/db-model-test.mdc` – Database Model testing guide
|
||||
**Scenario**: Working on a new Zustand store slice
|
||||
1. Follow always_applied_workspace_rules ✅
|
||||
2. If store files were @ mentioned → use cursor_rules_context rules ✅
|
||||
3. Need detailed Zustand guidance → `read_file('.cursor/rules/zustand-slice-organization.mdc')` ✅
|
||||
4. All rules apply simultaneously - no conflicts ✅
|
||||
@@ -1,31 +1,38 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
## System Role
|
||||
|
||||
You are an expert in full-stack Web development, proficient in JavaScript, TypeScript, CSS, React, Node.js, Next.js, Postgresql, Redis, S3, all kinds of network protocols.
|
||||
You are an expert in full-stack Web development, proficient in JavaScript, TypeScript, CSS, React, Node.js, Next.js, Postgresql, all kinds of network protocols.
|
||||
|
||||
You are an LLM expert, you are familiar with all kinds of LLM models, ai agents, ai workflow, prompt engineering and context engineering.
|
||||
|
||||
You are an expert in Ai art. In Ai image generation, you are proficient in Stable Diffusion and ComfyUI's architectural principles, workflows, model structures, parameter configurations, training methods, and inference optimization.
|
||||
You are an expert in LLM and Ai art. In Ai image generation, you are proficient in Stable Diffusion and ComfyUI's architectural principles, workflows, model structures, parameter configurations, training methods, and inference optimization.
|
||||
|
||||
You are an expert in UI/UX design, proficient in web interaction patterns, responsive design, accessibility, and user behavior optimization. You excel at improving user retention and paid conversion rates through various interaction details.
|
||||
|
||||
|
||||
## Problem Solving
|
||||
|
||||
- Before formulating any response, you must first gather context by using tools like codebase_search, grep_search, file_search, web_search, fetch_rules, context7, and read_file to avoid making assumptions.
|
||||
- When modifying existing code, clearly describe the differences and reasons for the changes
|
||||
- Provide alternative solutions that may be better overall or superior in specific aspects
|
||||
- Provide optimization suggestions for deprecated API usage
|
||||
- Cite sources whenever possible at the end, not inline
|
||||
- When you provide multiple solutions, provide the recommended solution first, and note it as `Recommended`
|
||||
- Express uncertainty when there might not be a correct answer, instead of take action by guessing and assuming
|
||||
- Express uncertainty when there might not be a correct answer
|
||||
- Admit when you don't know something instead of guessing
|
||||
|
||||
## Code Implementation
|
||||
|
||||
- Write correct, up-to-date, bug-free, fully functional, secure, maintainable and efficient code
|
||||
- First, think step-by-step: describe your plan in detailed pseudocode before implementation
|
||||
- Confirm the plan before writing code
|
||||
- Focus on maintainable over being performant
|
||||
- Be sure to reference file path
|
||||
- If doc links or required files are missing, ask for them before proceeding with the task rather than making assumptions
|
||||
- If you're unable to get valid result when using tools, please clearly state in the output
|
||||
- Leave NO TODOs, placeholders, or missing pieces
|
||||
- Be sure to reference file names
|
||||
- When you notice I have manually modified the code, that was definitely on purpose and do not revert them
|
||||
- If documentation links or required files are missing, ask for them before proceeding with the task rather than making assumptions
|
||||
- If you're unable to access or retrieve content from websites, please inform me immediately and request the specific information needed rather than making assumptions
|
||||
- You can use emojis, npm packages like `chalk`/`chalk-animation`/`terminal-link`/`gradient-string`/`log-symbols`/`boxen`/`consola`/`@clack/prompts` to create beautiful terminal output
|
||||
- Don't run `tsc --noEmit` to check ts syntax error, because our project is very large and the validate very slow
|
||||
|
||||
@@ -0,0 +1,881 @@
|
||||
---
|
||||
description:
|
||||
globs: *.test.ts,*.test.tsx
|
||||
alwaysApply: false
|
||||
---
|
||||
---
|
||||
type: agent-requested
|
||||
title: 测试指南 - LobeChat Testing Guide
|
||||
description: LobeChat 项目的 Vitest 测试环境配置、运行方式、修复原则指南
|
||||
---
|
||||
|
||||
# 测试指南 - LobeChat Testing Guide
|
||||
|
||||
## 🧪 测试环境概览
|
||||
|
||||
LobeChat 项目使用 Vitest 测试库,配置了两种不同的测试环境:
|
||||
|
||||
### 客户端测试环境 (DOM Environment)
|
||||
|
||||
- **配置文件**: [vitest.config.ts](mdc:vitest.config.ts)
|
||||
- **环境**: Happy DOM (浏览器环境模拟)
|
||||
- **数据库**: PGLite (浏览器环境的 PostgreSQL)
|
||||
- **用途**: 测试前端组件、客户端逻辑、React 组件等
|
||||
- **设置文件**: [tests/setup.ts](mdc:tests/setup.ts)
|
||||
|
||||
### 服务端测试环境 (Node Environment)
|
||||
|
||||
- **配置文件**: [vitest.config.server.ts](mdc:vitest.config.server.ts)
|
||||
- **环境**: Node.js
|
||||
- **数据库**: 真实的 PostgreSQL 数据库
|
||||
- **并发限制**: 单线程运行 (`singleFork: true`)
|
||||
- **用途**: 测试数据库模型、服务端逻辑、API 端点等
|
||||
- **设置文件**: [tests/setup-db.ts](mdc:tests/setup-db.ts)
|
||||
|
||||
## 🚀 测试运行命令
|
||||
|
||||
### package.json 脚本说明
|
||||
|
||||
查看 [package.json](mdc:package.json) 中的测试相关脚本:
|
||||
|
||||
```json
|
||||
{
|
||||
"test": "npm run test-app && npm run test-server",
|
||||
"test-app": "vitest run --config vitest.config.ts",
|
||||
"test-app:coverage": "vitest run --config vitest.config.ts --coverage",
|
||||
"test-server": "vitest run --config vitest.config.server.ts",
|
||||
"test-server:coverage": "vitest run --config vitest.config.server.ts --coverage"
|
||||
}
|
||||
```
|
||||
|
||||
### 推荐的测试运行方式
|
||||
|
||||
#### ✅ 正确的命令格式
|
||||
|
||||
```bash
|
||||
# 运行所有客户端测试
|
||||
npx vitest run --config vitest.config.ts
|
||||
|
||||
# 运行所有服务端测试
|
||||
npx vitest run --config vitest.config.server.ts
|
||||
|
||||
# 运行特定测试文件 (支持模糊匹配)
|
||||
npx vitest run --config vitest.config.ts basic
|
||||
npx vitest run --config vitest.config.ts user.test.ts
|
||||
|
||||
# 运行特定文件的特定行号
|
||||
npx vitest run --config vitest.config.ts src/utils/helper.test.ts:25
|
||||
npx vitest run --config vitest.config.ts basic/foo.test.ts:10,basic/foo.test.ts:25
|
||||
|
||||
# 过滤特定测试用例名称
|
||||
npx vitest -t "test case name" --config vitest.config.ts
|
||||
|
||||
# 组合使用文件和测试名称过滤
|
||||
npx vitest run --config vitest.config.ts filename.test.ts -t "specific test"
|
||||
```
|
||||
|
||||
#### ❌ 避免的命令格式
|
||||
|
||||
```bash
|
||||
# ❌ 不要使用 pnpm test xxx (这不是有效的 vitest 命令)
|
||||
pnpm test some-file
|
||||
|
||||
# ❌ 不要使用裸 vitest (会进入 watch 模式)
|
||||
vitest test-file.test.ts
|
||||
|
||||
# ❌ 不要混淆测试环境
|
||||
npx vitest run --config vitest.config.server.ts client-component.test.ts
|
||||
```
|
||||
|
||||
### 关键运行参数说明
|
||||
|
||||
- **`vitest run`**: 运行一次测试然后退出 (避免 watch 模式)
|
||||
- **`vitest`**: 默认进入 watch 模式,持续监听文件变化
|
||||
- **`--config`**: 指定配置文件,选择正确的测试环境
|
||||
- **`-t`**: 过滤测试用例名称,支持正则表达式
|
||||
- **`--coverage`**: 生成测试覆盖率报告
|
||||
|
||||
## 🔧 测试修复原则
|
||||
|
||||
### 核心原则 ⚠️
|
||||
|
||||
1. **充分阅读测试代码**: 在修复测试之前,必须完整理解测试的意图和实现
|
||||
2. **测试优先修复**: 如果是测试本身写错了,修改测试而不是实现代码
|
||||
3. **专注单一问题**: 只修复指定的测试,不要添加额外测试或功能
|
||||
4. **不自作主张**: 不要因为发现其他问题就直接修改,先提出再讨论
|
||||
|
||||
### 测试修复流程
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph "阶段一:分析与复现"
|
||||
A[开始:收到测试失败报告] --> B[定位并运行失败的测试];
|
||||
B --> C{是否能在本地复现?};
|
||||
C -->|否| D[检查测试环境/配置/依赖];
|
||||
C -->|是| E[分析:阅读测试代码、错误日志、Git 历史];
|
||||
end
|
||||
|
||||
subgraph "阶段二:诊断与调试"
|
||||
E --> F[建立假设:问题出在测试、代码还是环境?];
|
||||
F --> G["调试:使用 console.log 或 debugger 深入检查"];
|
||||
G --> H{假设是否被证实?};
|
||||
H -->|否, 重新假设| F;
|
||||
end
|
||||
|
||||
subgraph "阶段三:修复与验证"
|
||||
H -->|是| I{确定根本原因};
|
||||
I -->|测试逻辑错误| J[修复测试代码];
|
||||
I -->|实现代码 Bug| K[修复实现代码];
|
||||
I -->|环境/配置问题| L[修复配置或依赖];
|
||||
J --> M[验证修复:重新运行失败的测试];
|
||||
K --> M;
|
||||
L --> M;
|
||||
M --> N{测试是否通过?};
|
||||
N -->|否, 修复无效| F;
|
||||
N -->|是| O[扩大验证:运行当前文件内所有测试];
|
||||
O --> P{是否全部通过?};
|
||||
P -->|否, 引入新问题| F;
|
||||
end
|
||||
|
||||
subgraph "阶段四:总结"
|
||||
P -->|是| Q[完成:撰写修复总结];
|
||||
end
|
||||
|
||||
D --> F;
|
||||
```
|
||||
|
||||
### 修复完成后的总结
|
||||
|
||||
测试修复完成后,应该提供简要说明,包括:
|
||||
|
||||
1. **错误原因分析**: 说明测试失败的根本原因
|
||||
- 测试逻辑错误
|
||||
- 实现代码bug
|
||||
- 环境配置问题
|
||||
- 依赖变更导致的问题
|
||||
|
||||
2. **修复方法说明**: 简述采用的修复方式
|
||||
- 修改了哪些文件
|
||||
- 采用了什么解决方案
|
||||
- 为什么选择这种修复方式
|
||||
|
||||
**示例格式**:
|
||||
|
||||
```markdown
|
||||
## 测试修复总结
|
||||
|
||||
**错误原因**: 测试中的 mock 数据格式与实际 API 返回格式不匹配,导致断言失败。
|
||||
|
||||
**修复方法**: 更新了测试文件中的 mock 数据结构,使其与最新的 API 响应格式保持一致。具体修改了 `user.test.ts` 中的 `mockUserData` 对象结构。
|
||||
```
|
||||
|
||||
## 📂 测试文件组织
|
||||
|
||||
### 文件命名约定
|
||||
|
||||
- **客户端测试**: `*.test.ts`, `*.test.tsx` (任意位置)
|
||||
- **服务端测试**: `src/database/models/**/*.test.ts`, `src/database/server/**/*.test.ts` (限定路径)
|
||||
|
||||
### 测试文件组织风格
|
||||
|
||||
项目采用 **测试文件与源文件同目录** 的组织风格:
|
||||
|
||||
- 测试文件放在对应源文件的同一目录下
|
||||
- 命名格式:`原文件名.test.ts` 或 `原文件名.test.tsx`
|
||||
|
||||
例如:
|
||||
|
||||
```
|
||||
src/components/Button/
|
||||
├── index.tsx # 源文件
|
||||
└── index.test.tsx # 测试文件
|
||||
```
|
||||
|
||||
## 🛠️ 测试调试技巧
|
||||
|
||||
### 运行失败测试的步骤
|
||||
|
||||
1. **确定测试类型**: 查看文件路径确定使用哪个配置
|
||||
2. **运行单个测试**: 使用 `-t` 参数隔离问题
|
||||
3. **检查错误日志**: 仔细阅读错误信息和堆栈跟踪
|
||||
4. **查看最近修改记录**: 检查相关文件的最近变更情况
|
||||
5. **添加调试日志**: 在测试中添加 `console.log` 了解执行流程
|
||||
|
||||
### Electron IPC 接口测试策略 🖥️
|
||||
|
||||
对于涉及 Electron IPC 接口的测试,由于提供真实的 Electron 环境比较复杂,采用 **Mock 返回值** 的方式进行测试。
|
||||
|
||||
#### 基本 Mock 设置
|
||||
|
||||
```typescript
|
||||
import { vi } from "vitest";
|
||||
import { electronIpcClient } from "@/server/modules/ElectronIPCClient";
|
||||
|
||||
// Mock Electron IPC 客户端
|
||||
vi.mock("@/server/modules/ElectronIPCClient", () => ({
|
||||
electronIpcClient: {
|
||||
getFilePathById: vi.fn(),
|
||||
deleteFiles: vi.fn(),
|
||||
// 根据需要添加其他 IPC 方法
|
||||
},
|
||||
}));
|
||||
```
|
||||
|
||||
#### 在测试中设置 Mock 行为
|
||||
|
||||
```typescript
|
||||
beforeEach(() => {
|
||||
// 重置所有 Mock
|
||||
vi.resetAllMocks();
|
||||
|
||||
// 设置默认的 Mock 返回值
|
||||
vi.mocked(electronIpcClient.getFilePathById).mockResolvedValue(
|
||||
"/path/to/file.txt"
|
||||
);
|
||||
vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({
|
||||
success: true,
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
#### 测试不同场景的示例
|
||||
|
||||
```typescript
|
||||
it("应该处理文件删除成功的情况", async () => {
|
||||
// 设置成功场景的 Mock
|
||||
vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({
|
||||
success: true,
|
||||
});
|
||||
|
||||
const result = await service.deleteFiles(["desktop://file1.txt"]);
|
||||
|
||||
expect(electronIpcClient.deleteFiles).toHaveBeenCalledWith([
|
||||
"desktop://file1.txt",
|
||||
]);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("应该处理文件删除失败的情况", async () => {
|
||||
// 设置失败场景的 Mock
|
||||
vi.mocked(electronIpcClient.deleteFiles).mockRejectedValue(
|
||||
new Error("删除失败")
|
||||
);
|
||||
|
||||
const result = await service.deleteFiles(["desktop://file1.txt"]);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.errors).toBeDefined();
|
||||
});
|
||||
```
|
||||
|
||||
#### Mock 策略的优势
|
||||
|
||||
1. **环境简化**: 避免了复杂的 Electron 环境搭建
|
||||
2. **测试可控**: 可以精确控制 IPC 调用的返回值和行为
|
||||
3. **场景覆盖**: 容易测试各种成功/失败场景
|
||||
4. **执行速度**: Mock 调用比真实 IPC 调用更快
|
||||
|
||||
#### 注意事项
|
||||
|
||||
- **Mock 准确性**: 确保 Mock 的行为与真实 IPC 接口行为一致
|
||||
- **类型安全**: 使用 `vi.mocked()` 确保类型安全
|
||||
- **Mock 重置**: 在 `beforeEach` 中重置 Mock 状态,避免测试间干扰
|
||||
- **调用验证**: 不仅要验证返回值,还要验证 IPC 方法是否被正确调用
|
||||
|
||||
### 检查最近修改记录 🔍
|
||||
|
||||
为了更好地判断测试失败的根本原因,需要**系统性地检查相关文件的修改历史**。这是问题定位的关键步骤。
|
||||
|
||||
#### 第一步:确定需要检查的文件范围
|
||||
|
||||
1. **测试文件本身**: `path/to/component.test.ts`
|
||||
2. **对应的实现文件**: `path/to/component.ts` 或 `path/to/component/index.ts`
|
||||
3. **相关依赖文件**: 测试或实现中导入的其他模块
|
||||
|
||||
#### 第二步:检查当前工作目录状态
|
||||
|
||||
```bash
|
||||
# 查看所有未提交的修改状态
|
||||
git status
|
||||
|
||||
# 重点关注测试文件和实现文件是否有未提交的修改
|
||||
git status | grep -E "(test|spec)"
|
||||
```
|
||||
|
||||
#### 第三步:检查未提交的修改内容
|
||||
|
||||
```bash
|
||||
# 查看测试文件的未提交修改 (工作区 vs 暂存区)
|
||||
git diff path/to/component.test.ts | cat
|
||||
|
||||
# 查看对应实现文件的未提交修改
|
||||
git diff path/to/component.ts | cat
|
||||
|
||||
# 查看已暂存但未提交的修改
|
||||
git diff --cached path/to/component.test.ts | cat
|
||||
git diff --cached path/to/component.ts | cat
|
||||
```
|
||||
|
||||
#### 第四步:检查提交历史和时间相关性
|
||||
|
||||
**首先查看提交时间,判断修改的时效性**:
|
||||
|
||||
```bash
|
||||
# 查看测试文件的最近提交历史,包含提交时间
|
||||
git log --pretty=format:"%h %ad %s" --date=relative -5 path/to/component.test.ts | cat
|
||||
|
||||
# 查看实现文件的最近提交历史,包含提交时间
|
||||
git log --pretty=format:"%h %ad %s" --date=relative -5 path/to/component.ts | cat
|
||||
|
||||
# 查看详细的提交时间(ISO格式,便于精确判断)
|
||||
git log --pretty=format:"%h %ad %an %s" --date=iso -3 path/to/component.ts | cat
|
||||
git log --pretty=format:"%h %ad %an %s" --date=iso -3 path/to/component.test.ts | cat
|
||||
```
|
||||
|
||||
**判断提交的参考价值**:
|
||||
|
||||
1. **最近提交(24小时内)**: 🔴 **高度相关** - 很可能是导致测试失败的直接原因
|
||||
2. **近期提交(1-7天内)**: 🟡 **中等相关** - 可能相关,需要仔细分析修改内容
|
||||
3. **较早提交(超过1周)**: ⚪ **低相关性** - 除非是重大重构,否则不太可能是直接原因
|
||||
|
||||
#### 第五步:基于时间相关性查看具体修改内容
|
||||
|
||||
**根据提交时间的远近,优先查看最近的修改**:
|
||||
|
||||
```bash
|
||||
# 如果有24小时内的提交,重点查看这些修改
|
||||
git show HEAD -- path/to/component.test.ts | cat
|
||||
git show HEAD -- path/to/component.ts | cat
|
||||
|
||||
# 查看次新的提交(如果最新提交时间较远)
|
||||
git show HEAD~1 -- path/to/component.ts | cat
|
||||
git show <recent-commit-hash> -- path/to/component.ts | cat
|
||||
|
||||
# 对比最近两次提交的差异
|
||||
git diff HEAD~1 HEAD -- path/to/component.ts | cat
|
||||
```
|
||||
|
||||
#### 第六步:分析修改与测试失败的关系
|
||||
|
||||
基于修改记录和时间相关性判断:
|
||||
|
||||
1. **最近修改了实现代码**:
|
||||
|
||||
```bash
|
||||
# 重点检查实现逻辑的变化
|
||||
git diff HEAD~1 path/to/component.ts | cat
|
||||
```
|
||||
|
||||
- 很可能是实现代码的变更导致测试失败
|
||||
- 检查实现逻辑是否正确
|
||||
- 确认测试是否需要相应更新
|
||||
|
||||
2. **最近修改了测试代码**:
|
||||
|
||||
```bash
|
||||
# 重点检查测试逻辑的变化
|
||||
git diff HEAD~1 path/to/component.test.ts | cat
|
||||
```
|
||||
|
||||
- 可能是测试本身写错了
|
||||
- 检查测试逻辑和断言是否正确
|
||||
- 确认测试是否符合实现的预期行为
|
||||
|
||||
3. **两者都有最近修改**:
|
||||
|
||||
```bash
|
||||
# 对比两个文件的修改时间
|
||||
git log --pretty=format:"%ad %f" --date=iso -1 path/to/component.ts | cat
|
||||
git log --pretty=format:"%ad %f" --date=iso -1 path/to/component.test.ts | cat
|
||||
```
|
||||
|
||||
- 需要综合分析两者的修改
|
||||
- 确定哪个修改更可能导致问题
|
||||
- 优先检查时间更近的修改
|
||||
|
||||
4. **都没有最近修改**:
|
||||
- 可能是依赖变更或环境问题
|
||||
- 检查 `package.json`、配置文件等的修改
|
||||
- 查看是否有全局性的代码重构
|
||||
|
||||
#### 修改记录检查示例
|
||||
|
||||
```bash
|
||||
# 完整的检查流程示例
|
||||
echo "=== 检查文件修改状态 ==="
|
||||
git status | grep component
|
||||
|
||||
echo "=== 检查未提交修改 ==="
|
||||
git diff src/components/Button/index.test.tsx | cat
|
||||
git diff src/components/Button/index.tsx | cat
|
||||
|
||||
echo "=== 检查提交历史和时间 ==="
|
||||
git log --pretty=format:"%h %ad %s" --date=relative -3 src/components/Button/index.test.tsx | cat
|
||||
git log --pretty=format:"%h %ad %s" --date=relative -3 src/components/Button/index.tsx | cat
|
||||
|
||||
echo "=== 根据时间优先级查看修改内容 ==="
|
||||
# 如果有24小时内的提交,重点查看
|
||||
git show HEAD -- src/components/Button/index.tsx | cat
|
||||
```
|
||||
|
||||
## 🗃️ 数据库 Model 测试指南
|
||||
|
||||
### 测试环境选择 💡
|
||||
|
||||
数据库 Model 层通过环境变量控制数据库类型,在两种测试环境下有不同的数据库后端:客户端环境 (PGLite) 和 服务端环境 (PostgreSQL)
|
||||
|
||||
### ⚠️ 双环境验证要求
|
||||
|
||||
**对于所有 Model 测试,必须在两个环境下都验证通过**:
|
||||
|
||||
#### 完整验证流程
|
||||
|
||||
```bash
|
||||
# 1. 先在客户端环境测试(快速验证)
|
||||
npx vitest run --config vitest.config.ts src/database/models/__tests__/myModel.test.ts
|
||||
|
||||
# 2. 再在服务端环境测试(兼容性验证)
|
||||
npx vitest run --config vitest.config.server.ts src/database/models/__tests__/myModel.test.ts
|
||||
```
|
||||
|
||||
### 创建新 Model 测试的最佳实践 📋
|
||||
|
||||
#### 1. 参考现有实现和测试模板
|
||||
|
||||
创建新 Model 测试前,**必须先参考现有的实现模式**:
|
||||
|
||||
- **Model 实现参考**:
|
||||
- **测试模板参考**:
|
||||
- **复杂示例参考**:
|
||||
|
||||
#### 2. 用户权限检查 - 安全第一 🔒
|
||||
|
||||
这是**最关键的安全要求**。所有涉及用户数据的操作都必须包含用户权限检查:
|
||||
|
||||
**❌ 错误示例 - 存在安全漏洞**:
|
||||
|
||||
```typescript
|
||||
// 危险:缺少用户权限检查,任何用户都能操作任何数据
|
||||
update = async (id: string, data: Partial<MyModel>) => {
|
||||
return this.db
|
||||
.update(myTable)
|
||||
.set(data)
|
||||
.where(eq(myTable.id, id)) // ❌ 只检查 ID,没有检查 userId
|
||||
.returning();
|
||||
};
|
||||
```
|
||||
|
||||
**✅ 正确示例 - 安全的实现**:
|
||||
|
||||
```typescript
|
||||
// 安全:必须同时匹配 ID 和 userId
|
||||
update = async (id: string, data: Partial<MyModel>) => {
|
||||
return this.db
|
||||
.update(myTable)
|
||||
.set(data)
|
||||
.where(
|
||||
and(
|
||||
eq(myTable.id, id),
|
||||
eq(myTable.userId, this.userId) // ✅ 用户权限检查
|
||||
)
|
||||
)
|
||||
.returning();
|
||||
};
|
||||
```
|
||||
|
||||
**必须进行用户权限检查的方法**:
|
||||
|
||||
- `update()` - 更新操作
|
||||
- `delete()` - 删除操作
|
||||
- `findById()` - 查找特定记录
|
||||
- 任何涉及特定记录的查询或修改操作
|
||||
|
||||
#### 3. 测试文件结构和必测场景
|
||||
|
||||
**基本测试结构**:
|
||||
|
||||
```typescript
|
||||
// @vitest-environment node
|
||||
describe("MyModel", () => {
|
||||
describe("create", () => {
|
||||
it("should create a new record");
|
||||
it("should handle edge cases");
|
||||
});
|
||||
|
||||
describe("queryAll", () => {
|
||||
it("should return records for current user only");
|
||||
it("should handle empty results");
|
||||
});
|
||||
|
||||
describe("update", () => {
|
||||
it("should update own records");
|
||||
it("should NOT update other users records"); // 🔒 安全测试
|
||||
});
|
||||
|
||||
describe("delete", () => {
|
||||
it("should delete own records");
|
||||
it("should NOT delete other users records"); // 🔒 安全测试
|
||||
});
|
||||
|
||||
describe("user isolation", () => {
|
||||
it("should enforce user data isolation"); // 🔒 核心安全测试
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
**必须测试的安全场景** 🔒:
|
||||
|
||||
```typescript
|
||||
it("should not update records of other users", async () => {
|
||||
// 创建其他用户的记录
|
||||
const [otherUserRecord] = await serverDB
|
||||
.insert(myTable)
|
||||
.values({ userId: "other-user", data: "original" })
|
||||
.returning();
|
||||
|
||||
// 尝试更新其他用户的记录
|
||||
const result = await myModel.update(otherUserRecord.id, { data: "hacked" });
|
||||
|
||||
// 应该返回 undefined 或空数组(因为权限检查失败)
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
// 验证原始数据未被修改
|
||||
const unchanged = await serverDB.query.myTable.findFirst({
|
||||
where: eq(myTable.id, otherUserRecord.id),
|
||||
});
|
||||
expect(unchanged?.data).toBe("original"); // 数据应该保持不变
|
||||
});
|
||||
```
|
||||
|
||||
#### 4. Mock 外部依赖服务
|
||||
|
||||
如果 Model 依赖外部服务(如 FileService),需要正确 Mock:
|
||||
|
||||
**设置 Mock**:
|
||||
|
||||
```typescript
|
||||
// 在文件顶部设置 Mock
|
||||
const mockGetFullFileUrl = vi.fn();
|
||||
vi.mock("@/server/services/file", () => ({
|
||||
FileService: vi.fn().mockImplementation(() => ({
|
||||
getFullFileUrl: mockGetFullFileUrl,
|
||||
})),
|
||||
}));
|
||||
|
||||
// 在 beforeEach 中重置和配置 Mock
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
mockGetFullFileUrl.mockImplementation(
|
||||
(url: string) => `https://example.com/${url}`
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
**验证 Mock 调用**:
|
||||
|
||||
```typescript
|
||||
it("should process URLs through FileService", async () => {
|
||||
// ... 测试逻辑
|
||||
|
||||
// 验证 Mock 被正确调用
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledWith("expected-url");
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
```
|
||||
|
||||
#### 5. 数据库状态管理
|
||||
|
||||
**正确的数据清理模式**:
|
||||
|
||||
```typescript
|
||||
const userId = "test-user";
|
||||
const otherUserId = "other-user";
|
||||
|
||||
beforeEach(async () => {
|
||||
// 清理用户表(级联删除相关数据)
|
||||
await serverDB.delete(users);
|
||||
|
||||
// 创建测试用户
|
||||
await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// 清理测试数据
|
||||
await serverDB.delete(users);
|
||||
});
|
||||
```
|
||||
|
||||
#### 6. 测试数据类型和外键约束处理 ⚠️
|
||||
|
||||
**必须使用 Schema 导出的类型**:
|
||||
|
||||
```typescript
|
||||
// ✅ 正确:使用 schema 导出的类型
|
||||
import { NewGenerationBatch, NewGeneration } from '../../schemas';
|
||||
|
||||
const testBatch: NewGenerationBatch = {
|
||||
userId,
|
||||
generationTopicId: 'test-topic-id',
|
||||
provider: 'test-provider',
|
||||
model: 'test-model',
|
||||
prompt: 'Test prompt for image generation',
|
||||
width: 1024,
|
||||
height: 1024,
|
||||
config: { /* ... */ },
|
||||
};
|
||||
|
||||
const testGeneration: NewGeneration = {
|
||||
id: 'test-gen-id',
|
||||
generationBatchId: 'test-batch-id',
|
||||
asyncTaskId: null, // 处理外键约束
|
||||
fileId: null, // 处理外键约束
|
||||
seed: 12345,
|
||||
userId,
|
||||
};
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:没有类型声明或使用错误类型
|
||||
const testBatch = { // 缺少类型声明
|
||||
generationTopicId: 'test-topic-id',
|
||||
// ...
|
||||
};
|
||||
|
||||
const testGeneration = { // 缺少类型声明
|
||||
asyncTaskId: 'invalid-uuid', // 外键约束错误
|
||||
fileId: 'non-existent-file', // 外键约束错误
|
||||
// ...
|
||||
};
|
||||
```
|
||||
|
||||
**外键约束处理策略**:
|
||||
|
||||
1. **使用 null 值**: 对于可选的外键字段,使用 null 避免约束错误
|
||||
2. **创建关联记录**: 如果需要测试关联关系,先创建被引用的记录
|
||||
3. **理解约束关系**: 了解哪些字段有外键约束,避免引用不存在的记录
|
||||
|
||||
```typescript
|
||||
// 外键约束处理示例
|
||||
beforeEach(async () => {
|
||||
// 清理数据库
|
||||
await serverDB.delete(users);
|
||||
|
||||
// 创建测试用户
|
||||
await serverDB.insert(users).values([{ id: userId }]);
|
||||
|
||||
// 如果需要测试文件关联,创建文件记录
|
||||
if (needsFileAssociation) {
|
||||
await serverDB.insert(files).values({
|
||||
id: 'test-file-id',
|
||||
userId,
|
||||
name: 'test.jpg',
|
||||
url: 'test-url',
|
||||
size: 1024,
|
||||
fileType: 'image/jpeg',
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**排序测试的可预测性**:
|
||||
|
||||
```typescript
|
||||
// ✅ 正确:使用明确的时间戳确保排序结果可预测
|
||||
it('should find batches by topic id in correct order', async () => {
|
||||
const oldDate = new Date('2024-01-01T10:00:00Z');
|
||||
const newDate = new Date('2024-01-02T10:00:00Z');
|
||||
|
||||
const batch1 = { ...testBatch, prompt: 'First batch', userId, createdAt: oldDate };
|
||||
const batch2 = { ...testBatch, prompt: 'Second batch', userId, createdAt: newDate };
|
||||
|
||||
await serverDB.insert(generationBatches).values([batch1, batch2]);
|
||||
|
||||
const results = await generationBatchModel.findByTopicId(testTopic.id);
|
||||
|
||||
expect(results[0].prompt).toBe('Second batch'); // 最新优先 (desc order)
|
||||
expect(results[1].prompt).toBe('First batch');
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:依赖数据库的默认时间戳,结果不可预测
|
||||
it('should find batches by topic id', async () => {
|
||||
const batch1 = { ...testBatch, prompt: 'First batch', userId };
|
||||
const batch2 = { ...testBatch, prompt: 'Second batch', userId };
|
||||
|
||||
await serverDB.insert(generationBatches).values([batch1, batch2]);
|
||||
|
||||
// 插入顺序和数据库时间戳可能不一致,导致测试不稳定
|
||||
const results = await generationBatchModel.findByTopicId(testTopic.id);
|
||||
expect(results[0].prompt).toBe('Second batch'); // 可能失败
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
|
||||
### 常见问题和解决方案 💡
|
||||
|
||||
#### 问题 1:权限检查缺失导致安全漏洞
|
||||
|
||||
**现象**: 测试失败,用户能修改其他用户的数据
|
||||
**解决**: 在 Model 的 `update` 和 `delete` 方法中添加 `and(eq(table.id, id), eq(table.userId, this.userId))`
|
||||
|
||||
#### 问题 2:Mock 未生效或验证失败
|
||||
|
||||
**现象**: `undefined is not a spy` 错误
|
||||
**解决**: 检查 Mock 设置位置和方式,确保在测试文件顶部设置,在 `beforeEach` 中重置
|
||||
|
||||
#### 问题 3:测试数据污染
|
||||
|
||||
**现象**: 测试间相互影响,结果不稳定
|
||||
**解决**: 在 `beforeEach` 和 `afterEach` 中正确清理数据库状态
|
||||
|
||||
#### 问题 4:外部依赖导致测试失败
|
||||
|
||||
**现象**: 因为真实的外部服务调用导致测试不稳定
|
||||
**解决**: Mock 所有外部依赖,使测试更可控和快速
|
||||
|
||||
#### 问题 5:外键约束违反导致测试失败
|
||||
|
||||
**现象**: `insert or update on table "xxx" violates foreign key constraint`
|
||||
**解决**:
|
||||
- 将可选外键字段设为 `null` 而不是无效的字符串值
|
||||
- 或者先创建被引用的记录,再创建当前记录
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:无效的外键值
|
||||
const testData = {
|
||||
asyncTaskId: 'invalid-uuid', // 表中不存在此记录
|
||||
fileId: 'non-existent-file', // 表中不存在此记录
|
||||
};
|
||||
|
||||
// ✅ 正确:使用 null 值
|
||||
const testData = {
|
||||
asyncTaskId: null, // 避免外键约束
|
||||
fileId: null, // 避免外键约束
|
||||
};
|
||||
|
||||
// ✅ 或者:先创建被引用的记录
|
||||
beforeEach(async () => {
|
||||
const [asyncTask] = await serverDB.insert(asyncTasks).values({
|
||||
id: 'valid-task-id',
|
||||
status: 'pending',
|
||||
type: 'generation',
|
||||
}).returning();
|
||||
|
||||
const testData = {
|
||||
asyncTaskId: asyncTask.id, // 使用有效的外键值
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
#### 问题 6:排序测试结果不一致
|
||||
|
||||
**现象**: 相同的测试有时通过,有时失败,特别是涉及排序的测试
|
||||
**解决**: 使用明确的时间戳,不要依赖数据库的默认时间戳
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:依赖插入顺序和默认时间戳
|
||||
await serverDB.insert(table).values([data1, data2]); // 时间戳不可预测
|
||||
|
||||
// ✅ 正确:明确指定时间戳
|
||||
const oldDate = new Date('2024-01-01T10:00:00Z');
|
||||
const newDate = new Date('2024-01-02T10:00:00Z');
|
||||
await serverDB.insert(table).values([
|
||||
{ ...data1, createdAt: oldDate },
|
||||
{ ...data2, createdAt: newDate },
|
||||
]);
|
||||
```
|
||||
|
||||
#### 问题 7:Mock 验证失败或调用次数不匹配
|
||||
|
||||
**现象**: `expect(mockFunction).toHaveBeenCalledWith(...)` 失败
|
||||
**解决**:
|
||||
- 检查 Mock 函数的实际调用参数和期望参数是否完全匹配
|
||||
- 确认 Mock 在正确的时机被重置和配置
|
||||
- 使用 `toHaveBeenCalledTimes()` 验证调用次数
|
||||
|
||||
```typescript
|
||||
// 在 beforeEach 中正确配置 Mock
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks(); // 重置所有 Mock
|
||||
|
||||
mockGetFullFileUrl.mockImplementation((url: string) => `https://example.com/${url}`);
|
||||
mockTransformGeneration.mockResolvedValue({
|
||||
id: 'test-id',
|
||||
// ... 其他字段
|
||||
});
|
||||
});
|
||||
|
||||
// 测试中验证 Mock 调用
|
||||
it('should call FileService with correct parameters', async () => {
|
||||
await model.someMethod();
|
||||
|
||||
// 验证调用参数
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledWith('expected-url');
|
||||
// 验证调用次数
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
```
|
||||
|
||||
### Model 测试检查清单 ✅
|
||||
|
||||
创建 Model 测试时,请确保以下各项都已完成:
|
||||
|
||||
#### 🔧 基础配置
|
||||
- [ ] **双环境验证** - 在客户端环境 (vitest.config.ts) 和服务端环境 (vitest.config.server.ts) 下都测试通过
|
||||
- [ ] 参考了 `_template.ts` 和现有 Model 的实现模式
|
||||
- [ ] **使用正确的 Schema 类型** - 测试数据使用 `NewXxx` 类型声明,如 `NewGenerationBatch`、`NewGeneration`
|
||||
|
||||
#### 🔒 安全测试
|
||||
- [ ] **所有涉及用户数据的操作都包含用户权限检查**
|
||||
- [ ] 包含了用户权限隔离的安全测试
|
||||
- [ ] 测试了用户无法访问其他用户数据的场景
|
||||
|
||||
#### 🗃️ 数据处理
|
||||
- [ ] **正确处理外键约束** - 使用 `null` 值或先创建被引用记录
|
||||
- [ ] **排序测试使用明确时间戳** - 不依赖数据库默认时间,确保结果可预测
|
||||
- [ ] 在 `beforeEach` 和 `afterEach` 中正确管理数据库状态
|
||||
- [ ] 所有测试都能独立运行且互不干扰
|
||||
|
||||
#### 🎭 Mock 和外部依赖
|
||||
- [ ] 正确 Mock 了外部依赖服务 (如 FileService、GenerationModel)
|
||||
- [ ] 在 `beforeEach` 中重置和配置 Mock
|
||||
- [ ] 验证了 Mock 服务的调用参数和次数
|
||||
- [ ] 测试了外部服务错误场景的处理
|
||||
|
||||
#### 📋 测试覆盖
|
||||
- [ ] 测试覆盖了所有主要方法 (create, query, update, delete)
|
||||
- [ ] 测试了边界条件和错误场景
|
||||
- [ ] 包含了空结果处理的测试
|
||||
- [ ] **确认两个环境下的测试结果一致**
|
||||
|
||||
#### 🚨 常见问题检查
|
||||
- [ ] 没有外键约束违反错误
|
||||
- [ ] 排序测试结果稳定可预测
|
||||
- [ ] Mock 验证无失败
|
||||
- [ ] 无测试数据污染问题
|
||||
|
||||
### 安全警告 ⚠️
|
||||
|
||||
**数据库 Model 层是安全的第一道防线**。如果 Model 层缺少用户权限检查:
|
||||
|
||||
1. **任何用户都能访问和修改其他用户的数据**
|
||||
2. **即使上层有权限检查,也可能被绕过**
|
||||
3. **可能导致严重的数据泄露和安全事故**
|
||||
|
||||
因此,**每个涉及用户数据的 Model 方法都必须包含用户权限检查,且必须有对应的安全测试来验证这些检查的有效性**。
|
||||
|
||||
## 🎯 总结
|
||||
|
||||
修复测试时,记住以下关键点:
|
||||
|
||||
- **使用正确的命令**: `npx vitest run --config [config-file]`
|
||||
- **理解测试意图**: 先读懂测试再修复
|
||||
- **查看最近修改**: 检查相关文件的 git 修改记录,判断问题根源
|
||||
- **选择正确环境**: 客户端测试用 `vitest.config.ts`,服务端用 `vitest.config.server.ts`
|
||||
- **专注单一问题**: 只修复当前的测试失败
|
||||
- **验证修复结果**: 确保修复后测试通过且无副作用
|
||||
- **提供修复总结**: 说明错误原因和修复方法
|
||||
- **Model 测试安全第一**: 必须包含用户权限检查和对应的安全测试
|
||||
- **Model 双环境验证**: 必须在 PGLite 和 PostgreSQL 两个环境下都验证通过
|
||||
@@ -1,455 +0,0 @@
|
||||
---
|
||||
globs: src/database/**/*.test.ts
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
## 🗃️ 数据库 Model 测试指南
|
||||
|
||||
测试 `packages/database` 下的数据库 Model 层。
|
||||
|
||||
### 测试环境选择 💡
|
||||
|
||||
数据库 Model 层通过环境变量控制数据库类型,在两种测试环境下有不同的数据库后端:客户端环境 (PGLite) 和 服务端环境 (PostgreSQL)
|
||||
|
||||
### ⚠️ 双环境验证要求
|
||||
|
||||
**对于所有 Model 测试,必须在两个环境下都验证通过**:
|
||||
|
||||
#### 完整验证流程
|
||||
|
||||
```bash
|
||||
# 1. 先在客户端环境测试(快速验证)
|
||||
cd packages/database && TEST_SERVER_DB=0 bunx vitest run --silent='passed-only' src/database/models/__tests__/myModel.test.ts
|
||||
|
||||
# 2. 再在服务端环境测试(兼容性验证), 需要设置环境变量 `TEST_SERVER_DB=1`
|
||||
cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only' src/database/models/__tests__/myModel.test.ts #
|
||||
```
|
||||
|
||||
### 创建新 Model 测试的最佳实践 📋
|
||||
|
||||
#### 1. 参考现有实现和测试模板
|
||||
|
||||
创建新 Model 测试前,**必须先参考现有的实现模式**:
|
||||
|
||||
- **Model 实现参考**:
|
||||
- **测试模板参考**:
|
||||
- **复杂示例参考**:
|
||||
|
||||
#### 2. 用户权限检查 - 安全第一 🔒
|
||||
|
||||
这是**最关键的安全要求**。所有涉及用户数据的操作都必须包含用户权限检查:
|
||||
|
||||
**❌ 错误示例 - 存在安全漏洞**:
|
||||
|
||||
```typescript
|
||||
// 危险:缺少用户权限检查,任何用户都能操作任何数据
|
||||
update = async (id: string, data: Partial<MyModel>) => {
|
||||
return this.db
|
||||
.update(myTable)
|
||||
.set(data)
|
||||
.where(eq(myTable.id, id)) // ❌ 只检查 ID,没有检查 userId
|
||||
.returning();
|
||||
};
|
||||
```
|
||||
|
||||
**✅ 正确示例 - 安全的实现**:
|
||||
|
||||
```typescript
|
||||
// 安全:必须同时匹配 ID 和 userId
|
||||
update = async (id: string, data: Partial<MyModel>) => {
|
||||
return this.db
|
||||
.update(myTable)
|
||||
.set(data)
|
||||
.where(
|
||||
and(
|
||||
eq(myTable.id, id),
|
||||
eq(myTable.userId, this.userId), // ✅ 用户权限检查
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
};
|
||||
```
|
||||
|
||||
**必须进行用户权限检查的方法**:
|
||||
|
||||
- `update()` - 更新操作
|
||||
- `delete()` - 删除操作
|
||||
- `findById()` - 查找特定记录
|
||||
- 任何涉及特定记录的查询或修改操作
|
||||
|
||||
#### 3. 测试文件结构和必测场景
|
||||
|
||||
**基本测试结构**:
|
||||
|
||||
```typescript
|
||||
// @vitest-environment node
|
||||
describe('MyModel', () => {
|
||||
describe('create', () => {
|
||||
it('should create a new record');
|
||||
it('should handle edge cases');
|
||||
});
|
||||
|
||||
describe('queryAll', () => {
|
||||
it('should return records for current user only');
|
||||
it('should handle empty results');
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('should update own records');
|
||||
it('should NOT update other users records'); // 🔒 安全测试
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('should delete own records');
|
||||
it('should NOT delete other users records'); // 🔒 安全测试
|
||||
});
|
||||
|
||||
describe('user isolation', () => {
|
||||
it('should enforce user data isolation'); // 🔒 核心安全测试
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
**必须测试的安全场景** 🔒:
|
||||
|
||||
```typescript
|
||||
it('should not update records of other users', async () => {
|
||||
// 创建其他用户的记录
|
||||
const [otherUserRecord] = await serverDB
|
||||
.insert(myTable)
|
||||
.values({ userId: 'other-user', data: 'original' })
|
||||
.returning();
|
||||
|
||||
// 尝试更新其他用户的记录
|
||||
const result = await myModel.update(otherUserRecord.id, { data: 'hacked' });
|
||||
|
||||
// 应该返回 undefined 或空数组(因为权限检查失败)
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
// 验证原始数据未被修改
|
||||
const unchanged = await serverDB.query.myTable.findFirst({
|
||||
where: eq(myTable.id, otherUserRecord.id),
|
||||
});
|
||||
expect(unchanged?.data).toBe('original'); // 数据应该保持不变
|
||||
});
|
||||
```
|
||||
|
||||
#### 4. Mock 外部依赖服务
|
||||
|
||||
如果 Model 依赖外部服务(如 FileService),需要正确 Mock:
|
||||
|
||||
**设置 Mock**:
|
||||
|
||||
```typescript
|
||||
// 在文件顶部设置 Mock
|
||||
const mockGetFullFileUrl = vi.fn();
|
||||
vi.mock('@/server/services/file', () => ({
|
||||
FileService: vi.fn().mockImplementation(() => ({
|
||||
getFullFileUrl: mockGetFullFileUrl,
|
||||
})),
|
||||
}));
|
||||
|
||||
// 在 beforeEach 中重置和配置 Mock
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
mockGetFullFileUrl.mockImplementation((url: string) => `https://example.com/${url}`);
|
||||
});
|
||||
```
|
||||
|
||||
**验证 Mock 调用**:
|
||||
|
||||
```typescript
|
||||
it('should process URLs through FileService', async () => {
|
||||
// ... 测试逻辑
|
||||
|
||||
// 验证 Mock 被正确调用
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledWith('expected-url');
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
```
|
||||
|
||||
#### 5. 数据库状态管理
|
||||
|
||||
**正确的数据清理模式**:
|
||||
|
||||
```typescript
|
||||
const userId = 'test-user';
|
||||
const otherUserId = 'other-user';
|
||||
|
||||
beforeEach(async () => {
|
||||
// 清理用户表(级联删除相关数据)
|
||||
await serverDB.delete(users);
|
||||
|
||||
// 创建测试用户
|
||||
await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// 清理测试数据
|
||||
await serverDB.delete(users);
|
||||
});
|
||||
```
|
||||
|
||||
#### 6. 测试数据类型和外键约束处理 ⚠️
|
||||
|
||||
**必须使用 Schema 导出的类型**:
|
||||
|
||||
```typescript
|
||||
// ✅ 正确:使用 schema 导出的类型
|
||||
import { NewGeneration, NewGenerationBatch } from '../../schemas';
|
||||
|
||||
const testBatch: NewGenerationBatch = {
|
||||
userId,
|
||||
generationTopicId: 'test-topic-id',
|
||||
provider: 'test-provider',
|
||||
model: 'test-model',
|
||||
prompt: 'Test prompt for image generation',
|
||||
width: 1024,
|
||||
height: 1024,
|
||||
config: {
|
||||
/* ... */
|
||||
},
|
||||
};
|
||||
|
||||
const testGeneration: NewGeneration = {
|
||||
id: 'test-gen-id',
|
||||
generationBatchId: 'test-batch-id',
|
||||
asyncTaskId: null, // 处理外键约束
|
||||
fileId: null, // 处理外键约束
|
||||
seed: 12345,
|
||||
userId,
|
||||
};
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:没有类型声明或使用错误类型
|
||||
const testBatch = {
|
||||
// 缺少类型声明
|
||||
generationTopicId: 'test-topic-id',
|
||||
// ...
|
||||
};
|
||||
|
||||
const testGeneration = {
|
||||
// 缺少类型声明
|
||||
asyncTaskId: 'invalid-uuid', // 外键约束错误
|
||||
fileId: 'non-existent-file', // 外键约束错误
|
||||
// ...
|
||||
};
|
||||
```
|
||||
|
||||
**外键约束处理策略**:
|
||||
|
||||
1. **使用 null 值**: 对于可选的外键字段,使用 null 避免约束错误
|
||||
2. **创建关联记录**: 如果需要测试关联关系,先创建被引用的记录
|
||||
3. **理解约束关系**: 了解哪些字段有外键约束,避免引用不存在的记录
|
||||
|
||||
```typescript
|
||||
// 外键约束处理示例
|
||||
beforeEach(async () => {
|
||||
// 清理数据库
|
||||
await serverDB.delete(users);
|
||||
|
||||
// 创建测试用户
|
||||
await serverDB.insert(users).values([{ id: userId }]);
|
||||
|
||||
// 如果需要测试文件关联,创建文件记录
|
||||
if (needsFileAssociation) {
|
||||
await serverDB.insert(files).values({
|
||||
id: 'test-file-id',
|
||||
userId,
|
||||
name: 'test.jpg',
|
||||
url: 'test-url',
|
||||
size: 1024,
|
||||
fileType: 'image/jpeg',
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**排序测试的可预测性**:
|
||||
|
||||
```typescript
|
||||
// ✅ 正确:使用明确的时间戳确保排序结果可预测
|
||||
it('should find batches by topic id in correct order', async () => {
|
||||
const oldDate = new Date('2024-01-01T10:00:00Z');
|
||||
const newDate = new Date('2024-01-02T10:00:00Z');
|
||||
|
||||
const batch1 = { ...testBatch, prompt: 'First batch', userId, createdAt: oldDate };
|
||||
const batch2 = { ...testBatch, prompt: 'Second batch', userId, createdAt: newDate };
|
||||
|
||||
await serverDB.insert(generationBatches).values([batch1, batch2]);
|
||||
|
||||
const results = await generationBatchModel.findByTopicId(testTopic.id);
|
||||
|
||||
expect(results[0].prompt).toBe('Second batch'); // 最新优先 (desc order)
|
||||
expect(results[1].prompt).toBe('First batch');
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:依赖数据库的默认时间戳,结果不可预测
|
||||
it('should find batches by topic id', async () => {
|
||||
const batch1 = { ...testBatch, prompt: 'First batch', userId };
|
||||
const batch2 = { ...testBatch, prompt: 'Second batch', userId };
|
||||
|
||||
await serverDB.insert(generationBatches).values([batch1, batch2]);
|
||||
|
||||
// 插入顺序和数据库时间戳可能不一致,导致测试不稳定
|
||||
const results = await generationBatchModel.findByTopicId(testTopic.id);
|
||||
expect(results[0].prompt).toBe('Second batch'); // 可能失败
|
||||
});
|
||||
```
|
||||
|
||||
### 常见问题和解决方案 💡
|
||||
|
||||
#### 问题 1:权限检查缺失导致安全漏洞
|
||||
|
||||
**现象**: 测试失败,用户能修改其他用户的数据 **解决**: 在 Model 的 `update` 和 `delete` 方法中添加 `and(eq(table.id, id), eq(table.userId, this.userId))`
|
||||
|
||||
#### 问题 2:Mock 未生效或验证失败
|
||||
|
||||
**现象**: `undefined is not a spy` 错误 **解决**: 检查 Mock 设置位置和方式,确保在测试文件顶部设置,在 `beforeEach` 中重置
|
||||
|
||||
#### 问题 3:测试数据污染
|
||||
|
||||
**现象**: 测试间相互影响,结果不稳定 **解决**: 在 `beforeEach` 和 `afterEach` 中正确清理数据库状态
|
||||
|
||||
#### 问题 4:外部依赖导致测试失败
|
||||
|
||||
**现象**: 因为真实的外部服务调用导致测试不稳定 **解决**: Mock 所有外部依赖,使测试更可控和快速
|
||||
|
||||
#### 问题 5:外键约束违反导致测试失败
|
||||
|
||||
**现象**: `insert or update on table "xxx" violates foreign key constraint` **解决**:
|
||||
|
||||
- 将可选外键字段设为 `null` 而不是无效的字符串值
|
||||
- 或者先创建被引用的记录,再创建当前记录
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:无效的外键值
|
||||
const testData = {
|
||||
asyncTaskId: 'invalid-uuid', // 表中不存在此记录
|
||||
fileId: 'non-existent-file', // 表中不存在此记录
|
||||
};
|
||||
|
||||
// ✅ 正确:使用 null 值
|
||||
const testData = {
|
||||
asyncTaskId: null, // 避免外键约束
|
||||
fileId: null, // 避免外键约束
|
||||
};
|
||||
|
||||
// ✅ 或者:先创建被引用的记录
|
||||
beforeEach(async () => {
|
||||
const [asyncTask] = await serverDB.insert(asyncTasks).values({
|
||||
id: 'valid-task-id',
|
||||
status: 'pending',
|
||||
type: 'generation',
|
||||
}).returning();
|
||||
|
||||
const testData = {
|
||||
asyncTaskId: asyncTask.id, // 使用有效的外键值
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
#### 问题 6:排序测试结果不一致
|
||||
|
||||
**现象**: 相同的测试有时通过,有时失败,特别是涉及排序的测试 **解决**: 使用明确的时间戳,不要依赖数据库的默认时间戳
|
||||
|
||||
```typescript
|
||||
// ❌ 错误:依赖插入顺序和默认时间戳
|
||||
await serverDB.insert(table).values([data1, data2]); // 时间戳不可预测
|
||||
|
||||
// ✅ 正确:明确指定时间戳
|
||||
const oldDate = new Date('2024-01-01T10:00:00Z');
|
||||
const newDate = new Date('2024-01-02T10:00:00Z');
|
||||
await serverDB.insert(table).values([
|
||||
{ ...data1, createdAt: oldDate },
|
||||
{ ...data2, createdAt: newDate },
|
||||
]);
|
||||
```
|
||||
|
||||
#### 问题 7:Mock 验证失败或调用次数不匹配
|
||||
|
||||
**现象**: `expect(mockFunction).toHaveBeenCalledWith(...)` 失败 **解决**:
|
||||
|
||||
- 检查 Mock 函数的实际调用参数和期望参数是否完全匹配
|
||||
- 确认 Mock 在正确的时机被重置和配置
|
||||
- 使用 `toHaveBeenCalledTimes()` 验证调用次数
|
||||
|
||||
```typescript
|
||||
// 在 beforeEach 中正确配置 Mock
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks(); // 重置所有 Mock
|
||||
|
||||
mockGetFullFileUrl.mockImplementation((url: string) => `https://example.com/${url}`);
|
||||
mockTransformGeneration.mockResolvedValue({
|
||||
id: 'test-id',
|
||||
// ... 其他字段
|
||||
});
|
||||
});
|
||||
|
||||
// 测试中验证 Mock 调用
|
||||
it('should call FileService with correct parameters', async () => {
|
||||
await model.someMethod();
|
||||
|
||||
// 验证调用参数
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledWith('expected-url');
|
||||
// 验证调用次数
|
||||
expect(mockGetFullFileUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
```
|
||||
|
||||
### Model 测试检查清单 ✅
|
||||
|
||||
创建 Model 测试时,请确保以下各项都已完成:
|
||||
|
||||
#### 🔧 基础配置
|
||||
|
||||
- [ ] **双环境验证** - 在客户端环境 (vitest.config.ts) 和服务端环境 (vitest.config.server.ts) 下都测试通过
|
||||
- [ ] 参考了 `_template.ts` 和现有 Model 的实现模式
|
||||
- [ ] **使用正确的 Schema 类型** - 测试数据使用 `NewXxx` 类型声明,如 `NewGenerationBatch`、`NewGeneration`
|
||||
|
||||
#### 🔒 安全测试
|
||||
|
||||
- [ ] **所有涉及用户数据的操作都包含用户权限检查**
|
||||
- [ ] 包含了用户权限隔离的安全测试
|
||||
- [ ] 测试了用户无法访问其他用户数据的场景
|
||||
|
||||
#### 🗃️ 数据处理
|
||||
|
||||
- [ ] **正确处理外键约束** - 使用 `null` 值或先创建被引用记录
|
||||
- [ ] **排序测试使用明确时间戳** - 不依赖数据库默认时间,确保结果可预测
|
||||
- [ ] 在 `beforeEach` 和 `afterEach` 中正确管理数据库状态
|
||||
- [ ] 所有测试都能独立运行且互不干扰
|
||||
|
||||
#### 🎭 Mock 和外部依赖
|
||||
|
||||
- [ ] 正确 Mock 了外部依赖服务 (如 FileService、GenerationModel)
|
||||
- [ ] 在 `beforeEach` 中重置和配置 Mock
|
||||
- [ ] 验证了 Mock 服务的调用参数和次数
|
||||
- [ ] 测试了外部服务错误场景的处理
|
||||
|
||||
#### 📋 测试覆盖
|
||||
|
||||
- [ ] 测试覆盖了所有主要方法 (create, query, update, delete)
|
||||
- [ ] 测试了边界条件和错误场景
|
||||
- [ ] 包含了空结果处理的测试
|
||||
- [ ] **确认两个环境下的测试结果一致**
|
||||
|
||||
#### 🚨 常见问题检查
|
||||
|
||||
- [ ] 没有外键约束违反错误
|
||||
- [ ] 排序测试结果稳定可预测
|
||||
- [ ] Mock 验证无失败
|
||||
- [ ] 无测试数据污染问题
|
||||
|
||||
### 安全警告 ⚠️
|
||||
|
||||
**数据库 Model 层是安全的第一道防线**。如果 Model 层缺少用户权限检查:
|
||||
|
||||
1. **任何用户都能访问和修改其他用户的数据**
|
||||
2. **即使上层有权限检查,也可能被绕过**
|
||||
3. **可能导致严重的数据泄露和安全事故**
|
||||
|
||||
因此,**每个涉及用户数据的 Model 方法都必须包含用户权限检查,且必须有对应的安全测试来验证这些检查的有效性**。
|
||||
@@ -1,80 +0,0 @@
|
||||
---
|
||||
description: Electron IPC 接口测试策略
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
### Electron IPC 接口测试策略 🖥️
|
||||
|
||||
对于涉及 Electron IPC 接口的测试,由于提供真实的 Electron 环境比较复杂,采用 **Mock 返回值** 的方式进行测试。
|
||||
|
||||
#### 基本 Mock 设置
|
||||
|
||||
```typescript
|
||||
import { vi } from 'vitest';
|
||||
|
||||
import { electronIpcClient } from '@/server/modules/ElectronIPCClient';
|
||||
|
||||
// Mock Electron IPC 客户端
|
||||
vi.mock('@/server/modules/ElectronIPCClient', () => ({
|
||||
electronIpcClient: {
|
||||
getFilePathById: vi.fn(),
|
||||
deleteFiles: vi.fn(),
|
||||
// 根据需要添加其他 IPC 方法
|
||||
},
|
||||
}));
|
||||
```
|
||||
|
||||
#### 在测试中设置 Mock 行为
|
||||
|
||||
```typescript
|
||||
beforeEach(() => {
|
||||
// 重置所有 Mock
|
||||
vi.resetAllMocks();
|
||||
|
||||
// 设置默认的 Mock 返回值
|
||||
vi.mocked(electronIpcClient.getFilePathById).mockResolvedValue('/path/to/file.txt');
|
||||
vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({
|
||||
success: true,
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
#### 测试不同场景的示例
|
||||
|
||||
```typescript
|
||||
it('应该处理文件删除成功的情况', async () => {
|
||||
// 设置成功场景的 Mock
|
||||
vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({
|
||||
success: true,
|
||||
});
|
||||
|
||||
const result = await service.deleteFiles(['desktop://file1.txt']);
|
||||
|
||||
expect(electronIpcClient.deleteFiles).toHaveBeenCalledWith(['desktop://file1.txt']);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('应该处理文件删除失败的情况', async () => {
|
||||
// 设置失败场景的 Mock
|
||||
vi.mocked(electronIpcClient.deleteFiles).mockRejectedValue(new Error('删除失败'));
|
||||
|
||||
const result = await service.deleteFiles(['desktop://file1.txt']);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.errors).toBeDefined();
|
||||
});
|
||||
```
|
||||
|
||||
#### Mock 策略的优势
|
||||
|
||||
1. **环境简化**: 避免了复杂的 Electron 环境搭建
|
||||
2. **测试可控**: 可以精确控制 IPC 调用的返回值和行为
|
||||
3. **场景覆盖**: 容易测试各种成功/失败场景
|
||||
4. **执行速度**: Mock 调用比真实 IPC 调用更快
|
||||
|
||||
#### 注意事项
|
||||
|
||||
- **Mock 准确性**: 确保 Mock 的行为与真实 IPC 接口行为一致
|
||||
- **类型安全**: 使用 `vi.mocked()` 确保类型安全
|
||||
- **Mock 重置**: 在 `beforeEach` 中重置 Mock 状态,避免测试间干扰
|
||||
- **调用验证**: 不仅要验证返回值,还要验证 IPC 方法是否被正确调用
|
||||
@@ -1,510 +0,0 @@
|
||||
---
|
||||
globs: *.test.ts,*.test.tsx
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 测试指南 - LobeChat Testing Guide
|
||||
|
||||
## 测试环境概览
|
||||
|
||||
LobeChat 项目使用 Vitest 测试库,配置了两种不同的测试环境:
|
||||
|
||||
### 客户端数据库测试环境 (DOM Environment)
|
||||
|
||||
- **配置文件**: [vitest.config.ts](mdc:vitest.config.ts)
|
||||
- **环境**: Happy DOM (浏览器环境模拟)
|
||||
- **数据库**: PGLite (浏览器环境的 PostgreSQL)
|
||||
- **用途**: 测试前端组件、客户端逻辑、React 组件等
|
||||
- **设置文件**: [tests/setup.ts](mdc:tests/setup.ts)
|
||||
|
||||
### 服务端数据库测试环境 (Node Environment)
|
||||
|
||||
目前只有 `packages/database` 下的测试可以通过配置 `TEST_SERVER_DB=1` 环境变量来使用服务端数据库测试
|
||||
|
||||
- **配置文件**: [packages/database/vitest.config.mts](mdc:packages/database/vitest.config.mts) 并且设置环境变量 `TEST_SERVER_DB=1`
|
||||
- **环境**: Node.js
|
||||
- **数据库**: 真实的 PostgreSQL 数据库
|
||||
- **并发限制**: 单线程运行 (`singleFork: true`)
|
||||
- **用途**: 测试数据库模型、服务端逻辑、API 端点等
|
||||
- **设置文件**: [packages/database/tests/setup-db.ts](mdc:packages/database/tests/setup-db.ts)
|
||||
|
||||
## 测试运行命令
|
||||
|
||||
** 性能警告**: 项目包含 3000+ 测试用例,完整运行需要约 10 分钟。务必使用文件过滤或测试名称过滤。
|
||||
|
||||
### 正确的命令格式
|
||||
|
||||
```bash
|
||||
# 运行所有客户端/服务端测试
|
||||
bunx vitest run --silent='passed-only' # 客户端测试
|
||||
cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only' # 服务端测试
|
||||
|
||||
# 运行特定测试文件 (支持模糊匹配)
|
||||
bunx vitest run --silent='passed-only' user.test.ts
|
||||
|
||||
# 运行特定测试用例名称 (使用 -t 参数)
|
||||
bunx vitest run --silent='passed-only' -t "test case name"
|
||||
|
||||
# 组合使用文件和测试名称过滤
|
||||
bunx vitest run --silent='passed-only' filename.test.ts -t "specific test"
|
||||
|
||||
# 生成覆盖率报告 (使用 --coverage 参数)
|
||||
bunx vitest run --silent='passed-only' --coverage
|
||||
```
|
||||
|
||||
### 避免的命令格式
|
||||
|
||||
```bash
|
||||
# 这些命令会运行所有 3000+ 测试用例,耗时约 10 分钟!
|
||||
npm test
|
||||
npm test some-file.test.ts
|
||||
|
||||
# 不要使用裸 vitest (会进入 watch 模式)
|
||||
vitest test-file.test.ts
|
||||
```
|
||||
|
||||
## 测试修复原则
|
||||
|
||||
### 核心原则
|
||||
|
||||
1. **收集足够的上下文**
|
||||
在修复测试之前,务必做到:
|
||||
- 完整理解测试的意图和实现
|
||||
- 强烈建议阅读当前的 git diff 和 PR diff
|
||||
|
||||
2. **测试优先修复**
|
||||
如果是测试本身写错了,应优先修改测试,而不是实现代码。
|
||||
|
||||
3. **专注单一问题**
|
||||
只修复指定的测试,不要顺带添加额外测试。
|
||||
|
||||
4. **不自作主张**
|
||||
发现其他问题时,不要直接修改,需先提出并讨论。
|
||||
|
||||
### 测试协作最佳实践
|
||||
|
||||
基于实际开发经验总结的重要协作原则:
|
||||
|
||||
#### 1. 失败处理策略
|
||||
|
||||
**核心原则**: 避免盲目重试,快速识别问题并寻求帮助。
|
||||
|
||||
- **失败阈值**: 当连续尝试修复测试 1-2 次都失败后,应立即停止继续尝试
|
||||
- **问题总结**: 分析失败原因,整理已尝试的解决方案及其失败原因
|
||||
- **寻求帮助**: 带着清晰的问题摘要和尝试记录向团队寻求帮助
|
||||
- **避免陷阱**: 不要陷入"不断尝试相同或类似方法"的循环
|
||||
|
||||
```typescript
|
||||
// 错误做法:连续失败后继续盲目尝试
|
||||
// 第3次、第4次仍在用相似的方法修复同一个问题
|
||||
|
||||
// 正确做法:失败1-2次后总结问题
|
||||
/*
|
||||
问题总结:
|
||||
1. 尝试过的方法:修改 mock 数据结构
|
||||
2. 失败原因:仍然提示类型不匹配
|
||||
3. 具体错误:Expected 'UserData' but received 'UserProfile'
|
||||
4. 需要帮助:不确定最新的 UserData 接口定义
|
||||
*/
|
||||
```
|
||||
|
||||
#### 2. 测试用例命名规范
|
||||
|
||||
**核心原则**: 测试应该关注"行为",而不是"实现细节"。
|
||||
|
||||
- **描述业务场景**: `describe` 和 `it` 的标题应该描述具体的业务场景和预期行为
|
||||
- **避免实现绑定**: 不要在测试名称中提及具体的代码行号、覆盖率目标或实现细节
|
||||
- **保持稳定性**: 测试名称应该在代码重构后仍然有意义
|
||||
|
||||
```typescript
|
||||
// 错误的测试命名
|
||||
describe('User component coverage', () => {
|
||||
it('covers line 45-50 in getUserData', () => {
|
||||
// 为了覆盖第45-50行而写的测试
|
||||
});
|
||||
|
||||
it('tests the else branch', () => {
|
||||
// 仅为了测试某个分支而存在
|
||||
});
|
||||
});
|
||||
|
||||
// 正确的测试命名
|
||||
describe('<UserAvatar />', () => {
|
||||
it('should render fallback icon when image url is not provided', () => {
|
||||
// 测试具体的业务场景,自然会覆盖相关代码分支
|
||||
});
|
||||
|
||||
it('should display user initials when avatar image fails to load', () => {
|
||||
// 描述用户行为和预期结果
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
**覆盖率提升的正确思路**:
|
||||
|
||||
- 通过设计各种业务场景(正常流程、边缘情况、错误处理)来自然提升覆盖率
|
||||
- 不要为了达到覆盖率数字而写测试,更不要在测试中注释"为了覆盖 xxx 行"
|
||||
|
||||
#### 3. 测试组织结构
|
||||
|
||||
**核心原则**: 维护清晰的测试层次结构,避免冗余的顶级测试块。
|
||||
|
||||
- **复用现有结构**: 添加新测试时,优先在现有的 `describe` 块中寻找合适的位置
|
||||
- **逻辑分组**: 相关的测试用例应该组织在同一个 `describe` 块内
|
||||
- **避免碎片化**: 不要为了单个测试用例就创建新的顶级 `describe` 块
|
||||
|
||||
```typescript
|
||||
// 错误的组织方式:创建过多顶级块
|
||||
describe('<UserProfile />', () => {
|
||||
it('should render user name', () => {});
|
||||
});
|
||||
|
||||
describe('UserProfile new prop test', () => {
|
||||
// 不必要的新块
|
||||
it('should handle email display', () => {});
|
||||
});
|
||||
|
||||
describe('UserProfile edge cases', () => {
|
||||
// 不必要的新块
|
||||
it('should handle missing avatar', () => {});
|
||||
});
|
||||
|
||||
// 正确的组织方式:合并相关测试
|
||||
describe('<UserProfile />', () => {
|
||||
it('should render user name', () => {});
|
||||
|
||||
it('should handle email display', () => {});
|
||||
|
||||
it('should handle missing avatar', () => {});
|
||||
|
||||
describe('when user data is incomplete', () => {
|
||||
// 只有在有多个相关子场景时才创建子组
|
||||
it('should show placeholder for missing name', () => {});
|
||||
it('should hide email section when email is undefined', () => {});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
**组织决策流程**:
|
||||
|
||||
1. 是否存在逻辑相关的现有 `describe` 块? → 如果有,添加到其中
|
||||
2. 是否有多个(3个以上)相关的测试用例? → 如果有,可以考虑创建新的子 `describe`
|
||||
3. 是否是独立的、无关联的功能模块? → 如果是,才考虑创建新的顶级 `describe`
|
||||
|
||||
### 测试修复流程
|
||||
|
||||
1. **复现问题**: 定位并运行失败的测试,确认能在本地复现
|
||||
2. **分析原因**: 阅读测试代码、错误日志和相关文件的 Git 修改历史
|
||||
3. **建立假设**: 判断问题出在测试逻辑、实现代码还是环境配置
|
||||
4. **修复验证**: 根据假设进行修复,重新运行测试确认通过
|
||||
5. **扩大验证**: 运行当前文件内所有测试,确保没有引入新问题
|
||||
6. **撰写总结**: 说明错误原因和修复方法
|
||||
|
||||
### 修复完成后的总结
|
||||
|
||||
测试修复完成后,应该提供简要说明,包括:
|
||||
|
||||
1. **错误原因分析**: 说明测试失败的根本原因
|
||||
- 测试逻辑错误
|
||||
- 实现代码bug
|
||||
- 环境配置问题
|
||||
- 依赖变更导致的问题
|
||||
|
||||
2. **修复方法说明**: 简述采用的修复方式
|
||||
- 修改了哪些文件
|
||||
- 采用了什么解决方案
|
||||
- 为什么选择这种修复方式
|
||||
|
||||
**示例格式**:
|
||||
|
||||
```markdown
|
||||
## 测试修复总结
|
||||
|
||||
**错误原因**: 测试中的 mock 数据格式与实际 API 返回格式不匹配,导致断言失败。
|
||||
|
||||
**修复方法**: 更新了测试文件中的 mock 数据结构,使其与最新的 API 响应格式保持一致。具体修改了 `user.test.ts` 中的 `mockUserData` 对象结构。
|
||||
```
|
||||
|
||||
## 测试编写最佳实践
|
||||
|
||||
### Mock 数据策略:追求"低成本的真实性"
|
||||
|
||||
**核心原则**: 测试数据应默认追求真实性,只有在引入"高昂的测试成本"时才进行简化。
|
||||
|
||||
#### 什么是"高昂的测试成本"?
|
||||
|
||||
"高成本"指的是测试中引入了外部依赖,使测试变慢、不稳定或复杂:
|
||||
|
||||
- **文件 I/O 操作**:读写硬盘文件
|
||||
- **网络请求**:HTTP 调用、数据库连接
|
||||
- **系统调用**:获取系统时间、环境变量等
|
||||
|
||||
#### 推荐做法:Mock 依赖,保留真实数据
|
||||
|
||||
```typescript
|
||||
// 好的做法:Mock I/O 操作,但使用真实的文件内容格式
|
||||
describe('parseContentType', () => {
|
||||
beforeEach(() => {
|
||||
// Mock 文件读取操作(避免真实 I/O)
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path) => {
|
||||
// 但返回真实的文件内容格式
|
||||
if (path.includes('.pdf')) return '%PDF-1.4\n%âãÏÓ'; // 真实 PDF 文件头
|
||||
if (path.includes('.png')) return '\x89PNG\r\n\x1a\n'; // 真实 PNG 文件头
|
||||
return '';
|
||||
});
|
||||
});
|
||||
|
||||
it('should detect PDF content type correctly', () => {
|
||||
const result = parseContentType('/path/to/file.pdf');
|
||||
expect(result).toBe('application/pdf');
|
||||
});
|
||||
});
|
||||
|
||||
// 过度简化:使用不真实的数据
|
||||
describe('parseContentType', () => {
|
||||
it('should detect PDF content type correctly', () => {
|
||||
// 这种简化数据没有测试价值
|
||||
const result = parseContentType('fake-pdf-content');
|
||||
expect(result).toBe('application/pdf');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
#### 真实标识符的价值
|
||||
|
||||
```typescript
|
||||
// ✅ 使用真实标识符
|
||||
const result = parseModelString('openai', '+gpt-4,+gpt-3.5-turbo');
|
||||
|
||||
// ❌ 使用占位符(价值较低)
|
||||
const result = parseModelString('test-provider', '+model1,+model2');
|
||||
```
|
||||
|
||||
### 现代化Mock技巧:环境设置与Mock方法
|
||||
|
||||
**环境设置 + Mock方法结合使用**
|
||||
|
||||
客户端代码测试时,推荐使用环境注释配合现代化Mock方法:
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* @vitest-environment happy-dom // 提供浏览器API
|
||||
*/
|
||||
import { beforeEach, vi } from 'vitest';
|
||||
|
||||
beforeEach(() => {
|
||||
// 现代方法1:使用vi.stubGlobal替代global.xxx = ...
|
||||
const mockImage = vi.fn().mockImplementation(() => ({
|
||||
addEventListener: vi.fn(),
|
||||
naturalHeight: 600,
|
||||
naturalWidth: 800,
|
||||
}));
|
||||
vi.stubGlobal('Image', mockImage);
|
||||
|
||||
// 现代方法2:使用vi.spyOn保留原功能,只mock特定方法
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock-url');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
|
||||
});
|
||||
```
|
||||
|
||||
**环境选择优先级**
|
||||
|
||||
1. **@vitest-environment happy-dom** (推荐) - 轻量、快速,项目已安装
|
||||
2. **@vitest-environment jsdom** - 功能完整,但需要额外安装jsdom包
|
||||
3. **不设置环境** - Node.js环境,需要手动mock所有浏览器API
|
||||
|
||||
**Mock方法对比**
|
||||
|
||||
```typescript
|
||||
// ❌ 旧方法:直接操作global对象(类型问题)
|
||||
global.Image = mockImage;
|
||||
global.URL = { ...global.URL, createObjectURL: mockFn };
|
||||
|
||||
// ✅ 现代方法:类型安全的vi API
|
||||
vi.stubGlobal('Image', mockImage); // 完全替换全局对象
|
||||
vi.spyOn(URL, 'createObjectURL'); // 部分mock,保留其他功能
|
||||
```
|
||||
|
||||
### 测试覆盖率原则:代码分支优于用例数量
|
||||
|
||||
**核心原则**: 优先覆盖所有代码分支,而非编写大量重复用例
|
||||
|
||||
```typescript
|
||||
// ❌ 过度测试:29个测试用例都验证相同分支
|
||||
describe('getImageDimensions', () => {
|
||||
it('should reject .txt files');
|
||||
it('should reject .pdf files');
|
||||
// ... 25个类似测试,都走相同的验证分支
|
||||
});
|
||||
|
||||
// ✅ 精简测试:4个核心用例覆盖所有分支
|
||||
describe('getImageDimensions', () => {
|
||||
it('should return dimensions for valid File object'); // 成功路径 - File
|
||||
it('should return dimensions for valid data URI'); // 成功路径 - String
|
||||
it('should return undefined for invalid inputs'); // 输入验证分支
|
||||
it('should return undefined when image fails to load'); // 错误处理分支
|
||||
});
|
||||
```
|
||||
|
||||
**分支覆盖策略**
|
||||
|
||||
1. **成功路径** - 每种输入类型1个测试即可
|
||||
2. **边界条件** - 合并类似场景到单个测试
|
||||
3. **错误处理** - 测试代表性错误即可
|
||||
4. **业务逻辑** - 覆盖所有if/else分支
|
||||
|
||||
**合理测试数量**
|
||||
|
||||
- 简单工具函数:2-5个测试
|
||||
- 复杂业务逻辑:5-10个测试
|
||||
- 核心安全功能:适当增加,但避免重复路径
|
||||
|
||||
### 错误处理测试:测试"行为"而非"文本"
|
||||
|
||||
**核心原则**: 测试应该验证程序在错误发生时的行为是可预测的,而不是验证易变的错误信息文本。
|
||||
|
||||
#### 推荐的错误测试方式
|
||||
|
||||
```typescript
|
||||
// ✅ 测试错误类型和属性
|
||||
expect(() => validateUser({})).toThrow(ValidationError);
|
||||
expect(() => processPayment({})).toThrow(
|
||||
expect.objectContaining({
|
||||
code: 'INVALID_PAYMENT_DATA',
|
||||
statusCode: 400,
|
||||
}),
|
||||
);
|
||||
|
||||
// ❌ 避免测试具体错误文本
|
||||
expect(() => processUser({})).toThrow('用户数据不能为空,请检查输入参数');
|
||||
```
|
||||
|
||||
### 疑难解答:警惕模块污染
|
||||
|
||||
**识别信号**: 当你的测试出现以下"灵异"现象时,优先怀疑模块污染:
|
||||
|
||||
- 单独运行某个测试通过,但和其他测试一起运行就失败
|
||||
- 测试的执行顺序影响结果
|
||||
- Mock 设置看起来正确,但实际使用的是旧的 Mock 版本
|
||||
|
||||
#### 典型场景:动态 Mock 同一模块
|
||||
|
||||
```typescript
|
||||
// ❌ 问题:动态Mock同一模块
|
||||
it('dev mode', async () => {
|
||||
vi.doMock('./config', () => ({ isDev: true }));
|
||||
const { getSettings } = await import('./service'); // 可能使用缓存
|
||||
});
|
||||
|
||||
// ✅ 解决:清除模块缓存
|
||||
beforeEach(() => {
|
||||
vi.resetModules(); // 确保每个测试都是干净环境
|
||||
});
|
||||
```
|
||||
|
||||
**记住**: `vi.resetModules()` 是解决测试"灵异"失败的终极武器。
|
||||
|
||||
## 测试文件组织
|
||||
|
||||
### 文件命名约定
|
||||
|
||||
`*.test.ts`, `*.test.tsx` (任意位置)
|
||||
|
||||
### 测试文件组织风格
|
||||
|
||||
项目采用 **测试文件与源文件同目录** 的组织风格:
|
||||
|
||||
- 测试文件放在对应源文件的同一目录下
|
||||
- 命名格式:`原文件名.test.ts` 或 `原文件名.test.tsx`
|
||||
|
||||
例如:
|
||||
|
||||
```plaintext
|
||||
src/components/Button/
|
||||
├── index.tsx # 源文件
|
||||
└── index.test.tsx # 测试文件
|
||||
```
|
||||
|
||||
- 也有少数情况会统一放到 `__tests__` 文件夹, 例如 `packages/database/src/models/__tests__`
|
||||
- 测试使用的辅助文件放到 fixtures 文件夹
|
||||
|
||||
## 测试调试技巧
|
||||
|
||||
### 测试调试步骤
|
||||
|
||||
1. **确定测试环境**: 根据文件路径选择正确的配置文件
|
||||
2. **隔离问题**: 使用 `-t` 参数只运行失败的测试用例
|
||||
3. **分析错误**: 仔细阅读错误信息、堆栈跟踪和最近的文件修改记录
|
||||
4. **添加调试**: 在测试中添加 `console.log` 了解执行流程
|
||||
|
||||
### TypeScript 类型处理
|
||||
|
||||
在测试中,为了提高编写效率和可读性,可以适当放宽 TypeScript 类型检测:
|
||||
|
||||
#### 推荐的类型放宽策略
|
||||
|
||||
```typescript
|
||||
// 使用非空断言访问测试中确定存在的属性
|
||||
const result = await someFunction();
|
||||
expect(result!.data).toBeDefined();
|
||||
expect(result!.status).toBe('success');
|
||||
|
||||
// 使用 any 类型简化复杂的 Mock 设置
|
||||
const mockStream = new ReadableStream() as any;
|
||||
mockStream.toReadableStream = () => mockStream;
|
||||
|
||||
// 访问私有成员
|
||||
await instance['getFromCache']('key'); // 推荐中括号
|
||||
await (instance as any).getFromCache('key'); // 避免as any
|
||||
```
|
||||
|
||||
#### 适用场景
|
||||
|
||||
- **Mock 对象**: 对于测试用的 Mock 数据,使用 `as any` 避免复杂的类型定义
|
||||
- **第三方库**: 处理复杂的第三方库类型时,适当使用 `any` 提高效率
|
||||
- **测试断言**: 在确定对象存在的测试场景中,使用 `!` 非空断言
|
||||
- **私有成员访问**: 优先使用中括号 `instance['privateMethod']()` 而不是 `(instance as any).privateMethod()`
|
||||
- **临时调试**: 快速编写测试时,先用 `any` 保证功能,后续可选择性地优化类型
|
||||
|
||||
#### 注意事项
|
||||
|
||||
- **适度使用**: 不要过度依赖 `any`,核心业务逻辑的类型仍应保持严格
|
||||
- **私有成员访问优先级**: 中括号访问 > `as any` 转换,保持更好的类型安全性
|
||||
- **文档说明**: 对于使用 `any` 的复杂场景,添加注释说明原因
|
||||
- **测试覆盖**: 确保即使使用了 `any`,测试仍能有效验证功能正确性
|
||||
|
||||
### 检查最近修改记录
|
||||
|
||||
**核心原则**:测试突然失败时,优先检查最近的代码修改。
|
||||
|
||||
#### 快速检查方法
|
||||
|
||||
```bash
|
||||
git status # 查看当前修改状态
|
||||
git diff HEAD -- '*.test.*' # 检查测试文件改动
|
||||
git diff main...HEAD # 对比主分支差异
|
||||
gh pr diff # 查看PR中的所有改动
|
||||
```
|
||||
|
||||
#### 常见原因与解决
|
||||
|
||||
- **最新提交引入bug** → 检查并修复实现代码
|
||||
- **分支代码滞后** → `git rebase main` 同步主分支
|
||||
|
||||
## 特殊场景的测试
|
||||
|
||||
针对一些特殊场景的测试,需要阅读相关 rules:
|
||||
|
||||
- [Electron IPC 接口测试策略](mdc:./electron-ipc-test.mdc)
|
||||
- [数据库 Model 测试指南](mdc:./db-model-test.mdc)
|
||||
|
||||
## 核心要点
|
||||
|
||||
- **命令格式**: 使用 `bunx vitest run --silent='passed-only'` 并指定文件过滤
|
||||
- **修复原则**: 失败1-2次后寻求帮助,测试命名关注行为而非实现细节
|
||||
- **调试流程**: 复现 → 分析 → 假设 → 修复 → 验证 → 总结
|
||||
- **文件组织**: 优先在现有 `describe` 块中添加测试,避免创建冗余顶级块
|
||||
- **数据策略**: 默认追求真实性,只有高成本(I/O、网络等)时才简化
|
||||
- **错误测试**: 测试错误类型和行为,避免依赖具体的错误信息文本
|
||||
- **模块污染**: 测试"灵异"失败时,优先怀疑模块污染,使用 `vi.resetModules()` 解决
|
||||
- **安全要求**: Model 测试必须包含权限检查,并在双环境下验证通过
|
||||
@@ -1,62 +1,19 @@
|
||||
---
|
||||
description: TypeScript code style and optimization guidelines
|
||||
description:
|
||||
globs: *.ts,*.tsx,*.mts
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# TypeScript Code Style Guide
|
||||
|
||||
## Types and Type Safety
|
||||
TypeScript Code Style Guide:
|
||||
|
||||
- Avoid explicit type annotations when TypeScript can infer types.
|
||||
- Avoid implicitly `any` variables; explicitly type when necessary (e.g., `let a: number` instead of `let a`).
|
||||
- Use the most accurate type possible (e.g., prefer `Record<PropertyKey, unknown>` over `object`).
|
||||
- Prefer `interface` over `type` for object shapes (e.g., React component props). Keep `type` for unions, intersections, and utility types.
|
||||
- Prefer `as const satisfies XyzInterface` over plain `as const` when suitable.
|
||||
|
||||
## Imports and Modules
|
||||
|
||||
- When importing a directory module, prefer the explicit index path like `@/db/index` instead of `@/db`.
|
||||
|
||||
## Asynchronous Patterns and Concurrency
|
||||
|
||||
- Prefer `async`/`await` over callbacks or chained `.then` promises.
|
||||
- Prefer async APIs over sync ones (avoid `*Sync`).
|
||||
- Prefer promise-based variants (e.g., `import { readFile } from 'fs/promises'`) over callback-based APIs from `fs`.
|
||||
- Where safe, convert sequential async flows to concurrent ones with `Promise.all`, `Promise.race`, etc.
|
||||
|
||||
## Code Structure and Readability
|
||||
|
||||
- Refactor repeated logic into reusable functions.
|
||||
- Prefer object destructuring when accessing and using properties.
|
||||
- Use consistent, descriptive naming; avoid obscure abbreviations.
|
||||
- Use semantically meaningful variable, function, and class names.
|
||||
- Replace magic numbers or strings with well-named constants.
|
||||
- Keep meaningful code comments; do not remove them when applying edits. Update comments when behavior changes.
|
||||
- Ensure JSDoc comments accurately reflect the implementation.
|
||||
- Look for opportunities to simplify or modernize code with the latest JavaScript/TypeScript features where it improves clarity.
|
||||
- Defer formatting to tooling; ignore purely formatting-only issues and autofixable lint problems.
|
||||
- Respect project Prettier settings.
|
||||
|
||||
## UI and Theming
|
||||
|
||||
- Use components from `@lobehub/ui`, Ant Design, or existing design system components instead of raw HTML tags (e.g., `Button` vs. `button`).
|
||||
- Design for dark mode and mobile responsiveness:
|
||||
- Use the `antd-style` token system instead of hard-coded colors.
|
||||
- Select appropriate component variants.
|
||||
|
||||
## Performance
|
||||
|
||||
- Prefer `for…of` loops to index-based `for` loops when feasible.
|
||||
- Decide whether callbacks should be debounced or throttled based on UX and performance needs.
|
||||
- Reuse existing npm packages rather than reinventing the wheel (e.g., `lodash-es/omit`).
|
||||
- Query only the required columns from a database rather than selecting entire rows.
|
||||
|
||||
## Time and Consistency
|
||||
|
||||
- Instead of calling `Date.now()` multiple times, assign it to a constant once and reuse it to ensure consistency and improve readability.
|
||||
|
||||
## Some logging rules
|
||||
|
||||
- Never log user private information like api key, etc
|
||||
- Don't use `import { log } from 'debug'` to log messages, because it will directly log the message to the console.
|
||||
- Avoid defining `any` type variables (e.g., `let a: number;` instead of `let a;`).
|
||||
- Use the most accurate type possible (e.g., use `Record<PropertyKey, unknown>` instead of `object`).
|
||||
- Prefer `interface` over `type` (e.g., define react component props).
|
||||
- Use `as const satisfies XyzInterface` instead of `as const` when suitable
|
||||
- import index.ts module(directory module) like `@/db/index` instead of `@/db`
|
||||
- Instead of calling Date.now() multiple times, assign it to a constant once and reuse it. This ensures consistency and improves readability
|
||||
- Always refactor repeated logic into a reusable function
|
||||
- Don't remove meaningful code comments, be sure to keep original comments when providing applied code
|
||||
- Update the code comments when needed after you modify the related code
|
||||
- Please respect my prettier preferences when you provide code
|
||||
@@ -4,14 +4,6 @@
|
||||
# Specify your API Key selection method, currently supporting `random` and `turn`.
|
||||
# API_KEY_SELECT_MODE=random
|
||||
|
||||
########################################
|
||||
########### Security Settings ###########
|
||||
########################################
|
||||
|
||||
# Control Content Security Policy headers
|
||||
# Set to '1' to enable X-Frame-Options and Content-Security-Policy headers
|
||||
# Default is '0' (enabled)
|
||||
# ENABLED_CSP=1
|
||||
|
||||
########################################
|
||||
########## AI Provider Service #########
|
||||
@@ -148,31 +140,6 @@ OPENAI_API_KEY=sk-xxxxxxxxx
|
||||
|
||||
# INFINIAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
|
||||
### 302.AI ###
|
||||
|
||||
# AI302_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
### ModelScope ###
|
||||
|
||||
# MODELSCOPE_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
### AiHubMix ###
|
||||
|
||||
# AIHUBMIX_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
### BFL ###
|
||||
|
||||
# BFL_API_KEY=bfl-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
### FAL ###
|
||||
|
||||
# FAL_API_KEY=fal-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
### Nebius ###
|
||||
|
||||
# NEBIUS_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
########################################
|
||||
############ Market Service ############
|
||||
########################################
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
# LobeChat Development Server Configuration
|
||||
# This file contains environment variables for both LobeChat server mode and Docker compose setup
|
||||
|
||||
COMPOSE_FILE="docker-compose.development.yml"
|
||||
|
||||
# ⚠️⚠️⚠️ DO NOT USE THE SECRETS BELOW IN PRODUCTION!
|
||||
UNSAFE_SECRET="ww+0igxjGRAAR/eTNFQ55VmhQB5KE5trFZseuntThJs="
|
||||
UNSAFE_PASSWORD="CHANGE_THIS_PASSWORD_IN_PRODUCTION"
|
||||
|
||||
# Core Server Configuration
|
||||
# Service mode - set to 'server' for server-side deployment
|
||||
NEXT_PUBLIC_SERVICE_MODE=server
|
||||
|
||||
# Service Ports Configuration
|
||||
LOBE_PORT=3010
|
||||
|
||||
# Application URL - the base URL where LobeChat will be accessible
|
||||
APP_URL=http://localhost:${LOBE_PORT}
|
||||
|
||||
# Secret key for encrypting vault data (generate with: openssl rand -base64 32)
|
||||
KEY_VAULTS_SECRET=${UNSAFE_SECRET}
|
||||
|
||||
# Database Configuration
|
||||
# Database name for LobeChat
|
||||
LOBE_DB_NAME=lobechat
|
||||
|
||||
# PostgreSQL password
|
||||
POSTGRES_PASSWORD=${UNSAFE_PASSWORD}
|
||||
|
||||
# PostgreSQL database connection URL
|
||||
DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@localhost:5432/${LOBE_DB_NAME}
|
||||
|
||||
# Database driver type
|
||||
DATABASE_DRIVER=node
|
||||
|
||||
# Authentication Configuration
|
||||
# Enable NextAuth authentication
|
||||
NEXT_PUBLIC_ENABLE_NEXT_AUTH=1
|
||||
|
||||
# NextAuth secret for JWT signing (generate with: openssl rand -base64 32)
|
||||
NEXT_AUTH_SECRET=${UNSAFE_SECRET}
|
||||
|
||||
NEXTAUTH_URL=${APP_URL}
|
||||
|
||||
# Authentication URL
|
||||
AUTH_URL=${APP_URL}/api/auth
|
||||
|
||||
# SSO providers configuration - using Casdoor for development
|
||||
NEXT_AUTH_SSO_PROVIDERS=casdoor
|
||||
|
||||
# Casdoor Configuration
|
||||
# Casdoor service port
|
||||
CASDOOR_PORT=8000
|
||||
|
||||
# Casdoor OIDC issuer URL
|
||||
AUTH_CASDOOR_ISSUER=http://localhost:${CASDOOR_PORT}
|
||||
|
||||
# Casdoor application client ID
|
||||
AUTH_CASDOOR_ID=a387a4892ee19b1a2249 # DO NOT USE IN PROD
|
||||
|
||||
# Casdoor application client secret
|
||||
AUTH_CASDOOR_SECRET=dbf205949d704de81b0b5b3603174e23fbecc354 # DO NOT USE IN PROD
|
||||
|
||||
# Origin URL for Casdoor internal configuration
|
||||
origin=http://localhost:${CASDOOR_PORT}
|
||||
|
||||
# MinIO Storage Configuration
|
||||
# MinIO service port
|
||||
MINIO_PORT=9000
|
||||
|
||||
# MinIO root user (admin username)
|
||||
MINIO_ROOT_USER=admin
|
||||
|
||||
# MinIO root password
|
||||
MINIO_ROOT_PASSWORD=${UNSAFE_PASSWORD}
|
||||
|
||||
# MinIO bucket for LobeChat files
|
||||
MINIO_LOBE_BUCKET=lobe
|
||||
|
||||
# S3/MinIO Configuration for LobeChat
|
||||
# S3/MinIO access key ID
|
||||
S3_ACCESS_KEY_ID=${MINIO_ROOT_USER}
|
||||
|
||||
# S3/MinIO secret access key
|
||||
S3_SECRET_ACCESS_KEY=${MINIO_ROOT_PASSWORD}
|
||||
|
||||
# S3/MinIO endpoint URL
|
||||
S3_ENDPOINT=http://localhost:${MINIO_PORT}
|
||||
|
||||
# S3 bucket name for storing files
|
||||
S3_BUCKET=${MINIO_LOBE_BUCKET}
|
||||
|
||||
# Public domain for S3 file access
|
||||
S3_PUBLIC_DOMAIN=http://localhost:${MINIO_PORT}
|
||||
|
||||
# Enable path-style S3 requests (required for MinIO)
|
||||
S3_ENABLE_PATH_STYLE=1
|
||||
|
||||
# Disable S3 ACL setting (for MinIO compatibility)
|
||||
S3_SET_ACL=0
|
||||
|
||||
# Use base64 encoding for LLM vision images
|
||||
LLM_VISION_IMAGE_USE_BASE64=1
|
||||
|
||||
# Search Service Configuration
|
||||
# SearXNG search engine URL
|
||||
SEARXNG_URL=http://searxng:8080
|
||||
|
||||
# Development Options
|
||||
# Uncomment to skip authentication during development
|
||||
|
||||
# Proxy Configuration (Optional)
|
||||
# Uncomment if you need proxy support (e.g., for GitHub auth or API access)
|
||||
# HTTP_PROXY=http://localhost:7890
|
||||
# HTTPS_PROXY=http://localhost:7890
|
||||
|
||||
# AI Model Configuration (Optional)
|
||||
# Add your AI model API keys and configurations here
|
||||
# ⚠️ WARNING: Never commit real API keys to version control!
|
||||
# OPENAI_API_KEY=sk-NEVER_USE_REAL_API_KEYS_IN_CONFIG_FILES
|
||||
# OPENAI_PROXY_URL=https://api.openai.com/v1
|
||||
# OPENAI_MODEL_LIST=...
|
||||
@@ -29,20 +29,3 @@ logs
|
||||
# misc
|
||||
# add other ignore file below
|
||||
.next
|
||||
|
||||
# temporary directories
|
||||
tmp
|
||||
temp
|
||||
.temp
|
||||
.local
|
||||
docs/.local
|
||||
|
||||
# cache directories
|
||||
.cache
|
||||
|
||||
# AI coding tools directories
|
||||
.claude
|
||||
.serena
|
||||
|
||||
# MCP tools
|
||||
/.serena/**
|
||||
|
||||
@@ -36,16 +36,6 @@ config.overrides = [
|
||||
'mdx/code-blocks': false,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
files: ['src/store/image/**/*', 'src/types/generation/**/*'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-empty-interface': 0,
|
||||
'sort-keys-fix/sort-keys-fix': 0,
|
||||
'typescript-sort-keys/interface': 0,
|
||||
'typescript-sort-keys/string-enum': 0,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = config;
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
- [ ] 💄 style
|
||||
- [ ] 👷 build
|
||||
- [ ] ⚡️ perf
|
||||
- [ ] ✅ test
|
||||
- [ ] 📝 docs
|
||||
- [ ] 🔨 chore
|
||||
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
/**
|
||||
* Generate or update PR comment with Docker build info
|
||||
*/
|
||||
module.exports = async ({
|
||||
github,
|
||||
context,
|
||||
dockerMetaJson,
|
||||
image,
|
||||
version,
|
||||
dockerhubUrl,
|
||||
platforms,
|
||||
}) => {
|
||||
const COMMENT_IDENTIFIER = '<!-- DOCKER-BUILD-COMMENT -->';
|
||||
|
||||
const parseTags = () => {
|
||||
try {
|
||||
if (dockerMetaJson) {
|
||||
const parsed = JSON.parse(dockerMetaJson);
|
||||
if (Array.isArray(parsed.tags) && parsed.tags.length > 0) {
|
||||
return parsed.tags;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore parsing error, fallback below
|
||||
}
|
||||
if (image && version) {
|
||||
return [`${image}:${version}`];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const generateCommentBody = () => {
|
||||
const tags = parseTags();
|
||||
const buildTime = new Date().toISOString();
|
||||
|
||||
// Use the first tag as the main version
|
||||
const mainTag = tags.length > 0 ? tags[0] : `${image}:${version}`;
|
||||
const tagVersion = mainTag.includes(':') ? mainTag.split(':')[1] : version;
|
||||
|
||||
return [
|
||||
COMMENT_IDENTIFIER,
|
||||
'',
|
||||
'### 🐳 Database Docker Build Completed!',
|
||||
`**Version**: \`${tagVersion || 'N/A'}\``,
|
||||
`**Build Time**: \`${buildTime}\``,
|
||||
'',
|
||||
dockerhubUrl ? `🔗 View all tags on Docker Hub: ${dockerhubUrl}` : '',
|
||||
'',
|
||||
'### Pull Image',
|
||||
'Download the Docker image to your local machine:',
|
||||
'',
|
||||
'```bash',
|
||||
`docker pull ${mainTag}`,
|
||||
'```',
|
||||
'> [!IMPORTANT]',
|
||||
'> This build is for testing and validation purposes.',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
};
|
||||
|
||||
const body = generateCommentBody();
|
||||
|
||||
// List comments on the PR
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
});
|
||||
|
||||
const existing = comments.find((c) => c.body && c.body.includes(COMMENT_IDENTIFIER));
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
comment_id: existing.id,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body,
|
||||
});
|
||||
return { updated: true, id: existing.id };
|
||||
}
|
||||
|
||||
const result = await github.rest.issues.createComment({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body,
|
||||
});
|
||||
return { updated: false, id: result.data.id };
|
||||
};
|
||||
@@ -21,7 +21,7 @@ jobs:
|
||||
git config --global user.name "lobehubbot"
|
||||
git config --global user.email "i@lobehub.com"
|
||||
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.ref }}
|
||||
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
actions: read # Required for Claude to read CI results on PRs
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
|
||||
# This is an optional setting that allows Claude to read CI results on PRs
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
|
||||
# Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
|
||||
# model: 'claude-opus-4-1-20250805'
|
||||
allowed_bots: 'bot'
|
||||
|
||||
# Optional: Customize the trigger phrase (default: @claude)
|
||||
# trigger_phrase: "/claude"
|
||||
|
||||
# Optional: Trigger when specific user is assigned to an issue
|
||||
# assignee_trigger: "claude-bot"
|
||||
|
||||
# Optional: Allow Claude to run specific commands
|
||||
allowed_tools: 'Bash(bun run:*),Bash(pnpm run:*),Bash(npm run:*),Bash(npx:*),Bash(bunx:*),Bash(vitest:*),Bash(rg:*),Bash(find:*),Bash(sed:*),Bash(grep:*),Bash(awk:*),Bash(wc:*),Bash(xargs:*)'
|
||||
|
||||
# Optional: Add custom instructions for Claude to customize its behavior for your project
|
||||
# custom_instructions: |
|
||||
# Follow our coding standards
|
||||
# Ensure all new code has tests
|
||||
# Use TypeScript for new files
|
||||
|
||||
# Optional: Custom environment variables for Claude
|
||||
# claude_env: |
|
||||
# NODE_ENV: test
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
runs-on: ubuntu-latest # 只在 ubuntu 上运行一次检查
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 10
|
||||
version: 9
|
||||
|
||||
- name: Install deps
|
||||
run: pnpm install
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
# 输出版本信息,供后续 job 使用
|
||||
version: ${{ steps.set_version.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -95,7 +95,7 @@ jobs:
|
||||
matrix:
|
||||
os: [macos-latest, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 10
|
||||
version: 9
|
||||
|
||||
# node-linker=hoisted 模式将可以确保 asar 压缩可用
|
||||
- name: Install deps
|
||||
@@ -155,9 +155,9 @@ jobs:
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_NIGHTLY_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_NIGHTLY_DESKTOP_BASE_URL }}
|
||||
# 将 TEMP 和 TMP 目录设置到 C 盘
|
||||
TEMP: C:\temp
|
||||
TMP: C:\temp
|
||||
# 将 TEMP 和 TMP 目录设置到 D 盘
|
||||
TEMP: D:\temp
|
||||
TMP: D:\temp
|
||||
|
||||
# Linux 平台构建处理
|
||||
- name: Build artifact on Linux
|
||||
@@ -183,10 +183,6 @@ jobs:
|
||||
apps/desktop/release/*.zip*
|
||||
apps/desktop/release/*.exe*
|
||||
apps/desktop/release/*.AppImage
|
||||
apps/desktop/release/*.deb*
|
||||
apps/desktop/release/*.snap*
|
||||
apps/desktop/release/*.rpm*
|
||||
apps/desktop/release/*.tar.gz*
|
||||
retention-days: 5
|
||||
|
||||
publish-pr:
|
||||
@@ -200,7 +196,7 @@ jobs:
|
||||
outputs:
|
||||
artifact_path: ${{ steps.set_path.outputs.path }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -249,10 +245,6 @@ jobs:
|
||||
release/*.zip*
|
||||
release/*.exe*
|
||||
release/*.AppImage
|
||||
release/*.deb*
|
||||
release/*.snap*
|
||||
release/*.rpm*
|
||||
release/*.tar.gz*
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
|
||||
- name: Build and export
|
||||
id: build
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: .
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -159,24 +159,3 @@ jobs:
|
||||
- name: Inspect image
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
|
||||
- name: Comment on PR with Docker build info
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
const prComment = require('${{ github.workspace }}/.github/scripts/docker-pr-comment.js');
|
||||
const result = await prComment({
|
||||
github,
|
||||
context,
|
||||
dockerMetaJson: ${{ toJSON(steps.meta.outputs.json) }},
|
||||
image: "${{ env.REGISTRY_IMAGE }}",
|
||||
version: "${{ steps.meta.outputs.version }}",
|
||||
dockerhubUrl: "https://hub.docker.com/r/${{ env.REGISTRY_IMAGE }}/tags",
|
||||
platforms: "linux/amd64, linux/arm64",
|
||||
});
|
||||
core.info(`Status: ${result.updated ? 'Updated' : 'Created'}, ID: ${result.id}`);
|
||||
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
|
||||
- name: Build and export
|
||||
id: build
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: .
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
|
||||
- name: Build and export
|
||||
id: build
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: .
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -42,12 +42,12 @@ jobs:
|
||||
echo "BRANCH=$BRANCH" >> $GITHUB_ENV
|
||||
env:
|
||||
REPO_BRANCH: ${{ matrix.REPO_BRANCH || env.REPO_BRANCH }}
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ env.REPOSITORY }}
|
||||
token: ${{ secrets[matrix.TOKEN_NAME] || secrets[env.TOKEN_NAME] }}
|
||||
ref: ${{ env.BRANCH }}
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: 'myactionway/lighthouse-badges'
|
||||
path: temp_lighthouse_badges_nested
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
runs-on: ubuntu-latest # 只在 ubuntu 上运行一次检查
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 10
|
||||
version: 9
|
||||
|
||||
- name: Install deps
|
||||
run: pnpm install
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
version: ${{ steps.set_version.outputs.version }}
|
||||
is_pr_build: ${{ steps.set_version.outputs.is_pr_build }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
matrix:
|
||||
os: [macos-latest, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -94,7 +94,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 10
|
||||
version: 9
|
||||
|
||||
# node-linker=hoisted 模式将可以确保 asar 压缩可用
|
||||
- name: Install deps
|
||||
@@ -139,9 +139,9 @@ jobs:
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
|
||||
# 将 TEMP 和 TMP 目录设置到 C 盘
|
||||
TEMP: C:\temp
|
||||
TMP: C:\temp
|
||||
# 将 TEMP 和 TMP 目录设置到 D 盘
|
||||
TEMP: D:\temp
|
||||
TMP: D:\temp
|
||||
|
||||
# Linux 平台构建处理
|
||||
- name: Build artifact on Linux
|
||||
@@ -165,10 +165,6 @@ jobs:
|
||||
apps/desktop/release/*.zip*
|
||||
apps/desktop/release/*.exe*
|
||||
apps/desktop/release/*.AppImage
|
||||
apps/desktop/release/*.deb*
|
||||
apps/desktop/release/*.snap*
|
||||
apps/desktop/release/*.rpm*
|
||||
apps/desktop/release/*.tar.gz*
|
||||
retention-days: 5
|
||||
|
||||
# 正式版发布 job
|
||||
@@ -205,9 +201,5 @@ jobs:
|
||||
release/*.zip*
|
||||
release/*.exe*
|
||||
release/*.AppImage
|
||||
release/*.deb*
|
||||
release/*.snap*
|
||||
release/*.rpm*
|
||||
release/*.tar.gz*
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -11,20 +11,16 @@ jobs:
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: paradedb/paradedb:latest
|
||||
image: pgvector/pgvector:pg16
|
||||
env:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
options: >-
|
||||
--health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
|
||||
|
||||
|
||||
ports:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -42,8 +38,8 @@ jobs:
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Test Database Coverage
|
||||
run: bun run --filter @lobechat/database test
|
||||
- name: Test Server Coverage
|
||||
run: bun run test-server:coverage
|
||||
env:
|
||||
DATABASE_TEST_URL: postgresql://postgres:postgres@localhost:5432/postgres
|
||||
DATABASE_DRIVER: node
|
||||
@@ -52,8 +48,8 @@ jobs:
|
||||
S3_PUBLIC_DOMAIN: https://example.com
|
||||
APP_URL: https://home.com
|
||||
|
||||
- name: Test App
|
||||
run: bun run test-app
|
||||
- name: Test App Coverage
|
||||
run: bun run test-app:coverage
|
||||
|
||||
- name: Release
|
||||
run: bun run release
|
||||
|
||||
@@ -11,7 +11,7 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install dbdocs
|
||||
run: sudo npm install -g dbdocs
|
||||
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
if: ${{ github.event.repository.fork }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Clean issue notice
|
||||
uses: actions-cool/issues-helper@v3
|
||||
|
||||
@@ -2,115 +2,8 @@ name: Test CI
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# Package tests - using each package's own test script
|
||||
test-intenral-packages:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
package: [file-loaders, prompts, model-runtime, web-crawler, electron-server-ipc, utils]
|
||||
|
||||
name: Test package ${{ matrix.package }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: ${{ secrets.BUN_VERSION }}
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
|
||||
- name: Test ${{ matrix.package }} package with coverage
|
||||
run: bun run --filter @lobechat/${{ matrix.package }} test:coverage
|
||||
|
||||
- name: Upload ${{ matrix.package }} coverage to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./packages/${{ matrix.package }}/coverage/lcov.info
|
||||
flags: packages/${{ matrix.package }}
|
||||
|
||||
test-packages:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
package: [model-bank]
|
||||
|
||||
name: Test package ${{ matrix.package }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: ${{ secrets.BUN_VERSION }}
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
|
||||
- name: Test ${{ matrix.package }} package with coverage
|
||||
run: bun run --filter ${{ matrix.package }} test:coverage
|
||||
|
||||
- name: Upload ${{ matrix.package }} coverage to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./packages/${{ matrix.package }}/coverage/lcov.info
|
||||
flags: packages/${{ matrix.package }}
|
||||
|
||||
|
||||
# App tests
|
||||
test-website:
|
||||
name: Test Website
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: ${{ secrets.BUN_VERSION }}
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
|
||||
- name: Test App Coverage
|
||||
run: bun run test-app:coverage
|
||||
|
||||
- name: Upload App Coverage to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./coverage/app/lcov.info
|
||||
flags: app
|
||||
|
||||
test-databsae:
|
||||
name: Test Database
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
services:
|
||||
@@ -126,7 +19,7 @@ jobs:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -144,15 +37,8 @@ jobs:
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Test Client DB
|
||||
run: bun run --filter @lobechat/database test:client-db
|
||||
env:
|
||||
KEY_VAULTS_SECRET: LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=
|
||||
S3_PUBLIC_DOMAIN: https://example.com
|
||||
APP_URL: https://home.com
|
||||
|
||||
- name: Test Coverage
|
||||
run: bun run --filter @lobechat/database test:coverage
|
||||
- name: Test Server Coverage
|
||||
run: bun run test-server:coverage
|
||||
env:
|
||||
DATABASE_TEST_URL: postgresql://postgres:postgres@localhost:5432/postgres
|
||||
DATABASE_DRIVER: node
|
||||
@@ -161,9 +47,19 @@ jobs:
|
||||
S3_PUBLIC_DOMAIN: https://example.com
|
||||
APP_URL: https://home.com
|
||||
|
||||
- name: Upload Database coverage to Codecov
|
||||
- name: Upload Server coverage to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./packages/database/coverage/lcov.info
|
||||
flags: database
|
||||
files: ./coverage/server/lcov.info
|
||||
flags: server
|
||||
|
||||
- name: Test App Coverage
|
||||
run: bun run test-app:coverage
|
||||
|
||||
- name: Upload App Coverage to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./coverage/app/lcov.info
|
||||
flags: app
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
name: Wiki Sync
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
paths:
|
||||
- 'docs/wiki/**'
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
update-wiki:
|
||||
runs-on: ubuntu-latest
|
||||
name: Wiki sync
|
||||
steps:
|
||||
- uses: OrlovM/Wiki-Action@v1
|
||||
with:
|
||||
path: 'docs/wiki'
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
@@ -1,114 +1,73 @@
|
||||
# Gitignore for LobeHub
|
||||
################################################################
|
||||
|
||||
# System files
|
||||
# general
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
Desktop.ini
|
||||
|
||||
# Linux/Ubuntu system files
|
||||
*~
|
||||
*.swp
|
||||
*.swo
|
||||
.fuse_hidden*
|
||||
.directory
|
||||
.Trash-*
|
||||
.nfs*
|
||||
.gvfs-fuse-daemon-*
|
||||
|
||||
# IDE and editors
|
||||
.idea/
|
||||
*.sublime-*
|
||||
.history/
|
||||
.windsurfrules
|
||||
*.code-workspace
|
||||
|
||||
# Temporary files
|
||||
.temp/
|
||||
temp/
|
||||
tmp/
|
||||
*.tmp
|
||||
*.temp
|
||||
*.log
|
||||
*.cache
|
||||
.cache/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.idea
|
||||
.vscode
|
||||
.history
|
||||
.temp
|
||||
.env.local
|
||||
.env*.local
|
||||
venv/
|
||||
.venv/
|
||||
venv
|
||||
temp
|
||||
tmp
|
||||
.windsurfrules
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
# dependencies
|
||||
node_modules
|
||||
*.log
|
||||
*.lock
|
||||
package-lock.json
|
||||
bun.lockb
|
||||
.pnpm-store/
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
es/
|
||||
lib/
|
||||
.next/
|
||||
logs/
|
||||
test-output/
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# Framework specific
|
||||
# Umi
|
||||
.umi/
|
||||
.umi-production/
|
||||
.umi-test/
|
||||
.dumi/tmp*/
|
||||
|
||||
# Vercel
|
||||
.vercel/
|
||||
|
||||
# Testing and CI
|
||||
coverage/
|
||||
.coverage/
|
||||
.nyc_output/
|
||||
# ci
|
||||
coverage
|
||||
.coverage
|
||||
.eslintcache
|
||||
.stylelintcache
|
||||
|
||||
# Service Worker
|
||||
# production
|
||||
dist
|
||||
es
|
||||
lib
|
||||
logs
|
||||
test-output
|
||||
|
||||
# umi
|
||||
.umi
|
||||
.umi-production
|
||||
.umi-test
|
||||
.dumi/tmp*
|
||||
|
||||
# husky
|
||||
.husky/prepare-commit-msg
|
||||
|
||||
# misc
|
||||
# add other ignore file below
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
.next
|
||||
.env
|
||||
public/*.js
|
||||
public/sitemap.xml
|
||||
public/sitemap-index.xml
|
||||
bun.lockb
|
||||
sitemap*.xml
|
||||
robots.txt
|
||||
|
||||
# Serwist
|
||||
public/sw*
|
||||
public/swe-worker*
|
||||
|
||||
# Generated files
|
||||
public/*.js
|
||||
public/sitemap.xml
|
||||
public/sitemap-index.xml
|
||||
sitemap*.xml
|
||||
robots.txt
|
||||
|
||||
# Git hooks
|
||||
.husky/prepare-commit-msg
|
||||
|
||||
# Documents and media
|
||||
*.patch
|
||||
*.pdf
|
||||
|
||||
# Cloud service keys
|
||||
vertex-ai-key.json
|
||||
|
||||
# AI coding tools
|
||||
.local/
|
||||
.claude/
|
||||
.mcp.json
|
||||
|
||||
CLAUDE.local.md
|
||||
|
||||
# MCP tools
|
||||
.serena/**
|
||||
|
||||
# Misc
|
||||
.pnpm-store
|
||||
./packages/lobe-ui
|
||||
*.ppt*
|
||||
*.doc*
|
||||
*.xls*
|
||||
|
||||
@@ -4,9 +4,6 @@ resolution-mode=highest
|
||||
ignore-workspace-root-check=true
|
||||
enable-pre-post-scripts=true
|
||||
|
||||
# Load dotenv files for all the npm scripts
|
||||
node-options="--require dotenv-expand/config"
|
||||
|
||||
public-hoist-pattern[]=*@umijs/lint*
|
||||
public-hoist-pattern[]=*changelog*
|
||||
public-hoist-pattern[]=*commitlint*
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
.DS_Store
|
||||
.editorconfig
|
||||
.idea
|
||||
.vscode
|
||||
.history
|
||||
.temp
|
||||
.env.local
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
# Stylelintignore for LobeHub
|
||||
################################################################
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
|
||||
# ci
|
||||
coverage
|
||||
.coverage
|
||||
|
||||
# production
|
||||
dist
|
||||
es
|
||||
lib
|
||||
logs
|
||||
|
||||
# framework specific
|
||||
.next
|
||||
.umi
|
||||
.umi-production
|
||||
.umi-test
|
||||
.dumi/tmp*
|
||||
|
||||
# temporary directories
|
||||
tmp
|
||||
temp
|
||||
.temp
|
||||
.local
|
||||
docs/.local
|
||||
|
||||
# cache directories
|
||||
.cache
|
||||
|
||||
# AI coding tools directories
|
||||
.claude
|
||||
.serena
|
||||
|
||||
# MCP tools
|
||||
/.serena/**
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"Anthropic.claude-code",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"jrr997.antd-docs",
|
||||
"seatonjiang.gitmoji-vscode",
|
||||
"styled-components.vscode-styled-components",
|
||||
"stylelint.vscode-stylelint",
|
||||
"unifiedjs.vscode-mdx",
|
||||
"unifiedjs.vscode-remark",
|
||||
"vitest.explorer",
|
||||
]
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
{
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.addMissingImports": "explicit",
|
||||
"source.fixAll.eslint": "explicit",
|
||||
"source.fixAll.stylelint": "explicit"
|
||||
},
|
||||
"editor.formatOnSave": true,
|
||||
// don't show errors, but fix when save and git pre commit
|
||||
"eslint.rules.customizations": [
|
||||
{ "rule": "import/order", "severity": "off" },
|
||||
{ "rule": "prettier/prettier", "severity": "off" },
|
||||
{ "rule": "react/jsx-sort-props", "severity": "off" },
|
||||
{ "rule": "sort-keys-fix/sort-keys-fix", "severity": "off" },
|
||||
{ "rule": "typescript-sort-keys/interface", "severity": "off" }
|
||||
],
|
||||
"eslint.validate": [
|
||||
"javascript",
|
||||
"javascriptreact",
|
||||
"typescript",
|
||||
"typescriptreact",
|
||||
// support mdx
|
||||
"mdx"
|
||||
],
|
||||
"npm.packageManager": "pnpm",
|
||||
"search.exclude": {
|
||||
"**/node_modules": true,
|
||||
// useless to search this big folder
|
||||
"locales": true
|
||||
},
|
||||
"stylelint.validate": [
|
||||
"css",
|
||||
"postcss",
|
||||
// make stylelint work with tsx antd-style css template string
|
||||
"typescriptreact"
|
||||
],
|
||||
"vitest.maximumConfigs": 20,
|
||||
"workbench.editor.customLabels.patterns": {
|
||||
"**/app/**/[[]*[]]/[[]*[]]/page.tsx": "${dirname(2)}/${dirname(1)}/${dirname} • page component",
|
||||
"**/app/**/[[]*[]]/page.tsx": "${dirname(1)}/${dirname} • page component",
|
||||
"**/app/**/page.tsx": "${dirname} • page component",
|
||||
|
||||
"**/app/**/[[]*[]]/[[]*[]]/layout.tsx": "${dirname(2)}/${dirname(1)}/${dirname} • page layout",
|
||||
"**/app/**/[[]*[]]/layout.tsx": "${dirname(1)}/${dirname} • page layout",
|
||||
"**/app/**/layout.tsx": "${dirname} • page layout",
|
||||
|
||||
"**/app/**/[[]*[]]/[[]*[]]/default.tsx": "${dirname(2)}/${dirname(1)}/${dirname} • slot default",
|
||||
"**/app/**/[[]*[]]/default.tsx": "${dirname(1)}/${dirname} • slot default",
|
||||
"**/app/**/default.tsx": "${dirname} • slot default",
|
||||
|
||||
"**/app/**/[[]*[]]/[[]*[]]/error.tsx": "${dirname(2)}/${dirname(1)}/${dirname} • error component",
|
||||
"**/app/**/[[]*[]]/error.tsx": "${dirname(1)}/${dirname} • error component",
|
||||
"**/app/**/error.tsx": "${dirname} • error component",
|
||||
|
||||
"**/app/**/[[]*[]]/[[]*[]]/loading.tsx": "${dirname(2)}/${dirname(1)}/${dirname} • loading component",
|
||||
"**/app/**/[[]*[]]/loading.tsx": "${dirname(1)}/${dirname} • loading component",
|
||||
"**/app/**/loading.tsx": "${dirname} • loading component",
|
||||
|
||||
"**/src/**/route.ts": "${dirname(1)}/${dirname} • route",
|
||||
"**/src/**/index.tsx": "${dirname} • component",
|
||||
|
||||
"**/packages/database/src/repositories/*/index.ts": "${dirname} • db repository",
|
||||
"**/packages/database/src/models/*.ts": "${filename} • db model",
|
||||
"**/packages/database/src/schemas/*.ts": "${filename} • db schema",
|
||||
|
||||
"**/src/services/*.ts": "${filename} • service",
|
||||
"**/src/services/*/client.ts": "${dirname} • client service",
|
||||
"**/src/services/*/server.ts": "${dirname} • server service",
|
||||
|
||||
"**/src/store/*/action.ts": "${dirname} • action",
|
||||
"**/src/store/*/slices/*/action.ts": "${dirname(2)}/${dirname} • action",
|
||||
"**/src/store/*/slices/*/actions/*.ts": "${dirname(1)}/${dirname}/${filename} • action",
|
||||
|
||||
"**/src/store/*/initialState.ts": "${dirname} • state",
|
||||
"**/src/store/*/slices/*/initialState.ts": "${dirname(2)}/${dirname} • state",
|
||||
|
||||
"**/src/store/*/selectors.ts": "${dirname} • selectors",
|
||||
"**/src/store/*/slices/*/selectors.ts": "${dirname(2)}/${dirname} • selectors",
|
||||
|
||||
"**/src/store/*/reducer.ts": "${dirname} • reducer",
|
||||
"**/src/store/*/slices/*/reducer.ts": "${dirname(2)}/${dirname} • reducer",
|
||||
|
||||
"**/src/config/modelProviders/*.ts": "${filename} • provider",
|
||||
"**/packages/model-bank/src/aiModels/*.ts": "${filename} • model",
|
||||
"**/packages/model-runtime/src/*/index.ts": "${dirname} • runtime",
|
||||
|
||||
"**/src/server/services/*/index.ts": "${dirname} • server/service",
|
||||
"**/src/server/routers/lambda/*.ts": "${filename} • lambda",
|
||||
"**/src/server/routers/async/*.ts": "${filename} • async",
|
||||
"**/src/server/routers/edge/*.ts": "${filename} • edge",
|
||||
|
||||
"**/src/locales/default/*.ts": "${filename} • locale"
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
# LobeChat Development Guidelines
|
||||
|
||||
This document serves as a comprehensive guide for all team members when developing LobeChat.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
Built with modern technologies:
|
||||
|
||||
- **Frontend**: Next.js 15, React 19, TypeScript
|
||||
- **UI Components**: Ant Design, @lobehub/ui, antd-style
|
||||
- **State Management**: Zustand, SWR
|
||||
- **Database**: PostgreSQL, PGLite, Drizzle ORM
|
||||
- **Testing**: Vitest, Testing Library
|
||||
- **Package Manager**: pnpm (monorepo structure)
|
||||
- **Build Tools**: Next.js (Turbopack in dev, Webpack in prod), Vitest
|
||||
|
||||
## Directory Structure
|
||||
|
||||
The project follows a well-organized monorepo structure:
|
||||
|
||||
- `apps/` - Main applications
|
||||
- `packages/` - Shared packages and libraries
|
||||
- `src/` - Main source code
|
||||
- `docs/` - Documentation
|
||||
- `.cursor/rules/` - Development rules and guidelines
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Git Workflow
|
||||
|
||||
- Use rebase for git pull: `git pull --rebase`
|
||||
- Git commit messages should prefix with gitmoji
|
||||
- Git branch name format: `username/feat/feature-name`
|
||||
- Use `.github/PULL_REQUEST_TEMPLATE.md` for PR descriptions
|
||||
|
||||
### Package Management
|
||||
|
||||
- Use `pnpm` as the primary package manager
|
||||
- Use `bun` to run npm scripts
|
||||
- Use `bunx` to run executable npm packages
|
||||
- Navigate to specific packages using `cd packages/<package-name>`
|
||||
|
||||
### Code Style Guidelines
|
||||
|
||||
#### TypeScript
|
||||
|
||||
- Follow strict TypeScript practices for type safety and code quality
|
||||
- Use proper type annotations
|
||||
- Prefer interfaces over types for object shapes
|
||||
- Use generics for reusable components
|
||||
|
||||
#### React Components
|
||||
|
||||
- Use functional components with hooks
|
||||
- Follow the component structure guidelines
|
||||
- Use antd-style & @lobehub/ui for styling
|
||||
- Implement proper error boundaries
|
||||
|
||||
#### Database Schema
|
||||
|
||||
- Follow Drizzle ORM naming conventions
|
||||
- Use plural snake_case for table names
|
||||
- Implement proper foreign key relationships
|
||||
- Follow the schema style guide
|
||||
|
||||
### Testing Strategy
|
||||
|
||||
**Required Rule**: `testing-guide/testing-guide.mdc`
|
||||
|
||||
**Commands**:
|
||||
|
||||
- Web: `bunx vitest run --silent='passed-only' '[file-path-pattern]'`
|
||||
- Packages: `cd packages/[package-name] && bunx vitest run --silent='passed-only' '[file-path-pattern]'`
|
||||
|
||||
**Important Notes**:
|
||||
|
||||
- Wrap file paths in single quotes to avoid shell expansion
|
||||
- Never run `bun run test` - this runs all tests and takes ~10 minutes
|
||||
- If a test fails twice, stop and ask for help
|
||||
- Always add tests for new code
|
||||
|
||||
### Type Checking
|
||||
|
||||
- Use `bun run type-check` to check for type errors
|
||||
- Ensure all TypeScript errors are resolved before committing
|
||||
|
||||
### Internationalization
|
||||
|
||||
- Add new keys to `src/locales/default/namespace.ts`
|
||||
- Translate at least `zh-CN` files for development preview
|
||||
- Use hierarchical nested objects, not flat keys
|
||||
- Don't run `pnpm i18n` manually (handled by CI)
|
||||
|
||||
## Available Development Rules
|
||||
|
||||
The project provides comprehensive rules in `.cursor/rules/` directory:
|
||||
|
||||
### Core Development
|
||||
|
||||
- `backend-architecture.mdc` - Three-layer architecture and data flow
|
||||
- `react-component.mdc` - Component patterns and UI library usage
|
||||
- `drizzle-schema-style-guide.mdc` - Database schema conventions
|
||||
- `define-database-model.mdc` - Model templates and CRUD patterns
|
||||
- `i18n.mdc` - Internationalization workflow
|
||||
|
||||
### State Management & UI
|
||||
|
||||
- `zustand-slice-organization.mdc` - Store organization patterns
|
||||
- `zustand-action-patterns.mdc` - Action implementation patterns
|
||||
- `packages/react-layout-kit.mdc` - Flex layout component usage
|
||||
|
||||
### Testing & Quality
|
||||
|
||||
- `testing-guide/testing-guide.mdc` - Comprehensive testing strategy
|
||||
- `code-review.mdc` - Code review process and standards
|
||||
|
||||
### Desktop (Electron)
|
||||
|
||||
- `desktop-feature-implementation.mdc` - Main/renderer process patterns
|
||||
- `desktop-local-tools-implement.mdc` - Tool integration workflow
|
||||
- `desktop-menu-configuration.mdc` - Menu system configuration
|
||||
- `desktop-window-management.mdc` - Window management patterns
|
||||
- `desktop-controller-tests.mdc` - Controller testing guide
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Conservative for existing code, modern approaches for new features**
|
||||
- **Code Language**: Use Chinese for files with existing Chinese comments, American English for new files
|
||||
- Always add tests for new functionality
|
||||
- Follow the established patterns in the codebase
|
||||
- Use proper error handling and logging
|
||||
- Implement proper accessibility features
|
||||
- Consider internationalization from the start
|
||||
@@ -1,100 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This document serves as a shared guideline for all team members when using Claude Code in this repository.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
read @.cursor/rules/project-introduce.mdc
|
||||
|
||||
## Directory Structure
|
||||
|
||||
read @.cursor/rules/project-structure.mdc
|
||||
|
||||
## Development
|
||||
|
||||
### Git Workflow
|
||||
|
||||
- use rebase for git pull
|
||||
- git commit message should prefix with gitmoji
|
||||
- git branch name format example: tj/feat/feature-name
|
||||
- use .github/PULL_REQUEST_TEMPLATE.md to generate pull request description
|
||||
|
||||
### Package Management
|
||||
|
||||
This repository adopts a monorepo structure.
|
||||
|
||||
- Use `pnpm` as the primary package manager for dependency management
|
||||
- Use `bun` to run npm scripts
|
||||
- Use `bunx` to run executable npm packages
|
||||
|
||||
### TypeScript Code Style Guide
|
||||
|
||||
see @.cursor/rules/typescript.mdc
|
||||
|
||||
### Modify Code Rules
|
||||
|
||||
- **Code Language**:
|
||||
- For files with existing Chinese comments: Continue using Chinese to maintain consistency
|
||||
- For new files or files without Chinese comments: MUST use American English.
|
||||
- eg: new react tsx file and new test file
|
||||
- Conservative for existing code, modern approaches for new features
|
||||
|
||||
### Testing
|
||||
|
||||
Testing work follows the Rule-Aware Task Execution system above.
|
||||
|
||||
- **Required Rule**: `testing-guide/testing-guide.mdc`
|
||||
- **Command**:
|
||||
- web: `bunx vitest run --silent='passed-only' '[file-path-pattern]'`
|
||||
- packages(eg: database): `cd packages/database && bunx vitest run --silent='passed-only' '[file-path-pattern]'`
|
||||
|
||||
**Important**:
|
||||
|
||||
- wrapped the file path in single quotes to avoid shell expansion
|
||||
- Never run `bun run test` etc to run tests, this will run all tests and cost about 10mins
|
||||
- If try to fix the same test twice, but still failed, stop and ask for help.
|
||||
|
||||
### Typecheck
|
||||
|
||||
- use `bun run type-check` to check type errors.
|
||||
|
||||
### i18n
|
||||
|
||||
- **Keys**: Add to `src/locales/default/namespace.ts`
|
||||
- **Dev**: Translate `locales/zh-CN/namespace.json` locale file only for preview
|
||||
- DON'T run `pnpm i18n`, let CI auto handle it
|
||||
|
||||
## Rules Index
|
||||
|
||||
Some useful rules of this project. Read them when needed.
|
||||
|
||||
**IMPORTANT**: All rule files referenced in this document are located in the `.cursor/rules/` directory. Throughout this document, rule files are referenced by their filename only for brevity.
|
||||
|
||||
### 📋 Complete Rule Files
|
||||
|
||||
**Core Development**
|
||||
|
||||
- `backend-architecture.mdc` - Three-layer architecture, data flow
|
||||
- `react-component.mdc` - antd-style, Lobe UI usage
|
||||
- `drizzle-schema-style-guide.mdc` - Schema naming, patterns
|
||||
- `define-database-model.mdc` - Model templates, CRUD patterns
|
||||
- `i18n.mdc` - Internationalization workflow
|
||||
|
||||
**State & UI**
|
||||
|
||||
- `zustand-slice-organization.mdc` - Store organization
|
||||
- `zustand-action-patterns.mdc` - Action patterns
|
||||
- `packages/react-layout-kit.mdc` - flex layout components usage
|
||||
|
||||
**Testing & Quality**
|
||||
|
||||
- `testing-guide/testing-guide.mdc` - Test strategy, mock patterns
|
||||
- `code-review.mdc` - Review process and standards
|
||||
|
||||
**Desktop (Electron)**
|
||||
|
||||
- `desktop-feature-implementation.mdc` - Main/renderer process patterns
|
||||
- `desktop-local-tools-implement.mdc` - Tool integration workflow
|
||||
- `desktop-menu-configuration.mdc` - App menu, context menu, tray menu
|
||||
- `desktop-window-management.mdc` - Window creation, state management, multi-window
|
||||
- `desktop-controller-tests.mdc` - Controller unit testing guide
|
||||
@@ -53,8 +53,6 @@ ENV NEXT_PUBLIC_SENTRY_DSN="${NEXT_PUBLIC_SENTRY_DSN}" \
|
||||
SENTRY_ORG="" \
|
||||
SENTRY_PROJECT=""
|
||||
|
||||
ENV APP_URL="http://app.com"
|
||||
|
||||
# Posthog
|
||||
ENV NEXT_PUBLIC_ANALYTICS_POSTHOG="${NEXT_PUBLIC_ANALYTICS_POSTHOG}" \
|
||||
NEXT_PUBLIC_POSTHOG_HOST="${NEXT_PUBLIC_POSTHOG_HOST}" \
|
||||
@@ -66,7 +64,7 @@ ENV NEXT_PUBLIC_ANALYTICS_UMAMI="${NEXT_PUBLIC_ANALYTICS_UMAMI}" \
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID="${NEXT_PUBLIC_UMAMI_WEBSITE_ID}"
|
||||
|
||||
# Node
|
||||
ENV NODE_OPTIONS="--max-old-space-size=6144"
|
||||
ENV NODE_OPTIONS="--max-old-space-size=8192"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -150,8 +148,6 @@ ENV \
|
||||
AI21_API_KEY="" AI21_MODEL_LIST="" \
|
||||
# Ai360
|
||||
AI360_API_KEY="" AI360_MODEL_LIST="" \
|
||||
# AiHubMix
|
||||
AIHUBMIX_API_KEY="" AIHUBMIX_MODEL_LIST="" \
|
||||
# Anthropic
|
||||
ANTHROPIC_API_KEY="" ANTHROPIC_MODEL_LIST="" ANTHROPIC_PROXY_URL="" \
|
||||
# Amazon Bedrock
|
||||
@@ -194,8 +190,6 @@ ENV \
|
||||
MODELSCOPE_API_KEY="" MODELSCOPE_MODEL_LIST="" MODELSCOPE_PROXY_URL="" \
|
||||
# Moonshot
|
||||
MOONSHOT_API_KEY="" MOONSHOT_MODEL_LIST="" MOONSHOT_PROXY_URL="" \
|
||||
# Nebius
|
||||
NEBIUS_API_KEY="" NEBIUS_MODEL_LIST="" NEBIUS_PROXY_URL="" \
|
||||
# Novita
|
||||
NOVITA_API_KEY="" NOVITA_MODEL_LIST="" \
|
||||
# Nvidia NIM
|
||||
@@ -249,13 +243,7 @@ ENV \
|
||||
# Tencent Cloud
|
||||
TENCENT_CLOUD_API_KEY="" TENCENT_CLOUD_MODEL_LIST="" \
|
||||
# Infini-AI
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST="" \
|
||||
# 302.AI
|
||||
AI302_API_KEY="" AI302_MODEL_LIST="" \
|
||||
# FAL
|
||||
FAL_API_KEY="" FAL_MODEL_LIST="" \
|
||||
# BFL
|
||||
BFL_API_KEY="" BFL_MODEL_LIST=""
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST=""
|
||||
|
||||
USER nextjs
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ ENV NEXT_PUBLIC_ANALYTICS_UMAMI="${NEXT_PUBLIC_ANALYTICS_UMAMI}" \
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID="${NEXT_PUBLIC_UMAMI_WEBSITE_ID}"
|
||||
|
||||
# Node
|
||||
ENV NODE_OPTIONS="--max-old-space-size=6144"
|
||||
ENV NODE_OPTIONS="--max-old-space-size=8192"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -120,7 +120,7 @@ COPY --from=base /distroless/ /
|
||||
COPY --from=builder /app/.next/standalone /app/
|
||||
|
||||
# Copy database migrations
|
||||
COPY --from=builder /app/packages/database/migrations /app/migrations
|
||||
COPY --from=builder /app/src/database/migrations /app/migrations
|
||||
COPY --from=builder /app/scripts/migrateServerDB/docker.cjs /app/docker.cjs
|
||||
COPY --from=builder /app/scripts/migrateServerDB/errorHint.js /app/errorHint.js
|
||||
|
||||
@@ -192,8 +192,6 @@ ENV \
|
||||
AI21_API_KEY="" AI21_MODEL_LIST="" \
|
||||
# Ai360
|
||||
AI360_API_KEY="" AI360_MODEL_LIST="" \
|
||||
# AiHubMix
|
||||
AIHUBMIX_API_KEY="" AIHUBMIX_MODEL_LIST="" \
|
||||
# Anthropic
|
||||
ANTHROPIC_API_KEY="" ANTHROPIC_MODEL_LIST="" ANTHROPIC_PROXY_URL="" \
|
||||
# Amazon Bedrock
|
||||
@@ -236,8 +234,6 @@ ENV \
|
||||
MODELSCOPE_API_KEY="" MODELSCOPE_MODEL_LIST="" MODELSCOPE_PROXY_URL="" \
|
||||
# Moonshot
|
||||
MOONSHOT_API_KEY="" MOONSHOT_MODEL_LIST="" MOONSHOT_PROXY_URL="" \
|
||||
# Nebius
|
||||
NEBIUS_API_KEY="" NEBIUS_MODEL_LIST="" NEBIUS_PROXY_URL="" \
|
||||
# Novita
|
||||
NOVITA_API_KEY="" NOVITA_MODEL_LIST="" \
|
||||
# Nvidia NIM
|
||||
@@ -291,13 +287,7 @@ ENV \
|
||||
# Tencent Cloud
|
||||
TENCENT_CLOUD_API_KEY="" TENCENT_CLOUD_MODEL_LIST="" \
|
||||
# Infini-AI
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST="" \
|
||||
# 302.AI
|
||||
AI302_API_KEY="" AI302_MODEL_LIST="" \
|
||||
# FAL
|
||||
FAL_API_KEY="" FAL_MODEL_LIST="" \
|
||||
# BFL
|
||||
BFL_API_KEY="" BFL_MODEL_LIST=""
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST=""
|
||||
|
||||
USER nextjs
|
||||
|
||||
|
||||
@@ -55,8 +55,6 @@ ENV NEXT_PUBLIC_SENTRY_DSN="${NEXT_PUBLIC_SENTRY_DSN}" \
|
||||
SENTRY_ORG="" \
|
||||
SENTRY_PROJECT=""
|
||||
|
||||
ENV APP_URL="http://app.com"
|
||||
|
||||
# Posthog
|
||||
ENV NEXT_PUBLIC_ANALYTICS_POSTHOG="${NEXT_PUBLIC_ANALYTICS_POSTHOG}" \
|
||||
NEXT_PUBLIC_POSTHOG_HOST="${NEXT_PUBLIC_POSTHOG_HOST}" \
|
||||
@@ -68,7 +66,7 @@ ENV NEXT_PUBLIC_ANALYTICS_UMAMI="${NEXT_PUBLIC_ANALYTICS_UMAMI}" \
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID="${NEXT_PUBLIC_UMAMI_WEBSITE_ID}"
|
||||
|
||||
# Node
|
||||
ENV NODE_OPTIONS="--max-old-space-size=6144"
|
||||
ENV NODE_OPTIONS="--max-old-space-size=8192"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -152,8 +150,6 @@ ENV \
|
||||
AI21_API_KEY="" AI21_MODEL_LIST="" \
|
||||
# Ai360
|
||||
AI360_API_KEY="" AI360_MODEL_LIST="" \
|
||||
# AiHubMix
|
||||
AIHUBMIX_API_KEY="" AIHUBMIX_MODEL_LIST="" \
|
||||
# Anthropic
|
||||
ANTHROPIC_API_KEY="" ANTHROPIC_MODEL_LIST="" ANTHROPIC_PROXY_URL="" \
|
||||
# Amazon Bedrock
|
||||
@@ -196,8 +192,6 @@ ENV \
|
||||
MODELSCOPE_API_KEY="" MODELSCOPE_MODEL_LIST="" MODELSCOPE_PROXY_URL="" \
|
||||
# Moonshot
|
||||
MOONSHOT_API_KEY="" MOONSHOT_MODEL_LIST="" MOONSHOT_PROXY_URL="" \
|
||||
# Nebius
|
||||
NEBIUS_API_KEY="" NEBIUS_MODEL_LIST="" NEBIUS_PROXY_URL="" \
|
||||
# Novita
|
||||
NOVITA_API_KEY="" NOVITA_MODEL_LIST="" \
|
||||
# Nvidia NIM
|
||||
@@ -247,13 +241,7 @@ ENV \
|
||||
# Tencent Cloud
|
||||
TENCENT_CLOUD_API_KEY="" TENCENT_CLOUD_MODEL_LIST="" \
|
||||
# Infini-AI
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST="" \
|
||||
# 302.AI
|
||||
AI302_API_KEY="" AI302_MODEL_LIST="" \
|
||||
# FAL
|
||||
FAL_API_KEY="" FAL_MODEL_LIST="" \
|
||||
# BFL
|
||||
BFL_API_KEY="" BFL_MODEL_LIST=""
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST=""
|
||||
|
||||
USER nextjs
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ From productivity tools to development environments, discover new ways to extend
|
||||
|
||||
**Peak Performance, Zero Distractions**
|
||||
|
||||
Get the full LobeChat experience without browser limitations—comprehensive, focused, and always ready to go. Our desktop application provides a dedicated environment for your AI interactions, ensuring optimal performance and minimal distractions.
|
||||
Get the full LobeChat experience without browser limitations—lightweight, focused, and always ready to go. Our desktop application provides a dedicated environment for your AI interactions, ensuring optimal performance and minimal distractions.
|
||||
|
||||
Experience faster response times, better resource management, and a more stable connection to your AI assistant. The desktop app is designed for users who demand the best performance from their AI tools.
|
||||
|
||||
@@ -245,17 +245,15 @@ We have implemented support for the following model service providers:
|
||||
- **[Bedrock](https://lobechat.com/discover/provider/bedrock)**: Bedrock is a service provided by Amazon AWS, focusing on delivering advanced AI language and visual models for enterprises. Its model family includes Anthropic's Claude series, Meta's Llama 3.1 series, and more, offering a range of options from lightweight to high-performance, supporting tasks such as text generation, conversation, and image processing for businesses of varying scales and needs.
|
||||
- **[Google](https://lobechat.com/discover/provider/google)**: Google's Gemini series represents its most advanced, versatile AI models, developed by Google DeepMind, designed for multimodal capabilities, supporting seamless understanding and processing of text, code, images, audio, and video. Suitable for various environments from data centers to mobile devices, it significantly enhances the efficiency and applicability of AI models.
|
||||
- **[DeepSeek](https://lobechat.com/discover/provider/deepseek)**: DeepSeek is a company focused on AI technology research and application, with its latest model DeepSeek-V2.5 integrating general dialogue and code processing capabilities, achieving significant improvements in human preference alignment, writing tasks, and instruction following.
|
||||
- **[Moonshot](https://lobechat.com/discover/provider/moonshot)**: Moonshot is an open-source platform launched by Beijing Dark Side Technology Co., Ltd., providing various natural language processing models with a wide range of applications, including but not limited to content creation, academic research, intelligent recommendations, and medical diagnosis, supporting long text processing and complex generation tasks.
|
||||
- **[OpenRouter](https://lobechat.com/discover/provider/openrouter)**: OpenRouter is a service platform providing access to various cutting-edge large model interfaces, supporting OpenAI, Anthropic, LLaMA, and more, suitable for diverse development and application needs. Users can flexibly choose the optimal model and pricing based on their requirements, enhancing the AI experience.
|
||||
- **[HuggingFace](https://lobechat.com/discover/provider/huggingface)**: The HuggingFace Inference API provides a fast and free way for you to explore thousands of models for various tasks. Whether you are prototyping for a new application or experimenting with the capabilities of machine learning, this API gives you instant access to high-performance models across multiple domains.
|
||||
- **[OpenRouter](https://lobechat.com/discover/provider/openrouter)**: OpenRouter is a service platform providing access to various cutting-edge large model interfaces, supporting OpenAI, Anthropic, LLaMA, and more, suitable for diverse development and application needs. Users can flexibly choose the optimal model and pricing based on their requirements, enhancing the AI experience.
|
||||
- **[Cloudflare Workers AI](https://lobechat.com/discover/provider/cloudflare)**: Run serverless GPU-powered machine learning models on Cloudflare's global network.
|
||||
|
||||
<details><summary><kbd>See more providers (+32)</kbd></summary>
|
||||
|
||||
- **[GitHub](https://lobechat.com/discover/provider/github)**: With GitHub Models, developers can become AI engineers and leverage the industry's leading AI models.
|
||||
|
||||
<details><summary><kbd>See more providers (+31)</kbd></summary>
|
||||
|
||||
- **[Novita](https://lobechat.com/discover/provider/novita)**: Novita AI is a platform providing a variety of large language models and AI image generation API services, flexible, reliable, and cost-effective. It supports the latest open-source models like Llama3 and Mistral, offering a comprehensive, user-friendly, and auto-scaling API solution for generative AI application development, suitable for the rapid growth of AI startups.
|
||||
- **[PPIO](https://lobechat.com/discover/provider/ppio)**: PPIO supports stable and cost-efficient open-source LLM APIs, such as DeepSeek, Llama, Qwen etc.
|
||||
- **[302.AI](https://lobechat.com/discover/provider/ai302)**: 302.AI is an on-demand AI application platform offering the most comprehensive AI APIs and online AI applications available on the market.
|
||||
- **[Together AI](https://lobechat.com/discover/provider/togetherai)**: Together AI is dedicated to achieving leading performance through innovative AI models, offering extensive customization capabilities, including rapid scaling support and intuitive deployment processes to meet various enterprise needs.
|
||||
- **[Fireworks AI](https://lobechat.com/discover/provider/fireworksai)**: Fireworks AI is a leading provider of advanced language model services, focusing on functional calling and multimodal processing. Its latest model, Firefunction V2, is based on Llama-3, optimized for function calling, conversation, and instruction following. The visual language model FireLLaVA-13B supports mixed input of images and text. Other notable models include the Llama series and Mixtral series, providing efficient multilingual instruction following and generation support.
|
||||
- **[Groq](https://lobechat.com/discover/provider/groq)**: Groq's LPU inference engine has excelled in the latest independent large language model (LLM) benchmarks, redefining the standards for AI solutions with its remarkable speed and efficiency. Groq represents instant inference speed, demonstrating strong performance in cloud-based deployments.
|
||||
@@ -274,6 +272,7 @@ We have implemented support for the following model service providers:
|
||||
- **[Spark](https://lobechat.com/discover/provider/spark)**: iFlytek's Spark model provides powerful AI capabilities across multiple domains and languages, utilizing advanced natural language processing technology to build innovative applications suitable for smart hardware, smart healthcare, smart finance, and other vertical scenarios.
|
||||
- **[SenseNova](https://lobechat.com/discover/provider/sensenova)**: SenseNova, backed by SenseTime's robust infrastructure, offers efficient and user-friendly full-stack large model services.
|
||||
- **[Stepfun](https://lobechat.com/discover/provider/stepfun)**: StepFun's large model possesses industry-leading multimodal and complex reasoning capabilities, supporting ultra-long text understanding and powerful autonomous scheduling search engine functions.
|
||||
- **[Moonshot](https://lobechat.com/discover/provider/moonshot)**: Moonshot is an open-source platform launched by Beijing Dark Side Technology Co., Ltd., providing various natural language processing models with a wide range of applications, including but not limited to content creation, academic research, intelligent recommendations, and medical diagnosis, supporting long text processing and complex generation tasks.
|
||||
- **[Baichuan](https://lobechat.com/discover/provider/baichuan)**: Baichuan Intelligence is a company focused on the research and development of large AI models, with its models excelling in domestic knowledge encyclopedias, long text processing, and generative creation tasks in Chinese, surpassing mainstream foreign models. Baichuan Intelligence also possesses industry-leading multimodal capabilities, performing excellently in multiple authoritative evaluations. Its models include Baichuan 4, Baichuan 3 Turbo, and Baichuan 3 Turbo 128k, each optimized for different application scenarios, providing cost-effective solutions.
|
||||
- **[Minimax](https://lobechat.com/discover/provider/minimax)**: MiniMax is a general artificial intelligence technology company established in 2021, dedicated to co-creating intelligence with users. MiniMax has independently developed general large models of different modalities, including trillion-parameter MoE text models, voice models, and image models, and has launched applications such as Conch AI.
|
||||
- **[InternLM](https://lobechat.com/discover/provider/internlm)**: An open-source organization dedicated to the research and development of large model toolchains. It provides an efficient and user-friendly open-source platform for all AI developers, making cutting-edge large models and algorithm technologies easily accessible.
|
||||
@@ -287,7 +286,7 @@ We have implemented support for the following model service providers:
|
||||
|
||||
</details>
|
||||
|
||||
> 📊 Total providers: [<kbd>**42**</kbd>](https://lobechat.com/discover/providers)
|
||||
> 📊 Total providers: [<kbd>**41**</kbd>](https://lobechat.com/discover/providers)
|
||||
|
||||
<!-- PROVIDER LIST -->
|
||||
|
||||
@@ -384,7 +383,7 @@ In addition, these plugins are not limited to news aggregation, but can also ext
|
||||
|
||||
| Recent Submits | Description |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
||||
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-07-21**</sup> | Analyze stocks and get comprehensive real-time investment data and analytics.<br/>`stock` |
|
||||
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-05-27**</sup> | Analyze stocks and get comprehensive real-time investment data and analytics.<br/>`stock` |
|
||||
| [Web](https://lobechat.com/discover/plugin/web)<br/><sup>By **Proghit** on **2025-01-24**</sup> | Smart web search that reads and analyzes pages to deliver comprehensive answers from Google results.<br/>`web` `search` |
|
||||
| [Bing_websearch](https://lobechat.com/discover/plugin/Bingsearch-identifier)<br/><sup>By **FineHow** on **2024-12-22**</sup> | Search for information from the internet base BingApi<br/>`bingsearch` |
|
||||
| [Google CSE](https://lobechat.com/discover/plugin/google-cse)<br/><sup>By **vsnthdev** on **2024-12-02**</sup> | Searches Google through their official CSE API.<br/>`web` `search` |
|
||||
@@ -481,7 +480,7 @@ We deeply understand the importance of providing a seamless experience for users
|
||||
Therefore, we have adopted Progressive Web Application ([PWA](https://support.google.com/chrome/answer/9658361)) technology,
|
||||
a modern web technology that elevates web applications to an experience close to that of native apps.
|
||||
|
||||
Through PWA, LobeChat can offer a highly optimized user experience on both desktop and mobile devices while maintaining high-performance characteristics.
|
||||
Through PWA, LobeChat can offer a highly optimized user experience on both desktop and mobile devices while maintaining its lightweight and high-performance characteristics.
|
||||
Visually and in terms of feel, we have also meticulously designed the interface to ensure it is indistinguishable from native apps,
|
||||
providing smooth animations, responsive layouts, and adapting to different device screen resolutions.
|
||||
|
||||
|
||||
@@ -245,17 +245,15 @@ LobeChat 支持文件上传与知识库功能,你可以上传文件、图片
|
||||
- **[Bedrock](https://lobechat.com/discover/provider/bedrock)**: Bedrock 是亚马逊 AWS 提供的一项服务,专注于为企业提供先进的 AI 语言模型和视觉模型。其模型家族包括 Anthropic 的 Claude 系列、Meta 的 Llama 3.1 系列等,涵盖从轻量级到高性能的多种选择,支持文本生成、对话、图像处理等多种任务,适用于不同规模和需求的企业应用。
|
||||
- **[Google](https://lobechat.com/discover/provider/google)**: Google 的 Gemini 系列是其最先进、通用的 AI 模型,由 Google DeepMind 打造,专为多模态设计,支持文本、代码、图像、音频和视频的无缝理解与处理。适用于从数据中心到移动设备的多种环境,极大提升了 AI 模型的效率与应用广泛性。
|
||||
- **[DeepSeek](https://lobechat.com/discover/provider/deepseek)**: DeepSeek 是一家专注于人工智能技术研究和应用的公司,其最新模型 DeepSeek-V3 多项评测成绩超越 Qwen2.5-72B 和 Llama-3.1-405B 等开源模型,性能对齐领军闭源模型 GPT-4o 与 Claude-3.5-Sonnet。
|
||||
- **[Moonshot](https://lobechat.com/discover/provider/moonshot)**: Moonshot 是由北京月之暗面科技有限公司推出的开源平台,提供多种自然语言处理模型,应用领域广泛,包括但不限于内容创作、学术研究、智能推荐、医疗诊断等,支持长文本处理和复杂生成任务。
|
||||
- **[OpenRouter](https://lobechat.com/discover/provider/openrouter)**: OpenRouter 是一个提供多种前沿大模型接口的服务平台,支持 OpenAI、Anthropic、LLaMA 及更多,适合多样化的开发和应用需求。用户可根据自身需求灵活选择最优的模型和价格,助力 AI 体验的提升。
|
||||
- **[HuggingFace](https://lobechat.com/discover/provider/huggingface)**: HuggingFace Inference API 提供了一种快速且免费的方式,让您可以探索成千上万种模型,适用于各种任务。无论您是在为新应用程序进行原型设计,还是在尝试机器学习的功能,这个 API 都能让您即时访问多个领域的高性能模型。
|
||||
- **[OpenRouter](https://lobechat.com/discover/provider/openrouter)**: OpenRouter 是一个提供多种前沿大模型接口的服务平台,支持 OpenAI、Anthropic、LLaMA 及更多,适合多样化的开发和应用需求。用户可根据自身需求灵活选择最优的模型和价格,助力 AI 体验的提升。
|
||||
- **[Cloudflare Workers AI](https://lobechat.com/discover/provider/cloudflare)**: 在 Cloudflare 的全球网络上运行由无服务器 GPU 驱动的机器学习模型。
|
||||
|
||||
<details><summary><kbd>See more providers (+32)</kbd></summary>
|
||||
|
||||
- **[GitHub](https://lobechat.com/discover/provider/github)**: 通过 GitHub 模型,开发人员可以成为 AI 工程师,并使用行业领先的 AI 模型进行构建。
|
||||
|
||||
<details><summary><kbd>See more providers (+31)</kbd></summary>
|
||||
|
||||
- **[Novita](https://lobechat.com/discover/provider/novita)**: Novita AI 是一个提供多种大语言模型与 AI 图像生成的 API 服务的平台,灵活、可靠且具有成本效益。它支持 Llama3、Mistral 等最新的开源模型,并为生成式 AI 应用开发提供了全面、用户友好且自动扩展的 API 解决方案,适合 AI 初创公司的快速发展。
|
||||
- **[PPIO](https://lobechat.com/discover/provider/ppio)**: PPIO 派欧云提供稳定、高性价比的开源模型 API 服务,支持 DeepSeek 全系列、Llama、Qwen 等行业领先大模型。
|
||||
- **[302.AI](https://lobechat.com/discover/provider/ai302)**: 302.AI 是一个按需付费的 AI 应用平台,提供市面上最全的 AI API 和 AI 在线应用
|
||||
- **[Together AI](https://lobechat.com/discover/provider/togetherai)**: Together AI 致力于通过创新的 AI 模型实现领先的性能,提供广泛的自定义能力,包括快速扩展支持和直观的部署流程,满足企业的各种需求。
|
||||
- **[Fireworks AI](https://lobechat.com/discover/provider/fireworksai)**: Fireworks AI 是一家领先的高级语言模型服务商,专注于功能调用和多模态处理。其最新模型 Firefunction V2 基于 Llama-3,优化用于函数调用、对话及指令跟随。视觉语言模型 FireLLaVA-13B 支持图像和文本混合输入。其他 notable 模型包括 Llama 系列和 Mixtral 系列,提供高效的多语言指令跟随与生成支持。
|
||||
- **[Groq](https://lobechat.com/discover/provider/groq)**: Groq 的 LPU 推理引擎在最新的独立大语言模型(LLM)基准测试中表现卓越,以其惊人的速度和效率重新定义了 AI 解决方案的标准。Groq 是一种即时推理速度的代表,在基于云的部署中展现了良好的性能。
|
||||
@@ -274,6 +272,7 @@ LobeChat 支持文件上传与知识库功能,你可以上传文件、图片
|
||||
- **[Spark](https://lobechat.com/discover/provider/spark)**: 科大讯飞星火大模型提供多领域、多语言的强大 AI 能力,利用先进的自然语言处理技术,构建适用于智能硬件、智慧医疗、智慧金融等多种垂直场景的创新应用。
|
||||
- **[SenseNova](https://lobechat.com/discover/provider/sensenova)**: 商汤日日新,依托商汤大装置的强大的基础支撑,提供高效易用的全栈大模型服务。
|
||||
- **[Stepfun](https://lobechat.com/discover/provider/stepfun)**: 阶级星辰大模型具备行业领先的多模态及复杂推理能力,支持超长文本理解和强大的自主调度搜索引擎功能。
|
||||
- **[Moonshot](https://lobechat.com/discover/provider/moonshot)**: Moonshot 是由北京月之暗面科技有限公司推出的开源平台,提供多种自然语言处理模型,应用领域广泛,包括但不限于内容创作、学术研究、智能推荐、医疗诊断等,支持长文本处理和复杂生成任务。
|
||||
- **[Baichuan](https://lobechat.com/discover/provider/baichuan)**: 百川智能是一家专注于人工智能大模型研发的公司,其模型在国内知识百科、长文本处理和生成创作等中文任务上表现卓越,超越了国外主流模型。百川智能还具备行业领先的多模态能力,在多项权威评测中表现优异。其模型包括 Baichuan 4、Baichuan 3 Turbo 和 Baichuan 3 Turbo 128k 等,分别针对不同应用场景进行优化,提供高性价比的解决方案。
|
||||
- **[Minimax](https://lobechat.com/discover/provider/minimax)**: MiniMax 是 2021 年成立的通用人工智能科技公司,致力于与用户共创智能。MiniMax 自主研发了不同模态的通用大模型,其中包括万亿参数的 MoE 文本大模型、语音大模型以及图像大模型。并推出了海螺 AI 等应用。
|
||||
- **[InternLM](https://lobechat.com/discover/provider/internlm)**: 致力于大模型研究与开发工具链的开源组织。为所有 AI 开发者提供高效、易用的开源平台,让最前沿的大模型与算法技术触手可及
|
||||
@@ -287,7 +286,7 @@ LobeChat 支持文件上传与知识库功能,你可以上传文件、图片
|
||||
|
||||
</details>
|
||||
|
||||
> 📊 Total providers: [<kbd>**42**</kbd>](https://lobechat.com/discover/providers)
|
||||
> 📊 Total providers: [<kbd>**41**</kbd>](https://lobechat.com/discover/providers)
|
||||
|
||||
<!-- PROVIDER LIST -->
|
||||
|
||||
@@ -377,7 +376,7 @@ LobeChat 的插件生态系统是其核心功能的重要扩展,它极大地
|
||||
|
||||
| 最近新增 | 描述 |
|
||||
| -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-07-21**</sup> | 分析股票并获取全面的实时投资数据和分析。<br/>`股票` |
|
||||
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-05-27**</sup> | 分析股票并获取全面的实时投资数据和分析。<br/>`股票` |
|
||||
| [网页](https://lobechat.com/discover/plugin/web)<br/><sup>By **Proghit** on **2025-01-24**</sup> | 智能网页搜索,读取和分析页面,以提供来自 Google 结果的全面答案。<br/>`网页` `搜索` |
|
||||
| [必应网页搜索](https://lobechat.com/discover/plugin/Bingsearch-identifier)<br/><sup>By **FineHow** on **2024-12-22**</sup> | 通过 BingApi 搜索互联网上的信息<br/>`bingsearch` |
|
||||
| [谷歌自定义搜索引擎](https://lobechat.com/discover/plugin/google-cse)<br/><sup>By **vsnthdev** on **2024-12-02**</sup> | 通过他们的官方自定义搜索引擎 API 搜索谷歌。<br/>`网络` `搜索` |
|
||||
|
||||
@@ -23,9 +23,8 @@ module.exports = defineConfig({
|
||||
'vi-VN',
|
||||
'fa-IR',
|
||||
],
|
||||
saveImmediately: true,
|
||||
temperature: 0,
|
||||
modelName: 'gpt-4.1-mini',
|
||||
modelName: 'gpt-4o-mini',
|
||||
experimental: {
|
||||
jsonMode: true,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
lockfile=false
|
||||
shamefully-hoist=true
|
||||
ignore-workspace-root-check=true
|
||||
|
||||
electron_mirror=https://npmmirror.com/mirrors/electron/
|
||||
electron_builder_binaries_mirror=https://npmmirror.com/mirrors/electron-builder-binaries/
|
||||
ignore-workspace-root-check=true
|
||||
|
||||
@@ -1,353 +1,60 @@
|
||||
# 🤯 LobeHub Desktop Application
|
||||
# LobeHub Desktop Application
|
||||
|
||||
LobeHub Desktop is a cross-platform desktop application for [LobeChat](https://github.com/lobehub/lobe-chat), built with Electron, providing a more native desktop experience and functionality.
|
||||
LobeHub Desktop 是 [LobeChat](https://github.com/lobehub/lobe-chat) 的跨平台桌面应用程序,使用 Electron 构建,提供了更加原生的桌面体验和功能。
|
||||
|
||||
## ✨ Features
|
||||
## 功能特点
|
||||
|
||||
- **🌍 Cross-platform Support**: Supports macOS (Intel/Apple Silicon), Windows, and Linux systems
|
||||
- **🔄 Auto Updates**: Built-in update mechanism ensures you always have the latest version
|
||||
- **🌐 Multi-language Support**: Complete i18n support for 18+ languages with lazy loading
|
||||
- **🎨 Native Integration**: Deep OS integration with native menus, shortcuts, and notifications
|
||||
- **🔒 Secure & Reliable**: macOS notarized, encrypted token storage, secure OAuth flow
|
||||
- **📦 Multiple Release Channels**: Stable, beta, and nightly build versions
|
||||
- **⚡ Advanced Window Management**: Multi-window architecture with theme synchronization
|
||||
- **🔗 Remote Server Sync**: Secure data synchronization with remote LobeChat instances
|
||||
- **🎯 Developer Tools**: Built-in development panel and comprehensive debugging tools
|
||||
- **跨平台支持**:支持 macOS (Intel/Apple Silicon)、Windows 和 Linux 系统
|
||||
- **自动更新**:内置更新机制,确保您始终使用最新版本
|
||||
- **多语言支持**:完整的国际化支持,包括中文、英文等多种语言
|
||||
- **原生集成**:与操作系统深度集成,提供原生菜单、快捷键和通知
|
||||
- **安全可靠**:macOS 版本经过公证,确保安全性
|
||||
- **多渠道发布**:提供稳定版、测试版和每日构建版本
|
||||
|
||||
## 🚀 Development Setup
|
||||
## 开发环境设置
|
||||
|
||||
### Prerequisites
|
||||
### 前提条件
|
||||
|
||||
- **Node.js** 22+
|
||||
- **pnpm** 10+
|
||||
- **Electron** compatible development environment
|
||||
- Node.js 22+
|
||||
- pnpm 10+
|
||||
|
||||
### Quick Start
|
||||
### 安装依赖
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
pnpm install-isolated
|
||||
```
|
||||
|
||||
# Start development server
|
||||
### 开发模式运行
|
||||
|
||||
```bash
|
||||
pnpm electron:dev
|
||||
|
||||
# Type checking
|
||||
pnpm typecheck
|
||||
|
||||
# Run tests
|
||||
pnpm test
|
||||
```
|
||||
|
||||
### Environment Configuration
|
||||
### 构建应用
|
||||
|
||||
Copy `.env.desktop` to `.env` and configure as needed:
|
||||
构建所有平台:
|
||||
|
||||
```bash
|
||||
cp .env.desktop .env
|
||||
pnpm build
|
||||
```
|
||||
|
||||
> \[!WARNING]
|
||||
> Backup your `.env` file before making changes to avoid losing configurations.
|
||||
|
||||
### Build Commands
|
||||
|
||||
| Command | Description |
|
||||
| ------------------ | --------------------------------------- |
|
||||
| `pnpm build` | Build for all platforms |
|
||||
| `pnpm build:mac` | Build for macOS (Intel + Apple Silicon) |
|
||||
| `pnpm build:win` | Build for Windows |
|
||||
| `pnpm build:linux` | Build for Linux |
|
||||
| `pnpm build-local` | Local development build |
|
||||
|
||||
### Development Workflow
|
||||
构建特定平台:
|
||||
|
||||
```bash
|
||||
# 1. Development
|
||||
pnpm electron:dev # Start with hot reload
|
||||
# macOS
|
||||
pnpm build:mac
|
||||
|
||||
# 2. Code Quality
|
||||
pnpm lint # ESLint checking
|
||||
pnpm format # Prettier formatting
|
||||
pnpm typecheck # TypeScript validation
|
||||
# Windows
|
||||
pnpm build:win
|
||||
|
||||
# 3. Testing
|
||||
pnpm test # Run Vitest tests
|
||||
|
||||
# 4. Build & Package
|
||||
pnpm build # Production build
|
||||
pnpm build-local # Local testing build
|
||||
# Linux
|
||||
pnpm build:linux
|
||||
```
|
||||
|
||||
## 🎯 Release Channels
|
||||
## 发布渠道
|
||||
|
||||
| Channel | Description | Stability | Auto-Updates |
|
||||
| ----------- | -------------------------------- | --------- | ------------ |
|
||||
| **Stable** | Thoroughly tested releases | 🟢 High | ✅ Yes |
|
||||
| **Beta** | Pre-release with new features | 🟡 Medium | ✅ Yes |
|
||||
| **Nightly** | Daily builds with latest changes | 🟠 Low | ✅ Yes |
|
||||
应用提供三个发布渠道:
|
||||
|
||||
## 🛠 Technology Stack
|
||||
|
||||
### Core Framework
|
||||
|
||||
- **Electron** `37.1.0` - Cross-platform desktop framework
|
||||
- **Node.js** `22+` - Backend runtime
|
||||
- **TypeScript** `5.7+` - Type-safe development
|
||||
- **Vite** `6.2+` - Build tooling
|
||||
|
||||
### Architecture & Patterns
|
||||
|
||||
- **Dependency Injection** - IoC container with decorator-based registration
|
||||
- **Event-Driven Architecture** - IPC communication between processes
|
||||
- **Module Federation** - Dynamic controller and service loading
|
||||
- **Observer Pattern** - State management and UI synchronization
|
||||
|
||||
### Development Tools
|
||||
|
||||
- **Vitest** - Unit testing framework
|
||||
- **ESLint** - Code linting
|
||||
- **Prettier** - Code formatting
|
||||
- **electron-builder** - Application packaging
|
||||
- **electron-updater** - Auto-update mechanism
|
||||
|
||||
### Security & Storage
|
||||
|
||||
- **Electron Safe Storage** - Encrypted token storage
|
||||
- **OAuth 2.0 + PKCE** - Secure authentication flow
|
||||
- **electron-store** - Persistent configuration
|
||||
- **Custom Protocol Handler** - Secure callback handling
|
||||
|
||||
## 🏗 Architecture
|
||||
|
||||
The desktop application uses a sophisticated dependency injection and event-driven architecture:
|
||||
|
||||
### 📁 Core Structure
|
||||
|
||||
```
|
||||
src/main/core/
|
||||
├── App.ts # 🎯 Main application orchestrator
|
||||
├── IoCContainer.ts # 🔌 Dependency injection container
|
||||
├── window/ # 🪟 Window management modules
|
||||
│ ├── WindowThemeManager.ts # 🎨 Theme synchronization
|
||||
│ ├── WindowPositionManager.ts # 📐 Position persistence
|
||||
│ ├── WindowErrorHandler.ts # ⚠️ Error boundaries
|
||||
│ └── WindowConfigBuilder.ts # ⚙️ Configuration builder
|
||||
├── browser/ # 🌐 Browser management modules
|
||||
│ ├── Browser.ts # 🪟 Individual window instances
|
||||
│ └── BrowserManager.ts # 👥 Multi-window coordinator
|
||||
├── ui/ # 🎨 UI system modules
|
||||
│ ├── Tray.ts # 📍 System tray integration
|
||||
│ ├── TrayManager.ts # 🔧 Tray management
|
||||
│ ├── MenuManager.ts # 📋 Native menu system
|
||||
│ └── ShortcutManager.ts # ⌨️ Global shortcuts
|
||||
└── infrastructure/ # 🔧 Infrastructure services
|
||||
├── StoreManager.ts # 💾 Configuration storage
|
||||
├── I18nManager.ts # 🌍 Internationalization
|
||||
├── UpdaterManager.ts # 📦 Auto-update system
|
||||
└── StaticFileServerManager.ts # 🗂️ Local file serving
|
||||
```
|
||||
|
||||
### 🔄 Application Lifecycle
|
||||
|
||||
The `App.ts` class orchestrates the entire application lifecycle through key phases:
|
||||
|
||||
#### 1. 🚀 Initialization Phase
|
||||
|
||||
- **System Information Logging** - Captures OS, CPU, RAM, and locale details
|
||||
- **Store Manager Setup** - Initializes persistent configuration storage
|
||||
- **Dynamic Module Loading** - Auto-discovers controllers and services via glob imports
|
||||
- **IPC Event Registration** - Sets up inter-process communication channels
|
||||
|
||||
#### 2. 🏃 Bootstrap Phase
|
||||
|
||||
- **Single Instance Check** - Ensures only one application instance runs
|
||||
- **IPC Server Launch** - Starts the communication server
|
||||
- **Core Manager Initialization** - Sequential initialization of all managers:
|
||||
- 🌍 I18n for internationalization
|
||||
- 📋 Menu system for native menus
|
||||
- 🗂️ Static file server for local assets
|
||||
- ⌨️ Global shortcuts registration
|
||||
- 🪟 Browser window management
|
||||
- 📍 System tray (Windows only)
|
||||
- 📦 Auto-updater system
|
||||
|
||||
### 🔧 Core Components Deep Dive
|
||||
|
||||
#### 🌐 Browser Management System
|
||||
|
||||
- **Multi-Window Architecture** - Supports chat, settings, and devtools windows
|
||||
- **Window State Management** - Handles positioning, theming, and lifecycle
|
||||
- **WebContents Mapping** - Bidirectional mapping between WebContents and identifiers
|
||||
- **Event Broadcasting** - Centralized event distribution to all or specific windows
|
||||
|
||||
#### 🔌 Dependency Injection & Event System
|
||||
|
||||
- **IoC Container** - WeakMap-based container for decorated controller methods
|
||||
- **Decorator Registration** - `@ipcClientEvent` and `@ipcServerEvent` decorators
|
||||
- **Automatic Event Mapping** - Events registered during controller loading
|
||||
- **Service Locator** - Type-safe service and controller retrieval
|
||||
|
||||
#### 🪟 Window Management
|
||||
|
||||
- **Theme-Aware Windows** - Automatic adaptation to system dark/light mode
|
||||
- **Platform-Specific Styling** - Windows title bar and overlay customization
|
||||
- **Position Persistence** - Save and restore window positions across sessions
|
||||
- **Error Boundaries** - Centralized error handling for window operations
|
||||
|
||||
#### 🔧 Infrastructure Services
|
||||
|
||||
##### 🌍 I18n Manager
|
||||
|
||||
- **18+ Language Support** with lazy loading and namespace organization
|
||||
- **System Integration** with Electron's locale detection
|
||||
- **Dynamic UI Refresh** on language changes
|
||||
- **Resource Management** with efficient loading strategies
|
||||
|
||||
##### 📦 Update Manager
|
||||
|
||||
- **Multi-Channel Support** (stable, beta, nightly) with configurable intervals
|
||||
- **Background Downloads** with progress tracking and user notifications
|
||||
- **Rollback Protection** with error handling and recovery mechanisms
|
||||
- **Channel Management** with automatic channel switching
|
||||
|
||||
##### 💾 Store Manager
|
||||
|
||||
- **Type-Safe Storage** using electron-store with TypeScript interfaces
|
||||
- **Encrypted Secrets** via Electron's Safe Storage API
|
||||
- **Configuration Validation** with default value management
|
||||
- **File System Integration** with automatic directory creation
|
||||
|
||||
##### 🗂️ Static File Server
|
||||
|
||||
- **Local HTTP Server** for serving application assets and user files
|
||||
- **Security Controls** with request filtering and access validation
|
||||
- **File Management** with upload, download, and deletion capabilities
|
||||
- **Path Resolution** with intelligent routing between storage locations
|
||||
|
||||
#### 🎨 UI System Integration
|
||||
|
||||
- **Global Shortcuts** - Platform-aware keyboard shortcut registration with conflict detection
|
||||
- **System Tray** - Native integration with context menus and notifications
|
||||
- **Native Menus** - Platform-specific application and context menus with i18n
|
||||
- **Theme Synchronization** - Automatic theme updates across all UI components
|
||||
|
||||
### 🏛 Controller & Service Architecture
|
||||
|
||||
#### 🎮 Controller Pattern
|
||||
|
||||
- **IPC Event Handling** - Processes events from renderer with decorator-based registration
|
||||
- **Lifecycle Hooks** - `beforeAppReady` and `afterAppReady` for initialization phases
|
||||
- **Type-Safe Communication** - Strong typing for all IPC events and responses
|
||||
- **Error Boundaries** - Comprehensive error handling with proper propagation
|
||||
|
||||
#### 🔧 Service Pattern
|
||||
|
||||
- **Business Logic Encapsulation** - Clean separation of concerns
|
||||
- **Dependency Management** - Managed through IoC container
|
||||
- **Cross-Controller Sharing** - Services accessible via service locator pattern
|
||||
- **Resource Management** - Proper initialization and cleanup
|
||||
|
||||
### 🔗 Inter-Process Communication
|
||||
|
||||
#### 📡 IPC System Features
|
||||
|
||||
- **Bidirectional Communication** - Main↔Renderer and Main↔Next.js server
|
||||
- **Type-Safe Events** - TypeScript interfaces for all event parameters
|
||||
- **Context Awareness** - Events include sender context for window-specific operations
|
||||
- **Error Propagation** - Centralized error handling with proper status codes
|
||||
|
||||
#### 🛡️ Security Features
|
||||
|
||||
- **OAuth 2.0 + PKCE** - Secure authentication with state parameter validation
|
||||
- **Encrypted Token Storage** - Using Electron's Safe Storage API when available
|
||||
- **Custom Protocol Handler** - Secure callback handling for OAuth flows
|
||||
- **Request Filtering** - Security controls for web requests and external links
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
### Test Structure
|
||||
|
||||
```bash
|
||||
apps/desktop/src/main/controllers/__tests__/ # Controller unit tests
|
||||
tests/ # Integration tests
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
pnpm test # Run all tests
|
||||
pnpm test:watch # Watch mode
|
||||
pnpm typecheck # Type validation
|
||||
```
|
||||
|
||||
### Test Coverage
|
||||
|
||||
- **Controller Tests** - IPC event handling validation
|
||||
- **Service Tests** - Business logic verification
|
||||
- **Integration Tests** - End-to-end workflow testing
|
||||
- **Type Tests** - TypeScript interface validation
|
||||
|
||||
## 🔒 Security Features
|
||||
|
||||
### Authentication & Authorization
|
||||
|
||||
- **OAuth 2.0 Flow** with PKCE for secure token exchange
|
||||
- **State Parameter Validation** to prevent CSRF attacks
|
||||
- **Encrypted Token Storage** using platform-native secure storage
|
||||
- **Automatic Token Refresh** with fallback to re-authentication
|
||||
|
||||
### Application Security
|
||||
|
||||
- **Code Signing** - macOS notarization for enhanced security
|
||||
- **Sandboxing** - Controlled access to system resources
|
||||
- **CSP Controls** - Content Security Policy management
|
||||
- **Request Filtering** - Security controls for external requests
|
||||
|
||||
### Data Protection
|
||||
|
||||
- **Encrypted Configuration** - Sensitive data encrypted at rest
|
||||
- **Secure IPC** - Type-safe communication channels
|
||||
- **Path Validation** - Secure file system access controls
|
||||
- **Network Security** - HTTPS enforcement and proxy support
|
||||
|
||||
## 🤝 Contribution
|
||||
|
||||
Desktop application development involves complex cross-platform considerations and native integrations. We welcome community contributions to improve functionality, performance, and user experience. You can participate in improvements through:
|
||||
|
||||
### How to Contribute
|
||||
|
||||
1. **Platform Support**: Enhance cross-platform compatibility and native integrations
|
||||
2. **Performance Optimization**: Improve application startup time, memory usage, and responsiveness
|
||||
3. **Feature Development**: Add new desktop-specific features and capabilities
|
||||
4. **Bug Fixes**: Fix platform-specific issues and edge cases
|
||||
5. **Security Improvements**: Enhance security measures and authentication flows
|
||||
6. **UI/UX Enhancements**: Improve desktop user interface and experience
|
||||
|
||||
### Contribution Process
|
||||
|
||||
1. Fork the [LobeChat repository](https://github.com/lobehub/lobe-chat)
|
||||
2. Set up the desktop development environment following our setup guide
|
||||
3. Make your changes to the desktop application
|
||||
4. Submit a Pull Request describing:
|
||||
|
||||
- Platform compatibility testing results
|
||||
- Performance impact analysis
|
||||
- Security considerations
|
||||
- User experience improvements
|
||||
- Breaking changes (if any)
|
||||
|
||||
### Development Areas
|
||||
|
||||
- **Core Architecture**: Dependency injection, event system, and lifecycle management
|
||||
- **Window Management**: Multi-window support, theme synchronization, and state persistence
|
||||
- **IPC Communication**: Type-safe inter-process communication between main and renderer
|
||||
- **Platform Integration**: Native menus, shortcuts, notifications, and system tray
|
||||
- **Security Features**: OAuth flows, token encryption, and secure storage
|
||||
- **Auto-Update System**: Multi-channel updates and rollback mechanisms
|
||||
|
||||
## 📚 Additional Resources
|
||||
|
||||
- **Development Guide**: [`Development.md`](./Development.md) - Comprehensive development documentation
|
||||
- **Architecture Docs**: [`/docs`](../../docs/) - Detailed technical specifications
|
||||
- **Contributing**: [`CONTRIBUTING.md`](../../CONTRIBUTING.md) - Contribution guidelines
|
||||
- **Issues & Support**: [GitHub Issues](https://github.com/lobehub/lobe-chat/issues)
|
||||
- **稳定版**:经过充分测试的正式版本
|
||||
- **测试版 (Beta)**:预发布版本,包含即将发布的新功能
|
||||
- **每日构建版 (Nightly)**:包含最新开发进展的构建版本
|
||||
|
||||
@@ -1,353 +0,0 @@
|
||||
# 🤯 LobeHub 桌面应用程序
|
||||
|
||||
LobeHub Desktop 是 [LobeChat](https://github.com/lobehub/lobe-chat) 的跨平台桌面应用程序,使用 Electron 构建,提供了更加原生的桌面体验和功能。
|
||||
|
||||
## ✨ 功能特点
|
||||
|
||||
- **🌍 跨平台支持**:支持 macOS (Intel/Apple Silicon)、Windows 和 Linux 系统
|
||||
- **🔄 自动更新**:内置更新机制,确保您始终使用最新版本
|
||||
- **🌐 多语言支持**:完整的 i18n 支持,包含 18+ 种语言的懒加载
|
||||
- **🎨 原生集成**:与操作系统深度集成,提供原生菜单、快捷键和通知
|
||||
- **🔒 安全可靠**:macOS 公证认证,加密令牌存储,安全的 OAuth 流程
|
||||
- **📦 多渠道发布**:提供稳定版、测试版和每日构建版本
|
||||
- **⚡ 高级窗口管理**:多窗口架构,支持主题同步
|
||||
- **🔗 远程服务器同步**:与远程 LobeChat 实例的安全数据同步
|
||||
- **🎯 开发者工具**:内置开发面板和全面的调试工具
|
||||
|
||||
## 🚀 开发环境设置
|
||||
|
||||
### 前提条件
|
||||
|
||||
- **Node.js** 22+
|
||||
- **pnpm** 10+
|
||||
- **Electron** 兼容的开发环境
|
||||
|
||||
### 快速开始
|
||||
|
||||
```bash
|
||||
# 安装依赖
|
||||
pnpm install-isolated
|
||||
|
||||
# 启动开发服务器
|
||||
pnpm electron:dev
|
||||
|
||||
# 类型检查
|
||||
pnpm typecheck
|
||||
|
||||
# 运行测试
|
||||
pnpm test
|
||||
```
|
||||
|
||||
### 环境变量配置
|
||||
|
||||
复制 `.env.desktop` 到 `.env` 并根据需要配置:
|
||||
|
||||
```bash
|
||||
cp .env.desktop .env
|
||||
```
|
||||
|
||||
> \[!WARNING]
|
||||
> 在进行更改之前请备份您的 `.env` 文件,避免丢失配置。
|
||||
|
||||
### 构建命令
|
||||
|
||||
| 命令 | 描述 |
|
||||
| ------------------ | ---------------------------------- |
|
||||
| `pnpm build` | 构建所有平台 |
|
||||
| `pnpm build:mac` | 构建 macOS (Intel + Apple Silicon) |
|
||||
| `pnpm build:win` | 构建 Windows |
|
||||
| `pnpm build:linux` | 构建 Linux |
|
||||
| `pnpm build-local` | 本地开发构建 |
|
||||
|
||||
### 开发工作流
|
||||
|
||||
```bash
|
||||
# 1. 开发
|
||||
pnpm electron:dev # 启动热重载开发服务器
|
||||
|
||||
# 2. 代码质量
|
||||
pnpm lint # ESLint 检查
|
||||
pnpm format # Prettier 格式化
|
||||
pnpm typecheck # TypeScript 验证
|
||||
|
||||
# 3. 测试
|
||||
pnpm test # 运行 Vitest 测试
|
||||
|
||||
# 4. 构建和打包
|
||||
pnpm build # 生产构建
|
||||
pnpm build-local # 本地测试构建
|
||||
```
|
||||
|
||||
## 🎯 发布渠道
|
||||
|
||||
| 渠道 | 描述 | 稳定性 | 自动更新 |
|
||||
| ------------------------ | ---------------------- | ------ | -------- |
|
||||
| **稳定版** | 经过充分测试的正式版本 | 🟢 高 | ✅ 是 |
|
||||
| **测试版 (Beta)** | 包含新功能的预发布版本 | 🟡 中 | ✅ 是 |
|
||||
| **每日构建版 (Nightly)** | 包含最新更改的每日构建 | 🟠 低 | ✅ 是 |
|
||||
|
||||
## 🛠 技术栈
|
||||
|
||||
### 核心框架
|
||||
|
||||
- **Electron** `37.1.0` - 跨平台桌面框架
|
||||
- **Node.js** `22+` - 后端运行时
|
||||
- **TypeScript** `5.7+` - 类型安全开发
|
||||
- **Vite** `6.2+` - 构建工具
|
||||
|
||||
### 架构和模式
|
||||
|
||||
- **依赖注入** - 基于装饰器注册的 IoC 容器
|
||||
- **事件驱动架构** - 进程间 IPC 通信
|
||||
- **模块联邦** - 动态控制器和服务加载
|
||||
- **观察者模式** - 状态管理和 UI 同步
|
||||
|
||||
### 开发工具
|
||||
|
||||
- **Vitest** - 单元测试框架
|
||||
- **ESLint** - 代码检查
|
||||
- **Prettier** - 代码格式化
|
||||
- **electron-builder** - 应用程序打包
|
||||
- **electron-updater** - 自动更新机制
|
||||
|
||||
### 安全和存储
|
||||
|
||||
- **Electron Safe Storage** - 加密令牌存储
|
||||
- **OAuth 2.0 + PKCE** - 安全认证流程
|
||||
- **electron-store** - 持久化配置
|
||||
- **自定义协议处理器** - 安全回调处理
|
||||
|
||||
## 🏗 架构设计
|
||||
|
||||
桌面应用程序采用了复杂的依赖注入和事件驱动架构:
|
||||
|
||||
### 📁 核心结构
|
||||
|
||||
```
|
||||
src/main/core/
|
||||
├── App.ts # 🎯 主应用程序协调器
|
||||
├── IoCContainer.ts # 🔌 依赖注入容器
|
||||
├── window/ # 🪟 窗口管理模块
|
||||
│ ├── WindowThemeManager.ts # 🎨 主题同步
|
||||
│ ├── WindowPositionManager.ts # 📐 位置持久化
|
||||
│ ├── WindowErrorHandler.ts # ⚠️ 错误边界
|
||||
│ └── WindowConfigBuilder.ts # ⚙️ 配置构建器
|
||||
├── browser/ # 🌐 浏览器管理模块
|
||||
│ ├── Browser.ts # 🪟 单个窗口实例
|
||||
│ └── BrowserManager.ts # 👥 多窗口协调器
|
||||
├── ui/ # 🎨 UI 系统模块
|
||||
│ ├── Tray.ts # 📍 系统托盘集成
|
||||
│ ├── TrayManager.ts # 🔧 托盘管理
|
||||
│ ├── MenuManager.ts # 📋 原生菜单系统
|
||||
│ └── ShortcutManager.ts # ⌨️ 全局快捷键
|
||||
└── infrastructure/ # 🔧 基础设施服务
|
||||
├── StoreManager.ts # 💾 配置存储
|
||||
├── I18nManager.ts # 🌍 国际化
|
||||
├── UpdaterManager.ts # 📦 自动更新系统
|
||||
└── StaticFileServerManager.ts # 🗂️ 本地文件服务
|
||||
```
|
||||
|
||||
### 🔄 应用程序生命周期
|
||||
|
||||
`App.ts` 类通过几个关键阶段协调整个应用程序的生命周期:
|
||||
|
||||
#### 1. 🚀 初始化阶段
|
||||
|
||||
- **系统信息记录** - 捕获操作系统、CPU、内存和区域设置详细信息
|
||||
- **存储管理器设置** - 初始化持久配置存储
|
||||
- **动态模块加载** - 通过 glob 导入自动发现控制器和服务
|
||||
- **IPC 事件注册** - 设置进程间通信通道
|
||||
|
||||
#### 2. 🏃 引导阶段
|
||||
|
||||
- **单实例检查** - 确保只运行一个应用程序实例
|
||||
- **IPC 服务器启动** - 启动通信服务器
|
||||
- **核心管理器初始化** - 按顺序初始化所有管理器:
|
||||
- 🌍 国际化管理器
|
||||
- 📋 原生菜单系统
|
||||
- 🗂️ 本地资源服务器
|
||||
- ⌨️ 全局快捷键注册
|
||||
- 🪟 浏览器窗口管理
|
||||
- 📍 系统托盘(仅 Windows)
|
||||
- 📦 自动更新系统
|
||||
|
||||
### 🔧 核心组件深度解析
|
||||
|
||||
#### 🌐 浏览器管理系统
|
||||
|
||||
- **多窗口架构** - 支持聊天、设置和开发工具窗口
|
||||
- **窗口状态管理** - 处理定位、主题和生命周期
|
||||
- **WebContents 映射** - WebContents 和标识符之间的双向映射
|
||||
- **事件广播** - 向所有或特定窗口的集中事件分发
|
||||
|
||||
#### 🔌 依赖注入和事件系统
|
||||
|
||||
- **IoC 容器** - 基于 WeakMap 的装饰控制器方法容器
|
||||
- **装饰器注册** - `@ipcClientEvent` 和 `@ipcServerEvent` 装饰器
|
||||
- **自动事件映射** - 控制器加载期间注册的事件
|
||||
- **服务定位器** - 类型安全的服务和控制器检索
|
||||
|
||||
#### 🪟 窗口管理
|
||||
|
||||
- **主题感知窗口** - 自动适应系统深色 / 浅色模式
|
||||
- **平台特定样式** - Windows 标题栏和覆盖自定义
|
||||
- **位置持久化** - 跨会话保存和恢复窗口位置
|
||||
- **错误边界** - 窗口操作的集中错误处理
|
||||
|
||||
#### 🔧 基础设施服务
|
||||
|
||||
##### 🌍 国际化管理器
|
||||
|
||||
- **18+ 语言支持** 懒加载和命名空间组织
|
||||
- **系统集成** 与 Electron 的区域检测集成
|
||||
- **动态 UI 刷新** 语言更改时的 UI 更新
|
||||
- **资源管理** 高效的加载策略
|
||||
|
||||
##### 📦 更新管理器
|
||||
|
||||
- **多渠道支持** (稳定版、测试版、每日构建)可配置间隔
|
||||
- **后台下载** 进度跟踪和用户通知
|
||||
- **回滚保护** 错误处理和恢复机制
|
||||
- **渠道管理** 自动渠道切换
|
||||
|
||||
##### 💾 存储管理器
|
||||
|
||||
- **类型安全存储** 使用带有 TypeScript 接口的 electron-store
|
||||
- **加密机密** 通过 Electron 的安全存储 API
|
||||
- **配置验证** 默认值管理
|
||||
- **文件系统集成** 自动目录创建
|
||||
|
||||
##### 🗂️ 静态文件服务器
|
||||
|
||||
- **本地 HTTP 服务器** 用于提供应用程序资源和用户文件
|
||||
- **安全控制** 请求过滤和访问验证
|
||||
- **文件管理** 上传、下载和删除功能
|
||||
- **路径解析** 存储位置之间的智能路由
|
||||
|
||||
#### 🎨 UI 系统集成
|
||||
|
||||
- **全局快捷键** - 平台感知的键盘快捷键注册与冲突检测
|
||||
- **系统托盘** - 带有上下文菜单和通知的原生集成
|
||||
- **原生菜单** - 带有 i18n 的平台特定应用程序和上下文菜单
|
||||
- **主题同步** - 所有 UI 组件的自动主题更新
|
||||
|
||||
### 🏛 控制器和服务架构
|
||||
|
||||
#### 🎮 控制器模式
|
||||
|
||||
- **IPC 事件处理** - 通过基于装饰器的注册处理来自渲染器的事件
|
||||
- **生命周期钩子** - 初始化阶段的 `beforeAppReady` 和 `afterAppReady`
|
||||
- **类型安全通信** - 所有 IPC 事件和响应的强类型
|
||||
- **错误边界** - 具有适当传播的全面错误处理
|
||||
|
||||
#### 🔧 服务模式
|
||||
|
||||
- **业务逻辑封装** - 关注点的清晰分离
|
||||
- **依赖管理** - 通过 IoC 容器管理
|
||||
- **跨控制器共享** - 通过服务定位器模式访问的服务
|
||||
- **资源管理** - 适当的初始化和清理
|
||||
|
||||
### 🔗 进程间通信
|
||||
|
||||
#### 📡 IPC 系统功能
|
||||
|
||||
- **双向通信** - Main↔Renderer 和 Main↔Next.js 服务器
|
||||
- **类型安全事件** - 所有事件参数的 TypeScript 接口
|
||||
- **上下文感知** - 事件包含用于窗口特定操作的发送者上下文
|
||||
- **错误传播** - 具有适当状态码的集中错误处理
|
||||
|
||||
#### 🛡️ 安全功能
|
||||
|
||||
- **OAuth 2.0 + PKCE** - 具有状态参数验证的安全认证
|
||||
- **加密令牌存储** - 在可用时使用 Electron 的安全存储 API
|
||||
- **自定义协议处理器** - OAuth 流程的安全回调处理
|
||||
- **请求过滤** - 网络请求和外部链接的安全控制
|
||||
|
||||
## 🧪 测试
|
||||
|
||||
### 测试结构
|
||||
|
||||
```bash
|
||||
apps/desktop/src/main/controllers/__tests__/ # 控制器单元测试
|
||||
tests/ # 集成测试
|
||||
```
|
||||
|
||||
### 运行测试
|
||||
|
||||
```bash
|
||||
pnpm test # 运行所有测试
|
||||
pnpm test:watch # 监视模式
|
||||
pnpm typecheck # 类型验证
|
||||
```
|
||||
|
||||
### 测试覆盖
|
||||
|
||||
- **控制器测试** - IPC 事件处理验证
|
||||
- **服务测试** - 业务逻辑验证
|
||||
- **集成测试** - 端到端工作流测试
|
||||
- **类型测试** - TypeScript 接口验证
|
||||
|
||||
## 🔒 安全功能
|
||||
|
||||
### 认证和授权
|
||||
|
||||
- **OAuth 2.0 流程** 使用 PKCE 进行安全令牌交换
|
||||
- **状态参数验证** 防止 CSRF 攻击
|
||||
- **加密令牌存储** 使用平台原生安全存储
|
||||
- **自动令牌刷新** 在失败时回退到重新认证
|
||||
|
||||
### 应用程序安全
|
||||
|
||||
- **代码签名** - macOS 公证认证以增强安全性
|
||||
- **沙盒** - 对系统资源的受控访问
|
||||
- **CSP 控制** - 内容安全策略管理
|
||||
- **请求过滤** - 外部请求的安全控制
|
||||
|
||||
### 数据保护
|
||||
|
||||
- **加密配置** - 敏感数据静态加密
|
||||
- **安全 IPC** - 类型安全的通信通道
|
||||
- **路径验证** - 安全的文件系统访问控制
|
||||
- **网络安全** - HTTPS 强制和代理支持
|
||||
|
||||
## 🤝 参与贡献
|
||||
|
||||
桌面应用程序开发涉及复杂的跨平台考虑和原生集成。我们欢迎社区贡献来改进功能、性能和用户体验。您可以通过以下方式参与改进:
|
||||
|
||||
### 如何贡献
|
||||
|
||||
1. **平台支持**:增强跨平台兼容性和原生集成
|
||||
2. **性能优化**:改进应用程序启动时间、内存使用和响应性
|
||||
3. **功能开发**:添加新的桌面特定功能和能力
|
||||
4. **错误修复**:修复平台特定问题和边缘情况
|
||||
5. **安全改进**:增强安全措施和认证流程
|
||||
6. **UI/UX 增强**:改进桌面用户界面和体验
|
||||
|
||||
### 贡献流程
|
||||
|
||||
1. Fork [LobeChat 仓库](https://github.com/lobehub/lobe-chat)
|
||||
2. 按照我们的设置指南建立桌面开发环境
|
||||
3. 对桌面应用程序进行修改
|
||||
4. 提交 Pull Request 并描述:
|
||||
|
||||
- 平台兼容性测试结果
|
||||
- 性能影响分析
|
||||
- 安全考虑
|
||||
- 用户体验改进
|
||||
- 破坏性更改(如有)
|
||||
|
||||
### 开发领域
|
||||
|
||||
- **核心架构**:依赖注入、事件系统和生命周期管理
|
||||
- **窗口管理**:多窗口支持、主题同步和状态持久化
|
||||
- **IPC 通信**:主进程和渲染进程之间的类型安全进程间通信
|
||||
- **平台集成**:原生菜单、快捷键、通知和系统托盘
|
||||
- **安全功能**:OAuth 流程、令牌加密和安全存储
|
||||
- **自动更新系统**:多渠道更新和回滚机制
|
||||
|
||||
## 📚 其他资源
|
||||
|
||||
- **开发指南**:[`Development.md`](./Development.md) - 全面的开发文档
|
||||
- **架构文档**:[`/docs`](../../docs/) - 详细的技术规范
|
||||
- **贡献指南**:[`CONTRIBUTING.md`](../../CONTRIBUTING.md) - 贡献指导
|
||||
- **问题和支持**:[GitHub Issues](https://github.com/lobehub/lobe-chat/issues)
|
||||
|
Before Width: | Height: | Size: 171 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 156 KiB |
|
Before Width: | Height: | Size: 171 KiB After Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 171 KiB After Width: | Height: | Size: 72 KiB |
@@ -0,0 +1,229 @@
|
||||
# Claude Code Integration
|
||||
|
||||
This document describes the Claude Code SDK integration in LobeChat Desktop application.
|
||||
|
||||
## Overview
|
||||
|
||||
Claude Code SDK enables running Claude Code as a subprocess, providing AI-powered coding assistance capabilities. The integration supports:
|
||||
|
||||
- **Multi-turn conversations** with context retention
|
||||
- **File operations** (read/write)
|
||||
- **Code execution** through bash commands
|
||||
- **Session management** and continuation
|
||||
- **Real-time streaming** responses
|
||||
- **Cost tracking** per session
|
||||
|
||||
## Accessing Claude Code
|
||||
|
||||
In the LobeChat Desktop application, you can access Claude Code through:
|
||||
|
||||
1. **Sidebar Navigation**: Click the code icon (`</>`) in the sidebar (desktop only)
|
||||
2. **Direct URL**: Navigate to `/claude-code` in the application
|
||||
|
||||
The Claude Code interface provides:
|
||||
- A code editor for writing prompts
|
||||
- Real-time streaming message display
|
||||
- Session management with history
|
||||
- Cost tracking and usage statistics
|
||||
|
||||
## Architecture
|
||||
|
||||
### Components
|
||||
|
||||
1. **IPC Layer** (`packages/electron-client-ipc`)
|
||||
- Type definitions for Claude Code events
|
||||
- IPC event interfaces for main/render communication
|
||||
|
||||
2. **Main Process Controller** (`apps/desktop/src/main/controllers/ClaudeCodeCtr.ts`)
|
||||
- Handles Claude Code SDK integration
|
||||
- Manages streaming sessions and abort controllers
|
||||
- Tracks session history
|
||||
|
||||
3. **React Hook** (`src/hooks/useClaudeCode.ts`)
|
||||
- Provides easy-to-use interface for React components
|
||||
- Handles IPC communication with main process
|
||||
- Manages streaming state and events
|
||||
|
||||
4. **UI Page** (`src/app/[variants]/(main)/claude-code/`)
|
||||
- User interface for interacting with Claude Code
|
||||
- Query editor with syntax highlighting
|
||||
- Session management interface
|
||||
- Real-time message streaming display
|
||||
|
||||
## Setup
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. Install Claude Code SDK dependency:
|
||||
```bash
|
||||
npm install @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
2. Set up authentication:
|
||||
```bash
|
||||
# Option 1: Anthropic API Key
|
||||
export ANTHROPIC_API_KEY="your-api-key"
|
||||
|
||||
# Option 2: Amazon Bedrock
|
||||
export CLAUDE_CODE_USE_BEDROCK=1
|
||||
# Configure AWS credentials
|
||||
|
||||
# Option 3: Google Vertex AI
|
||||
export CLAUDE_CODE_USE_VERTEX=1
|
||||
# Configure Google Cloud credentials
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Query
|
||||
|
||||
```typescript
|
||||
import { useClaudeCode } from '@/hooks/useClaudeCode';
|
||||
|
||||
const MyComponent = () => {
|
||||
const { query, isLoading } = useClaudeCode();
|
||||
|
||||
const handleQuery = async () => {
|
||||
const result = await query('Write a function to calculate Fibonacci numbers', {
|
||||
maxTurns: 3,
|
||||
outputFormat: 'json',
|
||||
});
|
||||
|
||||
console.log(result.messages);
|
||||
console.log(result.sessionId);
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
### Streaming Query
|
||||
|
||||
```typescript
|
||||
const { startStreamingQuery, isLoading } = useClaudeCode({
|
||||
onStreamMessage: (message) => {
|
||||
console.log('New message:', message);
|
||||
},
|
||||
onStreamComplete: (sessionId) => {
|
||||
console.log('Stream completed:', sessionId);
|
||||
},
|
||||
onStreamError: (error) => {
|
||||
console.error('Stream error:', error);
|
||||
},
|
||||
});
|
||||
|
||||
const handleStream = async () => {
|
||||
await startStreamingQuery('Build a React component', {
|
||||
maxTurns: 5,
|
||||
outputFormat: 'stream-json',
|
||||
allowedTools: ['Read', 'Write', 'Bash'],
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### Session Management
|
||||
|
||||
```typescript
|
||||
const { recentSessions, fetchRecentSessions, clearSession } = useClaudeCode();
|
||||
|
||||
// Get recent sessions
|
||||
await fetchRecentSessions();
|
||||
|
||||
// Continue a previous session
|
||||
await startStreamingQuery('Continue', {
|
||||
resumeSessionId: session.sessionId,
|
||||
});
|
||||
|
||||
// Clear a session
|
||||
await clearSession(sessionId);
|
||||
```
|
||||
|
||||
## IPC Events
|
||||
|
||||
### Client Dispatch Events (Renderer → Main)
|
||||
|
||||
- `claudeCodeQuery` - Execute a Claude Code query
|
||||
- `claudeCodeStreamStart` - Start a streaming query
|
||||
- `claudeCodeStreamStop` - Stop an active stream
|
||||
- `claudeCodeCreateAbortController` - Create abort controller
|
||||
- `claudeCodeAbort` - Trigger abort
|
||||
- `claudeCodeGetRecentSessions` - Get session history
|
||||
- `claudeCodeClearSession` - Clear a specific session
|
||||
- `claudeCodeCheckAvailability` - Check if Claude Code is available
|
||||
|
||||
### Broadcast Events (Main → Renderer)
|
||||
|
||||
- `claudeCodeStreamMessage` - Stream message event
|
||||
- `claudeCodeStreamComplete` - Stream completion event
|
||||
- `claudeCodeStreamError` - Stream error event
|
||||
|
||||
## Configuration Options
|
||||
|
||||
```typescript
|
||||
interface ClaudeCodeOptions {
|
||||
maxTurns?: number; // Maximum conversation turns
|
||||
systemPrompt?: string; // Override system prompt
|
||||
appendSystemPrompt?: string; // Append to system prompt
|
||||
cwd?: string; // Working directory
|
||||
allowedTools?: string[] | string; // Allowed tools
|
||||
disallowedTools?: string[] | string; // Disallowed tools
|
||||
permissionMode?: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
|
||||
outputFormat?: 'text' | 'json' | 'stream-json';
|
||||
inputFormat?: 'text' | 'stream-json';
|
||||
mcpConfig?: string; // MCP configuration file path
|
||||
permissionPromptTool?: string; // MCP tool for permissions
|
||||
verbose?: boolean; // Enable verbose logging
|
||||
continueLastSession?: boolean; // Continue last session
|
||||
resumeSessionId?: string; // Resume specific session
|
||||
}
|
||||
```
|
||||
|
||||
## Message Types
|
||||
|
||||
```typescript
|
||||
interface ClaudeCodeMessage {
|
||||
type: 'assistant' | 'user' | 'system' | 'result';
|
||||
message?: any;
|
||||
session_id?: string;
|
||||
subtype?: string;
|
||||
duration_ms?: number;
|
||||
duration_api_ms?: number;
|
||||
is_error?: boolean;
|
||||
num_turns?: number;
|
||||
result?: string;
|
||||
total_cost_usd?: number;
|
||||
apiKeySource?: string;
|
||||
cwd?: string;
|
||||
tools?: string[];
|
||||
mcp_servers?: Array<{ name: string; status: string }>;
|
||||
model?: string;
|
||||
permissionMode?: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Always check availability** before using Claude Code
|
||||
2. **Handle errors gracefully** - both sync and async errors
|
||||
3. **Use abort controllers** for long-running operations
|
||||
4. **Monitor costs** through session tracking
|
||||
5. **Clean up sessions** when no longer needed
|
||||
6. **Set appropriate tool permissions** based on use case
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Claude Code not available
|
||||
|
||||
1. Check if running in Electron desktop app
|
||||
2. Verify API key is set correctly
|
||||
3. Check environment variables
|
||||
|
||||
### Streaming not working
|
||||
|
||||
1. Ensure proper event listeners are set up
|
||||
2. Check for abort controller conflicts
|
||||
3. Verify stream ID is unique
|
||||
|
||||
### Session continuation fails
|
||||
|
||||
1. Check if session ID is valid
|
||||
2. Ensure session hasn't been cleared
|
||||
3. Verify prompt is appropriate for continuation
|
||||
@@ -11,16 +11,6 @@ console.log(`🚄 Build Version ${packageJSON.version}, Channel: ${channel}`);
|
||||
const isNightly = channel === 'nightly';
|
||||
const isBeta = packageJSON.name.includes('beta');
|
||||
|
||||
// 根据版本类型确定协议 scheme
|
||||
const getProtocolScheme = () => {
|
||||
if (isNightly) return 'lobehub-nightly';
|
||||
if (isBeta) return 'lobehub-beta';
|
||||
|
||||
return 'lobehub';
|
||||
};
|
||||
|
||||
const protocolScheme = getProtocolScheme();
|
||||
|
||||
/**
|
||||
* @type {import('electron-builder').Configuration}
|
||||
* @see https://www.electron.build/configuration
|
||||
@@ -35,11 +25,6 @@ const config = {
|
||||
artifactName: '${productName}-${version}.${ext}',
|
||||
},
|
||||
asar: true,
|
||||
asarUnpack: [
|
||||
// https://github.com/electron-userland/electron-builder/issues/9001#issuecomment-2778802044
|
||||
'**/node_modules/sharp/**/*',
|
||||
'**/node_modules/@img/**/*',
|
||||
],
|
||||
detectUpdateChannel: true,
|
||||
directories: {
|
||||
buildResources: 'build',
|
||||
@@ -64,18 +49,12 @@ const config = {
|
||||
linux: {
|
||||
category: 'Utility',
|
||||
maintainer: 'electronjs.org',
|
||||
target: ['AppImage', 'snap', 'deb', 'rpm', 'tar.gz'],
|
||||
target: ['AppImage', 'snap', 'deb'],
|
||||
},
|
||||
mac: {
|
||||
compression: 'maximum',
|
||||
entitlementsInherit: 'build/entitlements.mac.plist',
|
||||
extendInfo: {
|
||||
CFBundleURLTypes: [
|
||||
{
|
||||
CFBundleURLName: 'LobeHub Protocol',
|
||||
CFBundleURLSchemes: [protocolScheme],
|
||||
},
|
||||
],
|
||||
NSCameraUsageDescription: "Application requests access to the device's camera.",
|
||||
NSDocumentsFolderUsageDescription:
|
||||
"Application requests access to the user's Documents folder.",
|
||||
@@ -107,12 +86,6 @@ const config = {
|
||||
uninstallDisplayName: '${productName}',
|
||||
uninstallerSidebar: './build/nsis-sidebar.bmp',
|
||||
},
|
||||
protocols: [
|
||||
{
|
||||
name: 'LobeHub Protocol',
|
||||
schemes: [protocolScheme],
|
||||
},
|
||||
],
|
||||
publish: [
|
||||
{
|
||||
owner: 'lobehub',
|
||||
|
||||
@@ -11,9 +11,8 @@ console.log(`[electron-vite.config.ts] Detected UPDATE_CHANNEL: ${updateChannel}
|
||||
export default defineConfig({
|
||||
main: {
|
||||
build: {
|
||||
minify: !isDev,
|
||||
outDir: 'dist/main',
|
||||
sourcemap: isDev ? 'inline' : false,
|
||||
sourcemap: isDev,
|
||||
},
|
||||
// 这里是关键:在构建时进行文本替换
|
||||
define: {
|
||||
@@ -31,9 +30,8 @@ export default defineConfig({
|
||||
},
|
||||
preload: {
|
||||
build: {
|
||||
minify: !isDev,
|
||||
outDir: 'dist/preload',
|
||||
sourcemap: isDev ? 'inline' : false,
|
||||
sourcemap: isDev,
|
||||
},
|
||||
plugins: [externalizeDepsPlugin({})],
|
||||
resolve: {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"name": "lobehub-desktop-dev",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"version": "0.0.10",
|
||||
"description": "LobeHub Desktop Application",
|
||||
"homepage": "https://lobehub.com",
|
||||
"repository": {
|
||||
@@ -15,23 +14,20 @@
|
||||
"build-local": "npm run build && electron-builder --dir --config electron-builder.js --c.mac.notarize=false -c.mac.identity=null --c.asar=false",
|
||||
"build:linux": "npm run build && electron-builder --linux --config electron-builder.js --publish never",
|
||||
"build:mac": "npm run build && electron-builder --mac --config electron-builder.js --publish never",
|
||||
"build:mac:local": "npm run build && UPDATE_CHANNEL=nightly electron-builder --mac --config electron-builder.js --publish never",
|
||||
"build:win": "npm run build && electron-builder --win --config electron-builder.js --publish never",
|
||||
"electron:dev": "electron-vite dev",
|
||||
"electron:run-unpack": "electron .",
|
||||
"format": "prettier --write ",
|
||||
"i18n": "tsx scripts/i18nWorkflow/index.ts && lobe-i18n",
|
||||
"i18n": "bun run scripts/i18nWorkflow/index.ts && lobe-i18n",
|
||||
"postinstall": "electron-builder install-app-deps",
|
||||
"install-isolated": "pnpm install",
|
||||
"lint": "eslint --cache ",
|
||||
"pg-server": "bun run scripts/pglite-server.ts",
|
||||
"start": "electron-vite preview",
|
||||
"test": "vitest --run",
|
||||
"typecheck": "tsgo --noEmit -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron-updater": "^6.6.2",
|
||||
"electron-window-state": "^5.0.3",
|
||||
"fetch-socks": "^1.3.2",
|
||||
"get-port-please": "^3.1.2",
|
||||
"pdfjs-dist": "4.10.38"
|
||||
},
|
||||
@@ -49,10 +45,10 @@
|
||||
"@types/resolve": "^1.20.6",
|
||||
"@types/semver": "^7.7.0",
|
||||
"@types/set-cookie-parser": "^2.4.10",
|
||||
"@typescript/native-preview": "7.0.0-dev.20250711.1",
|
||||
"@typescript/native-preview": "latest",
|
||||
"consola": "^3.1.0",
|
||||
"cookie": "^1.0.2",
|
||||
"electron": "^37.4.0",
|
||||
"electron": "^37.2.0",
|
||||
"electron-builder": "^26.0.12",
|
||||
"electron-is": "^3.0.0",
|
||||
"electron-log": "^5.3.3",
|
||||
@@ -60,24 +56,19 @@
|
||||
"electron-vite": "^3.0.0",
|
||||
"execa": "^9.5.2",
|
||||
"fix-path": "^4.0.0",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"just-diff": "^6.0.2",
|
||||
"lodash": "^4.17.21",
|
||||
"lodash-es": "^4.17.21",
|
||||
"pglite-server": "^0.1.4",
|
||||
"resolve": "^1.22.8",
|
||||
"semver": "^7.5.4",
|
||||
"set-cookie-parser": "^2.7.1",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.7.3",
|
||||
"undici": "^7.9.0",
|
||||
"vite": "^6.3.5",
|
||||
"vitest": "^3.2.4"
|
||||
"vite": "^6.2.5"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
"electron",
|
||||
"electron-builder"
|
||||
"electron"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "نسخ",
|
||||
"cut": "قص",
|
||||
"delete": "حذف",
|
||||
"paste": "لصق",
|
||||
"redo": "إعادة",
|
||||
"selectAll": "تحديد الكل",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Копиране",
|
||||
"cut": "Изрязване",
|
||||
"delete": "Изтрий",
|
||||
"paste": "Поставяне",
|
||||
"redo": "Повторно",
|
||||
"selectAll": "Избери всичко",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Kopieren",
|
||||
"cut": "Ausschneiden",
|
||||
"delete": "Löschen",
|
||||
"paste": "Einfügen",
|
||||
"redo": "Wiederherstellen",
|
||||
"selectAll": "Alles auswählen",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Copy",
|
||||
"cut": "Cut",
|
||||
"delete": "Delete",
|
||||
"paste": "Paste",
|
||||
"redo": "Redo",
|
||||
"selectAll": "Select All",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Copiar",
|
||||
"cut": "Cortar",
|
||||
"delete": "Eliminar",
|
||||
"paste": "Pegar",
|
||||
"redo": "Rehacer",
|
||||
"selectAll": "Seleccionar todo",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "کپی",
|
||||
"cut": "برش",
|
||||
"delete": "حذف",
|
||||
"paste": "چسباندن",
|
||||
"redo": "انجام مجدد",
|
||||
"selectAll": "انتخاب همه",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Copier",
|
||||
"cut": "Couper",
|
||||
"delete": "Supprimer",
|
||||
"paste": "Coller",
|
||||
"redo": "Rétablir",
|
||||
"selectAll": "Tout sélectionner",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Copia",
|
||||
"cut": "Taglia",
|
||||
"delete": "Elimina",
|
||||
"paste": "Incolla",
|
||||
"redo": "Ripeti",
|
||||
"selectAll": "Seleziona tutto",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "コピー",
|
||||
"cut": "切り取り",
|
||||
"delete": "削除",
|
||||
"paste": "貼り付け",
|
||||
"redo": "やり直し",
|
||||
"selectAll": "すべて選択",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "복사",
|
||||
"cut": "잘라내기",
|
||||
"delete": "삭제",
|
||||
"paste": "붙여넣기",
|
||||
"redo": "다시 실행",
|
||||
"selectAll": "모두 선택",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Kopiëren",
|
||||
"cut": "Knippen",
|
||||
"delete": "Verwijderen",
|
||||
"paste": "Plakken",
|
||||
"redo": "Opnieuw doen",
|
||||
"selectAll": "Alles selecteren",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Kopiuj",
|
||||
"cut": "Wytnij",
|
||||
"delete": "Usuń",
|
||||
"paste": "Wklej",
|
||||
"redo": "Ponów",
|
||||
"selectAll": "Zaznacz wszystko",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Copiar",
|
||||
"cut": "Cortar",
|
||||
"delete": "Excluir",
|
||||
"paste": "Colar",
|
||||
"redo": "Refazer",
|
||||
"selectAll": "Selecionar Tudo",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Копировать",
|
||||
"cut": "Вырезать",
|
||||
"delete": "Удалить",
|
||||
"paste": "Вставить",
|
||||
"redo": "Повторить",
|
||||
"selectAll": "Выбрать все",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Kopyala",
|
||||
"cut": "Kes",
|
||||
"delete": "Sil",
|
||||
"paste": "Yapıştır",
|
||||
"redo": "Yinele",
|
||||
"selectAll": "Tümünü Seç",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "Sao chép",
|
||||
"cut": "Cắt",
|
||||
"delete": "Xóa",
|
||||
"paste": "Dán",
|
||||
"redo": "Làm lại",
|
||||
"selectAll": "Chọn tất cả",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "复制",
|
||||
"cut": "剪切",
|
||||
"delete": "删除",
|
||||
"paste": "粘贴",
|
||||
"redo": "重做",
|
||||
"selectAll": "全选",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"edit": {
|
||||
"copy": "複製",
|
||||
"cut": "剪下",
|
||||
"delete": "刪除",
|
||||
"paste": "貼上",
|
||||
"redo": "重做",
|
||||
"selectAll": "全選",
|
||||
|
||||
|
Before Width: | Height: | Size: 807 B |
|
After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 738 B |
|
Before Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,14 @@
|
||||
import { PGlite } from "@electric-sql/pglite";
|
||||
import { createServer } from "pglite-server";
|
||||
|
||||
// 创建或连接到您现有的 PGlite 数据库
|
||||
const db = new PGlite("/Users/arvinxx/Library/Application Support/lobehub-desktop/lobehub-local-db");
|
||||
await db.waitReady;
|
||||
|
||||
// 创建服务器并监听端口
|
||||
const PORT = 6543;
|
||||
const pgServer = createServer(db);
|
||||
|
||||
pgServer.listen(PORT, () => {
|
||||
console.log(`PGlite 服务器已启动,监听端口 ${PORT}`);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BrowserWindowOpts } from './core/browser/Browser';
|
||||
import type { BrowserWindowOpts } from './core/Browser';
|
||||
|
||||
export const BrowsersIdentifiers = {
|
||||
chat: 'chat',
|
||||
@@ -13,7 +13,7 @@ export const appBrowsers = {
|
||||
identifier: 'chat',
|
||||
keepAlive: true,
|
||||
minWidth: 400,
|
||||
path: '/chat',
|
||||
path: '/claude-code',
|
||||
showOnInit: true,
|
||||
titleBarStyle: 'hidden',
|
||||
vibrancy: 'under-window',
|
||||
|
||||
@@ -27,6 +27,3 @@ export const LOCAL_DATABASE_DIR = 'lobehub-local-db';
|
||||
export const FILE_STORAGE_DIR = 'file-storage';
|
||||
// Plugin 安装目录
|
||||
export const INSTALL_PLUGINS_DIR = 'plugins';
|
||||
|
||||
// Desktop file service
|
||||
export const LOCAL_STORAGE_URL_PREFIX = '/lobe-desktop-file';
|
||||
|
||||
@@ -1,29 +1,3 @@
|
||||
import { dev, linux, macOS, windows } from 'electron-is';
|
||||
import os from 'node:os';
|
||||
|
||||
export const isDev = dev();
|
||||
export const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
export const OFFICIAL_CLOUD_SERVER = process.env.OFFICIAL_CLOUD_SERVER || 'https://lobechat.com';
|
||||
|
||||
export const isMac = macOS();
|
||||
export const isWindows = windows();
|
||||
export const isLinux = linux();
|
||||
|
||||
function getIsWindows11() {
|
||||
if (!isWindows) return false;
|
||||
// 获取操作系统版本(如 "10.0.22621")
|
||||
const release = os.release();
|
||||
const parts = release.split('.');
|
||||
|
||||
// 主版本和次版本
|
||||
const majorVersion = parseInt(parts[0], 10);
|
||||
const minorVersion = parseInt(parts[1], 10);
|
||||
|
||||
// 构建号是第三部分
|
||||
const buildNumber = parseInt(parts[2], 10);
|
||||
|
||||
// Windows 11 的构建号从 22000 开始
|
||||
return majorVersion === 10 && minorVersion === 0 && buildNumber >= 22_000;
|
||||
}
|
||||
|
||||
export const isWindows11 = getIsWindows11();
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/**
|
||||
* 应用设置存储相关常量
|
||||
*/
|
||||
import { NetworkProxySettings } from '@lobechat/electron-client-ipc';
|
||||
|
||||
import { appStorageDir } from '@/const/dir';
|
||||
import { DEFAULT_SHORTCUTS_CONFIG } from '@/shortcuts';
|
||||
import { ElectronMainStore } from '@/types/store';
|
||||
@@ -12,25 +10,13 @@ import { ElectronMainStore } from '@/types/store';
|
||||
*/
|
||||
export const STORE_NAME = 'lobehub-settings';
|
||||
|
||||
export const defaultProxySettings: NetworkProxySettings = {
|
||||
enableProxy: false,
|
||||
proxyBypass: 'localhost, 127.0.0.1, ::1',
|
||||
proxyPort: '',
|
||||
proxyRequireAuth: false,
|
||||
proxyServer: '',
|
||||
proxyType: 'http',
|
||||
};
|
||||
|
||||
/**
|
||||
* 存储默认值
|
||||
*/
|
||||
export const STORE_DEFAULTS: ElectronMainStore = {
|
||||
autoUpdateNotificationEnabled: true,
|
||||
dataSyncConfig: { storageMode: 'local' },
|
||||
encryptedTokens: {},
|
||||
locale: 'auto',
|
||||
networkProxy: defaultProxySettings,
|
||||
shortcuts: DEFAULT_SHORTCUTS_CONFIG,
|
||||
storagePath: appStorageDir,
|
||||
themeMode: 'auto',
|
||||
};
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
// Theme colors
|
||||
export const BACKGROUND_DARK = '#000';
|
||||
export const BACKGROUND_LIGHT = '#f8f8f8';
|
||||
export const SYMBOL_COLOR_DARK = '#ffffff80';
|
||||
export const SYMBOL_COLOR_LIGHT = '#00000080';
|
||||
|
||||
// Window dimensions and constraints
|
||||
export const TITLE_BAR_HEIGHT = 29;
|
||||
|
||||
// Default window configuration
|
||||
export const THEME_CHANGE_DELAY = 100;
|
||||
@@ -1,9 +1,10 @@
|
||||
import { DataSyncConfig } from '@lobechat/electron-client-ipc';
|
||||
import { BrowserWindow, shell } from 'electron';
|
||||
import { BrowserWindow, app, shell } from 'electron';
|
||||
import crypto from 'node:crypto';
|
||||
import querystring from 'node:querystring';
|
||||
import { URL } from 'node:url';
|
||||
|
||||
import { name } from '@/../../package.json';
|
||||
import { createLogger } from '@/utils/logger';
|
||||
|
||||
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
|
||||
@@ -12,9 +13,10 @@ import { ControllerModule, ipcClientEvent } from './index';
|
||||
// Create logger
|
||||
const logger = createLogger('controllers:AuthCtr');
|
||||
|
||||
const protocolPrefix = `com.lobehub.${name}`;
|
||||
/**
|
||||
* Authentication Controller
|
||||
* 使用中间页 + 轮询的方式实现 OAuth 授权流程
|
||||
* Used to implement the OAuth authorization flow
|
||||
*/
|
||||
export default class AuthCtr extends ControllerModule {
|
||||
/**
|
||||
@@ -30,29 +32,9 @@ export default class AuthCtr extends ControllerModule {
|
||||
private codeVerifier: string | null = null;
|
||||
private authRequestState: string | null = null;
|
||||
|
||||
/**
|
||||
* 轮询相关参数
|
||||
*/
|
||||
// eslint-disable-next-line no-undef
|
||||
private pollingInterval: NodeJS.Timeout | null = null;
|
||||
private cachedRemoteUrl: string | null = null;
|
||||
|
||||
/**
|
||||
* 自动刷新定时器
|
||||
*/
|
||||
// eslint-disable-next-line no-undef
|
||||
private autoRefreshTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
/**
|
||||
* 构造 redirect_uri,确保授权和令牌交换时使用相同的 URI
|
||||
* @param remoteUrl 远程服务器 URL
|
||||
* @param includeHandoffId 是否包含 handoff ID(仅在授权时需要)
|
||||
*/
|
||||
private constructRedirectUri(remoteUrl: string): string {
|
||||
const callbackUrl = new URL('/oidc/callback/desktop', remoteUrl);
|
||||
|
||||
return callbackUrl.toString();
|
||||
}
|
||||
beforeAppReady = () => {
|
||||
this.registerProtocolHandler();
|
||||
};
|
||||
|
||||
/**
|
||||
* Request OAuth authorization
|
||||
@@ -61,9 +43,6 @@ export default class AuthCtr extends ControllerModule {
|
||||
async requestAuthorization(config: DataSyncConfig) {
|
||||
const remoteUrl = await this.remoteServerConfigCtr.getRemoteServerUrl(config);
|
||||
|
||||
// 缓存远程服务器 URL 用于后续轮询
|
||||
this.cachedRemoteUrl = remoteUrl;
|
||||
|
||||
logger.info(
|
||||
`Requesting OAuth authorization, storageMode:${config.storageMode} server URL: ${remoteUrl}`,
|
||||
);
|
||||
@@ -78,11 +57,8 @@ export default class AuthCtr extends ControllerModule {
|
||||
this.authRequestState = crypto.randomBytes(16).toString('hex');
|
||||
logger.debug(`Generated state parameter: ${this.authRequestState}`);
|
||||
|
||||
// Construct authorization URL with new redirect_uri
|
||||
// Construct authorization URL
|
||||
const authUrl = new URL('/oidc/auth', remoteUrl);
|
||||
const redirectUri = this.constructRedirectUri(remoteUrl);
|
||||
|
||||
logger.info('redirectUri', redirectUri);
|
||||
|
||||
// Add query parameters
|
||||
authUrl.search = querystring.stringify({
|
||||
@@ -90,9 +66,7 @@ export default class AuthCtr extends ControllerModule {
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
prompt: 'consent',
|
||||
redirect_uri: redirectUri,
|
||||
// https://github.com/lobehub/lobe-chat/pull/8450
|
||||
resource: 'urn:lobehub:chat',
|
||||
redirect_uri: `${protocolPrefix}://auth/callback`,
|
||||
response_type: 'code',
|
||||
scope: 'profile email offline_access',
|
||||
state: this.authRequestState,
|
||||
@@ -104,9 +78,6 @@ export default class AuthCtr extends ControllerModule {
|
||||
await shell.openExternal(authUrl.toString());
|
||||
logger.debug('Opening authorization URL in default browser');
|
||||
|
||||
// Start polling for credentials
|
||||
this.startPolling();
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('Authorization request failed:', error);
|
||||
@@ -115,188 +86,85 @@ export default class AuthCtr extends ControllerModule {
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动轮询机制获取凭证
|
||||
* Handle authorization callback
|
||||
* This method is called when the browser redirects to our custom protocol
|
||||
*/
|
||||
private startPolling() {
|
||||
if (!this.authRequestState) {
|
||||
logger.error('No handoff ID available for polling');
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info('Starting credential polling');
|
||||
const pollInterval = 3000; // 3 seconds
|
||||
const maxPollTime = 5 * 60 * 1000; // 5 minutes
|
||||
const startTime = Date.now();
|
||||
|
||||
this.pollingInterval = setInterval(async () => {
|
||||
try {
|
||||
// Check if polling has timed out
|
||||
if (Date.now() - startTime > maxPollTime) {
|
||||
logger.warn('Credential polling timed out');
|
||||
this.stopPolling();
|
||||
this.broadcastAuthorizationFailed('Authorization timed out');
|
||||
return;
|
||||
}
|
||||
|
||||
// Poll for credentials
|
||||
const result = await this.pollForCredentials();
|
||||
|
||||
if (result) {
|
||||
logger.info('Successfully received credentials from polling');
|
||||
this.stopPolling();
|
||||
|
||||
// Validate state parameter
|
||||
if (result.state !== this.authRequestState) {
|
||||
logger.error(
|
||||
`Invalid state parameter: expected ${this.authRequestState}, received ${result.state}`,
|
||||
);
|
||||
this.broadcastAuthorizationFailed('Invalid state parameter');
|
||||
return;
|
||||
}
|
||||
|
||||
// Exchange code for tokens
|
||||
const exchangeResult = await this.exchangeCodeForToken(result.code, this.codeVerifier!);
|
||||
|
||||
if (exchangeResult.success) {
|
||||
logger.info('Authorization successful');
|
||||
this.broadcastAuthorizationSuccessful();
|
||||
} else {
|
||||
logger.warn(`Authorization failed: ${exchangeResult.error || 'Unknown error'}`);
|
||||
this.broadcastAuthorizationFailed(exchangeResult.error || 'Unknown error');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error during credential polling:', error);
|
||||
this.stopPolling();
|
||||
this.broadcastAuthorizationFailed('Polling error: ' + error.message);
|
||||
}
|
||||
}, pollInterval);
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止轮询
|
||||
*/
|
||||
private stopPolling() {
|
||||
if (this.pollingInterval) {
|
||||
clearInterval(this.pollingInterval);
|
||||
this.pollingInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动自动刷新定时器
|
||||
*/
|
||||
private startAutoRefresh() {
|
||||
// 先停止现有的定时器
|
||||
this.stopAutoRefresh();
|
||||
|
||||
const checkInterval = 2 * 60 * 1000; // 每 2 分钟检查一次
|
||||
logger.debug('Starting auto-refresh timer');
|
||||
|
||||
this.autoRefreshTimer = setInterval(async () => {
|
||||
try {
|
||||
// 检查 token 是否即将过期 (提前 5 分钟刷新)
|
||||
if (this.remoteServerConfigCtr.isTokenExpiringSoon()) {
|
||||
const expiresAt = this.remoteServerConfigCtr.getTokenExpiresAt();
|
||||
logger.info(
|
||||
`Token is expiring soon, triggering auto-refresh. Expires at: ${expiresAt ? new Date(expiresAt).toISOString() : 'unknown'}`,
|
||||
);
|
||||
|
||||
const result = await this.remoteServerConfigCtr.refreshAccessToken();
|
||||
if (result.success) {
|
||||
logger.info('Auto-refresh successful');
|
||||
this.broadcastTokenRefreshed();
|
||||
} else {
|
||||
logger.error(`Auto-refresh failed: ${result.error}`);
|
||||
// 如果自动刷新失败,停止定时器并清除 token
|
||||
this.stopAutoRefresh();
|
||||
await this.remoteServerConfigCtr.clearTokens();
|
||||
await this.remoteServerConfigCtr.setRemoteServerConfig({ active: false });
|
||||
this.broadcastAuthorizationRequired();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error during auto-refresh check:', error);
|
||||
}
|
||||
}, checkInterval);
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止自动刷新定时器
|
||||
*/
|
||||
private stopAutoRefresh() {
|
||||
if (this.autoRefreshTimer) {
|
||||
clearInterval(this.autoRefreshTimer);
|
||||
this.autoRefreshTimer = null;
|
||||
logger.debug('Stopped auto-refresh timer');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询获取凭证
|
||||
* 直接发送 HTTP 请求到远程服务器
|
||||
*/
|
||||
private async pollForCredentials(): Promise<{ code: string; state: string } | null> {
|
||||
if (!this.authRequestState || !this.cachedRemoteUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async handleAuthCallback(callbackUrl: string) {
|
||||
logger.info(`Handling authorization callback: ${callbackUrl}`);
|
||||
try {
|
||||
// 使用缓存的远程服务器 URL
|
||||
const remoteUrl = this.cachedRemoteUrl;
|
||||
const url = new URL(callbackUrl);
|
||||
const params = new URLSearchParams(url.search);
|
||||
|
||||
// 构造请求 URL
|
||||
const url = new URL('/oidc/handoff', remoteUrl);
|
||||
url.searchParams.set('id', this.authRequestState);
|
||||
url.searchParams.set('client', 'desktop');
|
||||
// Get authorization code
|
||||
const code = params.get('code');
|
||||
const state = params.get('state');
|
||||
logger.debug(`Got parameters from callback URL: code=${code}, state=${state}`);
|
||||
|
||||
logger.debug(`Polling for credentials: ${url.toString()}`);
|
||||
// Validate state parameter to prevent CSRF attacks
|
||||
if (state !== this.authRequestState) {
|
||||
logger.error(
|
||||
`Invalid state parameter: expected ${this.authRequestState}, received ${state}`,
|
||||
);
|
||||
throw new Error('Invalid state parameter');
|
||||
}
|
||||
logger.debug('State parameter validation passed');
|
||||
|
||||
// 直接发送 HTTP 请求
|
||||
const response = await fetch(url.toString(), {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
// 检查响应状态
|
||||
if (response.status === 404) {
|
||||
// 凭证还未准备好,这是正常情况
|
||||
return null;
|
||||
if (!code) {
|
||||
logger.error('No authorization code received');
|
||||
throw new Error('No authorization code received');
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
// Get configuration information
|
||||
const config = await this.remoteServerConfigCtr.getRemoteServerConfig();
|
||||
logger.debug(`Getting remote server configuration: url=${config.remoteServerUrl}`);
|
||||
|
||||
if (config.storageMode === 'selfHost' && !config.remoteServerUrl) {
|
||||
logger.error('Server URL not configured');
|
||||
throw new Error('No server URL configured');
|
||||
}
|
||||
|
||||
// 解析响应数据
|
||||
const data = (await response.json()) as {
|
||||
data: {
|
||||
id: string;
|
||||
payload: { code: string; state: string };
|
||||
};
|
||||
success: boolean;
|
||||
};
|
||||
// Get the previously saved code_verifier
|
||||
const codeVerifier = this.codeVerifier;
|
||||
if (!codeVerifier) {
|
||||
logger.error('Code verifier not found');
|
||||
throw new Error('No code verifier found');
|
||||
}
|
||||
logger.debug('Found code verifier');
|
||||
|
||||
if (data.success && data.data?.payload) {
|
||||
logger.debug('Successfully retrieved credentials from handoff');
|
||||
return {
|
||||
code: data.data.payload.code,
|
||||
state: data.data.payload.state,
|
||||
};
|
||||
// Exchange authorization code for token
|
||||
logger.debug('Starting to exchange authorization code for token');
|
||||
const result = await this.exchangeCodeForToken(code, codeVerifier);
|
||||
|
||||
if (result.success) {
|
||||
logger.info('Authorization successful');
|
||||
// Notify render process of successful authorization
|
||||
this.broadcastAuthorizationSuccessful();
|
||||
} else {
|
||||
logger.warn(`Authorization failed: ${result.error || 'Unknown error'}`);
|
||||
// Notify render process of failed authorization
|
||||
this.broadcastAuthorizationFailed(result.error || 'Unknown error');
|
||||
}
|
||||
|
||||
return null;
|
||||
return result;
|
||||
} catch (error) {
|
||||
logger.debug('Polling attempt failed (this is normal):', error.message);
|
||||
return null;
|
||||
logger.error('Handling authorization callback failed:', error);
|
||||
|
||||
// Notify render process of failed authorization
|
||||
this.broadcastAuthorizationFailed(error.message);
|
||||
|
||||
return { error: error.message, success: false };
|
||||
} finally {
|
||||
// Clear authorization request state
|
||||
logger.debug('Clearing authorization request state');
|
||||
this.authRequestState = null;
|
||||
this.codeVerifier = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh access token
|
||||
*/
|
||||
@ipcClientEvent('refreshAccessToken')
|
||||
async refreshAccessToken() {
|
||||
logger.info('Starting to refresh access token');
|
||||
try {
|
||||
@@ -307,8 +175,6 @@ export default class AuthCtr extends ControllerModule {
|
||||
logger.info('Token refresh successful via AuthCtr call.');
|
||||
// Notify render process that token has been refreshed
|
||||
this.broadcastTokenRefreshed();
|
||||
// Restart auto-refresh timer with new expiration time
|
||||
this.startAutoRefresh();
|
||||
return { success: true };
|
||||
} else {
|
||||
// Throw an error to be caught by the catch block below
|
||||
@@ -322,7 +188,6 @@ export default class AuthCtr extends ControllerModule {
|
||||
|
||||
// Refresh failed, clear tokens and disable remote server
|
||||
logger.warn('Refresh failed, clearing tokens and disabling remote server');
|
||||
this.stopAutoRefresh();
|
||||
await this.remoteServerConfigCtr.clearTokens();
|
||||
await this.remoteServerConfigCtr.setRemoteServerConfig({ active: false });
|
||||
|
||||
@@ -333,15 +198,48 @@ export default class AuthCtr extends ControllerModule {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register custom protocol handler
|
||||
*/
|
||||
private registerProtocolHandler() {
|
||||
logger.info(`Registering custom protocol handler ${protocolPrefix}://`);
|
||||
app.setAsDefaultProtocolClient(protocolPrefix);
|
||||
|
||||
// Register custom protocol handler
|
||||
if (process.platform === 'darwin') {
|
||||
// Handle open-url event on macOS
|
||||
logger.debug('Registering open-url event handler for macOS');
|
||||
app.on('open-url', (event, url) => {
|
||||
event.preventDefault();
|
||||
logger.info(`Received open-url event: ${url}`);
|
||||
this.handleAuthCallback(url);
|
||||
});
|
||||
} else {
|
||||
// Handle protocol callback via second-instance event on Windows and Linux
|
||||
logger.debug('Registering second-instance event handler for Windows/Linux');
|
||||
app.on('second-instance', async (event, commandLine) => {
|
||||
// Find the URL from command line arguments
|
||||
const url = commandLine.find((arg) => arg.startsWith(`${protocolPrefix}://`));
|
||||
if (url) {
|
||||
logger.info(`Found URL from second-instance command line arguments: ${url}`);
|
||||
const { success } = await this.handleAuthCallback(url);
|
||||
if (success) {
|
||||
this.app.browserManager.getMainWindow().show();
|
||||
}
|
||||
} else {
|
||||
logger.warn('Protocol URL not found in second-instance command line arguments');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
logger.info(`Registered ${protocolPrefix}:// custom protocol handler`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchange authorization code for token
|
||||
*/
|
||||
private async exchangeCodeForToken(code: string, codeVerifier: string) {
|
||||
if (!this.cachedRemoteUrl) {
|
||||
throw new Error('No cached remote URL available for token exchange');
|
||||
}
|
||||
|
||||
const remoteUrl = this.cachedRemoteUrl;
|
||||
const remoteUrl = await this.remoteServerConfigCtr.getRemoteServerUrl();
|
||||
logger.info('Starting to exchange authorization code for token');
|
||||
try {
|
||||
const tokenUrl = new URL('/oidc/token', remoteUrl);
|
||||
@@ -353,7 +251,7 @@ export default class AuthCtr extends ControllerModule {
|
||||
code,
|
||||
code_verifier: codeVerifier,
|
||||
grant_type: 'authorization_code',
|
||||
redirect_uri: this.constructRedirectUri(remoteUrl),
|
||||
redirect_uri: `${protocolPrefix}://auth/callback`,
|
||||
});
|
||||
|
||||
logger.debug('Sending token exchange request');
|
||||
@@ -374,20 +272,10 @@ export default class AuthCtr extends ControllerModule {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
let data;
|
||||
|
||||
// Parse response
|
||||
try {
|
||||
data = await response.clone().json();
|
||||
} catch {
|
||||
const status = response.status;
|
||||
|
||||
throw new Error(
|
||||
`Parse JSON failed, please check your server, response status: ${status}, detail:\n\n ${await response.text()} `,
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
logger.debug('Successfully received token exchange response');
|
||||
// console.log(data); // Keep original log for debugging, or remove/change to logger.debug as needed
|
||||
|
||||
// Ensure response contains necessary fields
|
||||
if (!data.access_token || !data.refresh_token) {
|
||||
@@ -397,20 +285,13 @@ export default class AuthCtr extends ControllerModule {
|
||||
|
||||
// Save tokens
|
||||
logger.debug('Starting to save exchanged tokens');
|
||||
await this.remoteServerConfigCtr.saveTokens(
|
||||
data.access_token,
|
||||
data.refresh_token,
|
||||
data.expires_in,
|
||||
);
|
||||
await this.remoteServerConfigCtr.saveTokens(data.access_token, data.refresh_token);
|
||||
logger.info('Successfully saved exchanged tokens');
|
||||
|
||||
// Set server to active state
|
||||
logger.debug(`Setting remote server to active state: ${remoteUrl}`);
|
||||
await this.remoteServerConfigCtr.setRemoteServerConfig({ active: true });
|
||||
|
||||
// Start auto-refresh timer
|
||||
this.startAutoRefresh();
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('Exchanging authorization code failed:', error);
|
||||
@@ -509,84 +390,4 @@ export default class AuthCtr extends ControllerModule {
|
||||
logger.debug('Generated code challenge (partial): ' + challenge.slice(0, 10) + '...'); // Avoid logging full sensitive info
|
||||
return challenge;
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用启动后初始化
|
||||
*/
|
||||
afterAppReady() {
|
||||
logger.debug('AuthCtr initialized, checking for existing tokens');
|
||||
this.initializeAutoRefresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理所有定时器
|
||||
*/
|
||||
cleanup() {
|
||||
logger.debug('Cleaning up AuthCtr timers');
|
||||
this.stopPolling();
|
||||
this.stopAutoRefresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化自动刷新功能
|
||||
* 在应用启动时检查是否有有效的 token,如果有就启动自动刷新定时器
|
||||
*/
|
||||
private async initializeAutoRefresh() {
|
||||
try {
|
||||
const config = await this.remoteServerConfigCtr.getRemoteServerConfig();
|
||||
|
||||
// 检查是否配置了远程服务器且处于活动状态
|
||||
if (!config.active || !config.remoteServerUrl) {
|
||||
logger.debug(
|
||||
'Remote server not active or configured, skipping auto-refresh initialization',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否有有效的访问令牌
|
||||
const accessToken = await this.remoteServerConfigCtr.getAccessToken();
|
||||
if (!accessToken) {
|
||||
logger.debug('No access token found, skipping auto-refresh initialization');
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否有过期时间信息
|
||||
const expiresAt = this.remoteServerConfigCtr.getTokenExpiresAt();
|
||||
if (!expiresAt) {
|
||||
logger.debug('No token expiration time found, skipping auto-refresh initialization');
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查 token 是否已经过期
|
||||
const currentTime = Date.now();
|
||||
if (currentTime >= expiresAt) {
|
||||
logger.info('Token has expired, attempting to refresh it');
|
||||
|
||||
// 尝试刷新 token
|
||||
const refreshResult = await this.remoteServerConfigCtr.refreshAccessToken();
|
||||
if (refreshResult.success) {
|
||||
logger.info('Token refresh successful during initialization');
|
||||
this.broadcastTokenRefreshed();
|
||||
// 重新启动自动刷新定时器
|
||||
this.startAutoRefresh();
|
||||
return;
|
||||
} else {
|
||||
logger.error(`Token refresh failed during initialization: ${refreshResult.error}`);
|
||||
// 只有在刷新失败时才清除 token 并要求重新授权
|
||||
await this.remoteServerConfigCtr.clearTokens();
|
||||
await this.remoteServerConfigCtr.setRemoteServerConfig({ active: false });
|
||||
this.broadcastAuthorizationRequired();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 启动自动刷新定时器
|
||||
logger.info(
|
||||
`Token is valid, starting auto-refresh timer. Token expires at: ${new Date(expiresAt).toISOString()}`,
|
||||
);
|
||||
this.startAutoRefresh();
|
||||
} catch (error) {
|
||||
logger.error('Error during auto-refresh initialization:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { IpcClientEventSender } from '@/types/ipcClientEvent';
|
||||
import { ControllerModule, ipcClientEvent, shortcut } from './index';
|
||||
|
||||
export default class BrowserWindowsCtr extends ControllerModule {
|
||||
@shortcut('showApp')
|
||||
@shortcut('toggleMainWindow')
|
||||
async toggleMainWindow() {
|
||||
const mainWindow = this.app.browserManager.getMainWindow();
|
||||
mainWindow.toggleVisible();
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
import {
|
||||
ClaudeCodeMessage,
|
||||
ClaudeCodeOptions,
|
||||
ClaudeCodeQueryParams,
|
||||
ClaudeCodeQueryResult,
|
||||
ClaudeCodeSessionInfo,
|
||||
ClaudeCodeStreamingParams,
|
||||
} from '@lobechat/electron-client-ipc';
|
||||
import { app } from 'electron';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { createClaudeCodeModule } from '@/modules/claudeCode';
|
||||
import { createLogger } from '@/utils/logger';
|
||||
|
||||
import { ControllerModule, ipcClientEvent } from './index';
|
||||
|
||||
const logger = createLogger('controllers:ClaudeCodeCtr');
|
||||
|
||||
interface StreamingSession {
|
||||
abortController: AbortController;
|
||||
sessionId?: string;
|
||||
streamId: string;
|
||||
}
|
||||
|
||||
export default class ClaudeCodeCtr extends ControllerModule {
|
||||
private claudeCodeModule = createClaudeCodeModule({
|
||||
debugMode: Boolean(process.env.DEBUG),
|
||||
});
|
||||
private streamingSessions = new Map<string, StreamingSession>();
|
||||
private abortControllers = new Map<string, AbortController>();
|
||||
private sessionHistory = new Map<string, ClaudeCodeSessionInfo>();
|
||||
|
||||
/**
|
||||
* 检查 Claude Code 是否可用
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeCheckAvailability')
|
||||
async checkAvailability(): Promise<{
|
||||
apiKeySource?: string;
|
||||
available: boolean;
|
||||
error?: string;
|
||||
version?: string;
|
||||
}> {
|
||||
try {
|
||||
return await this.claudeCodeModule.checkAvailability();
|
||||
} catch (error) {
|
||||
logger.error('Error checking Claude Code availability:', error);
|
||||
return {
|
||||
available: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 Claude Code 查询
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeQuery')
|
||||
async executeQuery(params: ClaudeCodeQueryParams): Promise<ClaudeCodeQueryResult> {
|
||||
try {
|
||||
logger.info('Executing Claude Code query:', params.prompt);
|
||||
|
||||
const abortController = params.abortSignal
|
||||
? this.abortControllers.get(params.abortSignal)
|
||||
: new AbortController();
|
||||
|
||||
const messages: ClaudeCodeMessage[] = [];
|
||||
let sessionId: string | undefined;
|
||||
|
||||
const queryParams = {
|
||||
abortController,
|
||||
options: this.buildOptions(params.options),
|
||||
prompt: params.prompt,
|
||||
};
|
||||
|
||||
for await (const message of this.claudeCodeModule.query(queryParams)) {
|
||||
messages.push(message);
|
||||
|
||||
if (message.session_id) {
|
||||
sessionId = message.session_id;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新会话历史
|
||||
if (sessionId) {
|
||||
this.updateSessionHistory(sessionId, messages);
|
||||
}
|
||||
|
||||
return {
|
||||
messages,
|
||||
sessionId: sessionId || '',
|
||||
success: true,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Error executing Claude Code query:', error);
|
||||
return {
|
||||
error: error.message,
|
||||
messages: [],
|
||||
sessionId: '',
|
||||
success: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始流式查询
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeStreamStart')
|
||||
async startStreamingQuery(
|
||||
params: ClaudeCodeStreamingParams,
|
||||
): Promise<{ error?: string; success: boolean }> {
|
||||
try {
|
||||
logger.info('Starting streaming Claude Code query:', params.streamId);
|
||||
|
||||
const abortController = params.abortSignal
|
||||
? this.abortControllers.get(params.abortSignal)
|
||||
: new AbortController();
|
||||
|
||||
const session: StreamingSession = {
|
||||
abortController,
|
||||
streamId: params.streamId,
|
||||
};
|
||||
|
||||
this.streamingSessions.set(params.streamId, session);
|
||||
|
||||
// 在后台执行流式查询
|
||||
this.executeStreamingQuery(params, abortController);
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('Error starting streaming query:', error);
|
||||
return { error: error.message, success: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止流式查询
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeStreamStop')
|
||||
async stopStreamingQuery(streamId: string): Promise<{ success: boolean }> {
|
||||
try {
|
||||
logger.info('Stopping streaming query:', streamId);
|
||||
|
||||
const session = this.streamingSessions.get(streamId);
|
||||
if (session) {
|
||||
session.abortController.abort();
|
||||
this.streamingSessions.delete(streamId);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('Error stopping streaming query:', error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 AbortController
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeCreateAbortController')
|
||||
createAbortController(): { signalId: string } {
|
||||
const signalId = `abort-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
||||
const abortController = new AbortController();
|
||||
this.abortControllers.set(signalId, abortController);
|
||||
|
||||
logger.debug('Created AbortController:', signalId);
|
||||
|
||||
// 清理过期的 AbortController(30分钟后)
|
||||
setTimeout(
|
||||
() => {
|
||||
this.abortControllers.delete(signalId);
|
||||
},
|
||||
30 * 60 * 1000,
|
||||
);
|
||||
|
||||
return { signalId };
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发 abort
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeAbort')
|
||||
abort(signalId: string): { success: boolean } {
|
||||
try {
|
||||
const abortController = this.abortControllers.get(signalId);
|
||||
if (abortController) {
|
||||
abortController.abort();
|
||||
this.abortControllers.delete(signalId);
|
||||
logger.debug('Aborted signal:', signalId);
|
||||
return { success: true };
|
||||
}
|
||||
return { success: false };
|
||||
} catch (error) {
|
||||
logger.error('Error aborting:', error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最近的会话列表
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeGetRecentSessions')
|
||||
getRecentSessions(): ClaudeCodeSessionInfo[] {
|
||||
const sessions = Array.from(this.sessionHistory.values());
|
||||
// 按最后活跃时间排序
|
||||
sessions.sort((a, b) => b.lastActiveAt - a.lastActiveAt);
|
||||
// 返回最近 20 个会话
|
||||
return sessions.slice(0, 20);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除指定会话
|
||||
*/
|
||||
@ipcClientEvent('claudeCodeClearSession')
|
||||
clearSession(sessionId: string): { success: boolean } {
|
||||
try {
|
||||
this.sessionHistory.delete(sessionId);
|
||||
logger.debug('Cleared session:', sessionId);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('Error clearing session:', error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行流式查询(后台)
|
||||
*/
|
||||
private async executeStreamingQuery(
|
||||
params: ClaudeCodeStreamingParams,
|
||||
abortController: AbortController,
|
||||
) {
|
||||
try {
|
||||
const { streamId } = params;
|
||||
let sessionId: string | undefined;
|
||||
let messageCount = 0;
|
||||
|
||||
logger.debug('Starting streaming query execution for stream:', streamId);
|
||||
|
||||
const queryParams = {
|
||||
abortController,
|
||||
options: this.buildOptions(params.options),
|
||||
prompt: params.prompt,
|
||||
};
|
||||
|
||||
try {
|
||||
for await (const message of this.claudeCodeModule.query(queryParams)) {
|
||||
messageCount++;
|
||||
|
||||
logger.debug(`Stream ${streamId} - Message ${messageCount}:`, message.type);
|
||||
logger.debug('output message:', message);
|
||||
|
||||
// 广播消息到渲染进程
|
||||
this.app.browserManager.broadcastToAllWindows('claudeCodeStreamMessage', {
|
||||
message,
|
||||
streamId,
|
||||
});
|
||||
|
||||
if (message.session_id) {
|
||||
sessionId = message.session_id;
|
||||
const session = this.streamingSessions.get(streamId);
|
||||
if (session) {
|
||||
session.sessionId = sessionId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug(`Stream ${streamId} completed with ${messageCount} messages`);
|
||||
} catch (queryError) {
|
||||
logger.error('Error in Claude Code query:', queryError);
|
||||
throw queryError;
|
||||
}
|
||||
|
||||
// 更新会话历史
|
||||
if (sessionId) {
|
||||
// 这里我们不存储所有消息,只更新会话信息
|
||||
const existingSession = this.sessionHistory.get(sessionId);
|
||||
if (existingSession) {
|
||||
existingSession.lastActiveAt = Date.now();
|
||||
existingSession.turnCount++;
|
||||
} else {
|
||||
this.sessionHistory.set(sessionId, {
|
||||
createdAt: Date.now(),
|
||||
lastActiveAt: Date.now(),
|
||||
sessionId,
|
||||
turnCount: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 广播完成事件
|
||||
this.app.browserManager.broadcastToAllWindows('claudeCodeStreamComplete', {
|
||||
sessionId: sessionId || '',
|
||||
streamId,
|
||||
});
|
||||
|
||||
logger.debug('Stream completed successfully:', streamId);
|
||||
|
||||
// 清理
|
||||
this.streamingSessions.delete(streamId);
|
||||
} catch (error) {
|
||||
logger.error('Error in streaming query:', error);
|
||||
|
||||
// 广播错误事件
|
||||
this.app.browserManager.broadcastToAllWindows('claudeCodeStreamError', {
|
||||
error: error.message,
|
||||
streamId: params.streamId,
|
||||
});
|
||||
|
||||
// 清理
|
||||
this.streamingSessions.delete(params.streamId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建选项对象
|
||||
*/
|
||||
private buildOptions(options?: ClaudeCodeOptions): ClaudeCodeOptions {
|
||||
const defaultOptions: ClaudeCodeOptions = {
|
||||
maxTurns: 5,
|
||||
outputFormat: 'stream-json',
|
||||
};
|
||||
|
||||
if (!options) {
|
||||
return defaultOptions;
|
||||
}
|
||||
|
||||
// 处理选项
|
||||
const processedOptions: ClaudeCodeOptions = { ...defaultOptions, ...options };
|
||||
|
||||
// 如果提供了 mcpConfig 路径,确保它是绝对路径
|
||||
if (options.mcpConfig && !join(options.mcpConfig).startsWith('/')) {
|
||||
processedOptions.mcpConfig = join(app.getPath('userData'), options.mcpConfig);
|
||||
}
|
||||
|
||||
return processedOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新会话历史
|
||||
*/
|
||||
private updateSessionHistory(sessionId: string, messages: ClaudeCodeMessage[]) {
|
||||
const resultMessage = messages.find((m) => m.type === 'result');
|
||||
|
||||
const existingSession = this.sessionHistory.get(sessionId);
|
||||
if (existingSession) {
|
||||
existingSession.lastActiveAt = Date.now();
|
||||
existingSession.turnCount++;
|
||||
if (resultMessage?.total_cost_usd) {
|
||||
existingSession.totalCost = (existingSession.totalCost || 0) + resultMessage.total_cost_usd;
|
||||
}
|
||||
} else {
|
||||
this.sessionHistory.set(sessionId, {
|
||||
createdAt: Date.now(),
|
||||
lastActiveAt: Date.now(),
|
||||
sessionId,
|
||||
totalCost: resultMessage?.total_cost_usd,
|
||||
turnCount: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { createLogger } from '@/utils/logger';
|
||||
|
||||
import { ControllerModule, ipcClientEvent } from './index';
|
||||
|
||||
// Create logger
|
||||
const logger = createLogger('controllers:DownloadCtr');
|
||||
|
||||
/**
|
||||
* 下载控制器
|
||||
* 处理桌面应用的下载相关功能,包括自动更新通知设置
|
||||
*/
|
||||
export default class DownloadCtr extends ControllerModule {
|
||||
/**
|
||||
* 获取自动更新通知设置
|
||||
*/
|
||||
@ipcClientEvent('getAutoUpdateNotificationEnabled')
|
||||
async getAutoUpdateNotificationEnabled(): Promise<boolean> {
|
||||
try {
|
||||
const enabled = this.app.storeManager.get('autoUpdateNotificationEnabled', true);
|
||||
logger.debug('Retrieved auto update notification setting:', enabled);
|
||||
return enabled;
|
||||
} catch (error) {
|
||||
logger.error('Failed to get auto update notification setting:', error);
|
||||
return true; // 默认启用
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置自动更新通知
|
||||
*/
|
||||
@ipcClientEvent('setAutoUpdateNotificationEnabled')
|
||||
async setAutoUpdateNotificationEnabled(enabled: boolean): Promise<void> {
|
||||
try {
|
||||
this.app.storeManager.set('autoUpdateNotificationEnabled', enabled);
|
||||
logger.info('Auto update notification setting updated:', enabled);
|
||||
} catch (error) {
|
||||
logger.error('Failed to set auto update notification setting:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
import { createLogger } from '@/utils/logger';
|
||||
|
||||
import { ControllerModule, createProtocolHandler } from '.';
|
||||
import { McpSchema } from '../types/protocol';
|
||||
|
||||
const logger = createLogger('controllers:McpInstallCtr');
|
||||
|
||||
const protocolHandler = createProtocolHandler('plugin');
|
||||
|
||||
/**
|
||||
* 验证 MCP Schema 对象结构
|
||||
*/
|
||||
function validateMcpSchema(schema: any): schema is McpSchema {
|
||||
if (!schema || typeof schema !== 'object') return false;
|
||||
|
||||
// 必填字段验证
|
||||
if (typeof schema.identifier !== 'string' || !schema.identifier) return false;
|
||||
if (typeof schema.name !== 'string' || !schema.name) return false;
|
||||
if (typeof schema.author !== 'string' || !schema.author) return false;
|
||||
if (typeof schema.description !== 'string' || !schema.description) return false;
|
||||
if (typeof schema.version !== 'string' || !schema.version) return false;
|
||||
|
||||
// 可选字段验证
|
||||
if (schema.homepage !== undefined && typeof schema.homepage !== 'string') return false;
|
||||
if (schema.icon !== undefined && typeof schema.icon !== 'string') return false;
|
||||
|
||||
// config 字段验证
|
||||
if (!schema.config || typeof schema.config !== 'object') return false;
|
||||
const config = schema.config;
|
||||
|
||||
if (config.type === 'stdio') {
|
||||
if (typeof config.command !== 'string' || !config.command) return false;
|
||||
if (config.args !== undefined && !Array.isArray(config.args)) return false;
|
||||
if (config.env !== undefined && typeof config.env !== 'object') return false;
|
||||
} else if (config.type === 'http') {
|
||||
if (typeof config.url !== 'string' || !config.url) return false;
|
||||
try {
|
||||
new URL(config.url); // 验证URL格式
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (config.headers !== undefined && typeof config.headers !== 'object') return false;
|
||||
} else {
|
||||
return false; // 未知的 config type
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
interface McpInstallParams {
|
||||
id: string;
|
||||
marketId?: string;
|
||||
schema?: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP 插件安装控制器
|
||||
* 负责处理 MCP 插件安装流程
|
||||
*/
|
||||
export default class McpInstallController extends ControllerModule {
|
||||
/**
|
||||
* 处理 MCP 插件安装请求
|
||||
* @param parsedData 解析后的协议数据
|
||||
* @returns 是否处理成功
|
||||
*/
|
||||
@protocolHandler('install')
|
||||
public async handleInstallRequest(parsedData: McpInstallParams): Promise<boolean> {
|
||||
try {
|
||||
// 从参数中提取必需字段
|
||||
const { id, schema: schemaParam, marketId } = parsedData;
|
||||
|
||||
if (!id) {
|
||||
logger.warn(`🔧 [McpInstall] Missing required MCP parameters:`, {
|
||||
id: !!id,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// 映射协议来源
|
||||
|
||||
const isOfficialMarket = marketId === 'lobehub';
|
||||
|
||||
// 对于官方市场,schema 是可选的;对于第三方市场,schema 是必需的
|
||||
if (!isOfficialMarket && !schemaParam) {
|
||||
logger.warn(`🔧 [McpInstall] Schema is required for third-party marketplace:`, {
|
||||
marketId,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
let mcpSchema: McpSchema | undefined;
|
||||
|
||||
// 如果提供了 schema 参数,则解析和验证
|
||||
if (schemaParam) {
|
||||
try {
|
||||
mcpSchema = JSON.parse(schemaParam);
|
||||
} catch (error) {
|
||||
logger.error(`🔧 [McpInstall] Failed to parse MCP schema:`, error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!validateMcpSchema(mcpSchema)) {
|
||||
logger.error(`🔧 [McpInstall] Invalid MCP Schema structure`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 验证 identifier 与 id 参数匹配
|
||||
if (mcpSchema.identifier !== id) {
|
||||
logger.error(`🔧 [McpInstall] Schema identifier does not match URL id parameter:`, {
|
||||
schemaId: mcpSchema.identifier,
|
||||
urlId: id,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug(`🔧 [McpInstall] MCP install request validated:`, {
|
||||
hasSchema: !!mcpSchema,
|
||||
marketId,
|
||||
pluginId: id,
|
||||
pluginName: mcpSchema?.name || 'Unknown',
|
||||
pluginVersion: mcpSchema?.version || 'Unknown',
|
||||
});
|
||||
|
||||
// 广播安装请求到前端
|
||||
const installRequest = {
|
||||
marketId,
|
||||
pluginId: id,
|
||||
schema: mcpSchema,
|
||||
};
|
||||
|
||||
logger.debug(`🔧 [McpInstall] Broadcasting install request:`, {
|
||||
hasSchema: !!installRequest.schema,
|
||||
marketId: installRequest.marketId,
|
||||
pluginId: installRequest.pluginId,
|
||||
pluginName: installRequest.schema?.name || 'Unknown',
|
||||
});
|
||||
|
||||
// 通过应用实例广播到前端
|
||||
if (this.app?.browserManager) {
|
||||
this.app.browserManager.broadcastToWindow('chat', 'mcpInstallRequest', installRequest);
|
||||
logger.debug(`🔧 [McpInstall] Install request broadcasted successfully`);
|
||||
return true;
|
||||
} else {
|
||||
logger.error(`🔧 [McpInstall] App or browserManager not available`);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`🔧 [McpInstall] Error processing install request:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,8 @@ export default class MenuController extends ControllerModule {
|
||||
* 显示上下文菜单
|
||||
*/
|
||||
@ipcClientEvent('showContextMenu')
|
||||
showContextMenu(params: { data?: any; type: string }) {
|
||||
return this.app.menuManager.showContextMenu(params.type, params.data);
|
||||
showContextMenu(type: string, data?: any) {
|
||||
return this.app.menuManager.showContextMenu(type, data);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
import { NetworkProxySettings } from '@lobechat/electron-client-ipc';
|
||||
import { merge } from 'lodash';
|
||||
import { isEqual } from 'lodash-es';
|
||||
|
||||
import { defaultProxySettings } from '@/const/store';
|
||||
import { createLogger } from '@/utils/logger';
|
||||
|
||||
import {
|
||||
ProxyConfigValidator,
|
||||
ProxyConnectionTester,
|
||||
ProxyDispatcherManager,
|
||||
ProxyTestResult,
|
||||
} from '../modules/networkProxy';
|
||||
import { ControllerModule, ipcClientEvent } from './index';
|
||||
|
||||
// Create logger
|
||||
const logger = createLogger('controllers:NetworkProxyCtr');
|
||||
|
||||
/**
|
||||
* 网络代理控制器
|
||||
* 处理桌面应用的网络代理相关功能
|
||||
*/
|
||||
export default class NetworkProxyCtr extends ControllerModule {
|
||||
/**
|
||||
* 获取代理设置
|
||||
*/
|
||||
@ipcClientEvent('getProxySettings')
|
||||
async getDesktopSettings(): Promise<NetworkProxySettings> {
|
||||
try {
|
||||
const settings = this.app.storeManager.get(
|
||||
'networkProxy',
|
||||
defaultProxySettings,
|
||||
) as NetworkProxySettings;
|
||||
logger.debug('Retrieved proxy settings:', {
|
||||
enableProxy: settings.enableProxy,
|
||||
proxyType: settings.proxyType,
|
||||
});
|
||||
return settings;
|
||||
} catch (error) {
|
||||
logger.error('Failed to get proxy settings:', error);
|
||||
return defaultProxySettings;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置代理配置
|
||||
*/
|
||||
@ipcClientEvent('setProxySettings')
|
||||
async setProxySettings(config: NetworkProxySettings): Promise<void> {
|
||||
try {
|
||||
// 验证配置
|
||||
const validation = ProxyConfigValidator.validate(config);
|
||||
if (!validation.isValid) {
|
||||
const errorMessage = `Invalid proxy configuration: ${validation.errors.join(', ')}`;
|
||||
logger.error(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// 获取当前配置
|
||||
const currentConfig = this.app.storeManager.get(
|
||||
'networkProxy',
|
||||
defaultProxySettings,
|
||||
) as NetworkProxySettings;
|
||||
|
||||
// 检查是否有变化
|
||||
if (isEqual(currentConfig, config)) {
|
||||
logger.debug('Proxy settings unchanged, skipping update');
|
||||
return;
|
||||
}
|
||||
|
||||
// 合并配置
|
||||
const newConfig = merge({}, currentConfig, config);
|
||||
|
||||
// 应用代理设置
|
||||
await ProxyDispatcherManager.applyProxySettings(newConfig);
|
||||
|
||||
// 保存到存储
|
||||
this.app.storeManager.set('networkProxy', newConfig);
|
||||
|
||||
logger.info('Proxy settings updated successfully', {
|
||||
enableProxy: newConfig.enableProxy,
|
||||
proxyPort: newConfig.proxyPort,
|
||||
proxyServer: newConfig.proxyServer,
|
||||
proxyType: newConfig.proxyType,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to update proxy settings:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试代理连接
|
||||
*/
|
||||
@ipcClientEvent('testProxyConnection')
|
||||
async testProxyConnection(url: string): Promise<{ message?: string; success: boolean }> {
|
||||
try {
|
||||
const result = await ProxyConnectionTester.testConnection(url);
|
||||
|
||||
if (result.success) {
|
||||
return { success: true };
|
||||
} else {
|
||||
throw new Error(result.message || 'Connection test failed');
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
logger.error('Proxy connection test failed:', errorMessage);
|
||||
throw new Error(`Connection failed: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试指定代理配置
|
||||
*/
|
||||
@ipcClientEvent('testProxyConfig')
|
||||
async testProxyConfig({
|
||||
config,
|
||||
testUrl,
|
||||
}: {
|
||||
config: NetworkProxySettings;
|
||||
testUrl?: string;
|
||||
}): Promise<ProxyTestResult> {
|
||||
try {
|
||||
return await ProxyConnectionTester.testProxyConfig(config, testUrl);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
logger.error('Proxy config test failed:', errorMessage);
|
||||
return {
|
||||
message: `Proxy config test failed: ${errorMessage}`,
|
||||
success: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用初始代理设置
|
||||
*/
|
||||
async beforeAppReady(): Promise<void> {
|
||||
try {
|
||||
// 获取存储的代理设置
|
||||
const networkProxy = this.app.storeManager.get(
|
||||
'networkProxy',
|
||||
defaultProxySettings,
|
||||
) as NetworkProxySettings;
|
||||
|
||||
// 验证配置
|
||||
const validation = ProxyConfigValidator.validate(networkProxy);
|
||||
if (!validation.isValid) {
|
||||
logger.warn('Invalid stored proxy configuration, using defaults:', validation.errors);
|
||||
await ProxyDispatcherManager.applyProxySettings(defaultProxySettings);
|
||||
return;
|
||||
}
|
||||
|
||||
// 应用代理设置
|
||||
await ProxyDispatcherManager.applyProxySettings(networkProxy);
|
||||
|
||||
logger.info('Initial proxy settings applied successfully', {
|
||||
enableProxy: networkProxy.enableProxy,
|
||||
proxyType: networkProxy.proxyType,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to apply initial proxy settings:', error);
|
||||
// 出错时使用默认设置
|
||||
try {
|
||||
await ProxyDispatcherManager.applyProxySettings(defaultProxySettings);
|
||||
logger.info('Fallback to default proxy settings');
|
||||
} catch (fallbackError) {
|
||||
logger.error('Failed to apply fallback proxy settings:', fallbackError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
import {
|
||||
DesktopNotificationResult,
|
||||
ShowDesktopNotificationParams,
|
||||
} from '@lobechat/electron-client-ipc';
|
||||
import { Notification, app } from 'electron';
|
||||
import { macOS, windows } from 'electron-is';
|
||||
|
||||
import { createLogger } from '@/utils/logger';
|
||||
|
||||
import { ControllerModule, ipcClientEvent } from './index';
|
||||
|
||||
const logger = createLogger('controllers:NotificationCtr');
|
||||
|
||||
export default class NotificationCtr extends ControllerModule {
|
||||
/**
|
||||
* 在应用准备就绪后设置桌面通知
|
||||
*/
|
||||
afterAppReady() {
|
||||
this.setupNotifications();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置桌面通知权限和配置
|
||||
*/
|
||||
private setupNotifications() {
|
||||
logger.debug('Setting up desktop notifications');
|
||||
|
||||
try {
|
||||
// 检查通知支持
|
||||
if (!Notification.isSupported()) {
|
||||
logger.warn('Desktop notifications are not supported on this platform');
|
||||
return;
|
||||
}
|
||||
|
||||
// 在 macOS 上,我们可能需要显式请求通知权限
|
||||
if (macOS()) {
|
||||
logger.debug('macOS detected, notification permissions should be handled by system');
|
||||
}
|
||||
|
||||
// 在 Windows 上设置应用用户模型 ID
|
||||
if (windows()) {
|
||||
app.setAppUserModelId('com.lobehub.chat');
|
||||
logger.debug('Set Windows App User Model ID for notifications');
|
||||
}
|
||||
|
||||
logger.info('Desktop notifications setup completed');
|
||||
} catch (error) {
|
||||
logger.error('Failed to setup desktop notifications:', error);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 显示系统桌面通知(仅当窗口隐藏时)
|
||||
*/
|
||||
@ipcClientEvent('showDesktopNotification')
|
||||
async showDesktopNotification(
|
||||
params: ShowDesktopNotificationParams,
|
||||
): Promise<DesktopNotificationResult> {
|
||||
logger.debug('收到桌面通知请求:', params);
|
||||
|
||||
try {
|
||||
// 检查通知支持
|
||||
if (!Notification.isSupported()) {
|
||||
logger.warn('系统不支持桌面通知');
|
||||
return { error: 'Desktop notifications not supported', success: false };
|
||||
}
|
||||
|
||||
// 检查窗口是否隐藏
|
||||
const isWindowHidden = this.isMainWindowHidden();
|
||||
|
||||
if (!isWindowHidden) {
|
||||
logger.debug('主窗口可见,跳过桌面通知');
|
||||
return { reason: 'Window is visible', skipped: true, success: true };
|
||||
}
|
||||
|
||||
logger.info('窗口已隐藏,显示桌面通知:', params.title);
|
||||
|
||||
const notification = new Notification({
|
||||
body: params.body,
|
||||
// 添加更多配置以确保通知能正常显示
|
||||
hasReply: false,
|
||||
silent: params.silent || false,
|
||||
timeoutType: 'default',
|
||||
title: params.title,
|
||||
urgency: 'normal',
|
||||
});
|
||||
|
||||
// 添加更多事件监听来调试
|
||||
notification.on('show', () => {
|
||||
logger.info('通知已显示');
|
||||
});
|
||||
|
||||
notification.on('click', () => {
|
||||
logger.debug('用户点击通知,显示主窗口');
|
||||
const mainWindow = this.app.browserManager.getMainWindow();
|
||||
mainWindow.show();
|
||||
mainWindow.browserWindow.focus();
|
||||
});
|
||||
|
||||
notification.on('close', () => {
|
||||
logger.debug('通知已关闭');
|
||||
});
|
||||
|
||||
notification.on('failed', (error) => {
|
||||
logger.error('通知显示失败:', error);
|
||||
});
|
||||
|
||||
// 使用 Promise 来确保通知显示
|
||||
return new Promise((resolve) => {
|
||||
notification.show();
|
||||
|
||||
// 给通知一些时间来显示,然后检查结果
|
||||
setTimeout(() => {
|
||||
logger.info('通知显示调用完成');
|
||||
resolve({ success: true });
|
||||
}, 100);
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('显示桌面通知失败:', error);
|
||||
return {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
success: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查主窗口是否隐藏
|
||||
*/
|
||||
@ipcClientEvent('isMainWindowHidden')
|
||||
isMainWindowHidden(): boolean {
|
||||
try {
|
||||
const mainWindow = this.app.browserManager.getMainWindow();
|
||||
const browserWindow = mainWindow.browserWindow;
|
||||
|
||||
// 如果窗口被销毁,认为是隐藏的
|
||||
if (browserWindow.isDestroyed()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查窗口是否可见和聚焦
|
||||
const isVisible = browserWindow.isVisible();
|
||||
const isFocused = browserWindow.isFocused();
|
||||
const isMinimized = browserWindow.isMinimized();
|
||||
|
||||
logger.debug('窗口状态检查:', { isFocused, isMinimized, isVisible });
|
||||
|
||||
// 窗口隐藏的条件:不可见或最小化或失去焦点
|
||||
return !isVisible || isMinimized || !isFocused;
|
||||
} catch (error) {
|
||||
logger.error('检查窗口状态失败:', error);
|
||||
return true; // 发生错误时认为窗口隐藏,确保通知能显示
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,12 +79,6 @@ export default class RemoteServerConfigCtr extends ControllerModule {
|
||||
private encryptedAccessToken?: string;
|
||||
private encryptedRefreshToken?: string;
|
||||
|
||||
/**
|
||||
* Token expiration time (timestamp in milliseconds)
|
||||
* Used for automatic token refresh
|
||||
*/
|
||||
private tokenExpiresAt?: number;
|
||||
|
||||
/**
|
||||
* Promise representing the ongoing token refresh operation.
|
||||
* Used to prevent concurrent refreshes and allow callers to wait.
|
||||
@@ -95,19 +89,10 @@ export default class RemoteServerConfigCtr extends ControllerModule {
|
||||
* Encrypt and store tokens
|
||||
* @param accessToken Access token
|
||||
* @param refreshToken Refresh token
|
||||
* @param expiresIn Token expiration time in seconds (optional)
|
||||
*/
|
||||
async saveTokens(accessToken: string, refreshToken: string, expiresIn?: number) {
|
||||
async saveTokens(accessToken: string, refreshToken: string) {
|
||||
logger.info('Saving encrypted tokens');
|
||||
|
||||
// Calculate expiration time if provided
|
||||
if (expiresIn) {
|
||||
this.tokenExpiresAt = Date.now() + expiresIn * 1000;
|
||||
logger.debug(`Token expires at: ${new Date(this.tokenExpiresAt).toISOString()}`);
|
||||
} else {
|
||||
this.tokenExpiresAt = undefined;
|
||||
}
|
||||
|
||||
// If platform doesn't support secure storage, store raw tokens
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
logger.warn('Safe storage not available, storing tokens unencrypted');
|
||||
@@ -116,7 +101,6 @@ export default class RemoteServerConfigCtr extends ControllerModule {
|
||||
// Persist unencrypted tokens (consider security implications)
|
||||
this.app.storeManager.set(this.encryptedTokensKey, {
|
||||
accessToken: this.encryptedAccessToken,
|
||||
expiresAt: this.tokenExpiresAt,
|
||||
refreshToken: this.encryptedRefreshToken,
|
||||
});
|
||||
return;
|
||||
@@ -136,7 +120,6 @@ export default class RemoteServerConfigCtr extends ControllerModule {
|
||||
logger.debug(`Persisting encrypted tokens to store key: ${this.encryptedTokensKey}`);
|
||||
this.app.storeManager.set(this.encryptedTokensKey, {
|
||||
accessToken: this.encryptedAccessToken,
|
||||
expiresAt: this.tokenExpiresAt,
|
||||
refreshToken: this.encryptedRefreshToken,
|
||||
});
|
||||
}
|
||||
@@ -216,40 +199,17 @@ export default class RemoteServerConfigCtr extends ControllerModule {
|
||||
logger.info('Clearing access and refresh tokens');
|
||||
this.encryptedAccessToken = undefined;
|
||||
this.encryptedRefreshToken = undefined;
|
||||
this.tokenExpiresAt = undefined;
|
||||
// Also clear from persistent storage
|
||||
logger.debug(`Deleting tokens from store key: ${this.encryptedTokensKey}`);
|
||||
this.app.storeManager.delete(this.encryptedTokensKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token expiration time
|
||||
*/
|
||||
getTokenExpiresAt(): number | undefined {
|
||||
return this.tokenExpiresAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if token is expired or will expire soon
|
||||
* @param bufferTimeMs Buffer time in milliseconds (default 5 minutes)
|
||||
* @returns true if token is expired or will expire soon
|
||||
*/
|
||||
isTokenExpiringSoon(bufferTimeMs: number = 5 * 60 * 1000): boolean {
|
||||
if (!this.tokenExpiresAt) {
|
||||
return false; // No expiration time available
|
||||
}
|
||||
|
||||
const currentTime = Date.now();
|
||||
const bufferTime = this.tokenExpiresAt - bufferTimeMs;
|
||||
|
||||
return currentTime >= bufferTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新访问令牌
|
||||
* 使用存储的刷新令牌获取新的访问令牌
|
||||
* Handles concurrent requests by returning the existing refresh promise if one is in progress.
|
||||
*/
|
||||
@ipcClientEvent('refreshAccessToken')
|
||||
async refreshAccessToken(): Promise<{ error?: string; success: boolean }> {
|
||||
// If a refresh is already in progress, return the existing promise
|
||||
if (this.refreshPromise) {
|
||||
@@ -330,7 +290,7 @@ export default class RemoteServerConfigCtr extends ControllerModule {
|
||||
|
||||
// 保存新令牌
|
||||
logger.info('Token refresh successful, saving new tokens.');
|
||||
await this.saveTokens(data.access_token, data.refresh_token, data.expires_in);
|
||||
await this.saveTokens(data.access_token, data.refresh_token);
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
@@ -356,13 +316,6 @@ export default class RemoteServerConfigCtr extends ControllerModule {
|
||||
logger.info('Successfully loaded tokens from store into memory.');
|
||||
this.encryptedAccessToken = storedTokens.accessToken;
|
||||
this.encryptedRefreshToken = storedTokens.refreshToken;
|
||||
this.tokenExpiresAt = storedTokens.expiresAt;
|
||||
|
||||
if (this.tokenExpiresAt) {
|
||||
logger.debug(
|
||||
`Loaded token expiration time: ${new Date(this.tokenExpiresAt).toISOString()}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logger.debug('No valid tokens found in store.');
|
||||
}
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import {
|
||||
ProxyTRPCRequestParams,
|
||||
ProxyTRPCRequestResult,
|
||||
ProxyTRPCStreamRequestParams,
|
||||
} from '@lobechat/electron-client-ipc';
|
||||
import { IpcMainEvent, WebContents, ipcMain } from 'electron';
|
||||
import { HttpProxyAgent } from 'http-proxy-agent';
|
||||
import { HttpsProxyAgent } from 'https-proxy-agent';
|
||||
} from '@lobechat/electron-client-ipc/src/types/proxyTRPCRequest';
|
||||
import { Buffer } from 'node:buffer';
|
||||
import http, { IncomingMessage, OutgoingHttpHeaders } from 'node:http';
|
||||
import https from 'node:https';
|
||||
import { URL } from 'node:url';
|
||||
|
||||
import { defaultProxySettings } from '@/const/store';
|
||||
import { createLogger } from '@/utils/logger';
|
||||
|
||||
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
|
||||
@@ -46,137 +41,6 @@ export default class RemoteServerSyncCtr extends ControllerModule {
|
||||
afterAppReady() {
|
||||
logger.info('RemoteServerSyncCtr initialized (IPC based)');
|
||||
// No need to register protocol handler anymore
|
||||
ipcMain.on('stream:start', this.handleStreamRequest);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理流式请求的 IPC 调用
|
||||
*/
|
||||
private handleStreamRequest = async (event: IpcMainEvent, args: ProxyTRPCStreamRequestParams) => {
|
||||
const { requestId } = args;
|
||||
const logPrefix = `[StreamProxy ${args.method} ${args.urlPath}][${requestId}]`;
|
||||
logger.debug(`${logPrefix} Received stream:start IPC call`);
|
||||
|
||||
try {
|
||||
const config = await this.remoteServerConfigCtr.getRemoteServerConfig();
|
||||
if (!config.active || (config.storageMode === 'selfHost' && !config.remoteServerUrl)) {
|
||||
logger.warn(`${logPrefix} Remote server sync not active or configured.`);
|
||||
event.sender.send(
|
||||
`stream:error:${requestId}`,
|
||||
new Error('Remote server sync not active or configured'),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const remoteServerUrl = await this.remoteServerConfigCtr.getRemoteServerUrl();
|
||||
const token = await this.remoteServerConfigCtr.getAccessToken();
|
||||
|
||||
if (!token) {
|
||||
// 401 Unauthorized
|
||||
event.sender.send(`stream:response:${requestId}`, {
|
||||
headers: {},
|
||||
status: 401,
|
||||
statusText: 'Authentication required, missing token',
|
||||
});
|
||||
event.sender.send(`stream:end:${requestId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 调用新的流式转发方法
|
||||
await this.forwardStreamRequest(event.sender, {
|
||||
...args,
|
||||
accessToken: token,
|
||||
remoteServerUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(`${logPrefix} Unhandled error processing stream request:`, error);
|
||||
event.sender.send(
|
||||
`stream:error:${requestId}`,
|
||||
error instanceof Error ? error : new Error('Unknown error'),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 执行实际的流式请求转发
|
||||
*/
|
||||
private async forwardStreamRequest(
|
||||
sender: WebContents,
|
||||
args: ProxyTRPCStreamRequestParams & { accessToken: string; remoteServerUrl: string },
|
||||
) {
|
||||
const {
|
||||
urlPath,
|
||||
method,
|
||||
headers: originalHeaders,
|
||||
body: requestBody,
|
||||
accessToken,
|
||||
remoteServerUrl,
|
||||
requestId,
|
||||
} = args;
|
||||
const targetUrl = new URL(urlPath, remoteServerUrl);
|
||||
const logPrefix = `[ForwardStream ${method} ${targetUrl.pathname}][${requestId}]`;
|
||||
|
||||
const { requestOptions, requester } = this.createRequester({
|
||||
accessToken,
|
||||
headers: originalHeaders,
|
||||
method,
|
||||
url: targetUrl,
|
||||
});
|
||||
|
||||
const clientReq = requester.request(requestOptions, (clientRes: IncomingMessage) => {
|
||||
logger.debug(`${logPrefix} Received response with status ${clientRes.statusCode}`);
|
||||
|
||||
// 添加调试信息
|
||||
logger.debug(`${logPrefix} Response details:`, {
|
||||
headers: clientRes.headers,
|
||||
statusCode: clientRes.statusCode,
|
||||
statusMessage: clientRes.statusMessage,
|
||||
});
|
||||
|
||||
// 1. 立刻发送响应头和状态码
|
||||
const responseData = {
|
||||
headers: clientRes.headers || {},
|
||||
status: clientRes.statusCode || 500,
|
||||
statusText: clientRes.statusMessage || 'Unknown Status',
|
||||
};
|
||||
|
||||
logger.debug(`${logPrefix} Sending response data:`, responseData);
|
||||
sender.send(`stream:response:${requestId}`, responseData);
|
||||
|
||||
// 2. 监听数据块并转发
|
||||
clientRes.on('data', (chunk: Buffer) => {
|
||||
if (sender.isDestroyed()) return;
|
||||
logger.debug(`${logPrefix} Received data chunk, size: ${chunk.length}. Forwarding...`);
|
||||
sender.send(`stream:data:${requestId}`, chunk);
|
||||
});
|
||||
|
||||
// 3. 监听结束信号并转发
|
||||
clientRes.on('end', () => {
|
||||
logger.debug(`${logPrefix} Stream ended. Forwarding end signal...`);
|
||||
if (sender.isDestroyed()) return;
|
||||
sender.send(`stream:end:${requestId}`);
|
||||
});
|
||||
|
||||
// 4. 监听响应流错误并转发
|
||||
clientRes.on('error', (error) => {
|
||||
logger.error(`${logPrefix} Error reading response stream:`, error);
|
||||
if (sender.isDestroyed()) return;
|
||||
sender.send(`stream:error:${requestId}`, error);
|
||||
});
|
||||
});
|
||||
|
||||
// 5. 监听请求本身的错误(如 DNS 解析失败)
|
||||
clientReq.on('error', (error) => {
|
||||
logger.error(`${logPrefix} Error forwarding request:`, error);
|
||||
if (sender.isDestroyed()) return;
|
||||
sender.send(`stream:error:${requestId}`, error);
|
||||
});
|
||||
|
||||
if (requestBody) {
|
||||
clientReq.write(Buffer.from(requestBody));
|
||||
}
|
||||
|
||||
clientReq.end();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -221,12 +85,28 @@ export default class RemoteServerSyncCtr extends ControllerModule {
|
||||
|
||||
// 1. Determine target URL and prepare request options
|
||||
const targetUrl = new URL(urlPath, remoteServerUrl); // Combine base URL and path
|
||||
const { requestOptions, requester } = this.createRequester({
|
||||
accessToken,
|
||||
headers: originalHeaders,
|
||||
method,
|
||||
url: targetUrl,
|
||||
});
|
||||
|
||||
// Prepare headers, cloning and adding Authorization
|
||||
const requestHeaders: OutgoingHttpHeaders = { ...originalHeaders }; // Use OutgoingHttpHeaders
|
||||
requestHeaders['Authorization'] = `Bearer ${accessToken}`;
|
||||
|
||||
// Let node handle Host, Content-Length etc. Remove potentially problematic headers
|
||||
delete requestHeaders['host'];
|
||||
delete requestHeaders['connection']; // Often causes issues
|
||||
// delete requestHeaders['content-length']; // Let node handle it based on body
|
||||
|
||||
const requestOptions: https.RequestOptions | http.RequestOptions = {
|
||||
// Use union type
|
||||
headers: requestHeaders,
|
||||
hostname: targetUrl.hostname,
|
||||
method: method,
|
||||
path: targetUrl.pathname + targetUrl.search,
|
||||
port: targetUrl.port || (targetUrl.protocol === 'https:' ? 443 : 80),
|
||||
protocol: targetUrl.protocol,
|
||||
// agent: false, // Consider for keep-alive issues if they arise
|
||||
};
|
||||
|
||||
const requester = targetUrl.protocol === 'https:' ? https : http;
|
||||
|
||||
// 2. Make the request and capture response
|
||||
return new Promise((resolve) => {
|
||||
@@ -296,51 +176,6 @@ export default class RemoteServerSyncCtr extends ControllerModule {
|
||||
});
|
||||
}
|
||||
|
||||
private createRequester({
|
||||
headers,
|
||||
accessToken,
|
||||
method,
|
||||
url,
|
||||
}: {
|
||||
accessToken: string;
|
||||
headers: Record<string, string>;
|
||||
method: string;
|
||||
url: URL;
|
||||
}) {
|
||||
// Prepare headers, cloning and adding Oidc-Auth
|
||||
const requestHeaders: OutgoingHttpHeaders = { ...headers }; // Use OutgoingHttpHeaders
|
||||
requestHeaders['Oidc-Auth'] = accessToken;
|
||||
|
||||
// Let node handle Host, Content-Length etc. Remove potentially problematic headers
|
||||
delete requestHeaders['host'];
|
||||
delete requestHeaders['connection']; // Often causes issues
|
||||
// delete requestHeaders['content-length']; // Let node handle it based on body
|
||||
|
||||
// 读取代理配置
|
||||
const proxyConfig = this.app.storeManager.get('networkProxy', defaultProxySettings);
|
||||
|
||||
let agent;
|
||||
if (proxyConfig?.enableProxy && proxyConfig.proxyServer) {
|
||||
const proxyUrl = `${proxyConfig.proxyType}://${proxyConfig.proxyServer}${proxyConfig.proxyPort ? `:${proxyConfig.proxyPort}` : ''}`;
|
||||
agent =
|
||||
url.protocol === 'https:' ? new HttpsProxyAgent(proxyUrl) : new HttpProxyAgent(proxyUrl);
|
||||
}
|
||||
|
||||
const requestOptions: https.RequestOptions | http.RequestOptions = {
|
||||
agent,
|
||||
// Use union type
|
||||
headers: requestHeaders,
|
||||
hostname: url.hostname,
|
||||
method: method,
|
||||
path: url.pathname + url.search,
|
||||
port: url.port || (url.protocol === 'https:' ? 443 : 80),
|
||||
protocol: url.protocol,
|
||||
};
|
||||
|
||||
const requester = url.protocol === 'https:' ? https : http;
|
||||
return { requestOptions, requester };
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the 'proxy-trpc-request' IPC call from the renderer process.
|
||||
* This method should be invoked by the ipcMain.handle setup in your main process entry point.
|
||||
|
||||