mirror of
https://github.com/lobehub/lobe-chat.git
synced 2026-06-14 19:50:09 +00:00
Compare commits
424 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 28a56999a5 | |||
| 8920213e24 | |||
| e41b2d5701 | |||
| 4f42de75e1 | |||
| c7c4ab55b1 | |||
| 350e66a320 | |||
| f534d19338 | |||
| b15e90e1ae | |||
| 55079fc321 | |||
| 1080ff33aa | |||
| 837065f08a | |||
| 305e910e98 | |||
| 7e291c23f7 | |||
| 7634f511bf | |||
| 5e611f2fba | |||
| 411f88eca1 | |||
| 0e38ce159e | |||
| 27bcf18c4c | |||
| 298cd4f8c9 | |||
| 7bd25d96fe | |||
| 3d7ce4a18a | |||
| 56f55da260 | |||
| f456e91d7b | |||
| 2fa57ff557 | |||
| 3d671740a3 | |||
| 970ece0498 | |||
| c5ed5fdf2e | |||
| e8db8b9b99 | |||
| 759f30e5b7 | |||
| 43ef47c522 | |||
| d013a166ce | |||
| 86fc3912e0 | |||
| 6d438262b0 | |||
| e58864f361 | |||
| 9c2b411493 | |||
| da2c0a2c57 | |||
| 14ac6d1515 | |||
| 8b9fced111 | |||
| eea96605cf | |||
| 612866dea1 | |||
| a9c660c26e | |||
| 4813b6df27 | |||
| 0a1dcf943e | |||
| 9eec81c551 | |||
| b13563cb34 | |||
| ef79721828 | |||
| 20a53cbd34 | |||
| a76ad2344d | |||
| 58e19f856c | |||
| d1c5645517 | |||
| 0884747bb3 | |||
| 8169eae189 | |||
| 650e552aa8 | |||
| 11b27e5bf7 | |||
| a6367a5166 | |||
| 1224f4e4a7 | |||
| 1e1dbb7829 | |||
| 49fd419b72 | |||
| bad009a43c | |||
| 987e87ad8b | |||
| b36d8c7466 | |||
| 2590d72ae3 | |||
| c6038c0670 | |||
| 4ccf4c341b | |||
| c922ff2d68 | |||
| c15791d852 | |||
| 7ffb30713e | |||
| 18d2e6d50b | |||
| 2a5f8d712f | |||
| 82f5abf83b | |||
| 332e06ee6b | |||
| f1cddf9802 | |||
| 2525740b9d | |||
| a6b2a19b0e | |||
| 63760f9059 | |||
| 043e7da368 | |||
| f594fe16b1 | |||
| 0924d98f5e | |||
| dac5a6f22d | |||
| 44ffe14b9f | |||
| ddba451027 | |||
| bd5fb75efc | |||
| d7294ddebc | |||
| b0e163cb2b | |||
| 9f7677d560 | |||
| 999a63f648 | |||
| d8531ab120 | |||
| 099965a78f | |||
| 7c7de40007 | |||
| 5b043d81b1 | |||
| f326e8989e | |||
| 604234029c | |||
| a6d929bc2d | |||
| 54b6062c2e | |||
| 5d538a235a | |||
| 33050d6abe | |||
| 00822ef502 | |||
| 136bc5a917 | |||
| 3e1b360186 | |||
| cc882be4ef | |||
| ce623bb280 | |||
| e56e475331 | |||
| 41d7efcf54 | |||
| 58b73ecc95 | |||
| b25b5a0657 | |||
| c65eb095ba | |||
| 323425bd90 | |||
| 4cb831c15a | |||
| b7111be400 | |||
| 548c4e2ac2 | |||
| 1dc82d0184 | |||
| 09ce90a35a | |||
| 2071d27335 | |||
| c4fd337288 | |||
| 276e7d7bb4 | |||
| dbcec3d07e | |||
| 85f9ca5c40 | |||
| 34f88cdaab | |||
| 5d4ed11ad6 | |||
| 9250540912 | |||
| 0220e81a92 | |||
| d9024085ed | |||
| 2f3bf0fedf | |||
| 30bb028a09 | |||
| 3ac3b8304e | |||
| d6a3a26e4d | |||
| e09817e7a6 | |||
| df5d0d07f9 | |||
| eafe75bc20 | |||
| 23dcf4c617 | |||
| 3fa2573207 | |||
| 68727985d1 | |||
| d3dad7973d | |||
| 64b969ec35 | |||
| 3336dca328 | |||
| 8737f675f4 | |||
| 836546f235 | |||
| 7164b4c9ab | |||
| 82abf6d7d0 | |||
| 4b3f8d4abb | |||
| 5989a022dd | |||
| de9d479f28 | |||
| f900f7ce4e | |||
| d847e44ef7 | |||
| 4872cc1c41 | |||
| 27a4b34612 | |||
| dbeca5da70 | |||
| b836d0398d | |||
| ccdbbb927e | |||
| 8d479074fd | |||
| 5cbf9136ff | |||
| 17472aa7a5 | |||
| 0778fb5548 | |||
| 2eeab57c1e | |||
| a397a4eed7 | |||
| 885fbbe024 | |||
| 26c2dd68de | |||
| be388b8433 | |||
| afd05a2364 | |||
| 74d9bb5b6a | |||
| c9a65f78c5 | |||
| 9832bf758b | |||
| 9a6657e52e | |||
| 45f05a0169 | |||
| 29137c74d1 | |||
| 1eb64328e8 | |||
| 0efe28d122 | |||
| 33611397b2 | |||
| 0a398a8f82 | |||
| 1a2aa249fb | |||
| 6100d21038 | |||
| ccc733dac5 | |||
| c7e94e7446 | |||
| d4eb117b0c | |||
| 915c0ff5d7 | |||
| a47347d95a | |||
| c9163bc9e8 | |||
| 8dedc2d3e1 | |||
| af1f71572f | |||
| 7e68cc5b5a | |||
| 91e081885c | |||
| 3ae5134984 | |||
| df97d76c36 | |||
| 95246c5ee2 | |||
| 133fd564f1 | |||
| 9ec3315595 | |||
| d07e2acae8 | |||
| 499a9ca53e | |||
| 9f1069a51f | |||
| c576b971ad | |||
| 1a71188a1d | |||
| 79c81bb954 | |||
| 1ee6724168 | |||
| f36f6f7724 | |||
| 6d214d7bef | |||
| 4d7a060268 | |||
| 64a5d51f87 | |||
| 88c8c2dc12 | |||
| ce4969698b | |||
| 3c408e444b | |||
| ffa9b1b909 | |||
| fcc32d5e0a | |||
| 07a9b341b4 | |||
| b4b00f7c70 | |||
| 78a6483630 | |||
| ab043d45f2 | |||
| 1b8b86d8a5 | |||
| 927055871b | |||
| 7562bf4acf | |||
| 2564ebd6d5 | |||
| a00fd9d236 | |||
| 24a5e0d419 | |||
| a7b9bcd78f | |||
| 5689dd8656 | |||
| 519e03e87a | |||
| 6ac6ca59da | |||
| 4d164ae083 | |||
| 5cab2ee5b5 | |||
| 65dddfa47f | |||
| dfa2a2c279 | |||
| d82e7bb9b0 | |||
| 3fbbfc6d96 | |||
| faefe71c9a | |||
| 30a4734577 | |||
| 9e7bea6d88 | |||
| d0ceab9dd6 | |||
| 09055595e4 | |||
| 86a28d9615 | |||
| 164c8b344e | |||
| 9b354af18c | |||
| 62f5a1b93c | |||
| 2e9ad20675 | |||
| 15e15e84ca | |||
| 05cb6bb7de | |||
| a1c66c81fc | |||
| c1ddb6fa23 | |||
| 439fb6eb9d | |||
| 27d48e89e9 | |||
| 54b08fd139 | |||
| 8e2d47d595 | |||
| 75bde54d95 | |||
| b69e75cfca | |||
| 1d466e514f | |||
| a51b33f154 | |||
| 485e6cf47e | |||
| b0d59f8b1b | |||
| 8ceb25f8c2 | |||
| 1fae49042d | |||
| 96ae8034fb | |||
| b3120167ce | |||
| 51ad3998e4 | |||
| 6435935f10 | |||
| 45f71478c4 | |||
| 0a724aae32 | |||
| 1cf4355e94 | |||
| 74a702a5ff | |||
| 6c83807218 | |||
| e5eb7a280d | |||
| a21c05bf64 | |||
| 1e61e79034 | |||
| 4556bdf1c2 | |||
| dbc4b10837 | |||
| 0f10efcb5d | |||
| 68aad95c04 | |||
| 7b12e54646 | |||
| e10a433610 | |||
| 327a56474e | |||
| abb93a6f79 | |||
| d861bb0421 | |||
| 7f00b530fa | |||
| 4cefafd5c5 | |||
| 135c9bea7f | |||
| 862ab713e1 | |||
| e1424ad797 | |||
| 652bf08ab8 | |||
| 025d00202c | |||
| 04db9c59ff | |||
| d9642fc6c5 | |||
| efc7eaf537 | |||
| acec55f605 | |||
| e96750cff3 | |||
| 4eee917d45 | |||
| 96b7508e01 | |||
| f44bf9180b | |||
| 18eee1f75d | |||
| 769fda060d | |||
| 8a88bd099b | |||
| 6b0a411caf | |||
| 600c29b13f | |||
| 2b93efff5a | |||
| 05b99d6c97 | |||
| b46fa8ee99 | |||
| b764c4258d | |||
| 7b726f2846 | |||
| ff94ef0fea | |||
| dfe300622e | |||
| 2b4d657f28 | |||
| 47227cc486 | |||
| 0ee89ff96f | |||
| 0b37014c95 | |||
| 6cc49259c2 | |||
| 8e8505702e | |||
| 5b409ccfa2 | |||
| b525728da9 | |||
| 76d8d502e9 | |||
| 4e71af77f5 | |||
| 7abeee2416 | |||
| f7effe92a2 | |||
| 88e7d2ada1 | |||
| 8c0101e67c | |||
| d796b85ee8 | |||
| 641dfca67c | |||
| aa126fe06f | |||
| 3dcc5da11a | |||
| 6d531d7cc1 | |||
| 0b30d05aaa | |||
| c13e11ce3f | |||
| 8777a4e42a | |||
| 41b4363802 | |||
| d34ba6496e | |||
| 6bdc75781f | |||
| 022d858cbc | |||
| f7302b5886 | |||
| 2077251a16 | |||
| d95c7f4142 | |||
| ceb5289d57 | |||
| 926fa9a1a2 | |||
| d2fba0fb7f | |||
| c883ad1a13 | |||
| 6e0c386090 | |||
| ef599cff43 | |||
| 151e75ef60 | |||
| 3a3e73e419 | |||
| 539932af69 | |||
| de94b3ecd0 | |||
| 2a7e8a89e0 | |||
| 7eae4308ec | |||
| b4ac89d281 | |||
| 223b0c7fa9 | |||
| 9ed268cd36 | |||
| 7c33ccaf53 | |||
| 0a5ae9f1a8 | |||
| e172055a52 | |||
| db57461337 | |||
| 2c6df10136 | |||
| 65609dd1e9 | |||
| f97c62e196 | |||
| 526e0bf473 | |||
| 0a3ff2ce9e | |||
| e208b01472 | |||
| 904ee138ba | |||
| 1e3597200b | |||
| 89b93b396d | |||
| 9c28a88561 | |||
| 7c1ca41c53 | |||
| 740a28e4aa | |||
| ddddb1e881 | |||
| bba3179b47 | |||
| ce159a33f0 | |||
| b0be9be7c0 | |||
| 6db157ed64 | |||
| af071015d0 | |||
| 0458190d16 | |||
| 4306558781 | |||
| 954eb2cb18 | |||
| 3cc4a54d6f | |||
| bb1a3d9a08 | |||
| adcedf41ca | |||
| d79f2f99fd | |||
| 3b87fe70b2 | |||
| 29417d5e18 | |||
| 9b74e172a0 | |||
| 0c00c89374 | |||
| 4db6485410 | |||
| 1257d905c7 | |||
| 896020a7ba | |||
| 411ed7eac1 | |||
| c36ec9bdbd | |||
| b8d51a9c87 | |||
| 433e679844 | |||
| fe7062f796 | |||
| b278458f2d | |||
| d136b6eb55 | |||
| ef42644d03 | |||
| dfb8687f0e | |||
| 14c41c488f | |||
| bc984529a6 | |||
| f72eadee09 | |||
| 21cac39e72 | |||
| b7f8e6e521 | |||
| 6e7035e1e5 | |||
| 0dd157b2f6 | |||
| a796495e1c | |||
| 4f4620c3c3 | |||
| 96301670c4 | |||
| d7763c38c5 | |||
| b1e01d377a | |||
| 0ed73685dc | |||
| f92b86b194 | |||
| 1cf58899d8 | |||
| c1dfa7ab49 | |||
| f8a01aacb0 | |||
| c29559cb2e | |||
| 16dd71b5e9 | |||
| ad8f5e451b | |||
| 67abdfe153 | |||
| 672580737f | |||
| 778152f966 | |||
| 018ca7598c | |||
| 6bfba72dce | |||
| b7dbcfd310 | |||
| 3264cf2106 | |||
| 9a372f622d | |||
| de05d4165f | |||
| 57118b031e | |||
| c4b2bb59c3 | |||
| 2211cd7632 | |||
| 2a3754a436 | |||
| e448d52d5c | |||
| 04edfca6e0 | |||
| b9e3e6633e | |||
| 17a289066e | |||
| 5e99b815f7 | |||
| 07472e0555 |
@@ -0,0 +1,183 @@
|
||||
---
|
||||
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`
|
||||
@@ -26,28 +26,11 @@ Gather the modified code and context. Please strictly follow the process below:
|
||||
|
||||
### Code Style
|
||||
|
||||
read [typescript.mdc](mdc:.cursor/rules/typescript.mdc) to learn the project's code style.
|
||||
|
||||
- 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.
|
||||
read [typescript.mdc](mdc:.cursor/rules/typescript.mdc) for the consolidated project code style and optimization rules.
|
||||
|
||||
### Code Optimization
|
||||
|
||||
- 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.
|
||||
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.
|
||||
|
||||
### Obvious Bugs
|
||||
|
||||
|
||||
@@ -30,75 +30,3 @@ alwaysApply: true
|
||||
- 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!**
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
---
|
||||
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. **分解问题** - 将复杂问题拆解为更小的子问题
|
||||
@@ -1,6 +1,5 @@
|
||||
---
|
||||
description: i18n workflow and troubleshooting
|
||||
globs:
|
||||
globs: *.tsx
|
||||
alwaysApply: false
|
||||
---
|
||||
# LobeChat 国际化指南
|
||||
|
||||
@@ -10,7 +10,7 @@ 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.
|
||||
read [package.json](mdc:package.json) to know all npm packages you can use.
|
||||
|
||||
The project uses the following technologies:
|
||||
|
||||
@@ -42,17 +42,3 @@ The project uses the following technologies:
|
||||
- Cursor AI for code editing and AI coding assistance
|
||||
|
||||
Note: All tools and libraries used are the latest versions. The application only needs to be compatible with the latest browsers;
|
||||
|
||||
## Often used npm scripts
|
||||
|
||||
```bash
|
||||
# type check
|
||||
bun type-check
|
||||
|
||||
# install dependencies
|
||||
pnpm install
|
||||
|
||||
# !: don't any build script to check weather code can work after modify
|
||||
```
|
||||
|
||||
check [testing guide](./testing-guide/testing-guide.mdc) to learn test scripts.
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
---
|
||||
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,6 +3,7 @@ description:
|
||||
globs: *.tsx
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# react component 编写指南
|
||||
|
||||
- 如果要写复杂样式的话用 antd-style ,简单的话可以用 style 属性直接写内联样式
|
||||
@@ -20,18 +21,20 @@ 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
|
||||
@@ -53,13 +56,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>
|
||||
@@ -74,80 +77,96 @@ 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
|
||||
Icon
|
||||
- ActionIcon
|
||||
- ActionIconGroup
|
||||
- Block
|
||||
- Button
|
||||
- DownloadButton
|
||||
- Icon
|
||||
- Data Display
|
||||
Avatar
|
||||
Collapse
|
||||
FileTypeIcon
|
||||
FluentEmoji
|
||||
GuideCard
|
||||
Highlighter
|
||||
Hotkey
|
||||
Image
|
||||
List
|
||||
Markdown
|
||||
MaterialFileTypeIcon
|
||||
Mermaid
|
||||
Segmented
|
||||
Snippet
|
||||
SortableList
|
||||
Tag
|
||||
Tooltip
|
||||
Video
|
||||
- Avatar
|
||||
- AvatarGroup
|
||||
- GroupAvatar
|
||||
- Collapse
|
||||
- FileTypeIcon
|
||||
- FluentEmoji
|
||||
- GuideCard
|
||||
- Highlighter
|
||||
- Hotkey
|
||||
- Image
|
||||
- List
|
||||
- Markdown
|
||||
- SearchResultCards
|
||||
- MaterialFileTypeIcon
|
||||
- Mermaid
|
||||
- Typography
|
||||
- Text
|
||||
- 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
|
||||
Footer
|
||||
Grid
|
||||
Header
|
||||
Layout
|
||||
MaskShadow
|
||||
ScrollShadow
|
||||
- DraggablePanel
|
||||
- DraggablePanelBody
|
||||
- DraggablePanelContainer
|
||||
- DraggablePanelFooter
|
||||
- DraggablePanelHeader
|
||||
- Footer
|
||||
- Grid
|
||||
- Header
|
||||
- Layout
|
||||
- LayoutFooter
|
||||
- LayoutHeader
|
||||
- LayoutMain
|
||||
- LayoutSidebar
|
||||
- LayoutSidebarInner
|
||||
- LayoutToc
|
||||
- MaskShadow
|
||||
- ScrollShadow
|
||||
- Navigation
|
||||
Burger
|
||||
Dropdown
|
||||
Menu
|
||||
SideNav
|
||||
Tabs
|
||||
Toc
|
||||
- Burger
|
||||
- Dropdown
|
||||
- Menu
|
||||
- SideNav
|
||||
- Tabs
|
||||
- Toc
|
||||
- Theme
|
||||
ConfigProvider
|
||||
FontLoader
|
||||
ThemeProvider
|
||||
- ConfigProvider
|
||||
- FontLoader
|
||||
- ThemeProvider
|
||||
|
||||
@@ -4,82 +4,49 @@ globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# LobeChat Cursor Rules System Guide
|
||||
|
||||
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
|
||||
# 📋 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
|
||||
- `testing-guide.mdc` – Comprehensive testing guide for Vitest environment
|
||||
- `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
|
||||
|
||||
## ❌ Common Misunderstandings to Avoid
|
||||
## Desktop (Electron)
|
||||
|
||||
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
|
||||
- `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
|
||||
|
||||
## 🛠️ Practical Workflow
|
||||
## Debugging
|
||||
|
||||
```
|
||||
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)
|
||||
```
|
||||
- `debug.mdc` – General debugging guide
|
||||
- `debug-usage.mdc` – Using the debug package and namespace conventions
|
||||
|
||||
## Example Decision Flow
|
||||
## Testing
|
||||
|
||||
**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 ✅
|
||||
- `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
|
||||
|
||||
@@ -6,38 +6,26 @@ alwaysApply: true
|
||||
|
||||
## System Role
|
||||
|
||||
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 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 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 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 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
|
||||
- Admit when you don't know something instead of guessing
|
||||
- Express uncertainty when there might not be a correct answer, instead of take action by guessing and assuming
|
||||
|
||||
## 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
|
||||
- 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
|
||||
|
||||
## 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.
|
||||
- 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
|
||||
|
||||
@@ -5,6 +5,8 @@ alwaysApply: false
|
||||
|
||||
## 🗃️ 数据库 Model 测试指南
|
||||
|
||||
测试 `packages/database` 下的数据库 Model 层。
|
||||
|
||||
### 测试环境选择 💡
|
||||
|
||||
数据库 Model 层通过环境变量控制数据库类型,在两种测试环境下有不同的数据库后端:客户端环境 (PGLite) 和 服务端环境 (PostgreSQL)
|
||||
@@ -17,10 +19,10 @@ alwaysApply: false
|
||||
|
||||
```bash
|
||||
# 1. 先在客户端环境测试(快速验证)
|
||||
npx vitest run --config vitest.config.ts src/database/models/__tests__/myModel.test.ts
|
||||
cd packages/database && TEST_SERVER_DB=0 bunx vitest run --silent='passed-only' src/database/models/__tests__/myModel.test.ts
|
||||
|
||||
# 2. 再在服务端环境测试(兼容性验证)
|
||||
npx vitest run --config vitest.config.server.ts 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 测试的最佳实践 📋
|
||||
|
||||
@@ -5,11 +5,11 @@ alwaysApply: false
|
||||
|
||||
# 测试指南 - LobeChat Testing Guide
|
||||
|
||||
## 🧪 测试环境概览
|
||||
## 测试环境概览
|
||||
|
||||
LobeChat 项目使用 Vitest 测试库,配置了两种不同的测试环境:
|
||||
|
||||
### 客户端测试环境 (DOM Environment)
|
||||
### 客户端数据库测试环境 (DOM Environment)
|
||||
|
||||
- **配置文件**: [vitest.config.ts](mdc:vitest.config.ts)
|
||||
- **环境**: Happy DOM (浏览器环境模拟)
|
||||
@@ -17,60 +17,71 @@ LobeChat 项目使用 Vitest 测试库,配置了两种不同的测试环境:
|
||||
- **用途**: 测试前端组件、客户端逻辑、React 组件等
|
||||
- **设置文件**: [tests/setup.ts](mdc:tests/setup.ts)
|
||||
|
||||
### 服务端测试环境 (Node Environment)
|
||||
### 服务端数据库测试环境 (Node Environment)
|
||||
|
||||
- **配置文件**: [vitest.config.server.ts](mdc:vitest.config.server.ts)
|
||||
目前只有 `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 端点等
|
||||
- **设置文件**: [tests/setup-db.ts](mdc:tests/setup-db.ts)
|
||||
- **设置文件**: [packages/database/tests/setup-db.ts](mdc:packages/database/tests/setup-db.ts)
|
||||
|
||||
## 🚀 测试运行命令
|
||||
## 测试运行命令
|
||||
|
||||
**🚨 性能警告**: 项目包含 3000+ 测试用例,完整运行需要约 10 分钟。务必使用文件过滤或测试名称过滤。
|
||||
** 性能警告**: 项目包含 3000+ 测试用例,完整运行需要约 10 分钟。务必使用文件过滤或测试名称过滤。
|
||||
|
||||
### ✅ 正确的命令格式
|
||||
### 正确的命令格式
|
||||
|
||||
```bash
|
||||
# 运行所有客户端/服务端测试
|
||||
npx vitest run --config vitest.config.ts # 客户端测试
|
||||
npx vitest run --config vitest.config.server.ts # 服务端测试
|
||||
bunx vitest run --silent='passed-only' # 客户端测试
|
||||
cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only' # 服务端测试
|
||||
|
||||
# 运行特定测试文件 (支持模糊匹配)
|
||||
npx vitest run --config vitest.config.ts user.test.ts
|
||||
bunx vitest run --silent='passed-only' user.test.ts
|
||||
|
||||
# 运行特定测试用例名称 (使用 -t 参数)
|
||||
npx vitest run --config vitest.config.ts -t "test case name"
|
||||
bunx vitest run --silent='passed-only' -t "test case name"
|
||||
|
||||
# 组合使用文件和测试名称过滤
|
||||
npx vitest run --config vitest.config.ts filename.test.ts -t "specific test"
|
||||
bunx vitest run --silent='passed-only' filename.test.ts -t "specific test"
|
||||
|
||||
# 生成覆盖率报告 (使用 --coverage 参数)
|
||||
npx vitest run --config vitest.config.ts --coverage
|
||||
bunx vitest run --silent='passed-only' --coverage
|
||||
```
|
||||
|
||||
### ❌ 避免的命令格式
|
||||
### 避免的命令格式
|
||||
|
||||
```bash
|
||||
# ❌ 这些命令会运行所有 3000+ 测试用例,耗时约 10 分钟!
|
||||
# 这些命令会运行所有 3000+ 测试用例,耗时约 10 分钟!
|
||||
npm test
|
||||
npm test some-file.test.ts
|
||||
|
||||
# ❌ 不要使用裸 vitest (会进入 watch 模式)
|
||||
# 不要使用裸 vitest (会进入 watch 模式)
|
||||
vitest test-file.test.ts
|
||||
```
|
||||
|
||||
## 🔧 测试修复原则
|
||||
## 测试修复原则
|
||||
|
||||
### 核心原则 ⚠️
|
||||
### 核心原则
|
||||
|
||||
1. **充分阅读测试代码**: 在修复测试之前,必须完整理解测试的意图和实现
|
||||
2. **测试优先修复**: 如果是测试本身写错了,修改测试而不是实现代码
|
||||
3. **专注单一问题**: 只修复指定的测试,不要添加额外测试或功能
|
||||
4. **不自作主张**: 不要因为发现其他问题就直接修改,先提出再讨论
|
||||
1. **收集足够的上下文**
|
||||
在修复测试之前,务必做到:
|
||||
- 完整理解测试的意图和实现
|
||||
- 强烈建议阅读当前的 git diff 和 PR diff
|
||||
|
||||
### 测试协作最佳实践 🤝
|
||||
2. **测试优先修复**
|
||||
如果是测试本身写错了,应优先修改测试,而不是实现代码。
|
||||
|
||||
3. **专注单一问题**
|
||||
只修复指定的测试,不要顺带添加额外测试。
|
||||
|
||||
4. **不自作主张**
|
||||
发现其他问题时,不要直接修改,需先提出并讨论。
|
||||
|
||||
### 测试协作最佳实践
|
||||
|
||||
基于实际开发经验总结的重要协作原则:
|
||||
|
||||
@@ -84,10 +95,10 @@ vitest test-file.test.ts
|
||||
- **避免陷阱**: 不要陷入"不断尝试相同或类似方法"的循环
|
||||
|
||||
```typescript
|
||||
// ❌ 错误做法:连续失败后继续盲目尝试
|
||||
// 错误做法:连续失败后继续盲目尝试
|
||||
// 第3次、第4次仍在用相似的方法修复同一个问题
|
||||
|
||||
// ✅ 正确做法:失败1-2次后总结问题
|
||||
// 正确做法:失败1-2次后总结问题
|
||||
/*
|
||||
问题总结:
|
||||
1. 尝试过的方法:修改 mock 数据结构
|
||||
@@ -106,7 +117,7 @@ vitest test-file.test.ts
|
||||
- **保持稳定性**: 测试名称应该在代码重构后仍然有意义
|
||||
|
||||
```typescript
|
||||
// ❌ 错误的测试命名
|
||||
// 错误的测试命名
|
||||
describe('User component coverage', () => {
|
||||
it('covers line 45-50 in getUserData', () => {
|
||||
// 为了覆盖第45-50行而写的测试
|
||||
@@ -117,7 +128,7 @@ describe('User component coverage', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ✅ 正确的测试命名
|
||||
// 正确的测试命名
|
||||
describe('<UserAvatar />', () => {
|
||||
it('should render fallback icon when image url is not provided', () => {
|
||||
// 测试具体的业务场景,自然会覆盖相关代码分支
|
||||
@@ -131,8 +142,8 @@ describe('<UserAvatar />', () => {
|
||||
|
||||
**覆盖率提升的正确思路**:
|
||||
|
||||
- ✅ 通过设计各种业务场景(正常流程、边缘情况、错误处理)来自然提升覆盖率
|
||||
- ❌ 不要为了达到覆盖率数字而写测试,更不要在测试中注释"为了覆盖 xxx 行"
|
||||
- 通过设计各种业务场景(正常流程、边缘情况、错误处理)来自然提升覆盖率
|
||||
- 不要为了达到覆盖率数字而写测试,更不要在测试中注释"为了覆盖 xxx 行"
|
||||
|
||||
#### 3. 测试组织结构
|
||||
|
||||
@@ -143,7 +154,7 @@ describe('<UserAvatar />', () => {
|
||||
- **避免碎片化**: 不要为了单个测试用例就创建新的顶级 `describe` 块
|
||||
|
||||
```typescript
|
||||
// ❌ 错误的组织方式:创建过多顶级块
|
||||
// 错误的组织方式:创建过多顶级块
|
||||
describe('<UserProfile />', () => {
|
||||
it('should render user name', () => {});
|
||||
});
|
||||
@@ -158,7 +169,7 @@ describe('UserProfile edge cases', () => {
|
||||
it('should handle missing avatar', () => {});
|
||||
});
|
||||
|
||||
// ✅ 正确的组织方式:合并相关测试
|
||||
// 正确的组织方式:合并相关测试
|
||||
describe('<UserProfile />', () => {
|
||||
it('should render user name', () => {});
|
||||
|
||||
@@ -214,9 +225,9 @@ describe('<UserProfile />', () => {
|
||||
**修复方法**: 更新了测试文件中的 mock 数据结构,使其与最新的 API 响应格式保持一致。具体修改了 `user.test.ts` 中的 `mockUserData` 对象结构。
|
||||
```
|
||||
|
||||
## 🎯 测试编写最佳实践
|
||||
## 测试编写最佳实践
|
||||
|
||||
### Mock 数据策略:追求"低成本的真实性" 📋
|
||||
### Mock 数据策略:追求"低成本的真实性"
|
||||
|
||||
**核心原则**: 测试数据应默认追求真实性,只有在引入"高昂的测试成本"时才进行简化。
|
||||
|
||||
@@ -228,10 +239,10 @@ describe('<UserProfile />', () => {
|
||||
- **网络请求**:HTTP 调用、数据库连接
|
||||
- **系统调用**:获取系统时间、环境变量等
|
||||
|
||||
#### ✅ 推荐做法:Mock 依赖,保留真实数据
|
||||
#### 推荐做法:Mock 依赖,保留真实数据
|
||||
|
||||
```typescript
|
||||
// ✅ 好的做法:Mock I/O 操作,但使用真实的文件内容格式
|
||||
// 好的做法:Mock I/O 操作,但使用真实的文件内容格式
|
||||
describe('parseContentType', () => {
|
||||
beforeEach(() => {
|
||||
// Mock 文件读取操作(避免真实 I/O)
|
||||
@@ -249,7 +260,7 @@ describe('parseContentType', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ❌ 过度简化:使用不真实的数据
|
||||
// 过度简化:使用不真实的数据
|
||||
describe('parseContentType', () => {
|
||||
it('should detect PDF content type correctly', () => {
|
||||
// 这种简化数据没有测试价值
|
||||
@@ -259,78 +270,116 @@ describe('parseContentType', () => {
|
||||
});
|
||||
```
|
||||
|
||||
#### 🎯 真实标识符的价值
|
||||
#### 真实标识符的价值
|
||||
|
||||
```typescript
|
||||
// ✅ 使用真实的提供商标识符
|
||||
it('should parse OpenAI model list correctly', () => {
|
||||
const result = parseModelString('openai', '+gpt-4,+gpt-3.5-turbo');
|
||||
expect(result.add).toHaveLength(2);
|
||||
expect(result.add[0].id).toBe('gpt-4');
|
||||
});
|
||||
// ✅ 使用真实标识符
|
||||
const result = parseModelString('openai', '+gpt-4,+gpt-3.5-turbo');
|
||||
|
||||
// ❌ 使用占位符标识符(价值较低)
|
||||
it('should parse model list correctly', () => {
|
||||
const result = parseModelString('test-provider', '+model1,+model2');
|
||||
expect(result.add).toHaveLength(2);
|
||||
// 这种测试对理解真实场景帮助不大
|
||||
// ❌ 使用占位符(价值较低)
|
||||
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
|
||||
// ✅ 测试是否抛出错误
|
||||
it('should throw error when invalid input provided', () => {
|
||||
expect(() => processInput(null)).toThrow();
|
||||
});
|
||||
// ✅ 测试错误类型和属性
|
||||
expect(() => validateUser({})).toThrow(ValidationError);
|
||||
expect(() => processPayment({})).toThrow(
|
||||
expect.objectContaining({
|
||||
code: 'INVALID_PAYMENT_DATA',
|
||||
statusCode: 400,
|
||||
}),
|
||||
);
|
||||
|
||||
// ✅ 测试错误类型(最推荐)
|
||||
it('should throw ValidationError for invalid data', () => {
|
||||
expect(() => validateUser({})).toThrow(ValidationError);
|
||||
});
|
||||
|
||||
// ✅ 测试错误属性而非消息文本
|
||||
it('should throw error with correct error code', () => {
|
||||
expect(() => processPayment({})).toThrow(
|
||||
expect.objectContaining({
|
||||
code: 'INVALID_PAYMENT_DATA',
|
||||
statusCode: 400,
|
||||
}),
|
||||
);
|
||||
});
|
||||
// ❌ 避免测试具体错误文本
|
||||
expect(() => processUser({})).toThrow('用户数据不能为空,请检查输入参数');
|
||||
```
|
||||
|
||||
#### ❌ 应避免的做法
|
||||
|
||||
```typescript
|
||||
// ❌ 过度依赖具体错误信息文本
|
||||
it('should throw specific error message', () => {
|
||||
expect(() => processUser({})).toThrow('用户数据不能为空,请检查输入参数');
|
||||
// 这种测试很脆弱,错误文案稍有修改就会失败
|
||||
});
|
||||
```
|
||||
|
||||
#### 🎯 例外情况:何时可以测试错误信息
|
||||
|
||||
```typescript
|
||||
// ✅ 测试标准 API 错误(这是契约的一部分)
|
||||
it('should return proper HTTP error for API', () => {
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.error).toBe('Bad Request');
|
||||
});
|
||||
|
||||
// ✅ 测试错误信息的关键部分(使用正则)
|
||||
it('should include field name in validation error', () => {
|
||||
expect(() => validateField('email', '')).toThrow(/email/i);
|
||||
});
|
||||
```
|
||||
|
||||
### 疑难解答:警惕模块污染 🚨
|
||||
### 疑难解答:警惕模块污染
|
||||
|
||||
**识别信号**: 当你的测试出现以下"灵异"现象时,优先怀疑模块污染:
|
||||
|
||||
@@ -341,55 +390,25 @@ it('should include field name in validation error', () => {
|
||||
#### 典型场景:动态 Mock 同一模块
|
||||
|
||||
```typescript
|
||||
// ❌ 容易出现模块污染的写法
|
||||
describe('ConfigService', () => {
|
||||
it('should work in development mode', async () => {
|
||||
vi.doMock('./config', () => ({ isDev: true }));
|
||||
const { getSettings } = await import('./configService'); // 第一次加载
|
||||
expect(getSettings().debugMode).toBe(true);
|
||||
});
|
||||
|
||||
it('should work in production mode', async () => {
|
||||
vi.doMock('./config', () => ({ isDev: false }));
|
||||
const { getSettings } = await import('./configService'); // 可能使用缓存的旧版本!
|
||||
expect(getSettings().debugMode).toBe(false); // ❌ 可能失败
|
||||
});
|
||||
// ❌ 问题:动态Mock同一模块
|
||||
it('dev mode', async () => {
|
||||
vi.doMock('./config', () => ({ isDev: true }));
|
||||
const { getSettings } = await import('./service'); // 可能使用缓存
|
||||
});
|
||||
|
||||
// ✅ 使用 resetModules 解决模块污染
|
||||
describe('ConfigService', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules(); // 清除模块缓存,确保每个测试都是干净的环境
|
||||
});
|
||||
|
||||
it('should work in development mode', async () => {
|
||||
vi.doMock('./config', () => ({ isDev: true }));
|
||||
const { getSettings } = await import('./configService');
|
||||
expect(getSettings().debugMode).toBe(true);
|
||||
});
|
||||
|
||||
it('should work in production mode', async () => {
|
||||
vi.doMock('./config', () => ({ isDev: false }));
|
||||
const { getSettings } = await import('./configService');
|
||||
expect(getSettings().debugMode).toBe(false); // ✅ 测试通过
|
||||
});
|
||||
// ✅ 解决:清除模块缓存
|
||||
beforeEach(() => {
|
||||
vi.resetModules(); // 确保每个测试都是干净环境
|
||||
});
|
||||
```
|
||||
|
||||
#### 🔧 排查和解决步骤
|
||||
**记住**: `vi.resetModules()` 是解决测试"灵异"失败的终极武器。
|
||||
|
||||
1. **识别问题**: 测试失败时,首先问自己:"是否有多个测试在 Mock 同一个模块?"
|
||||
2. **添加隔离**: 在 `beforeEach` 中添加 `vi.resetModules()`
|
||||
3. **验证修复**: 重新运行测试,确认问题解决
|
||||
|
||||
**记住**: `vi.resetModules()` 是解决测试"灵异"失败的终极武器,当常规调试方法都无效时,它往往能一针见血地解决问题。
|
||||
|
||||
## 📂 测试文件组织
|
||||
## 测试文件组织
|
||||
|
||||
### 文件命名约定
|
||||
|
||||
- **客户端测试**: `*.test.ts`, `*.test.tsx` (任意位置)
|
||||
- **服务端测试**: `src/database/models/**/*.test.ts`, `src/database/server/**/*.test.ts` (限定路径)
|
||||
`*.test.ts`, `*.test.tsx` (任意位置)
|
||||
|
||||
### 测试文件组织风格
|
||||
|
||||
@@ -406,7 +425,10 @@ src/components/Button/
|
||||
└── index.test.tsx # 测试文件
|
||||
```
|
||||
|
||||
## 🛠️ 测试调试技巧
|
||||
- 也有少数情况会统一放到 `__tests__` 文件夹, 例如 `packages/database/src/models/__tests__`
|
||||
- 测试使用的辅助文件放到 fixtures 文件夹
|
||||
|
||||
## 测试调试技巧
|
||||
|
||||
### 测试调试步骤
|
||||
|
||||
@@ -415,67 +437,59 @@ src/components/Button/
|
||||
3. **分析错误**: 仔细阅读错误信息、堆栈跟踪和最近的文件修改记录
|
||||
4. **添加调试**: 在测试中添加 `console.log` 了解执行流程
|
||||
|
||||
### TypeScript 类型处理 📝
|
||||
### TypeScript 类型处理
|
||||
|
||||
在测试中,为了提高编写效率和可读性,可以适当放宽 TypeScript 类型检测:
|
||||
|
||||
#### ✅ 推荐的类型放宽策略
|
||||
#### 推荐的类型放宽策略
|
||||
|
||||
```typescript
|
||||
// ✅ 使用非空断言访问测试中确定存在的属性
|
||||
// 使用非空断言访问测试中确定存在的属性
|
||||
const result = await someFunction();
|
||||
expect(result!.data).toBeDefined();
|
||||
expect(result!.status).toBe('success');
|
||||
|
||||
// ✅ 使用 any 类型简化复杂的 Mock 设置
|
||||
// 使用 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`,测试仍能有效验证功能正确性
|
||||
|
||||
### 检查最近修改记录 🔍
|
||||
### 检查最近修改记录
|
||||
|
||||
系统性地检查相关文件的修改历史是问题定位的关键步骤。
|
||||
**核心原则**:测试突然失败时,优先检查最近的代码修改。
|
||||
|
||||
#### 三步检查法
|
||||
|
||||
**Step 1: 查看当前状态**
|
||||
#### 快速检查方法
|
||||
|
||||
```bash
|
||||
git status # 查看未提交的修改
|
||||
git diff path/to/component.test.ts | cat # 查看测试文件修改
|
||||
git diff path/to/component.ts | cat # 查看实现文件修改
|
||||
git status # 查看当前修改状态
|
||||
git diff HEAD -- '*.test.*' # 检查测试文件改动
|
||||
git diff main...HEAD # 对比主分支差异
|
||||
gh pr diff # 查看PR中的所有改动
|
||||
```
|
||||
|
||||
**Step 2: 查看提交历史**
|
||||
#### 常见原因与解决
|
||||
|
||||
```bash
|
||||
git log --pretty=format:"%h %ad %s" --date=relative -3 path/to/component.ts | cat
|
||||
```
|
||||
|
||||
**Step 3: 查看具体修改内容**
|
||||
|
||||
```bash
|
||||
git show HEAD -- path/to/component.ts | cat # 查看最新提交的修改
|
||||
```
|
||||
|
||||
#### 时间相关性判断
|
||||
|
||||
- **24小时内的提交**: 🔴 **高度相关** - 很可能是直接原因
|
||||
- **1-7天内的提交**: 🟡 **中等相关** - 需要仔细分析
|
||||
- **超过1周的提交**: ⚪ **低相关性** - 除非重大重构
|
||||
- **最新提交引入bug** → 检查并修复实现代码
|
||||
- **分支代码滞后** → `git rebase main` 同步主分支
|
||||
|
||||
## 特殊场景的测试
|
||||
|
||||
@@ -484,9 +498,9 @@ git show HEAD -- path/to/component.ts | cat # 查看最新提交的修改
|
||||
- [Electron IPC 接口测试策略](mdc:./electron-ipc-test.mdc)
|
||||
- [数据库 Model 测试指南](mdc:./db-model-test.mdc)
|
||||
|
||||
## 🎯 核心要点
|
||||
## 核心要点
|
||||
|
||||
- **命令格式**: 使用 `npx vitest run --config [config-file]` 并指定文件过滤
|
||||
- **命令格式**: 使用 `bunx vitest run --silent='passed-only'` 并指定文件过滤
|
||||
- **修复原则**: 失败1-2次后寻求帮助,测试命名关注行为而非实现细节
|
||||
- **调试流程**: 复现 → 分析 → 假设 → 修复 → 验证 → 总结
|
||||
- **文件组织**: 优先在现有 `describe` 块中添加测试,避免创建冗余顶级块
|
||||
|
||||
@@ -1,21 +1,62 @@
|
||||
---
|
||||
description:
|
||||
description: TypeScript code style and optimization guidelines
|
||||
globs: *.ts,*.tsx,*.mts
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
TypeScript Code Style Guide:
|
||||
# TypeScript Code Style Guide
|
||||
|
||||
## Types and Type Safety
|
||||
|
||||
- Avoid explicit type annotations when TypeScript can infer types.
|
||||
- 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
|
||||
- Prefer object destructuring when accessing and using properties
|
||||
- Prefer async version api than sync version, eg: use readFile from 'fs/promises' instead of 'fs'
|
||||
- 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.
|
||||
|
||||
@@ -4,6 +4,14 @@
|
||||
# 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 #########
|
||||
@@ -140,6 +148,31 @@ 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 ############
|
||||
########################################
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# 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,3 +29,20 @@ 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/**
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
- [ ] 💄 style
|
||||
- [ ] 👷 build
|
||||
- [ ] ⚡️ perf
|
||||
- [ ] ✅ test
|
||||
- [ ] 📝 docs
|
||||
- [ ] 🔨 chore
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* 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@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.ref }}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
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@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 9
|
||||
version: 10
|
||||
|
||||
- name: Install deps
|
||||
run: pnpm install
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
# 输出版本信息,供后续 job 使用
|
||||
version: ${{ steps.set_version.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -95,7 +95,7 @@ jobs:
|
||||
matrix:
|
||||
os: [macos-latest, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 9
|
||||
version: 10
|
||||
|
||||
# node-linker=hoisted 模式将可以确保 asar 压缩可用
|
||||
- name: Install deps
|
||||
@@ -183,6 +183,10 @@ 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:
|
||||
@@ -196,7 +200,7 @@ jobs:
|
||||
outputs:
|
||||
artifact_path: ${{ steps.set_path.outputs.path }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -245,6 +249,10 @@ 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@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
|
||||
- name: Build and export
|
||||
id: build
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: .
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -159,3 +159,24 @@ 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@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
|
||||
- name: Build and export
|
||||
id: build
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: .
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
|
||||
- name: Build and export
|
||||
id: build
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: .
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
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@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ env.REPOSITORY }}
|
||||
token: ${{ secrets[matrix.TOKEN_NAME] || secrets[env.TOKEN_NAME] }}
|
||||
ref: ${{ env.BRANCH }}
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
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@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 9
|
||||
version: 10
|
||||
|
||||
- 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@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
matrix:
|
||||
os: [macos-latest, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -94,7 +94,7 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 9
|
||||
version: 10
|
||||
|
||||
# node-linker=hoisted 模式将可以确保 asar 压缩可用
|
||||
- name: Install deps
|
||||
@@ -165,6 +165,10 @@ 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
|
||||
@@ -201,5 +205,9 @@ jobs:
|
||||
release/*.zip*
|
||||
release/*.exe*
|
||||
release/*.AppImage
|
||||
release/*.deb*
|
||||
release/*.snap*
|
||||
release/*.rpm*
|
||||
release/*.tar.gz*
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -11,16 +11,20 @@ jobs:
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: pgvector/pgvector:pg16
|
||||
image: paradedb/paradedb:latest
|
||||
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@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -38,8 +42,8 @@ jobs:
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Test Server Coverage
|
||||
run: bun run test-server:coverage
|
||||
- name: Test Database Coverage
|
||||
run: bun run --filter @lobechat/database test
|
||||
env:
|
||||
DATABASE_TEST_URL: postgresql://postgres:postgres@localhost:5432/postgres
|
||||
DATABASE_DRIVER: node
|
||||
@@ -48,8 +52,8 @@ jobs:
|
||||
S3_PUBLIC_DOMAIN: https://example.com
|
||||
APP_URL: https://home.com
|
||||
|
||||
- name: Test App Coverage
|
||||
run: bun run test-app:coverage
|
||||
- name: Test App
|
||||
run: bun run test-app
|
||||
|
||||
- name: Release
|
||||
run: bun run release
|
||||
|
||||
@@ -11,7 +11,7 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Install dbdocs
|
||||
run: sudo npm install -g dbdocs
|
||||
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
if: ${{ github.event.repository.fork }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Clean issue notice
|
||||
uses: actions-cool/issues-helper@v3
|
||||
|
||||
+121
-17
@@ -2,8 +2,115 @@ name: Test CI
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
# 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
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
services:
|
||||
@@ -19,7 +126,7 @@ jobs:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -37,8 +144,15 @@ jobs:
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Test Server Coverage
|
||||
run: bun run test-server:coverage
|
||||
- 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
|
||||
env:
|
||||
DATABASE_TEST_URL: postgresql://postgres:postgres@localhost:5432/postgres
|
||||
DATABASE_DRIVER: node
|
||||
@@ -47,19 +161,9 @@ jobs:
|
||||
S3_PUBLIC_DOMAIN: https://example.com
|
||||
APP_URL: https://home.com
|
||||
|
||||
- name: Upload Server coverage to Codecov
|
||||
- name: Upload Database coverage to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
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
|
||||
files: ./packages/database/coverage/lcov.info
|
||||
flags: database
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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 }}
|
||||
+93
-56
@@ -1,77 +1,114 @@
|
||||
# Gitignore for LobeHub
|
||||
################################################################
|
||||
|
||||
# general
|
||||
# System files
|
||||
.DS_Store
|
||||
.idea
|
||||
.vscode
|
||||
.history
|
||||
.temp
|
||||
.env.local
|
||||
venv
|
||||
temp
|
||||
tmp
|
||||
.windsurfrules
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
Desktop.ini
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
# 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
|
||||
.env.local
|
||||
.env*.local
|
||||
venv/
|
||||
.venv/
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
*.lock
|
||||
package-lock.json
|
||||
bun.lockb
|
||||
.pnpm-store/
|
||||
|
||||
# ci
|
||||
coverage
|
||||
.coverage
|
||||
# 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/
|
||||
.eslintcache
|
||||
.stylelintcache
|
||||
|
||||
# production
|
||||
dist
|
||||
es
|
||||
lib
|
||||
logs
|
||||
test-output
|
||||
|
||||
# umi
|
||||
.umi
|
||||
.umi-production
|
||||
.umi-test
|
||||
.dumi/tmp*
|
||||
|
||||
# husky
|
||||
.husky/prepare-commit-msg
|
||||
|
||||
# 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
|
||||
|
||||
# Service Worker
|
||||
# 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
|
||||
.pnpm-store
|
||||
./packages/lobe-ui
|
||||
|
||||
|
||||
# local use ai coding files
|
||||
docs/.prd
|
||||
.claude
|
||||
# AI coding tools
|
||||
.local/
|
||||
.claude/
|
||||
.mcp.json
|
||||
CLAUDE.md
|
||||
|
||||
CLAUDE.local.md
|
||||
|
||||
# MCP tools
|
||||
.serena/**
|
||||
|
||||
# Misc
|
||||
./packages/lobe-ui
|
||||
*.ppt*
|
||||
*.doc*
|
||||
*.xls*
|
||||
|
||||
@@ -4,6 +4,9 @@ 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,7 +5,6 @@
|
||||
.DS_Store
|
||||
.editorconfig
|
||||
.idea
|
||||
.vscode
|
||||
.history
|
||||
.temp
|
||||
.env.local
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# 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/**
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"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",
|
||||
]
|
||||
}
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
# 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
|
||||
+2736
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,100 @@
|
||||
# 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
|
||||
+12
-2
@@ -66,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=8192"
|
||||
ENV NODE_OPTIONS="--max-old-space-size=6144"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -150,6 +150,8 @@ 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
|
||||
@@ -192,6 +194,8 @@ 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
|
||||
@@ -245,7 +249,13 @@ ENV \
|
||||
# Tencent Cloud
|
||||
TENCENT_CLOUD_API_KEY="" TENCENT_CLOUD_MODEL_LIST="" \
|
||||
# Infini-AI
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST=""
|
||||
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=""
|
||||
|
||||
USER nextjs
|
||||
|
||||
|
||||
+13
-3
@@ -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=8192"
|
||||
ENV NODE_OPTIONS="--max-old-space-size=6144"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -120,7 +120,7 @@ COPY --from=base /distroless/ /
|
||||
COPY --from=builder /app/.next/standalone /app/
|
||||
|
||||
# Copy database migrations
|
||||
COPY --from=builder /app/src/database/migrations /app/migrations
|
||||
COPY --from=builder /app/packages/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,6 +192,8 @@ 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
|
||||
@@ -234,6 +236,8 @@ 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
|
||||
@@ -287,7 +291,13 @@ ENV \
|
||||
# Tencent Cloud
|
||||
TENCENT_CLOUD_API_KEY="" TENCENT_CLOUD_MODEL_LIST="" \
|
||||
# Infini-AI
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST=""
|
||||
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=""
|
||||
|
||||
USER nextjs
|
||||
|
||||
|
||||
+12
-2
@@ -68,7 +68,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=8192"
|
||||
ENV NODE_OPTIONS="--max-old-space-size=6144"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -152,6 +152,8 @@ 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,6 +196,8 @@ 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
|
||||
@@ -243,7 +247,13 @@ ENV \
|
||||
# Tencent Cloud
|
||||
TENCENT_CLOUD_API_KEY="" TENCENT_CLOUD_MODEL_LIST="" \
|
||||
# Infini-AI
|
||||
INFINIAI_API_KEY="" INFINIAI_MODEL_LIST=""
|
||||
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=""
|
||||
|
||||
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—lightweight, 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—comprehensive, 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,15 +245,17 @@ 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.
|
||||
- **[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.
|
||||
- **[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.
|
||||
- **[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.
|
||||
@@ -272,7 +274,6 @@ 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.
|
||||
@@ -286,7 +287,7 @@ We have implemented support for the following model service providers:
|
||||
|
||||
</details>
|
||||
|
||||
> 📊 Total providers: [<kbd>**41**</kbd>](https://lobechat.com/discover/providers)
|
||||
> 📊 Total providers: [<kbd>**42**</kbd>](https://lobechat.com/discover/providers)
|
||||
|
||||
<!-- PROVIDER LIST -->
|
||||
|
||||
@@ -384,11 +385,11 @@ 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` |
|
||||
| [Speak](https://lobechat.com/discover/plugin/speak)<br/><sup>By **speak** on **2025-07-18**</sup> | Learn how to say anything in another language with Speak, your AI-powered language tutor.<br/>`education` `language` |
|
||||
| [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` |
|
||||
|
||||
> 📊 Total plugins: [<kbd>**43**</kbd>](https://lobechat.com/discover/plugins)
|
||||
> 📊 Total plugins: [<kbd>**42**</kbd>](https://lobechat.com/discover/plugins)
|
||||
|
||||
<!-- PLUGIN LIST -->
|
||||
|
||||
@@ -480,7 +481,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 its lightweight and high-performance characteristics.
|
||||
Through PWA, LobeChat can offer a highly optimized user experience on both desktop and mobile devices while maintaining 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.
|
||||
|
||||
|
||||
+9
-8
@@ -245,15 +245,17 @@ 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。
|
||||
- **[HuggingFace](https://lobechat.com/discover/provider/huggingface)**: HuggingFace Inference API 提供了一种快速且免费的方式,让您可以探索成千上万种模型,适用于各种任务。无论您是在为新应用程序进行原型设计,还是在尝试机器学习的功能,这个 API 都能让您即时访问多个领域的高性能模型。
|
||||
- **[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 都能让您即时访问多个领域的高性能模型。
|
||||
- **[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 是一种即时推理速度的代表,在基于云的部署中展现了良好的性能。
|
||||
@@ -272,7 +274,6 @@ 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 开发者提供高效、易用的开源平台,让最前沿的大模型与算法技术触手可及
|
||||
@@ -286,7 +287,7 @@ LobeChat 支持文件上传与知识库功能,你可以上传文件、图片
|
||||
|
||||
</details>
|
||||
|
||||
> 📊 Total providers: [<kbd>**41**</kbd>](https://lobechat.com/discover/providers)
|
||||
> 📊 Total providers: [<kbd>**42**</kbd>](https://lobechat.com/discover/providers)
|
||||
|
||||
<!-- PROVIDER LIST -->
|
||||
|
||||
@@ -377,11 +378,11 @@ LobeChat 的插件生态系统是其核心功能的重要扩展,它极大地
|
||||
| 最近新增 | 描述 |
|
||||
| -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||
| [PortfolioMeta](https://lobechat.com/discover/plugin/StockData)<br/><sup>By **portfoliometa** on **2025-07-21**</sup> | 分析股票并获取全面的实时投资数据和分析。<br/>`股票` |
|
||||
| [Speak](https://lobechat.com/discover/plugin/speak)<br/><sup>By **speak** on **2025-07-18**</sup> | 使用 Speak,您的 AI 语言导师,学习如何用另一种语言说任何事情。<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/>`网络` `搜索` |
|
||||
|
||||
> 📊 Total plugins: [<kbd>**43**</kbd>](https://lobechat.com/discover/plugins)
|
||||
> 📊 Total plugins: [<kbd>**42**</kbd>](https://lobechat.com/discover/plugins)
|
||||
|
||||
<!-- PLUGIN LIST -->
|
||||
|
||||
|
||||
@@ -23,8 +23,9 @@ module.exports = defineConfig({
|
||||
'vi-VN',
|
||||
'fa-IR',
|
||||
],
|
||||
saveImmediately: true,
|
||||
temperature: 0,
|
||||
modelName: 'gpt-4o-mini',
|
||||
modelName: 'gpt-4.1-mini',
|
||||
experimental: {
|
||||
jsonMode: true,
|
||||
},
|
||||
|
||||
@@ -11,6 +11,16 @@ 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
|
||||
@@ -54,12 +64,18 @@ const config = {
|
||||
linux: {
|
||||
category: 'Utility',
|
||||
maintainer: 'electronjs.org',
|
||||
target: ['AppImage', 'snap', 'deb'],
|
||||
target: ['AppImage', 'snap', 'deb', 'rpm', 'tar.gz'],
|
||||
},
|
||||
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.",
|
||||
@@ -91,6 +107,12 @@ const config = {
|
||||
uninstallDisplayName: '${productName}',
|
||||
uninstallerSidebar: './build/nsis-sidebar.bmp',
|
||||
},
|
||||
protocols: [
|
||||
{
|
||||
name: 'LobeHub Protocol',
|
||||
schemes: [protocolScheme],
|
||||
},
|
||||
],
|
||||
publish: [
|
||||
{
|
||||
owner: 'lobehub',
|
||||
|
||||
@@ -20,11 +20,10 @@
|
||||
"electron:dev": "electron-vite dev",
|
||||
"electron:run-unpack": "electron .",
|
||||
"format": "prettier --write ",
|
||||
"i18n": "bun run scripts/i18nWorkflow/index.ts && lobe-i18n",
|
||||
"i18n": "tsx 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"
|
||||
@@ -32,6 +31,7 @@
|
||||
"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"
|
||||
},
|
||||
@@ -52,7 +52,7 @@
|
||||
"@typescript/native-preview": "7.0.0-dev.20250711.1",
|
||||
"consola": "^3.1.0",
|
||||
"cookie": "^1.0.2",
|
||||
"electron": "~37.1.0",
|
||||
"electron": "^37.4.0",
|
||||
"electron-builder": "^26.0.12",
|
||||
"electron-is": "^3.0.0",
|
||||
"electron-log": "^5.3.3",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "نسخ",
|
||||
"cut": "قص",
|
||||
"delete": "حذف",
|
||||
"paste": "لصق",
|
||||
"redo": "إعادة",
|
||||
"selectAll": "تحديد الكل",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Копиране",
|
||||
"cut": "Изрязване",
|
||||
"delete": "Изтрий",
|
||||
"paste": "Поставяне",
|
||||
"redo": "Повторно",
|
||||
"selectAll": "Избери всичко",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Kopieren",
|
||||
"cut": "Ausschneiden",
|
||||
"delete": "Löschen",
|
||||
"paste": "Einfügen",
|
||||
"redo": "Wiederherstellen",
|
||||
"selectAll": "Alles auswählen",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Copy",
|
||||
"cut": "Cut",
|
||||
"delete": "Delete",
|
||||
"paste": "Paste",
|
||||
"redo": "Redo",
|
||||
"selectAll": "Select All",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Copiar",
|
||||
"cut": "Cortar",
|
||||
"delete": "Eliminar",
|
||||
"paste": "Pegar",
|
||||
"redo": "Rehacer",
|
||||
"selectAll": "Seleccionar todo",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "کپی",
|
||||
"cut": "برش",
|
||||
"delete": "حذف",
|
||||
"paste": "چسباندن",
|
||||
"redo": "انجام مجدد",
|
||||
"selectAll": "انتخاب همه",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Copier",
|
||||
"cut": "Couper",
|
||||
"delete": "Supprimer",
|
||||
"paste": "Coller",
|
||||
"redo": "Rétablir",
|
||||
"selectAll": "Tout sélectionner",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Copia",
|
||||
"cut": "Taglia",
|
||||
"delete": "Elimina",
|
||||
"paste": "Incolla",
|
||||
"redo": "Ripeti",
|
||||
"selectAll": "Seleziona tutto",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "コピー",
|
||||
"cut": "切り取り",
|
||||
"delete": "削除",
|
||||
"paste": "貼り付け",
|
||||
"redo": "やり直し",
|
||||
"selectAll": "すべて選択",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "복사",
|
||||
"cut": "잘라내기",
|
||||
"delete": "삭제",
|
||||
"paste": "붙여넣기",
|
||||
"redo": "다시 실행",
|
||||
"selectAll": "모두 선택",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Kopiëren",
|
||||
"cut": "Knippen",
|
||||
"delete": "Verwijderen",
|
||||
"paste": "Plakken",
|
||||
"redo": "Opnieuw doen",
|
||||
"selectAll": "Alles selecteren",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Kopiuj",
|
||||
"cut": "Wytnij",
|
||||
"delete": "Usuń",
|
||||
"paste": "Wklej",
|
||||
"redo": "Ponów",
|
||||
"selectAll": "Zaznacz wszystko",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Copiar",
|
||||
"cut": "Cortar",
|
||||
"delete": "Excluir",
|
||||
"paste": "Colar",
|
||||
"redo": "Refazer",
|
||||
"selectAll": "Selecionar Tudo",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Копировать",
|
||||
"cut": "Вырезать",
|
||||
"delete": "Удалить",
|
||||
"paste": "Вставить",
|
||||
"redo": "Повторить",
|
||||
"selectAll": "Выбрать все",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "Kopyala",
|
||||
"cut": "Kes",
|
||||
"delete": "Sil",
|
||||
"paste": "Yapıştır",
|
||||
"redo": "Yinele",
|
||||
"selectAll": "Tümünü Seç",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"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,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "复制",
|
||||
"cut": "剪切",
|
||||
"delete": "删除",
|
||||
"paste": "粘贴",
|
||||
"redo": "重做",
|
||||
"selectAll": "全选",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"edit": {
|
||||
"copy": "複製",
|
||||
"cut": "剪下",
|
||||
"delete": "刪除",
|
||||
"paste": "貼上",
|
||||
"redo": "重做",
|
||||
"selectAll": "全選",
|
||||
|
||||
@@ -25,6 +25,7 @@ export const defaultProxySettings: NetworkProxySettings = {
|
||||
* 存储默认值
|
||||
*/
|
||||
export const STORE_DEFAULTS: ElectronMainStore = {
|
||||
autoUpdateNotificationEnabled: true,
|
||||
dataSyncConfig: { storageMode: 'local' },
|
||||
encryptedTokens: {},
|
||||
locale: 'auto',
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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(type: string, data?: any) {
|
||||
return this.app.menuManager.showContextMenu(type, data);
|
||||
showContextMenu(params: { data?: any; type: string }) {
|
||||
return this.app.menuManager.showContextMenu(params.type, params.data);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,9 +29,9 @@ describe('MenuController', () => {
|
||||
it('should call menuManager.refreshMenus', () => {
|
||||
// 模拟返回值
|
||||
mockRefreshMenus.mockReturnValueOnce(true);
|
||||
|
||||
|
||||
const result = menuController.refreshAppMenu();
|
||||
|
||||
|
||||
expect(mockRefreshMenus).toHaveBeenCalled();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
@@ -41,9 +41,9 @@ describe('MenuController', () => {
|
||||
it('should call menuManager.showContextMenu with type only', () => {
|
||||
const menuType = 'chat';
|
||||
mockShowContextMenu.mockReturnValueOnce({ shown: true });
|
||||
|
||||
const result = menuController.showContextMenu(menuType);
|
||||
|
||||
|
||||
const result = menuController.showContextMenu({ type: menuType });
|
||||
|
||||
expect(mockShowContextMenu).toHaveBeenCalledWith(menuType, undefined);
|
||||
expect(result).toEqual({ shown: true });
|
||||
});
|
||||
@@ -52,9 +52,9 @@ describe('MenuController', () => {
|
||||
const menuType = 'file';
|
||||
const menuData = { fileId: '123', filePath: '/path/to/file.txt' };
|
||||
mockShowContextMenu.mockReturnValueOnce({ shown: true });
|
||||
|
||||
const result = menuController.showContextMenu(menuType, menuData);
|
||||
|
||||
|
||||
const result = menuController.showContextMenu({ type: menuType, data: menuData });
|
||||
|
||||
expect(mockShowContextMenu).toHaveBeenCalledWith(menuType, menuData);
|
||||
expect(result).toEqual({ shown: true });
|
||||
});
|
||||
@@ -63,20 +63,20 @@ describe('MenuController', () => {
|
||||
describe('setDevMenuVisibility', () => {
|
||||
it('should call menuManager.rebuildAppMenu with showDevItems true', () => {
|
||||
mockRebuildAppMenu.mockReturnValueOnce(true);
|
||||
|
||||
|
||||
const result = menuController.setDevMenuVisibility(true);
|
||||
|
||||
|
||||
expect(mockRebuildAppMenu).toHaveBeenCalledWith({ showDevItems: true });
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should call menuManager.rebuildAppMenu with showDevItems false', () => {
|
||||
mockRebuildAppMenu.mockReturnValueOnce(true);
|
||||
|
||||
|
||||
const result = menuController.setDevMenuVisibility(false);
|
||||
|
||||
|
||||
expect(mockRebuildAppMenu).toHaveBeenCalledWith({ showDevItems: false });
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -44,11 +44,30 @@ const shortcutDecorator = (name: string) => (target: any, methodName: string, de
|
||||
*/
|
||||
export const shortcut = (method: ShortcutActionType) => shortcutDecorator(method);
|
||||
|
||||
const protocolDecorator =
|
||||
(urlType: string, action: string) => (target: any, methodName: string, descriptor?: any) => {
|
||||
const handlers = IoCContainer.protocolHandlers.get(target.constructor) || [];
|
||||
handlers.push({ action, methodName, urlType });
|
||||
|
||||
IoCContainer.protocolHandlers.set(target.constructor, handlers);
|
||||
|
||||
return descriptor;
|
||||
};
|
||||
|
||||
/**
|
||||
* Protocol handler decorator
|
||||
* @param urlType 协议URL类型 (如: 'plugin')
|
||||
* @param action 操作类型 (如: 'install')
|
||||
*/
|
||||
export const createProtocolHandler = (urlType: string) => (action: string) =>
|
||||
protocolDecorator(urlType, action);
|
||||
|
||||
interface IControllerModule {
|
||||
afterAppReady?(): void;
|
||||
app: App;
|
||||
beforeAppReady?(): void;
|
||||
}
|
||||
|
||||
export class ControllerModule implements IControllerModule {
|
||||
constructor(public app: App) {
|
||||
this.app = app;
|
||||
|
||||
@@ -16,6 +16,7 @@ import { CustomRequestHandler, createHandler } from '@/utils/next-electron-rsc';
|
||||
import { BrowserManager } from './browser/BrowserManager';
|
||||
import { I18nManager } from './infrastructure/I18nManager';
|
||||
import { IoCContainer } from './infrastructure/IoCContainer';
|
||||
import { ProtocolManager } from './infrastructure/ProtocolManager';
|
||||
import { StaticFileServerManager } from './infrastructure/StaticFileServerManager';
|
||||
import { StoreManager } from './infrastructure/StoreManager';
|
||||
import { UpdaterManager } from './infrastructure/UpdaterManager';
|
||||
@@ -27,6 +28,7 @@ const logger = createLogger('core:App');
|
||||
|
||||
export type IPCEventMap = Map<string, { controller: any; methodName: string }>;
|
||||
export type ShortcutMethodMap = Map<string, () => Promise<void>>;
|
||||
export type ProtocolHandlerMap = Map<string, { controller: any; methodName: string }>;
|
||||
|
||||
type Class<T> = new (...args: any[]) => T;
|
||||
|
||||
@@ -43,6 +45,7 @@ export class App {
|
||||
shortcutManager: ShortcutManager;
|
||||
trayManager: TrayManager;
|
||||
staticFileServerManager: StaticFileServerManager;
|
||||
protocolManager: ProtocolManager;
|
||||
chromeFlags: string[] = ['OverlayScrollbar', 'FluentOverlayScrollbar', 'FluentScrollbar'];
|
||||
|
||||
/**
|
||||
@@ -100,11 +103,15 @@ export class App {
|
||||
this.shortcutManager = new ShortcutManager(this);
|
||||
this.trayManager = new TrayManager(this);
|
||||
this.staticFileServerManager = new StaticFileServerManager(this);
|
||||
this.protocolManager = new ProtocolManager(this);
|
||||
|
||||
// register the schema to interceptor url
|
||||
// it should register before app ready
|
||||
this.registerNextHandler();
|
||||
|
||||
// initialize protocol handlers
|
||||
this.protocolManager.initialize();
|
||||
|
||||
// 统一处理 before-quit 事件
|
||||
app.on('before-quit', this.handleBeforeQuit);
|
||||
|
||||
@@ -160,6 +167,10 @@ export class App {
|
||||
});
|
||||
|
||||
app.on('activate', this.onActivate);
|
||||
|
||||
// Process any pending protocol URLs after everything is ready
|
||||
await this.protocolManager.processPendingUrls();
|
||||
|
||||
logger.info('Application bootstrap completed');
|
||||
};
|
||||
|
||||
@@ -171,6 +182,32 @@ export class App {
|
||||
return this.controllers.get(controllerClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle protocol request by dispatching to registered handlers
|
||||
* @param urlType 协议URL类型 (如: 'plugin')
|
||||
* @param action 操作类型 (如: 'install')
|
||||
* @param data 解析后的协议数据
|
||||
* @returns 是否成功处理
|
||||
*/
|
||||
async handleProtocolRequest(urlType: string, action: string, data: any): Promise<boolean> {
|
||||
const key = `${urlType}:${action}`;
|
||||
const handler = this.protocolHandlerMap.get(key);
|
||||
|
||||
if (!handler) {
|
||||
logger.warn(`No protocol handler found for ${key}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug(`Dispatching protocol request ${key} to controller`);
|
||||
const result = await handler.controller[handler.methodName](data);
|
||||
return result !== false; // 假设控制器返回 false 表示处理失败
|
||||
} catch (error) {
|
||||
logger.error(`Error handling protocol request ${key}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private onActivate = () => {
|
||||
logger.debug('Application activated');
|
||||
this.browserManager.showMainWindow();
|
||||
@@ -233,6 +270,7 @@ export class App {
|
||||
private ipcClientEventMap: IPCEventMap = new Map();
|
||||
private ipcServerEventMap: IPCEventMap = new Map();
|
||||
shortcutMethodMap: ShortcutMethodMap = new Map();
|
||||
protocolHandlerMap: ProtocolHandlerMap = new Map();
|
||||
|
||||
/**
|
||||
* use in next router interceptor in prod browser render
|
||||
@@ -308,6 +346,14 @@ export class App {
|
||||
controller[shortcut.methodName]();
|
||||
});
|
||||
});
|
||||
|
||||
IoCContainer.protocolHandlers.get(ControllerClass)?.forEach((handler) => {
|
||||
const key = `${handler.urlType}:${handler.action}`;
|
||||
this.protocolHandlerMap.set(key, {
|
||||
controller,
|
||||
methodName: handler.methodName,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
private addService = (ServiceClass: IServiceModule) => {
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { buildDir, preloadDir, resourcesDir } from '@/const/dir';
|
||||
import { isDev, isWindows } from '@/const/env';
|
||||
import { isDev, isMac, isWindows } from '@/const/env';
|
||||
import {
|
||||
BACKGROUND_DARK,
|
||||
BACKGROUND_LIGHT,
|
||||
@@ -269,7 +269,20 @@ export default class Browser {
|
||||
|
||||
hide() {
|
||||
logger.debug(`Hiding window: ${this.identifier}`);
|
||||
this.browserWindow.hide();
|
||||
|
||||
// Fix for macOS fullscreen black screen issue
|
||||
// See: https://github.com/electron/electron/issues/20263
|
||||
if (isMac && this.browserWindow.isFullScreen()) {
|
||||
logger.debug(
|
||||
`[${this.identifier}] Window is in fullscreen mode, exiting fullscreen before hiding.`,
|
||||
);
|
||||
this.browserWindow.once('leave-full-screen', () => {
|
||||
this.browserWindow.hide();
|
||||
});
|
||||
this.browserWindow.setFullScreen(false);
|
||||
} else {
|
||||
this.browserWindow.hide();
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
@@ -413,7 +426,7 @@ export default class Browser {
|
||||
// logger.error(`[${this.identifier}] Failed to save window state on hide:`, error);
|
||||
// }
|
||||
e.preventDefault();
|
||||
browserWindow.hide();
|
||||
this.hide();
|
||||
} else {
|
||||
// Window is actually closing (not keepAlive)
|
||||
logger.debug(
|
||||
@@ -465,7 +478,7 @@ export default class Browser {
|
||||
toggleVisible() {
|
||||
logger.debug(`Toggling visibility for window: ${this.identifier}`);
|
||||
if (this._browserWindow.isVisible() && this._browserWindow.isFocused()) {
|
||||
this._browserWindow.hide();
|
||||
this.hide(); // Use the hide() method which handles fullscreen
|
||||
} else {
|
||||
this._browserWindow.show();
|
||||
this._browserWindow.focus();
|
||||
|
||||
@@ -8,5 +8,9 @@ export class IoCContainer {
|
||||
> = new WeakMap();
|
||||
|
||||
static shortcuts: WeakMap<any, { methodName: string; name: string }[]> = new WeakMap();
|
||||
|
||||
static protocolHandlers: WeakMap<any, { action: string; methodName: string; urlType: string }[]> =
|
||||
new WeakMap();
|
||||
|
||||
init() {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { app } from 'electron';
|
||||
|
||||
import { isDev } from '@/const/env';
|
||||
import { createLogger } from '@/utils/logger';
|
||||
import { getProtocolScheme, parseProtocolUrl } from '@/utils/protocol';
|
||||
|
||||
import { App } from '../App';
|
||||
|
||||
// Create logger
|
||||
const logger = createLogger('core:ProtocolManager');
|
||||
|
||||
/**
|
||||
* Protocol handler manager for custom URI schemes
|
||||
*/
|
||||
export class ProtocolManager {
|
||||
private app: App;
|
||||
private protocolScheme: string;
|
||||
private pendingUrls: string[] = [];
|
||||
|
||||
constructor(app: App) {
|
||||
logger.debug('Initializing ProtocolManager');
|
||||
this.app = app;
|
||||
this.protocolScheme = getProtocolScheme();
|
||||
logger.info(`ProtocolManager initialized for scheme: ${this.protocolScheme}://`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register protocol handlers and set up event listeners
|
||||
*/
|
||||
public initialize(): void {
|
||||
logger.debug('Setting up protocol handlers');
|
||||
|
||||
this.registerProtocolHandlers();
|
||||
this.setupEventListeners();
|
||||
|
||||
logger.debug('Protocol initialization completed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the application as default protocol client
|
||||
*/
|
||||
private registerProtocolHandlers(): void {
|
||||
logger.debug(`🔗 [Protocol] Registering protocol handlers for ${this.protocolScheme}://`);
|
||||
|
||||
// Debug info about current app
|
||||
logger.debug(`🔗 [Protocol] App name: ${app.name}`);
|
||||
logger.debug(`🔗 [Protocol] App path: ${app.getPath('exe')}`);
|
||||
logger.debug(`🔗 [Protocol] Is development: ${isDev}`);
|
||||
logger.debug(`🔗 [Protocol] Process argv[0]: ${process.argv[0]}`);
|
||||
|
||||
// Check if already registered
|
||||
const isCurrentlyRegistered = app.isDefaultProtocolClient(this.protocolScheme);
|
||||
logger.debug(`🔗 [Protocol] Is currently default protocol client: ${isCurrentlyRegistered}`);
|
||||
|
||||
// Register as default protocol client
|
||||
let registrationResult: boolean;
|
||||
|
||||
if (isDev) {
|
||||
// In development, use explicit parameters to ensure proper registration
|
||||
const appPath = process.cwd(); // Current working directory (our app)
|
||||
logger.debug(`🔗 [Protocol] Development mode: using explicit registration parameters`);
|
||||
logger.debug(`🔗 [Protocol] Executable path: ${process.execPath}`);
|
||||
logger.debug(`🔗 [Protocol] App path: ${appPath}`);
|
||||
logger.debug(`🔗 [Protocol] Arguments: ${JSON.stringify([appPath])}`);
|
||||
|
||||
registrationResult = app.setAsDefaultProtocolClient(this.protocolScheme, process.execPath, [
|
||||
appPath,
|
||||
]);
|
||||
} else {
|
||||
// In production, use simple registration
|
||||
registrationResult = app.setAsDefaultProtocolClient(this.protocolScheme);
|
||||
}
|
||||
|
||||
logger.debug(`🔗 [Protocol] Registration result: ${registrationResult}`);
|
||||
|
||||
if (!registrationResult) {
|
||||
logger.error(
|
||||
`🔗 [Protocol] Failed to register as default protocol client for ${this.protocolScheme}://`,
|
||||
);
|
||||
} else {
|
||||
logger.debug(`🔗 [Protocol] Successfully registered ${this.protocolScheme}:// protocol`);
|
||||
}
|
||||
|
||||
// Verify registration
|
||||
const isRegisteredAfter = app.isDefaultProtocolClient(this.protocolScheme);
|
||||
logger.debug(`🔗 [Protocol] Final registration status: ${isRegisteredAfter}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up protocol event listeners
|
||||
*/
|
||||
private setupEventListeners(): void {
|
||||
// Handle protocol URL from cold start (Windows/Linux)
|
||||
const protocolUrl = this.getProtocolUrlFromArgs(process.argv);
|
||||
if (protocolUrl) {
|
||||
logger.debug(`🔗 [Protocol] Found protocol URL from cold start: ${protocolUrl}`);
|
||||
this.pendingUrls.push(protocolUrl);
|
||||
}
|
||||
|
||||
// Handle protocol URL from macOS open-url event
|
||||
app.on('open-url', (event, url) => {
|
||||
event.preventDefault();
|
||||
logger.debug(`🔗 [Protocol] Received URL from open-url event: ${url}`);
|
||||
logger.debug(`🔗 [Protocol] App ready state: ${app.isReady()}`);
|
||||
logger.debug(`🔗 [Protocol] Event prevented, processing URL...`);
|
||||
this.handleProtocolUrl(url);
|
||||
});
|
||||
|
||||
// Handle protocol URL from second instance (Windows/Linux)
|
||||
app.on('second-instance', (event, commandLine) => {
|
||||
const url = this.getProtocolUrlFromArgs(commandLine);
|
||||
if (url) {
|
||||
logger.debug(`🔗 [Protocol] Received protocol URL from second instance: ${url}`);
|
||||
this.handleProtocolUrl(url);
|
||||
}
|
||||
// Show main window when second instance is triggered
|
||||
this.app.browserManager.showMainWindow();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract protocol URL from command line arguments
|
||||
*/
|
||||
private getProtocolUrlFromArgs(args: string[]): string | null {
|
||||
const protocolPrefix = `${this.protocolScheme}://`;
|
||||
|
||||
logger.debug(`🔗 [Protocol] Searching for protocol URLs in args: ${JSON.stringify(args)}`);
|
||||
logger.debug(`🔗 [Protocol] Looking for prefix: ${protocolPrefix}`);
|
||||
|
||||
for (const arg of args) {
|
||||
if (arg.startsWith(protocolPrefix)) {
|
||||
logger.debug(`🔗 [Protocol] Found protocol URL in args: ${arg}`);
|
||||
return arg;
|
||||
}
|
||||
}
|
||||
logger.debug(`🔗 [Protocol] No protocol URL found in args`);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle protocol URL - either immediately or store for later processing
|
||||
*/
|
||||
private handleProtocolUrl(url: string): void {
|
||||
try {
|
||||
logger.debug(`🔗 [Protocol] handleProtocolUrl called with: ${url}`);
|
||||
logger.debug(`🔗 [Protocol] App ready state: ${app.isReady()}`);
|
||||
logger.debug(`🔗 [Protocol] Current pending URLs count: ${this.pendingUrls.length}`);
|
||||
|
||||
if (!app.isReady()) {
|
||||
// App not ready yet, store for later processing
|
||||
logger.debug('🔗 [Protocol] App not ready, storing protocol URL for later processing');
|
||||
this.pendingUrls.push(url);
|
||||
logger.debug(`🔗 [Protocol] Pending URLs after push: ${this.pendingUrls.length}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// App is ready, process immediately
|
||||
logger.debug('🔗 [Protocol] App is ready, processing URL immediately');
|
||||
this.processProtocolUrl(url);
|
||||
} catch (error) {
|
||||
logger.error('🔗 [Protocol] Failed to handle protocol URL:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process protocol URL by showing main window and sending to renderer
|
||||
*/
|
||||
private async processProtocolUrl(url: string): Promise<void> {
|
||||
try {
|
||||
logger.debug(`🔗 [Protocol] processProtocolUrl called with: ${url}`);
|
||||
|
||||
// Basic URL validation - just check if it's our protocol
|
||||
if (!url.startsWith(`${this.protocolScheme}://`)) {
|
||||
logger.warn(`🔗 [Protocol] Invalid protocol scheme in URL: ${url}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Show main window
|
||||
logger.debug('🔗 [Protocol] Showing main window...');
|
||||
this.app.browserManager.showMainWindow();
|
||||
|
||||
// Parse protocol URL to extract urlType and action
|
||||
const parsed = parseProtocolUrl(url);
|
||||
|
||||
if (!parsed) {
|
||||
logger.warn(`🔗 [Protocol] Failed to parse protocol URL: ${url}`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug(
|
||||
`🔗 [Protocol] Parsed URL - type: ${parsed.urlType}, action: ${parsed.action}, data: %s`,
|
||||
parsed.params,
|
||||
);
|
||||
|
||||
// Dispatch to registered protocol handlers via App with parsed data
|
||||
logger.debug('🔗 [Protocol] Dispatching to protocol handlers...');
|
||||
const handled = await this.app.handleProtocolRequest(
|
||||
parsed.urlType,
|
||||
parsed.action,
|
||||
parsed.params,
|
||||
);
|
||||
|
||||
if (handled) {
|
||||
logger.debug('🔗 [Protocol] Protocol URL processed successfully by handler');
|
||||
} else {
|
||||
logger.warn(
|
||||
`🔗 [Protocol] No handler found for protocol: ${parsed.urlType}:${parsed.action}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('🔗 [Protocol] Failed to process protocol URL:', error);
|
||||
logger.error('🔗 [Protocol] Error details:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process any pending protocol URLs after app is ready
|
||||
*/
|
||||
public async processPendingUrls(): Promise<void> {
|
||||
logger.debug(`🔗 [Protocol] processPendingUrls called`);
|
||||
logger.debug(`🔗 [Protocol] Pending URLs count: ${this.pendingUrls.length}`);
|
||||
|
||||
if (this.pendingUrls.length === 0) {
|
||||
logger.debug(`🔗 [Protocol] No pending URLs to process`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug(
|
||||
`🔗 [Protocol] Processing ${this.pendingUrls.length} pending protocol URLs:`,
|
||||
this.pendingUrls,
|
||||
);
|
||||
|
||||
for (const url of this.pendingUrls) {
|
||||
logger.debug(`🔗 [Protocol] Processing pending URL: ${url}`);
|
||||
await this.processProtocolUrl(url);
|
||||
}
|
||||
|
||||
// Clear pending URLs
|
||||
this.pendingUrls = [];
|
||||
logger.debug(`🔗 [Protocol] All pending URLs processed and cleared`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current protocol scheme
|
||||
*/
|
||||
public getScheme(): string {
|
||||
return this.protocolScheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if protocol is registered
|
||||
*/
|
||||
public isRegistered(): boolean {
|
||||
return app.isDefaultProtocolClient(this.protocolScheme);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ const menu = {
|
||||
edit: {
|
||||
copy: '复制',
|
||||
cut: '剪切',
|
||||
delete: '删除',
|
||||
paste: '粘贴',
|
||||
redo: '重做',
|
||||
selectAll: '全选',
|
||||
|
||||
@@ -181,29 +181,15 @@ export class LinuxMenu extends BaseMenuPlatform implements IMenuPlatform {
|
||||
}
|
||||
|
||||
private getChatContextMenuTemplate(data?: any): MenuItemConstructorOptions[] {
|
||||
console.log(data);
|
||||
const t = this.app.i18n.ns('menu');
|
||||
const commonT = this.app.i18n.ns('common');
|
||||
|
||||
const items: MenuItemConstructorOptions[] = [
|
||||
{ label: t('edit.copy'), role: 'copy' },
|
||||
{ label: t('edit.paste'), role: 'paste' },
|
||||
return [
|
||||
{ accelerator: 'Ctrl+C', label: t('edit.copy'), role: 'copy' },
|
||||
{ accelerator: 'Ctrl+V', label: t('edit.paste'), role: 'paste' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.selectAll'), role: 'selectAll' },
|
||||
];
|
||||
|
||||
if (data?.messageId) {
|
||||
items.push(
|
||||
{ type: 'separator' },
|
||||
{
|
||||
click: () => {
|
||||
console.log('尝试删除消息:', data.messageId);
|
||||
},
|
||||
label: commonT('actions.delete'),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
@@ -211,14 +197,13 @@ export class LinuxMenu extends BaseMenuPlatform implements IMenuPlatform {
|
||||
const t = this.app.i18n.ns('menu');
|
||||
|
||||
return [
|
||||
{ label: t('edit.cut'), role: 'cut' },
|
||||
{ label: t('edit.copy'), role: 'copy' },
|
||||
{ label: t('edit.paste'), role: 'paste' },
|
||||
{ accelerator: 'Ctrl+X', label: t('edit.cut'), role: 'cut' },
|
||||
{ accelerator: 'Ctrl+C', label: t('edit.copy'), role: 'copy' },
|
||||
{ accelerator: 'Ctrl+V', label: t('edit.paste'), role: 'paste' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.undo'), role: 'undo' },
|
||||
{ label: t('edit.redo'), role: 'redo' },
|
||||
{ accelerator: 'Ctrl+A', label: t('edit.selectAll'), role: 'selectAll' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.selectAll'), role: 'selectAll' },
|
||||
{ label: t('edit.delete'), role: 'delete' },
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -301,48 +301,29 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {
|
||||
}
|
||||
|
||||
private getChatContextMenuTemplate(data?: any): MenuItemConstructorOptions[] {
|
||||
console.log(data);
|
||||
const t = this.app.i18n.ns('menu');
|
||||
const commonT = this.app.i18n.ns('common');
|
||||
|
||||
const items: MenuItemConstructorOptions[] = [
|
||||
{ label: t('edit.cut'), role: 'cut' },
|
||||
{ label: t('edit.copy'), role: 'copy' },
|
||||
{ label: t('edit.paste'), role: 'paste' },
|
||||
return [
|
||||
{ accelerator: 'Command+C', label: t('edit.copy'), role: 'copy' },
|
||||
{ accelerator: 'Command+V', label: t('edit.paste'), role: 'paste' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.selectAll'), role: 'selectAll' },
|
||||
];
|
||||
|
||||
if (data?.messageId) {
|
||||
items.push(
|
||||
{ type: 'separator' },
|
||||
{
|
||||
click: () => {
|
||||
console.log('尝试删除消息:', data.messageId);
|
||||
// 调用 MessageService (假设存在)
|
||||
// const messageService = this.app.getService(MessageService);
|
||||
// messageService?.deleteMessage(data.messageId);
|
||||
},
|
||||
label: commonT('actions.delete'),
|
||||
},
|
||||
);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
private getEditorContextMenuTemplate(_data?: any): MenuItemConstructorOptions[] {
|
||||
const t = this.app.i18n.ns('menu');
|
||||
|
||||
// 编辑器特定的上下文菜单
|
||||
return [
|
||||
{ label: t('edit.cut'), role: 'cut' },
|
||||
{ label: t('edit.copy'), role: 'copy' },
|
||||
{ label: t('edit.paste'), role: 'paste' },
|
||||
{ accelerator: 'Command+X', label: t('edit.cut'), role: 'cut' },
|
||||
{ accelerator: 'Command+C', label: t('edit.copy'), role: 'copy' },
|
||||
{ accelerator: 'Command+V', label: t('edit.paste'), role: 'paste' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.undo'), role: 'undo' },
|
||||
{ label: t('edit.redo'), role: 'redo' },
|
||||
{ accelerator: 'Command+A', label: t('edit.selectAll'), role: 'selectAll' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.selectAll'), role: 'selectAll' },
|
||||
{ label: t('edit.delete'), role: 'delete' },
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -161,32 +161,15 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {
|
||||
}
|
||||
|
||||
private getChatContextMenuTemplate(data?: any): MenuItemConstructorOptions[] {
|
||||
console.log(data);
|
||||
const t = this.app.i18n.ns('menu');
|
||||
const commonT = this.app.i18n.ns('common');
|
||||
|
||||
const items: MenuItemConstructorOptions[] = [
|
||||
{ label: t('edit.copy'), role: 'copy' },
|
||||
{ label: t('edit.paste'), role: 'paste' },
|
||||
return [
|
||||
{ accelerator: 'Ctrl+C', label: t('edit.copy'), role: 'copy' },
|
||||
{ accelerator: 'Ctrl+V', label: t('edit.paste'), role: 'paste' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.selectAll'), role: 'selectAll' },
|
||||
];
|
||||
|
||||
if (data?.messageId) {
|
||||
items.push(
|
||||
{ type: 'separator' },
|
||||
{
|
||||
click: () => {
|
||||
console.log('尝试删除消息:', data.messageId);
|
||||
// 调用 MessageService (假设存在)
|
||||
// const messageService = this.app.getService(MessageService);
|
||||
// messageService?.deleteMessage(data.messageId);
|
||||
},
|
||||
label: commonT('actions.delete'),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
@@ -194,14 +177,13 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {
|
||||
const t = this.app.i18n.ns('menu');
|
||||
|
||||
return [
|
||||
{ label: t('edit.cut'), role: 'cut' },
|
||||
{ label: t('edit.copy'), role: 'copy' },
|
||||
{ label: t('edit.paste'), role: 'paste' },
|
||||
{ accelerator: 'Ctrl+X', label: t('edit.cut'), role: 'cut' },
|
||||
{ accelerator: 'Ctrl+C', label: t('edit.copy'), role: 'copy' },
|
||||
{ accelerator: 'Ctrl+V', label: t('edit.paste'), role: 'paste' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.undo'), role: 'undo' },
|
||||
{ label: t('edit.redo'), role: 'redo' },
|
||||
{ accelerator: 'Ctrl+A', label: t('edit.selectAll'), role: 'selectAll' },
|
||||
{ type: 'separator' },
|
||||
{ label: t('edit.selectAll'), role: 'selectAll' },
|
||||
{ label: t('edit.delete'), role: 'delete' },
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NetworkProxySettings } from '@lobechat/electron-client-ipc';
|
||||
import { SocksProxies, socksDispatcher } from 'fetch-socks';
|
||||
import { Agent, ProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
|
||||
|
||||
import { createLogger } from '@/utils/logger';
|
||||
@@ -91,8 +92,29 @@ export class ProxyDispatcherManager {
|
||||
*/
|
||||
static createProxyAgent(proxyType: string, proxyUrl: string) {
|
||||
try {
|
||||
// undici 的 ProxyAgent 支持 http, https 和 socks5
|
||||
return new ProxyAgent({ uri: proxyUrl });
|
||||
if (proxyType === 'socks5') {
|
||||
// 解析 SOCKS5 代理 URL
|
||||
const url = new URL(proxyUrl);
|
||||
const socksProxies: SocksProxies = [
|
||||
{
|
||||
host: url.hostname,
|
||||
port: parseInt(url.port, 10),
|
||||
type: 5,
|
||||
...(url.username && url.password
|
||||
? {
|
||||
password: url.password,
|
||||
userId: url.username,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
];
|
||||
|
||||
// 使用 fetch-socks 处理 SOCKS5 代理
|
||||
return socksDispatcher(socksProxies);
|
||||
} else {
|
||||
// undici 的 ProxyAgent 支持 http, https
|
||||
return new ProxyAgent({ uri: proxyUrl });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to create proxy agent for ${proxyType}:`, error);
|
||||
throw new Error(
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* MCP Schema - stdio 配置类型
|
||||
*/
|
||||
export interface McpStdioConfig {
|
||||
args?: string[];
|
||||
command: string;
|
||||
env?: Record<string, string>;
|
||||
type: 'stdio';
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP Schema - http 配置类型
|
||||
*/
|
||||
export interface McpHttpConfig {
|
||||
headers?: Record<string, string>;
|
||||
type: 'http';
|
||||
url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP Schema 配置类型
|
||||
*/
|
||||
export type McpConfig = McpStdioConfig | McpHttpConfig;
|
||||
|
||||
/**
|
||||
* MCP Schema 对象
|
||||
* 符合 RFC 0001 定义
|
||||
*/
|
||||
export interface McpSchema {
|
||||
/** 插件作者 */
|
||||
author: string;
|
||||
/** 插件配置 */
|
||||
config: McpConfig;
|
||||
/** 插件描述 */
|
||||
description: string;
|
||||
/** 插件主页 */
|
||||
homepage?: string;
|
||||
/** 插件图标 */
|
||||
icon?: string;
|
||||
/** 插件唯一标识符,必须与URL中的id参数匹配 */
|
||||
identifier: string;
|
||||
/** 插件名称 */
|
||||
name: string;
|
||||
/** 插件版本 (semver) */
|
||||
version: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 协议URL解析结果
|
||||
*/
|
||||
export interface ProtocolUrlParsed {
|
||||
/** 操作类型 (如: 'install') */
|
||||
action: string;
|
||||
/** 原始URL */
|
||||
originalUrl: string;
|
||||
/** 解析后的所有查询参数 */
|
||||
params: Record<string, string>;
|
||||
/** URL类型 (如: 'plugin') */
|
||||
urlType: string;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { DataSyncConfig, NetworkProxySettings } from '@lobechat/electron-client-ipc';
|
||||
|
||||
export interface ElectronMainStore {
|
||||
autoUpdateNotificationEnabled: boolean;
|
||||
dataSyncConfig: DataSyncConfig;
|
||||
encryptedTokens: {
|
||||
accessToken?: string;
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { McpSchema } from '../../types/protocol';
|
||||
import { generateRFCProtocolUrl, parseProtocolUrl } from '../protocol';
|
||||
|
||||
describe('Protocol', () => {
|
||||
describe('generateRFCProtocolUrl', () => {
|
||||
it('should generate valid RFC protocol URL for stdio type', () => {
|
||||
const schema: McpSchema = {
|
||||
identifier: 'edgeone-mcp',
|
||||
name: 'EdgeOne MCP',
|
||||
author: 'Higress Team',
|
||||
description: 'EdgeOne API integration for LobeChat',
|
||||
version: '1.0.0',
|
||||
homepage: 'https://github.com/higress/edgeone-mcp',
|
||||
config: {
|
||||
type: 'stdio',
|
||||
command: 'npx',
|
||||
args: ['-y', '@higress/edgeone-mcp'],
|
||||
env: { NODE_ENV: 'production' },
|
||||
},
|
||||
};
|
||||
|
||||
const url = generateRFCProtocolUrl({
|
||||
id: 'edgeone-mcp',
|
||||
schema,
|
||||
marketId: 'higress',
|
||||
});
|
||||
|
||||
expect(url).toMatch(/^lobehub:\/\/plugin\/install\?/);
|
||||
expect(url).toContain('id=edgeone-mcp');
|
||||
expect(url).toContain('marketId=higress');
|
||||
|
||||
// Verify schema is URL encoded
|
||||
const urlObj = new URL(url);
|
||||
const schemaParam = urlObj.searchParams.get('schema');
|
||||
expect(schemaParam).toBeTruthy();
|
||||
// URLSearchParams.get() 自动解码,所以这里得到的是解码后的JSON
|
||||
expect(schemaParam).toContain('"'); // 解码后的引号
|
||||
});
|
||||
|
||||
it('should generate valid RFC protocol URL for http type', () => {
|
||||
const schema: McpSchema = {
|
||||
identifier: 'awesome-api',
|
||||
name: 'Awesome API',
|
||||
author: 'Smithery',
|
||||
description: 'Awesome API integration',
|
||||
version: '2.0.0',
|
||||
config: {
|
||||
type: 'http',
|
||||
url: 'https://api.smithery.ai/v1/mcp',
|
||||
headers: {
|
||||
'Authorization': 'Bearer token123',
|
||||
'X-Custom-Header': 'value',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const url = generateRFCProtocolUrl({
|
||||
id: 'awesome-api',
|
||||
schema,
|
||||
marketId: 'smithery',
|
||||
});
|
||||
|
||||
expect(url).toMatch(/^lobehub:\/\/plugin\/install\?/);
|
||||
expect(url).toContain('id=awesome-api');
|
||||
expect(url).toContain('marketId=smithery');
|
||||
});
|
||||
|
||||
it('should throw error if schema identifier does not match id', () => {
|
||||
const schema: McpSchema = {
|
||||
identifier: 'wrong-id',
|
||||
name: 'Test',
|
||||
author: 'Test',
|
||||
description: 'Test',
|
||||
version: '1.0.0',
|
||||
config: { type: 'stdio', command: 'test' },
|
||||
};
|
||||
|
||||
expect(() => generateRFCProtocolUrl({ id: 'different-id', schema })).toThrowError(
|
||||
'Schema identifier must match the id parameter',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseProtocolUrl', () => {
|
||||
it('should parse RFC protocol URL correctly', () => {
|
||||
const schema: McpSchema = {
|
||||
identifier: 'test-mcp',
|
||||
name: 'Test MCP',
|
||||
author: 'Test Author',
|
||||
description: 'Test Description',
|
||||
version: '1.0.0',
|
||||
config: {
|
||||
type: 'stdio',
|
||||
command: 'test',
|
||||
args: ['arg1', 'arg2'],
|
||||
},
|
||||
};
|
||||
|
||||
const url = generateRFCProtocolUrl({
|
||||
id: 'test-mcp',
|
||||
schema,
|
||||
marketId: 'lobehub',
|
||||
});
|
||||
|
||||
const parsed = parseProtocolUrl(url);
|
||||
|
||||
expect(parsed).toBeTruthy();
|
||||
expect(parsed?.urlType).toBe('plugin');
|
||||
expect(parsed?.action).toBe('install');
|
||||
expect(parsed?.params.type).toBe('mcp');
|
||||
expect(parsed?.params.id).toBe('test-mcp');
|
||||
expect(parsed?.params.marketId).toBe('lobehub');
|
||||
expect(parsed?.originalUrl).toBe(url);
|
||||
|
||||
// 验证 schema 可以被解析
|
||||
const parsedSchema = JSON.parse(parsed?.params.schema || '{}');
|
||||
expect(parsedSchema).toEqual(schema);
|
||||
});
|
||||
|
||||
it('should return null for invalid protocol', () => {
|
||||
const result = parseProtocolUrl('http://example.com');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should parse URLs with any action', () => {
|
||||
const result = parseProtocolUrl('lobehub://plugin/configure?id=test');
|
||||
expect(result).toBeTruthy();
|
||||
expect(result?.urlType).toBe('plugin');
|
||||
expect(result?.action).toBe('configure');
|
||||
expect(result?.params.id).toBe('test');
|
||||
});
|
||||
|
||||
it('should parse URLs with any query parameters', () => {
|
||||
const result = parseProtocolUrl('lobehub://plugin/install?custom=value&another=param');
|
||||
expect(result).toBeTruthy();
|
||||
expect(result?.urlType).toBe('plugin');
|
||||
expect(result?.action).toBe('install');
|
||||
expect(result?.params.custom).toBe('value');
|
||||
expect(result?.params.another).toBe('param');
|
||||
});
|
||||
|
||||
it('should handle URLs without query parameters', () => {
|
||||
const result = parseProtocolUrl('lobehub://plugin/install');
|
||||
expect(result).toBeTruthy();
|
||||
expect(result?.urlType).toBe('plugin');
|
||||
expect(result?.action).toBe('install');
|
||||
expect(Object.keys(result?.params || {})).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return null for URLs without action', () => {
|
||||
const result = parseProtocolUrl('lobehub://plugin/');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('URL encoding/decoding', () => {
|
||||
it('should handle special characters correctly', () => {
|
||||
const schema: McpSchema = {
|
||||
identifier: 'special-chars',
|
||||
name: '特殊字符 ñ 🚀',
|
||||
author: 'Test <test@example.com>',
|
||||
description: 'Description with "quotes" and \'apostrophes\'',
|
||||
version: '1.0.0',
|
||||
config: {
|
||||
type: 'stdio',
|
||||
command: 'cmd',
|
||||
args: ['arg with spaces', 'arg/with/slashes'],
|
||||
},
|
||||
};
|
||||
|
||||
const url = generateRFCProtocolUrl({ id: 'special-chars', schema });
|
||||
const parsed = parseProtocolUrl(url);
|
||||
|
||||
expect(parsed).toBeTruthy();
|
||||
expect(parsed?.params.id).toBe('special-chars');
|
||||
expect(parsed?.params.type).toBe('mcp');
|
||||
|
||||
// 验证 schema 可以正确解析
|
||||
const parsedSchema = JSON.parse(parsed?.params.schema || '{}');
|
||||
expect(parsedSchema).toEqual(schema);
|
||||
});
|
||||
|
||||
it('should handle different protocol schemes', () => {
|
||||
const testCases = [
|
||||
'lobehub://plugin/install?test=value',
|
||||
'lobehub-dev://plugin/install?test=value',
|
||||
'lobehub-beta://plugin/install?test=value',
|
||||
'lobehub-nightly://plugin/install?test=value',
|
||||
];
|
||||
|
||||
testCases.forEach((url) => {
|
||||
const parsed = parseProtocolUrl(url);
|
||||
expect(parsed).toBeTruthy();
|
||||
expect(parsed?.urlType).toBe('plugin');
|
||||
expect(parsed?.action).toBe('install');
|
||||
expect(parsed?.params.test).toBe('value');
|
||||
expect(parsed?.originalUrl).toBe(url);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
import { app } from 'electron';
|
||||
|
||||
import { McpSchema, ProtocolUrlParsed } from '../types/protocol';
|
||||
|
||||
export type AppChannel = 'stable' | 'beta' | 'nightly';
|
||||
|
||||
export const getProtocolScheme = (): string => {
|
||||
// 在 Electron 环境中可以通过多种方式判断版本
|
||||
const bundleId = app.name;
|
||||
const appPath = app.getPath('exe');
|
||||
|
||||
// 通过 bundle identifier 判断
|
||||
if (bundleId?.toLowerCase().includes('nightly')) return 'lobehub-nightly';
|
||||
if (bundleId?.toLowerCase().includes('beta')) return 'lobehub-beta';
|
||||
if (bundleId?.includes('dev')) return 'lobehub-dev';
|
||||
|
||||
// 通过可执行文件路径判断
|
||||
if (appPath?.toLowerCase().includes('nightly')) return 'lobehub-nightly';
|
||||
if (appPath?.toLowerCase().includes('beta')) return 'lobehub-beta';
|
||||
if (appPath?.includes('dev')) return 'lobehub-dev';
|
||||
|
||||
return 'lobehub';
|
||||
};
|
||||
|
||||
export const getVersionInfo = (): { channel: AppChannel; protocolScheme: string } => {
|
||||
const protocolScheme = getProtocolScheme();
|
||||
|
||||
let appChannel: AppChannel = 'stable';
|
||||
if (protocolScheme.includes('nightly')) {
|
||||
appChannel = 'nightly';
|
||||
} else if (protocolScheme.includes('beta')) {
|
||||
appChannel = 'beta';
|
||||
}
|
||||
|
||||
return {
|
||||
channel: appChannel,
|
||||
protocolScheme,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 验证 MCP Schema 对象结构
|
||||
* @param schema 待验证的对象
|
||||
* @returns 是否为有效的 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 lobehub:// 协议 URL (支持多版本协议)
|
||||
*
|
||||
* 支持的URL格式:
|
||||
* - lobehub://plugin/install?id=figma&schema=xxx&marketId=lobehub
|
||||
* - lobehub://plugin/configure?id=xxx&...
|
||||
* - lobehub-bet://plugin/install?id=figma&schema=xxx&marketId=lobehub
|
||||
* - lobehub-nightly://plugin/install?id=figma&schema=xxx&marketId=lobehub
|
||||
* - lobehub-dev://plugin/install?id=figma&schema=xxx&marketId=lobehub
|
||||
*
|
||||
* @param url 协议 URL
|
||||
* @returns 解析结果,包含基本结构和所有查询参数
|
||||
*/
|
||||
export const parseProtocolUrl = (url: string): ProtocolUrlParsed | null => {
|
||||
try {
|
||||
const parsedUrl = new URL(url);
|
||||
|
||||
// 支持多种协议 scheme
|
||||
const validProtocols = ['lobehub:', 'lobehub-dev:', 'lobehub-nightly:', 'lobehub-beta:'];
|
||||
if (!validProtocols.includes(parsedUrl.protocol)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 对于自定义协议,URL 解析后:
|
||||
// lobehub://plugin/install -> hostname: "plugin", pathname: "/install"
|
||||
const urlType = parsedUrl.hostname; // "plugin"
|
||||
const pathParts = parsedUrl.pathname.split('/').filter(Boolean); // ["install"]
|
||||
|
||||
if (pathParts.length < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const action = pathParts[0]; // "install"
|
||||
|
||||
// 解析所有查询参数
|
||||
const params: Record<string, string> = {};
|
||||
const searchParams = new URLSearchParams(parsedUrl.search);
|
||||
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
params[key] = value;
|
||||
}
|
||||
|
||||
return {
|
||||
action,
|
||||
originalUrl: url,
|
||||
params,
|
||||
urlType,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to parse protocol URL:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成符合 RFC 0001 的协议 URL
|
||||
*
|
||||
* @param params 协议参数
|
||||
* @returns 生成的协议URL
|
||||
*/
|
||||
export function generateRFCProtocolUrl(params: {
|
||||
/** 插件唯一标识符 */
|
||||
id: string;
|
||||
/** Marketplace ID */
|
||||
marketId?: string;
|
||||
/** MCP Schema 对象 */
|
||||
schema: McpSchema;
|
||||
/** 协议 scheme (默认: lobehub) */
|
||||
scheme?: string;
|
||||
}): string {
|
||||
const { id, schema, marketId, scheme = 'lobehub' } = params;
|
||||
|
||||
// 验证 schema.identifier 与 id 匹配
|
||||
if (schema.identifier !== id) {
|
||||
throw new Error('Schema identifier must match the id parameter');
|
||||
}
|
||||
|
||||
// 验证 schema 结构
|
||||
if (!validateMcpSchema(schema)) {
|
||||
throw new Error('Invalid MCP Schema structure');
|
||||
}
|
||||
|
||||
// 构建基础 URL
|
||||
const baseUrl = `${scheme}://plugin/install`;
|
||||
|
||||
// 构建查询参数
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
// 必需参数
|
||||
searchParams.set('type', 'mcp');
|
||||
searchParams.set('id', id);
|
||||
|
||||
// 编码 schema - 直接传 JSON 字符串,让 URLSearchParams 自动编码
|
||||
const schemaJson = JSON.stringify(schema);
|
||||
searchParams.set('schema', schemaJson);
|
||||
|
||||
// 可选参数
|
||||
if (marketId) {
|
||||
searchParams.set('marketId', marketId);
|
||||
}
|
||||
|
||||
return `${baseUrl}?${searchParams.toString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成协议 URL 示例
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const url = generateRFCProtocolUrl({
|
||||
* id: 'edgeone-mcp',
|
||||
* schema: {
|
||||
* identifier: 'edgeone-mcp',
|
||||
* name: 'EdgeOne MCP',
|
||||
* author: 'Higress Team',
|
||||
* description: 'EdgeOne API integration for LobeChat',
|
||||
* version: '1.0.0',
|
||||
* config: {
|
||||
* type: 'stdio',
|
||||
* command: 'npx',
|
||||
* args: ['-y', '@higress/edgeone-mcp']
|
||||
* }
|
||||
* },
|
||||
* marketId: 'higress'
|
||||
* });
|
||||
* // Result: lobehub://plugin/install?id=edgeone-mcp&schema=%7B%22identifier%22%3A...&marketId=higress
|
||||
* ```
|
||||
*/
|
||||
@@ -25,6 +25,34 @@ export const setupRouteInterceptors = function () {
|
||||
// 存储被阻止的路径,避免pushState重复触发
|
||||
const preventedPaths = new Set<string>();
|
||||
|
||||
// 重写 window.open 方法来拦截 JavaScript 调用
|
||||
const originalWindowOpen = window.open;
|
||||
window.open = function (url?: string | URL, target?: string, features?: string) {
|
||||
if (url) {
|
||||
try {
|
||||
const urlString = typeof url === 'string' ? url : url.toString();
|
||||
const urlObj = new URL(urlString, window.location.href);
|
||||
|
||||
// 检查是否为外部链接
|
||||
if (urlObj.origin !== window.location.origin) {
|
||||
console.log(`[preload] Intercepted window.open for external URL:`, urlString);
|
||||
// 调用主进程处理外部链接
|
||||
invoke('openExternalLink', urlString);
|
||||
return null; // 返回 null 表示没有打开新窗口
|
||||
}
|
||||
} catch (error) {
|
||||
// 处理无效 URL 或特殊协议
|
||||
console.error(`[preload] Intercepted window.open for special protocol:`, url);
|
||||
console.error(error);
|
||||
invoke('openExternalLink', typeof url === 'string' ? url : url.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 对于内部链接,调用原始的 window.open
|
||||
return originalWindowOpen.call(window, url, target, features);
|
||||
};
|
||||
|
||||
// 拦截所有a标签的点击事件 - 针对Next.js的Link组件
|
||||
document.addEventListener(
|
||||
'click',
|
||||
|
||||
@@ -1,4 +1,716 @@
|
||||
[
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Not use branch topic when this topic is not save."]
|
||||
},
|
||||
"date": "2025-09-05",
|
||||
"version": "1.123.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-09-05",
|
||||
"version": "1.123.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Add NewAPI as a router provider for multi-model aggregation."]
|
||||
},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.123.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Make LobeNextAuthDBAdapter Edge Compatible."]
|
||||
},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.7"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Make LobeNextAuthDBAdapter Edge Compatible."]
|
||||
},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Support base64 image from markdown image syntax."],
|
||||
"improvements": ["Update the price of the o3 model in OpenRouter."]
|
||||
},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.3"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.2"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Refactor to speed up send message in server mode."]
|
||||
},
|
||||
"date": "2025-09-04",
|
||||
"version": "1.122.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix socks5 proxy not work problem, fix virtuaso minheight was null."]
|
||||
},
|
||||
"date": "2025-09-03",
|
||||
"version": "1.121.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Add nano banana Chinese prompt notify."]
|
||||
},
|
||||
"date": "2025-09-03",
|
||||
"version": "1.121.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-09-02",
|
||||
"version": "1.120.7"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Add upload hint for non-visual model."]
|
||||
},
|
||||
"date": "2025-09-01",
|
||||
"version": "1.120.6"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-09-01",
|
||||
"version": "1.120.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Adjust ControlsForm component to adapt to mobile phone display."]
|
||||
},
|
||||
"date": "2025-09-01",
|
||||
"version": "1.120.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Support new provider Nebius."]
|
||||
},
|
||||
"date": "2025-09-01",
|
||||
"version": "1.120.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Remove base path."]
|
||||
},
|
||||
"date": "2025-08-31",
|
||||
"version": "1.120.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-08-31",
|
||||
"version": "1.120.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Remove webrtc sync feature flag."],
|
||||
"features": ["Rename Gemini 2.5 flash image to Nano Banana."]
|
||||
},
|
||||
"date": "2025-08-30",
|
||||
"version": "1.120.0"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-30",
|
||||
"version": "1.119.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Update enableStreaming name."]
|
||||
},
|
||||
"date": "2025-08-30",
|
||||
"version": "1.119.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Added support for Azure OpenAI Image Generation."]
|
||||
},
|
||||
"date": "2025-08-30",
|
||||
"version": "1.119.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update DeepSeek V3.1 & Gemini 2.5 Flash Image Preview models."]
|
||||
},
|
||||
"date": "2025-08-30",
|
||||
"version": "1.118.8"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-08-30",
|
||||
"version": "1.118.7"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Support non-stream mode."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.118.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Fix clerk scrollBox style, ModelFetcher support getting prices."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.118.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Fix chat session part switch theme issue."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.118.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Correct totalOutputTokens calculation for XAI provider."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.118.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Add Grok Code Fast 1 model."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.118.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Add Content-Security-Policy env."],
|
||||
"improvements": ["Support Gemini URL context tool."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.118.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Add new provider AkashChat."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.118.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Move chat item into chat."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.117.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": [
|
||||
"Ai image support Gemini 2.5 Flash Image, Support Gemini 2.5 Flash Image Preview in OpenRouter."
|
||||
],
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-08-29",
|
||||
"version": "1.117.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Support html preview."]
|
||||
},
|
||||
"date": "2025-08-28",
|
||||
"version": "1.116.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix desktop route error."]
|
||||
},
|
||||
"date": "2025-08-28",
|
||||
"version": "1.116.3"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-28",
|
||||
"version": "1.116.2"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-27",
|
||||
"version": "1.116.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Add gemini 2.5 flash image for vertex ai."]
|
||||
},
|
||||
"date": "2025-08-27",
|
||||
"version": "1.116.0"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-26",
|
||||
"version": "1.115.0"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-22",
|
||||
"version": "1.114.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update mistral model vision ability."]
|
||||
},
|
||||
"date": "2025-08-22",
|
||||
"version": "1.114.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Move database to packages."]
|
||||
},
|
||||
"date": "2025-08-22",
|
||||
"version": "1.114.4"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-21",
|
||||
"version": "1.114.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Can't load custom provider config."]
|
||||
},
|
||||
"date": "2025-08-21",
|
||||
"version": "1.114.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Move chain into @lobechat/prompts."]
|
||||
},
|
||||
"date": "2025-08-21",
|
||||
"version": "1.114.1"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-19",
|
||||
"version": "1.114.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": [
|
||||
"Support Grok thinking models in AiHubMix, The 'stream_options' parameter is only allowed when 'stream' is enabled."
|
||||
]
|
||||
},
|
||||
"date": "2025-08-19",
|
||||
"version": "1.113.3"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-18",
|
||||
"version": "1.113.2"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-17",
|
||||
"version": "1.113.1"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-17",
|
||||
"version": "1.113.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Improve mcp tracing with user config."]
|
||||
},
|
||||
"date": "2025-08-17",
|
||||
"version": "1.112.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Refactor prompts folder to the @lobechat/prompts pacakge."]
|
||||
},
|
||||
"date": "2025-08-16",
|
||||
"version": "1.112.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Refactor const folder to a new package."]
|
||||
},
|
||||
"date": "2025-08-16",
|
||||
"version": "1.112.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["重构 ArgsInput 组件."]
|
||||
},
|
||||
"date": "2025-08-16",
|
||||
"version": "1.112.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Add Imagen 4 GA models, style improve auth sign in box loading."]
|
||||
},
|
||||
"date": "2025-08-16",
|
||||
"version": "1.112.1"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-15",
|
||||
"version": "1.112.0"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-14",
|
||||
"version": "1.111.12"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update Mistral AI models & Optimize many model providers fetching."]
|
||||
},
|
||||
"date": "2025-08-13",
|
||||
"version": "1.111.11"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Adjust near bottom size on thinking scroll."]
|
||||
},
|
||||
"date": "2025-08-12",
|
||||
"version": "1.111.10"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Improve Gemini error display with promptFeedback."]
|
||||
},
|
||||
"date": "2025-08-12",
|
||||
"version": "1.111.9"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Support new GPT-5 Verbosity params."]
|
||||
},
|
||||
"date": "2025-08-11",
|
||||
"version": "1.111.8"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Refactor model-runtime to a seperated package."]
|
||||
},
|
||||
"date": "2025-08-11",
|
||||
"version": "1.111.7"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Solve the cache problem caused by the same dom id when sharing pictures."]
|
||||
},
|
||||
"date": "2025-08-11",
|
||||
"version": "1.111.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Add mask effect to thinking scroll, update i18n."]
|
||||
},
|
||||
"date": "2025-08-10",
|
||||
"version": "1.111.5"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-09",
|
||||
"version": "1.111.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": [
|
||||
"Improve thinking auto scroll style, Support session switch shortcut key, update i18n."
|
||||
]
|
||||
},
|
||||
"date": "2025-08-09",
|
||||
"version": "1.111.3"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-08",
|
||||
"version": "1.111.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Add descriptions for the FLUX.1 Krea and Qwen Image."]
|
||||
},
|
||||
"date": "2025-08-08",
|
||||
"version": "1.111.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Add GPT-5 series models."]
|
||||
},
|
||||
"date": "2025-08-08",
|
||||
"version": "1.111.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Missing languages it-IT, pl-PL, nl-NL."]
|
||||
},
|
||||
"date": "2025-08-07",
|
||||
"version": "1.110.7"
|
||||
},
|
||||
{
|
||||
"children": {},
|
||||
"date": "2025-08-07",
|
||||
"version": "1.110.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Optimize Gemini error message display & Filter empty messages."]
|
||||
},
|
||||
"date": "2025-08-07",
|
||||
"version": "1.110.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Refactor trace type."]
|
||||
},
|
||||
"date": "2025-08-06",
|
||||
"version": "1.110.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Fix provider setting page hydration error."]
|
||||
},
|
||||
"date": "2025-08-06",
|
||||
"version": "1.110.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix fail to fetch aihubmix model on client mode."],
|
||||
"improvements": ["Add context menu for desktop, support different model tabs."]
|
||||
},
|
||||
"date": "2025-08-06",
|
||||
"version": "1.110.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix remote avatar broken in desktop again."]
|
||||
},
|
||||
"date": "2025-08-06",
|
||||
"version": "1.110.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Support mcp plugin install from web."]
|
||||
},
|
||||
"date": "2025-08-06",
|
||||
"version": "1.110.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix ollama model output without thinking."],
|
||||
"improvements": ["Add Claude Opus 4.1 model, update i18n."]
|
||||
},
|
||||
"date": "2025-08-06",
|
||||
"version": "1.109.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Support gpt-oss in ollama provider."]
|
||||
},
|
||||
"date": "2025-08-05",
|
||||
"version": "1.109.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Provider config checker uses outdated API key."]
|
||||
},
|
||||
"date": "2025-08-05",
|
||||
"version": "1.108.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix remote avatar broken in desktop."],
|
||||
"improvements": ["Update mask style."]
|
||||
},
|
||||
"date": "2025-08-05",
|
||||
"version": "1.108.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Support 302ai provider."]
|
||||
},
|
||||
"date": "2025-08-05",
|
||||
"version": "1.108.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Break line for Gemini Artifacts."]
|
||||
},
|
||||
"date": "2025-08-05",
|
||||
"version": "1.107.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update models."]
|
||||
},
|
||||
"date": "2025-08-04",
|
||||
"version": "1.107.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["When s3 files not exist , global files should delete."]
|
||||
},
|
||||
"date": "2025-08-04",
|
||||
"version": "1.107.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Aihubmix provider request headers."]
|
||||
},
|
||||
"date": "2025-08-03",
|
||||
"version": "1.107.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Move types to separate package."]
|
||||
},
|
||||
"date": "2025-08-02",
|
||||
"version": "1.107.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-08-01",
|
||||
"version": "1.107.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Support aihubmix provider."]
|
||||
},
|
||||
"date": "2025-08-01",
|
||||
"version": "1.107.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Support SenseNova V6.5 models."]
|
||||
},
|
||||
"date": "2025-07-31",
|
||||
"version": "1.106.8"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Update Aliyun Bailian models."]
|
||||
},
|
||||
"date": "2025-07-31",
|
||||
"version": "1.106.7"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix oidc oauth callback pages 404."]
|
||||
},
|
||||
"date": "2025-07-31",
|
||||
"version": "1.106.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Improve mcp plugin calling and display."]
|
||||
},
|
||||
"date": "2025-07-30",
|
||||
"version": "1.106.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix mcp calling missing array content."],
|
||||
"improvements": ["Update i18n."]
|
||||
},
|
||||
"date": "2025-07-30",
|
||||
"version": "1.106.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Moonshot assistant messages must not be empty."],
|
||||
"improvements": ["Add volcengine kimi-k2 model, Add Zhipu GLM-4.5 models."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.106.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix desktop auth redirect url error."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.106.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Support Minimax T2I models."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.106.1"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"features": ["Add support for Okta Authentication."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.106.0"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Open new topic by tap Just Chat again."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.105.6"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Reorder AppTheme and Locale to fix modal i18n."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.105.5"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Revert jose to ^5 to fix auth issue on desktop."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.105.4"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"fixes": ["Fix subscription plan tag display."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.105.3"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Add more OpenAI SDK Text2Image providers, update i18n."]
|
||||
},
|
||||
"date": "2025-07-29",
|
||||
"version": "1.105.2"
|
||||
},
|
||||
{
|
||||
"children": {
|
||||
"improvements": ["Support more Text2Image from Qwen."]
|
||||
|
||||
+30
-2
@@ -1,11 +1,39 @@
|
||||
component_management:
|
||||
individual_components:
|
||||
# App architecture layers
|
||||
- component_id: app_store
|
||||
name: "Store"
|
||||
paths:
|
||||
- src/store/**
|
||||
- component_id: app_services
|
||||
name: "Services"
|
||||
paths:
|
||||
- src/services/**
|
||||
- component_id: app_server
|
||||
name: "Server"
|
||||
paths:
|
||||
- src/server/**
|
||||
- component_id: app_libs
|
||||
name: "Libs"
|
||||
paths:
|
||||
- src/libs/**
|
||||
- component_id: app_utils
|
||||
name: "Utils"
|
||||
paths:
|
||||
- src/utils/**
|
||||
|
||||
coverage:
|
||||
status:
|
||||
project:
|
||||
default: off
|
||||
server:
|
||||
database:
|
||||
flags:
|
||||
- server
|
||||
- database
|
||||
app:
|
||||
flags:
|
||||
- app
|
||||
patch: off
|
||||
|
||||
|
||||
comment:
|
||||
layout: "header, diff, flags, components" # show component info in the PR comment
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
name: lobe-chat-development
|
||||
services:
|
||||
network-service:
|
||||
image: alpine
|
||||
container_name: lobe-network
|
||||
restart: always
|
||||
ports:
|
||||
- '${MINIO_PORT}:${MINIO_PORT}' # MinIO API
|
||||
- '9001:9001' # MinIO Console
|
||||
- '${CASDOOR_PORT}:${CASDOOR_PORT}' # Casdoor
|
||||
command: tail -f /dev/null
|
||||
networks:
|
||||
- lobe-network
|
||||
|
||||
postgresql:
|
||||
extends:
|
||||
file: docker-compose/local/docker-compose.yml
|
||||
service: postgresql
|
||||
minio:
|
||||
extends:
|
||||
file: docker-compose/local/docker-compose.yml
|
||||
service: minio
|
||||
casdoor:
|
||||
extends:
|
||||
file: docker-compose/local/docker-compose.yml
|
||||
service: casdoor
|
||||
searxng:
|
||||
extends:
|
||||
file: docker-compose/local/docker-compose.yml
|
||||
service: searxng
|
||||
|
||||
volumes:
|
||||
data:
|
||||
driver: local
|
||||
s3_data:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
lobe-network:
|
||||
driver: bridge
|
||||
@@ -27,6 +27,7 @@ AUTH_CASDOOR_ISSUER=http://localhost:8000
|
||||
# Casdoor secret
|
||||
AUTH_CASDOOR_ID=a387a4892ee19b1a2249
|
||||
AUTH_CASDOOR_SECRET=dbf205949d704de81b0b5b3603174e23fbecc354
|
||||
CASDOOR_WEBHOOK_SECRET=casdoor-secret
|
||||
|
||||
# MinIO S3 configuration
|
||||
MINIO_ROOT_USER=admin
|
||||
|
||||
@@ -27,6 +27,7 @@ AUTH_CASDOOR_ISSUER=http://localhost:8000
|
||||
# Casdoor secret
|
||||
AUTH_CASDOOR_ID=a387a4892ee19b1a2249
|
||||
AUTH_CASDOOR_SECRET=dbf205949d704de81b0b5b3603174e23fbecc354
|
||||
CASDOOR_WEBHOOK_SECRET=casdoor-secret
|
||||
|
||||
# MinIO S3 配置
|
||||
MINIO_ROOT_USER=admin
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
data/
|
||||
s3_data/
|
||||
@@ -60,7 +60,7 @@ services:
|
||||
|
||||
# version lock ref: https://github.com/lobehub/lobe-chat/pull/7331
|
||||
casdoor:
|
||||
image: casbin/casdoor:v1.843.0
|
||||
image: casbin/casdoor:v2.13.0
|
||||
container_name: lobe-casdoor
|
||||
entrypoint: /bin/sh -c './server --createDatabase=true'
|
||||
network_mode: 'service:network-service'
|
||||
|
||||
+752
-289
File diff suppressed because it is too large
Load Diff
@@ -450,7 +450,7 @@ ENV_EXAMPLES=(
|
||||
"$SUB_DIR/.env.example"
|
||||
)
|
||||
# Default values
|
||||
CASDOOR_PASSWORD="123"
|
||||
CASDOOR_PASSWORD="pswd123"
|
||||
CASDOOR_SECRET="CASDOOR_SECRET"
|
||||
MINIO_ROOT_PASSWORD="YOUR_MINIO_PASSWORD"
|
||||
CASDOOR_HOST="localhost:8000"
|
||||
@@ -657,10 +657,10 @@ section_regenerate_secrets() {
|
||||
CASDOOR_PASSWORD=$(generate_key 10)
|
||||
if [ $? -ne 0 ]; then
|
||||
echo $(show_message "security_secrect_regenerate_failed") "CASDOOR_PASSWORD"
|
||||
CASDOOR_PASSWORD="123"
|
||||
CASDOOR_PASSWORD="pswd123"
|
||||
else
|
||||
# replace `password` in init_data.json
|
||||
sed "${SED_INPLACE_ARGS[@]}" "s/"123"/${CASDOOR_PASSWORD}/" init_data.json
|
||||
sed "${SED_INPLACE_ARGS[@]}" "s/"pswd123"/${CASDOOR_PASSWORD}/" init_data.json
|
||||
if [ $? -ne 0 ]; then
|
||||
echo $(show_message "security_secrect_regenerate_failed") "CASDOOR_PASSWORD in \`init_data.json\`"
|
||||
fi
|
||||
|
||||
@@ -456,7 +456,7 @@ The project uses vitest for unit testing.
|
||||
|
||||
Since our two new configuration fields are both optional, theoretically you could pass the tests without updating them. However, since we added the `openingQuestions` field to the `DEFAULT_AGENT_CONFIG` mentioned earlier, this causes many tests to calculate configurations that include this field, so we still need to update some test snapshots.
|
||||
|
||||
For the current scenario, I recommend running the tests locally to see which tests fail, and then update them as needed. For example, for the test file `src/store/agent/slices/chat/selectors/agent.test.ts`, you need to run `npx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` to update the snapshot.
|
||||
For the current scenario, I recommend running the tests locally to see which tests fail, and then update them as needed. For example, for the test file `src/store/agent/slices/chat/selectors/agent.test.ts`, you need to run `bunx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` to update the snapshot.
|
||||
|
||||
## Summary
|
||||
|
||||
|
||||
@@ -456,7 +456,7 @@ export default WelcomeMessage;
|
||||
|
||||
由于我们目前两个新的配置字段都是可选的,所以理论上你不更新测试也能跑通,不过由于我们把前面提到的默认配置 `DEFAULT_AGENT_CONFIG` 增加了 `openingQuestions` 字段,这导致很多测试计算出的配置都是有这个字段的,因此我们还是需要更新一部分测试的快照。
|
||||
|
||||
对于当前这个场景,我建议是本地直接跑下测试,看哪些测试失败了,针对需要更新,例如测试文件 `src/store/agent/slices/chat/selectors/agent.test.ts` 需要执行一下 `npx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` 更新快照。
|
||||
对于当前这个场景,我建议是本地直接跑下测试,看哪些测试失败了,针对需要更新,例如测试文件 `src/store/agent/slices/chat/selectors/agent.test.ts` 需要执行一下 `bunx vitest -u src/store/agent/slices/chat/selectors/agent.test.ts` 更新快照。
|
||||
|
||||
## 总结
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
title: Image Generation Development Setup
|
||||
description: Configure local environment for developing text-to-image and image-to-image features
|
||||
---
|
||||
|
||||
# Image Generation Development Setup
|
||||
|
||||
This guide helps developers set up the local environment for developing image generation features (text-to-image, image-to-image) with file storage capabilities.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker installed and running
|
||||
- Node.js and pnpm installed
|
||||
- PostgreSQL client tools (optional, for debugging)
|
||||
|
||||
<Callout type="warning">
|
||||
**Security Notice**: This setup is designed for local development only. It uses default credentials and open permissions that are NOT suitable for production environments.
|
||||
</Callout>
|
||||
|
||||
## Quick Setup
|
||||
|
||||
Run the provided script to automatically set up all required services:
|
||||
|
||||
```bash
|
||||
# Set up PostgreSQL and MinIO for image storage
|
||||
./scripts/setup-image-generation-dev.sh
|
||||
|
||||
# Start the development server
|
||||
pnpm dev:desktop
|
||||
```
|
||||
|
||||
This script will:
|
||||
|
||||
1. Start PostgreSQL (no authentication for local development)
|
||||
2. Run database migrations to initialize schema
|
||||
3. Start MinIO (S3-compatible storage)
|
||||
4. Create and configure the storage bucket
|
||||
5. Add necessary S3 environment variables to `.env.desktop`
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
The image generation feature requires:
|
||||
|
||||
- **PostgreSQL**: Stores metadata about generated images
|
||||
- **MinIO/S3**: Stores the actual image files
|
||||
- **Server Mode**: Required for file handling (`NEXT_PUBLIC_SERVICE_MODE=server`)
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
The following environment variables are automatically configured by the setup script:
|
||||
|
||||
```bash
|
||||
# S3 Storage Configuration (MinIO for local development)
|
||||
S3_ACCESS_KEY_ID=minioadmin
|
||||
S3_SECRET_ACCESS_KEY=minioadmin
|
||||
S3_ENDPOINT=http://localhost:9000
|
||||
S3_BUCKET=lobe-chat
|
||||
S3_REGION=us-east-1
|
||||
S3_PUBLIC_DOMAIN=http://localhost:9000/lobe-chat
|
||||
S3_ENABLE_PATH_STYLE=1 # Required for MinIO
|
||||
```
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### 1. Image Generation API
|
||||
|
||||
When developing image generation features, generated images will be:
|
||||
|
||||
1. Created by the AI model
|
||||
2. Uploaded to S3/MinIO via presigned URLs
|
||||
3. Metadata stored in PostgreSQL
|
||||
4. Served via the public S3 URL
|
||||
|
||||
### 2. File Storage Structure
|
||||
|
||||
```
|
||||
lobe-chat/ # S3 Bucket
|
||||
├── generated/ # Generated images
|
||||
│ └── {userId}/
|
||||
│ └── {sessionId}/
|
||||
│ └── {imageId}.png
|
||||
└── uploads/ # User uploads for image-to-image
|
||||
└── {userId}/
|
||||
└── {fileId}.{ext}
|
||||
```
|
||||
|
||||
### 3. Testing Your Implementation
|
||||
|
||||
After setting up the environment, you can test:
|
||||
|
||||
```typescript
|
||||
// Example: Upload generated image
|
||||
const uploadUrl = await trpc.upload.createPresignedUrl.mutate({
|
||||
filename: 'generated-image.png',
|
||||
contentType: 'image/png',
|
||||
});
|
||||
|
||||
// Upload to S3
|
||||
await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: imageBlob,
|
||||
headers: { 'Content-Type': 'image/png' },
|
||||
});
|
||||
```
|
||||
|
||||
## Manual Setup
|
||||
|
||||
If you prefer to set up services manually:
|
||||
|
||||
### PostgreSQL
|
||||
|
||||
```bash
|
||||
docker run -d --name lobe-postgres \
|
||||
-p 5432:5432 \
|
||||
-e POSTGRES_HOST_AUTH_METHOD=trust \
|
||||
-e POSTGRES_DB=postgres \
|
||||
postgres:15
|
||||
```
|
||||
|
||||
### MinIO
|
||||
|
||||
```bash
|
||||
# Start MinIO
|
||||
docker run -d --name lobe-minio \
|
||||
-p 9000:9000 -p 9001:9001 \
|
||||
-e MINIO_ROOT_USER=minioadmin \
|
||||
-e MINIO_ROOT_PASSWORD=minioadmin \
|
||||
quay.io/minio/minio:RELEASE.2025-04-22T22-12-26Z \
|
||||
server /data --console-address ":9001"
|
||||
|
||||
# Create bucket
|
||||
docker run --rm \
|
||||
--link lobe-minio:minio \
|
||||
--entrypoint bash \
|
||||
quay.io/minio/mc:RELEASE.2025-04-18T16-45-00Z \
|
||||
-c "
|
||||
mc config host add minio http://minio:9000 minioadmin minioadmin &&
|
||||
mc mb minio/lobe-chat &&
|
||||
mc anonymous set public minio/lobe-chat
|
||||
"
|
||||
```
|
||||
|
||||
## Service URLs
|
||||
|
||||
- **PostgreSQL**: `postgres://postgres@localhost:5432/postgres`
|
||||
- **MinIO API**: `http://localhost:9000`
|
||||
- **MinIO Console**: `http://localhost:9001` (minioadmin/minioadmin)
|
||||
- **Application**: `http://localhost:3015`
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Port Conflicts
|
||||
|
||||
If ports are already in use:
|
||||
|
||||
```bash
|
||||
# Check what's using the ports
|
||||
lsof -i :5432 # PostgreSQL
|
||||
lsof -i :9000 # MinIO API
|
||||
lsof -i :9001 # MinIO Console
|
||||
```
|
||||
|
||||
### Reset Environment
|
||||
|
||||
To completely reset your development environment:
|
||||
|
||||
```bash
|
||||
# Stop and remove containers
|
||||
docker stop lobe-postgres lobe-minio
|
||||
docker rm lobe-postgres lobe-minio
|
||||
|
||||
# Re-run setup
|
||||
./scripts/setup-image-generation-dev.sh
|
||||
```
|
||||
|
||||
### Database Migrations
|
||||
|
||||
The setup script runs migrations automatically. If you need to run them manually:
|
||||
|
||||
```bash
|
||||
pnpm db:migrate
|
||||
```
|
||||
|
||||
Note: In development mode with `pnpm dev:desktop`, migrations also run automatically on startup.
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Server Database Setup](/docs/self-hosting/server-database)
|
||||
- [S3 Storage Configuration](/docs/self-hosting/advanced/s3)
|
||||
- [Environment Variables](/docs/self-hosting/environment-variables)
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
title: 图像生成开发环境配置
|
||||
description: 配置本地环境以开发文本生图和图像处理功能
|
||||
---
|
||||
|
||||
# 图像生成开发环境配置
|
||||
|
||||
本指南帮助开发者配置本地环境,用于开发图像生成功能(文生图、图生图)等和文件存储能力。
|
||||
|
||||
## 前置条件
|
||||
|
||||
- 已安装并运行 Docker
|
||||
- 已安装 Node.js 和 pnpm
|
||||
- PostgreSQL 客户端工具(可选,用于调试)
|
||||
|
||||
<Callout type="warning">
|
||||
**安全提醒**:此配置仅适用于本地开发。使用的默认凭据和开放权限不适合生产环境。
|
||||
</Callout>
|
||||
|
||||
## 快速配置
|
||||
|
||||
运行提供的脚本来自动配置所有必需的服务:
|
||||
|
||||
```bash
|
||||
# 配置 PostgreSQL 和 MinIO 用于图像存储
|
||||
./scripts/setup-image-generation-dev.sh
|
||||
|
||||
# 启动开发服务器
|
||||
pnpm dev:desktop
|
||||
```
|
||||
|
||||
此脚本将执行:
|
||||
|
||||
1. 启动 PostgreSQL(本地开发无需身份验证)
|
||||
2. 运行数据库迁移以初始化模式
|
||||
3. 启动 MinIO(S3 兼容存储)
|
||||
4. 创建并配置存储桶
|
||||
5. 在 `.env.desktop` 中添加必要的 S3 环境变量
|
||||
|
||||
## 架构概览
|
||||
|
||||
图像生成功能需要:
|
||||
|
||||
- **PostgreSQL**:存储生成图像的元数据
|
||||
- **MinIO/S3**:存储实际的图像文件
|
||||
- **服务器模式**:文件处理所需(`NEXT_PUBLIC_SERVICE_MODE=server`)
|
||||
|
||||
## 环境配置
|
||||
|
||||
以下环境变量会被配置脚本自动设置:
|
||||
|
||||
```bash
|
||||
# S3 存储配置(本地开发使用 MinIO)
|
||||
S3_ACCESS_KEY_ID=minioadmin
|
||||
S3_SECRET_ACCESS_KEY=minioadmin
|
||||
S3_ENDPOINT=http://localhost:9000
|
||||
S3_BUCKET=lobe-chat
|
||||
S3_REGION=us-east-1
|
||||
S3_PUBLIC_DOMAIN=http://localhost:9000/lobe-chat
|
||||
S3_ENABLE_PATH_STYLE=1 # MinIO 必需
|
||||
```
|
||||
|
||||
## 开发工作流
|
||||
|
||||
### 1. 图像生成 API
|
||||
|
||||
在开发图像生成功能时,生成的图像将:
|
||||
|
||||
1. 由 AI 模型创建
|
||||
2. 通过预签名 URL 上传到 S3/MinIO
|
||||
3. 元数据存储在 PostgreSQL 中
|
||||
4. 通过公共 S3 URL 提供服务
|
||||
|
||||
### 2. 文件存储结构
|
||||
|
||||
```
|
||||
lobe-chat/ # S3 存储桶
|
||||
├── generated/ # 生成的图像
|
||||
│ └── {userId}/
|
||||
│ └── {sessionId}/
|
||||
│ └── {imageId}.png
|
||||
└── uploads/ # 用户上传的图像处理文件
|
||||
└── {userId}/
|
||||
└── {fileId}.{ext}
|
||||
```
|
||||
|
||||
### 3. 测试您的实现
|
||||
|
||||
配置环境后,您可以测试:
|
||||
|
||||
```typescript
|
||||
// 示例:上传生成的图像
|
||||
const uploadUrl = await trpc.upload.createPresignedUrl.mutate({
|
||||
filename: 'generated-image.png',
|
||||
contentType: 'image/png',
|
||||
});
|
||||
|
||||
// 上传到 S3
|
||||
await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: imageBlob,
|
||||
headers: { 'Content-Type': 'image/png' },
|
||||
});
|
||||
```
|
||||
|
||||
## 手动配置
|
||||
|
||||
如果您希望手动配置服务:
|
||||
|
||||
### PostgreSQL
|
||||
|
||||
```bash
|
||||
docker run -d --name lobe-postgres \
|
||||
-p 5432:5432 \
|
||||
-e POSTGRES_HOST_AUTH_METHOD=trust \
|
||||
-e POSTGRES_DB=postgres \
|
||||
postgres:15
|
||||
```
|
||||
|
||||
### MinIO
|
||||
|
||||
```bash
|
||||
# 启动 MinIO
|
||||
docker run -d --name lobe-minio \
|
||||
-p 9000:9000 -p 9001:9001 \
|
||||
-e MINIO_ROOT_USER=minioadmin \
|
||||
-e MINIO_ROOT_PASSWORD=minioadmin \
|
||||
quay.io/minio/minio:RELEASE.2025-04-22T22-12-26Z \
|
||||
server /data --console-address ":9001"
|
||||
|
||||
# 创建存储桶
|
||||
docker run --rm \
|
||||
--link lobe-minio:minio \
|
||||
--entrypoint bash \
|
||||
quay.io/minio/mc:RELEASE.2025-04-18T16-45-00Z \
|
||||
-c "
|
||||
mc config host add minio http://minio:9000 minioadmin minioadmin &&
|
||||
mc mb minio/lobe-chat &&
|
||||
mc anonymous set public minio/lobe-chat
|
||||
"
|
||||
```
|
||||
|
||||
## 服务地址
|
||||
|
||||
- **PostgreSQL**:`postgres://postgres@localhost:5432/postgres`
|
||||
- **MinIO API**:`http://localhost:9000`
|
||||
- **MinIO 控制台**:`http://localhost:9001` (minioadmin/minioadmin)
|
||||
- **应用程序**:`http://localhost:3015`
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 端口冲突
|
||||
|
||||
如果端口已被占用:
|
||||
|
||||
```bash
|
||||
# 检查端口使用情况
|
||||
lsof -i :5432 # PostgreSQL
|
||||
lsof -i :9000 # MinIO API
|
||||
lsof -i :9001 # MinIO 控制台
|
||||
```
|
||||
|
||||
### 重置环境
|
||||
|
||||
要完全重置开发环境:
|
||||
|
||||
```bash
|
||||
# 停止并删除容器
|
||||
docker stop lobe-postgres lobe-minio
|
||||
docker rm lobe-postgres lobe-minio
|
||||
|
||||
# 重新运行配置
|
||||
./scripts/setup-image-generation-dev.sh
|
||||
```
|
||||
|
||||
### 数据库迁移
|
||||
|
||||
配置脚本会自动运行迁移。如需手动运行:
|
||||
|
||||
```bash
|
||||
pnpm db:migrate
|
||||
```
|
||||
|
||||
注意:在使用 `pnpm dev:desktop` 的开发模式下,迁移也会在启动时自动运行。
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [服务器数据库配置](/docs/self-hosting/server-database)
|
||||
- [S3 存储配置](/docs/self-hosting/advanced/s3)
|
||||
- [环境变量](/docs/self-hosting/environment-variables)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user