Dataset Viewer
owner
stringclasses 603
values | repo
stringclasses 778
values | repo_dir
stringclasses 830
values | file_rel_repo
stringlengths 6
222
| file_rel_outdir
stringlengths 16
235
| size
int64 0
2.36M
| mtime
int64 1.76B
1.76B
| lang
stringclasses 10
values | content
stringlengths 0
2.36M
| updated_at
stringdate 2025-09-24 14:46:58
2025-09-24 14:46:58
|
---|---|---|---|---|---|---|---|---|---|
hoppscotch
|
hoppscotch
|
hoppscotch__hoppscotch
|
README.md
|
hoppscotch__hoppscotch/README.md
| 11,659 | 1,758,620,342 |
en
|
<div align="center">
<a href="https://hoppscotch.io">
<img
src="https://avatars.githubusercontent.com/u/56705483"
alt="Hoppscotch"
height="64"
/>
</a>
<h3>
<b>
Hoppscotch
</b>
</h3>
<b>
Open Source API Development Ecosystem
</b>
<p>
[](CODE_OF_CONDUCT.md) [](https://hoppscotch.io) [](https://github.com/hoppscotch/hoppscotch/actions) [](https://twitter.com/share?text=%F0%9F%91%BD%20Hoppscotch%20%E2%80%A2%20Open%20source%20API%20development%20ecosystem%20-%20Helps%20you%20create%20requests%20faster,%20saving%20precious%20time%20on%20development.&url=https://hoppscotch.io&hashtags=hoppscotch&via=hoppscotch_io)
</p>
<p>
<sub>
Built with ❤︎ by
<a href="https://github.com/hoppscotch/hoppscotch/graphs/contributors">
contributors
</a>
</sub>
</p>
<br />
<p>
<a href="https://hoppscotch.io">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./packages/hoppscotch-common/public/images/banner-dark.png">
<source media="(prefers-color-scheme: light)" srcset="./packages/hoppscotch-common/public/images/banner-light.png">
<img alt="Hoppscotch" src="./packages/hoppscotch-common/public/images/banner-dark.png">
</picture>
</a>
</p>
</div>
_We highly recommend you take a look at the [**Hoppscotch Documentation**](https://docs.hoppscotch.io) to learn more about the app._
#### **Support**
[](https://hoppscotch.io/discord) [](https://hoppscotch.io/telegram) [](https://github.com/hoppscotch/hoppscotch/discussions)
### **Features**
❤️ **Lightweight:** Crafted with minimalistic UI design.
⚡️ **Fast:** Send requests and get responses in real time.
🗄️ **HTTP Methods:** Request methods define the type of action you are requesting to be performed.
- `GET` - Requests retrieve resource information
- `POST` - The server creates a new entry in a database
- `PUT` - Updates an existing resource
- `PATCH` - Very similar to `PUT` but makes a partial update on a resource
- `DELETE` - Deletes resource or related component
- `HEAD` - Retrieve response headers identical to those of a GET request, but without the response body.
- `CONNECT` - Establishes a tunnel to the server identified by the target resource
- `OPTIONS` - Describe the communication options for the target resource
- `TRACE` - Performs a message loop-back test along the path to the target resource
- `<custom>` - Some APIs use custom request methods such as `LIST`. Type in your custom methods.
🌈 **Theming:** Customizable combinations for background, foreground, and accent colors — [customize now](https://hoppscotch.io/settings).
- Choose a theme: System preference, Light, Dark, and Black
- Choose accent colors: Green, Teal, Blue, Indigo, Purple, Yellow, Orange, Red, and Pink
- Distraction-free Zen mode
_Customized themes are synced with your cloud/local session._
🔥 **PWA:** Install as a [Progressive Web App](https://web.dev/progressive-web-apps) on your device.
- Instant loading with Service Workers
- Offline support
- Low RAM/memory and CPU usage
- Add to Home Screen
- Desktop PWA
🚀 **Request:** Retrieve response from endpoint instantly.
1. Choose `method`
2. Enter `URL`
3. Send
- Copy/share public "Share URL"
- Generate/copy request code snippets for 10+ languages and frameworks
- Import `cURL`
- Label requests
🔌 **WebSocket:** Establish full-duplex communication channels over a single TCP connection.
📡 **Server-Sent Events:** Receive a stream of updates from a server over an HTTP connection without resorting to polling.
🌩 **Socket.IO:** Send and Receive data with the SocketIO server.
🦟 **MQTT:** Subscribe and Publish to topics of an MQTT Broker.
🔮 **GraphQL:** GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.
- Set endpoint and get schema
- Multi-column docs
- Set custom request headers
- Query schema
- Get query response
🔐 **Authorization:** Allows to identify the end-user.
- None
- Basic
- Bearer Token
- OAuth 2.0
- OIDC Access Token/PKCE
📢 **Headers:** Describes the format the body of your request is being sent in.
📫 **Parameters:** Use request parameters to set varying parts in simulated requests.
📃 **Request Body:** Used to send and receive data via the REST API.
- Set `Content Type`
- FormData, JSON, and many more
- Toggle between key-value and RAW input parameter list
📮 **Response:** Contains the status line, headers, and the message/response body.
- Copy the response to the clipboard
- Download the response as a file
- View response headers
- View raw and preview HTML, image, JSON, and XML responses
⏰ **History:** Request entries are synced with your cloud/local session storage.
📁 **Collections:** Keep your API requests organized with collections and folders. Reuse them with a single click.
- Unlimited collections, folders, and requests
- Nested folders
- Export and import as a file or GitHub gist
_Collections are synced with your cloud/local session storage._
📜 **Pre-Request Scripts:** Snippets of code associated with a request that is executed before the request is sent.
- Set environment variables
- Include timestamp in the request headers
- Send a random alphanumeric string in the URL parameters
- Any JavaScript functions
👨👩👧👦 **Teams:** Helps you collaborate across your teams to design, develop, and test APIs faster.
- Create unlimited teams
- Create unlimited shared collections
- Create unlimited team members
- Role-based access control
- Cloud sync
- Multiple devices
👥 **Workspaces:** Organize your personal and team collections environments into workspaces. Easily switch between workspaces to manage multiple projects.
- Create unlimited workspaces
- Switch between personal and team workspaces
⌨️ **Keyboard Shortcuts:** Optimized for efficiency.
> **[Read our documentation on Keyboard Shortcuts](https://docs.hoppscotch.io/documentation/features/shortcuts)**
🌐 **Proxy:** Enable Proxy Mode from Settings to access blocked APIs.
- Hide your IP address
- Fixes [`CORS`](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) (Cross-Origin Resource Sharing) issues
- Access APIs served in non-HTTPS (`http://`) endpoints
- Use your Proxy URL
_Official proxy server is hosted by Hoppscotch - **[GitHub](https://github.com/hoppscotch/proxyscotch)** - **[Privacy Policy](https://docs.hoppscotch.io/support/privacy)**._
🌎 **i18n:** Experience the app in your language.
Help us to translate Hoppscotch. Please read [`TRANSLATIONS`](TRANSLATIONS.md) for details on our [`CODE OF CONDUCT`](CODE_OF_CONDUCT.md) and the process for submitting pull requests to us.
☁️ **Auth + Sync:** Sign in and sync your data in real-time across all your devices.
**Sign in with:**
- GitHub
- Google
- Microsoft
- Email
- SSO (Single Sign-On)[^EE]
**🔄 Synchronize your data:** Handoff to continue tasks on your other devices.
- Workspaces
- History
- Collections
- Environments
- Settings
✅ **Post-Request Tests:** Write tests associated with a request that is executed after the request's response.
- Check the status code as an integer
- Filter response headers
- Parse the response data
- Set environment variables
- Write JavaScript code
🌱 **Environments:** Environment variables allow you to store and reuse values in your requests and scripts.
- Unlimited environments and variables
- Initialize through the pre-request script
- Export as / import from GitHub gist
<details>
<summary><i>Use-cases</i></summary>
---
- By storing a value in a variable, you can reference it throughout your request section
- If you need to update the value, you only have to change it in one place
- Using variables increases your ability to work efficiently and minimizes the likelihood of error
---
</details>
🚚 **Bulk Edit:** Edit key-value pairs in bulk.
- Entries are separated by newline
- Keys and values are separated by `:`
- Prepend `#` to any row you want to add but keep disabled
🎛️ **Admin dashboard:** Manage your team and invite members.
- Insights
- Manage users
- Manage teams
📦 **Add-ons:** Official add-ons for hoppscotch.
- **[Hoppscotch CLI](https://github.com/hoppscotch/hoppscotch/tree/main/packages/hoppscotch-cli)** - Command-line interface for Hoppscotch.
- **[Proxy](https://github.com/hoppscotch/proxyscotch)** - A simple proxy server created for Hoppscotch.
- **[Browser Extensions](https://github.com/hoppscotch/hoppscotch-extension)** - Browser extensions that enhance your Hoppscotch experience.
[ **Firefox**](https://addons.mozilla.org/en-US/firefox/addon/hoppscotch) | [ **Chrome**](https://chrome.google.com/webstore/detail/hoppscotch-extension-for-c/amknoiejhlmhancpahfcfcfhllgkpbld)
> **Extensions fix `CORS` issues.**
_Add-ons are developed and maintained under **[Hoppscotch Organization](https://github.com/hoppscotch)**._
**For a complete list of features, please read our [documentation](https://docs.hoppscotch.io).**
## **Demo**
- Web : [hoppscotch.io](https://hoppscotch.io)
- Windows/Linux/macOS : [Desktop Apps](https://docs.hoppscotch.io/documentation/clients/desktop#download-hoppscotch-desktop-app)
## Usage
1. Provide your API endpoint in the URL field
2. Click "Send" to simulate the request
3. View the response
## Developing
Follow our [self-hosting documentation](https://docs.hoppscotch.io/documentation/self-host/getting-started) to get started with the development environment.
## Contributing
Please contribute using [GitHub Flow](https://guides.github.com/introduction/flow). Create a branch, add commits, and [open a pull request](https://github.com/hoppscotch/hoppscotch/compare).
Please read [`CONTRIBUTING`](CONTRIBUTING.md) for details on our [`CODE OF CONDUCT`](CODE_OF_CONDUCT.md), and the process for submitting pull requests to us.
## Continuous Integration
We use [GitHub Actions](https://github.com/features/actions) for continuous integration. Check out our [build workflows](https://github.com/hoppscotch/hoppscotch/actions).
## Changelog
See the [`CHANGELOG`](CHANGELOG.md) file for details.
## Authors
This project owes its existence to the collective efforts of all those who contribute — [contribute now](CONTRIBUTING.md).
<div align="center">
<a href="https://github.com/hoppscotch/hoppscotch/graphs/contributors">
<img src="https://opencollective.com/hoppscotch/contributors.svg?width=840&button=false"
alt="Contributors"
width="100%" />
</a>
</div>
## License
This project is licensed under the [MIT License](https://opensource.org/licenses/MIT) — see the [`LICENSE`](LICENSE) file for details.
[^EE]: Enterprise edition feature. [Learn more](https://docs.hoppscotch.io/documentation/self-host/getting-started).
|
2025-09-24T14:46:58.085215
|
Mintplex-Labs
|
anythingllm-docs
|
Mintplex-Labs__anythingllm-docs
|
README.md
|
Mintplex-Labs__anythingllm-docs/README.md
| 1,723 | 1,758,118,064 |
la
|
<a name="readme-top"></a>
<p align="center">
<a href="https://anythingllm.com"><img src="https://github.com/Mintplex-Labs/anything-llm/blob/master/images/wordmark.png?raw=true" alt="AnythingLLM logo"></a>
</p>
## Project Structure
```
├── public/
│ ├── images/
│ │ ├── anythingllm-setup/
│ │ ├── cloud/
│ │ ├── faq/
│ │ ├── features/
│ │ ├── getting-started/
│ │ ├── guides/
│ │ ├── home/
│ │ ├── legal/
│ │ ├── product/
│ │ └── thumbnails/
│ ├── favicon.png
│ ├── licence.txt
│ └── robots.txt
├── pages/
│ ├── agent/
│ ├── api/
│ ├── changelog/
│ ├── cloud/
│ ├── features/
│ ├── installation/
│ ├── setup/
│ ├── _meta.json
│ └── index.mdx
├── components/
│ └── icons/
├── next-env.d.ts
├── next.config.js
├── package.json
├── pull-request-template.md
├── README.md
├── theme.config.tsx
└── tsconfig.json
```
## Setup for Local Development
1. Clone this Repository to your local machine using git clone:
```sh
git clone https://github.com/Mintplex-Labs/anythingllm-docs.git
```
2. Install dependencies using yarn:
```sh
yarn
```
3. Start the development server:
```sh
yarn dev
```
## Contributing
- Create issue
- Create PR with branch name format of `<issue number>-<short name>`
- yee haw let's merge
## License
This project is licensed under the MIT License.
_special thanks to [@ShadowArcanist](https://github.com/ShadowArcanist) for the migration to NextJS_
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
README.md
|
CherryHQ__cherry-studio/README.md
| 21,328 | 1,758,620,022 |
en
|
<div align="right" >
<details>
<summary >🌐 Language</summary>
<div>
<div align="right">
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=en">English</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=zh-CN">简体中文</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=zh-TW">繁體中文</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ja">日本語</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ko">한국어</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=hi">हिन्दी</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=th">ไทย</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=fr">Français</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=de">Deutsch</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=es">Español</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=it">Italiano</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ru">Русский</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=pt">Português</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=nl">Nederlands</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=pl">Polski</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ar">العربية</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=fa">فارسی</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=tr">Türkçe</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=vi">Tiếng Việt</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=id">Bahasa Indonesia</a></p>
</div>
</div>
</details>
</div>
<h1 align="center">
<a href="https://github.com/CherryHQ/cherry-studio/releases">
<img src="https://github.com/CherryHQ/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" /><br>
</a>
</h1>
<p align="center">English | <a href="./docs/README.zh.md">中文</a> | <a href="https://cherry-ai.com">Official Site</a> | <a href="https://docs.cherry-ai.com/cherry-studio-wen-dang/en-us">Documents</a> | <a href="./docs/dev.md">Development</a> | <a href="https://github.com/CherryHQ/cherry-studio/issues">Feedback</a><br></p>
<div align="center">
[![][deepwiki-shield]][deepwiki-link]
[![][twitter-shield]][twitter-link]
[![][discord-shield]][discord-link]
[![][telegram-shield]][telegram-link]
</div>
<div align="center">
[![][github-release-shield]][github-release-link]
[![][github-nightly-shield]][github-nightly-link]
[![][github-contributors-shield]][github-contributors-link]
[![][license-shield]][license-link]
[![][commercial-shield]][commercial-link]
[![][sponsor-shield]][sponsor-link]
</div>
<div align="center">
<a href="https://hellogithub.com/repository/1605492e1e2a4df3be07abfa4578dd37" target="_blank" style="text-decoration: none"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=1605492e1e2a4df3be07abfa4578dd37" alt="Featured|HelloGitHub" width="220" height="55" /></a>
<a href="https://trendshift.io/repositories/14318" target="_blank" style="text-decoration: none"><img src="https://trendshift.io/api/badge/repositories/14318" alt="CherryHQ%2Fcherry-studio | Trendshift" width="220" height="55" /></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry-studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry Studio - AI Chatbots, AI Desktop Client | Product Hunt" width="220" height="55" /></a>
</div>
# 🍒 Cherry Studio
Cherry Studio is a desktop client that supports multiple LLM providers, available on Windows, Mac and Linux.
👏 Join [Telegram Group](https://t.me/CherryStudioAI)|[Discord](https://discord.gg/wez8HtpxqQ) | [QQ Group(575014769)](https://qm.qq.com/q/lo0D4qVZKi)
❤️ Like Cherry Studio? Give it a star 🌟 or [Sponsor](docs/sponsor.md) to support the development!
# 🌠 Screenshot



# 🌟 Key Features
1. **Diverse LLM Provider Support**:
- ☁️ Major LLM Cloud Services: OpenAI, Gemini, Anthropic, and more
- 🔗 AI Web Service Integration: Claude, Perplexity, Poe, and others
- 💻 Local Model Support with Ollama, LM Studio
2. **AI Assistants & Conversations**:
- 📚 300+ Pre-configured AI Assistants
- 🤖 Custom Assistant Creation
- 💬 Multi-model Simultaneous Conversations
3. **Document & Data Processing**:
- 📄 Supports Text, Images, Office, PDF, and more
- ☁️ WebDAV File Management and Backup
- 📊 Mermaid Chart Visualization
- 💻 Code Syntax Highlighting
4. **Practical Tools Integration**:
- 🔍 Global Search Functionality
- 📝 Topic Management System
- 🔤 AI-powered Translation
- 🎯 Drag-and-drop Sorting
- 🔌 Mini Program Support
- ⚙️ MCP(Model Context Protocol) Server
5. **Enhanced User Experience**:
- 🖥️ Cross-platform Support for Windows, Mac, and Linux
- 📦 Ready to Use - No Environment Setup Required
- 🎨 Light/Dark Themes and Transparent Window
- 📝 Complete Markdown Rendering
- 🤲 Easy Content Sharing
# 📝 Roadmap
We're actively working on the following features and improvements:
1. 🎯 **Core Features**
- Selection Assistant with smart content selection enhancement
- Deep Research with advanced research capabilities
- Memory System with global context awareness
- Document Preprocessing with improved document handling
- MCP Marketplace for Model Context Protocol ecosystem
2. 🗂 **Knowledge Management**
- Notes and Collections
- Dynamic Canvas visualization
- OCR capabilities
- TTS (Text-to-Speech) support
3. 📱 **Platform Support**
- HarmonyOS Edition (PC)
- Android App (Phase 1)
- iOS App (Phase 1)
- Multi-Window support
- Window Pinning functionality
4. 🔌 **Advanced Features**
- Plugin System
- ASR (Automatic Speech Recognition)
- Assistant and Topic Interaction Refactoring
Track our progress and contribute on our [project board](https://github.com/orgs/CherryHQ/projects/7).
Want to influence our roadmap? Join our [GitHub Discussions](https://github.com/CherryHQ/cherry-studio/discussions) to share your ideas and feedback!
# 🌈 Theme
- Theme Gallery: <https://cherrycss.com>
- Aero Theme: <https://github.com/hakadao/CherryStudio-Aero>
- PaperMaterial Theme: <https://github.com/rainoffallingstar/CherryStudio-PaperMaterial>
- Claude dynamic-style: <https://github.com/bjl101501/CherryStudio-Claudestyle-dynamic>
- Maple Neon Theme: <https://github.com/BoningtonChen/CherryStudio_themes>
Welcome PR for more themes
# 🤝 Contributing
We welcome contributions to Cherry Studio! Here are some ways you can contribute:
1. **Contribute Code**: Develop new features or optimize existing code.
2. **Fix Bugs**: Submit fixes for any bugs you find.
3. **Maintain Issues**: Help manage GitHub issues.
4. **Product Design**: Participate in design discussions.
5. **Write Documentation**: Improve user manuals and guides.
6. **Community Engagement**: Join discussions and help users.
7. **Promote Usage**: Spread the word about Cherry Studio.
Refer to the [Branching Strategy](docs/branching-strategy-en.md) for contribution guidelines
## Getting Started
1. **Fork the Repository**: Fork and clone it to your local machine.
2. **Create a Branch**: For your changes.
3. **Submit Changes**: Commit and push your changes.
4. **Open a Pull Request**: Describe your changes and reasons.
For more detailed guidelines, please refer to our [Contributing Guide](CONTRIBUTING.md).
Thank you for your support and contributions!
# 🔧 Developer Co-creation Program
We are launching the Cherry Studio Developer Co-creation Program to foster a healthy and positive-feedback loop within the open-source ecosystem. We believe that great software is built collaboratively, and every merged pull request breathes new life into the project.
We sincerely invite you to join our ranks of contributors and shape the future of Cherry Studio with us.
## Contributor Rewards Program
To give back to our core contributors and create a virtuous cycle, we have established the following long-term incentive plan.
**The inaugural tracking period for this program will be Q3 2025 (July, August, September). Rewards for this cycle will be distributed on October 1st.**
Within any tracking period (e.g., July 1st to September 30th for the first cycle), any developer who contributes more than **30 meaningful commits** to any of Cherry Studio's open-source projects on GitHub will be eligible for the following benefits:
- **Cursor Subscription Sponsorship**: Receive a **$70 USD** credit or reimbursement for your [Cursor](https://cursor.sh/) subscription, making AI your most efficient coding partner.
- **Unlimited Model Access**: Get **unlimited** API calls for the **DeepSeek** and **Qwen** models.
- **Cutting-Edge Tech Access**: Enjoy occasional perks, including API access to models like **Claude**, **Gemini**, and **OpenAI**, keeping you at the forefront of technology.
## Growing Together & Future Plans
A vibrant community is the driving force behind any sustainable open-source project. As Cherry Studio grows, so will our rewards program. We are committed to continuously aligning our benefits with the best-in-class tools and resources in the industry. This ensures our core contributors receive meaningful support, creating a positive cycle where developers, the community, and the project grow together.
**Moving forward, the project will also embrace an increasingly open stance to give back to the entire open-source community.**
## How to Get Started?
We look forward to your first Pull Request!
You can start by exploring our repositories, picking up a `good first issue`, or proposing your own enhancements. Every commit is a testament to the spirit of open source.
Thank you for your interest and contributions.
Let's build together.
# 🏢 Enterprise Edition
Building on the Community Edition, we are proud to introduce **Cherry Studio Enterprise Edition**—a privately-deployable AI productivity and management platform designed for modern teams and enterprises.
The Enterprise Edition addresses core challenges in team collaboration by centralizing the management of AI resources, knowledge, and data. It empowers organizations to enhance efficiency, foster innovation, and ensure compliance, all while maintaining 100% control over their data in a secure environment.
## Core Advantages
- **Unified Model Management**: Centrally integrate and manage various cloud-based LLMs (e.g., OpenAI, Anthropic, Google Gemini) and locally deployed private models. Employees can use them out-of-the-box without individual configuration.
- **Enterprise-Grade Knowledge Base**: Build, manage, and share team-wide knowledge bases. Ensures knowledge retention and consistency, enabling team members to interact with AI based on unified and accurate information.
- **Fine-Grained Access Control**: Easily manage employee accounts and assign role-based permissions for different models, knowledge bases, and features through a unified admin backend.
- **Fully Private Deployment**: Deploy the entire backend service on your on-premises servers or private cloud, ensuring your data remains 100% private and under your control to meet the strictest security and compliance standards.
- **Reliable Backend Services**: Provides stable API services and enterprise-grade data backup and recovery mechanisms to ensure business continuity.
## ✨ Online Demo
> 🚧 **Public Beta Notice**
>
> The Enterprise Edition is currently in its early public beta stage, and we are actively iterating and optimizing its features. We are aware that it may not be perfectly stable yet. If you encounter any issues or have valuable suggestions during your trial, we would be very grateful if you could contact us via email to provide feedback.
**🔗 [Cherry Studio Enterprise](https://www.cherry-ai.com/enterprise)**
## Version Comparison
| Feature | Community Edition | Enterprise Edition |
| :---------------- | :----------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- |
| **Open Source** | ✅ Yes | ⭕️ Partially released to customers |
| **Cost** | Free for Personal Use / Commercial License | Buyout / Subscription Fee |
| **Admin Backend** | — | ● Centralized **Model** Access<br>● **Employee** Management<br>● Shared **Knowledge Base**<br>● **Access** Control<br>● **Data** Backup |
| **Server** | — | ✅ Dedicated Private Deployment |
## Get the Enterprise Edition
We believe the Enterprise Edition will become your team's AI productivity engine. If you are interested in Cherry Studio Enterprise Edition and would like to learn more, request a quote, or schedule a demo, please feel free to contact us.
- **For Business Inquiries & Purchasing**:
**📧 [[email protected]](mailto:[email protected])**
# 🔗 Related Projects
- [one-api](https://github.com/songquanpeng/one-api): LLM API management and distribution system supporting mainstream models like OpenAI, Azure, and Anthropic. Features a unified API interface, suitable for key management and secondary distribution.
- [ublacklist](https://github.com/iorate/ublacklist): Blocks specific sites from appearing in Google search results
# 🚀 Contributors
<a href="https://github.com/CherryHQ/cherry-studio/graphs/contributors">
<img src="https://contrib.rocks/image?repo=CherryHQ/cherry-studio" />
</a>
<br /><br />
# 📊 GitHub Stats

# ⭐️ Star History
<a href="https://www.star-history.com/#CherryHQ/cherry-studio&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Date" />
</picture>
</a>
<!-- Links & Images -->
[deepwiki-shield]: https://img.shields.io/badge/Deepwiki-CherryHQ-0088CC?logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNy45MyAzMiI+PHBhdGggZD0iTTE5LjMzIDE0LjEyYy42Ny0uMzkgMS41LS4zOSAyLjE4IDBsMS43NCAxYy4wNi4wMy4xMS4wNi4xOC4wN2guMDRjLjA2LjAzLjEyLjAzLjE4LjAzaC4wMmMuMDYgMCAuMTEgMCAuMTctLjAyaC4wM2MuMDYtLjAyLjEyLS4wNS4xNy0uMDhoLjAybDMuNDgtMi4wMWMuMjUtLjE0LjQtLjQxLjQtLjdWOC40YS44MS44MSAwIDAgMC0uNC0uN2wtMy40OC0yLjAxYS44My44MyAwIDAgMC0uODEgMEwxOS43NyA3LjdoLS4wMWwtLjE1LjEyLS4wMi4wMnMtLjA3LjA5LS4xLjE0VjhhLjQuNCAwIDAgMC0uMDguMTd2LjA0Yy0uMDMuMDYtLjAzLjEyLS4wMy4xOXYyLjAxYzAgLjc4LS40MSAxLjQ5LTEuMDkgMS44OC0uNjcuMzktMS41LjM5LTIuMTggMGwtMS43NC0xYS42LjYgMCAwIDAtLjIxLS4wOGMtLjA2LS4wMS0uMTItLjAyLS4xOC0uMDJoLS4wM2MtLjA2IDAtLjExLjAxLS4xNy4wMmgtLjAzYy0uMDYuMDItLjEyLjA0LS4xNy4wN2gtLjAybC0zLjQ3IDIuMDFjLS4yNS4xNC0uNC40MS0uNC43VjE4YzAgLjI5LjE1LjU1LjQuN2wzLjQ4IDIuMDFoLjAyYy4wNi4wNC4xMS4wNi4xNy4wOGguMDNjLjA1LjAyLjExLjAzLjE3LjAzaC4wMmMuMDYgMCAuMTIgMCAuMTgtLjAyaC4wNGMuMDYtLjAzLjEyLS4wNS4xOC0uMDhsMS43NC0xYy42Ny0uMzkgMS41LS4zOSAyLjE3IDBzMS4wOSAxLjExIDEuMDkgMS44OHYyLjAxYzAgLjA3IDAgLjEzLjAyLjE5di4wNGMuMDMuMDYuMDUuMTIuMDguMTd2LjAycy4wOC4wOS4xMi4xM2wuMDIuMDJzLjA5LjA4LjE1LjExYzAgMCAuMDEgMCAuMDEuMDFsMy40OCAyLjAxYy4yNS4xNC41Ni4xNC44MSAwbDMuNDgtMi4wMWMuMjUtLjE0LjQtLjQxLjQtLjd2LTQuMDFhLjgxLjgxIDAgMCAwLS40LS43bC0zLjQ4LTIuMDFoLS4wMmMtLjA1LS4wNC0uMTEtLjA2LS4xNy0uMDhoLS4wM2EuNS41IDAgMCAwLS4xNy0uMDNoLS4wM2MtLjA2IDAtLjEyIDAtLjE4LjAyLS4wNy4wMi0uMTUuMDUtLjIxLjA4bC0xLjc0IDFjLS42Ny4zOS0xLjUuMzktMi4xNyAwYTIuMTkgMi4xOSAwIDAgMS0xLjA5LTEuODhjMC0uNzguNDItMS40OSAxLjA5LTEuODhaIiBzdHlsZT0iZmlsbDojNWRiZjlkIi8+PHBhdGggZD0ibS40IDEzLjExIDMuNDcgMi4wMWMuMjUuMTQuNTYuMTQuOCAwbDMuNDctMi4wMWguMDFsLjE1LS4xMi4wMi0uMDJzLjA3LS4wOS4xLS4xNGwuMDItLjAyYy4wMy0uMDUuMDUtLjExLjA3LS4xN3YtLjA0Yy4wMy0uMDYuMDMtLjEyLjAzLS4xOVYxMC40YzAtLjc4LjQyLTEuNDkgMS4wOS0xLjg4czEuNS0uMzkgMi4xOCAwbDEuNzQgMWMuMDcuMDQuMTQuMDcuMjEuMDguMDYuMDEuMTIuMDIuMTguMDJoLjAzYy4wNiAwIC4xMS0uMDEuMTctLjAyaC4wM2MuMDYtLjAyLjEyLS4wNC4xNy0uMDdoLjAybDMuNDctMi4wMmMuMjUtLjE0LjQtLjQxLjQtLjd2LTRhLjgxLjgxIDAgMCAwLS40LS43bC0zLjQ2LTJhLjgzLjgzIDAgMCAwLS44MSAwbC0zLjQ4IDIuMDFoLS4wMWwtLjE1LjEyLS4wMi4wMi0uMS4xMy0uMDIuMDJjLS4wMy4wNS0uMDUuMTEtLjA3LjE3di4wNGMtLjAzLjA2LS4wMy4xMi0uMDMuMTl2Mi4wMWMwIC43OC0uNDIgMS40OS0xLjA5IDEuODhzLTEuNS4zOS0yLjE4IDBsLTEuNzQtMWEuNi42IDAgMCAwLS4yMS0uMDhjLS4wNi0uMDEtLjEyLS4wMi0uMTgtLjAyaC0uMDNjLS4wNiAwLS4xMS4wMS0uMTcuMDJoLS4wM2MtLjA2LjAyLS4xMi4wNS0uMTcuMDhoLS4wMkwuNCA3LjcxYy0uMjUuMTQtLjQuNDEtLjQuNjl2NC4wMWMwIC4yOS4xNS41Ni40LjciIHN0eWxlPSJmaWxsOiM0NDY4YzQiLz48cGF0aCBkPSJtMTcuODQgMjQuNDgtMy40OC0yLjAxaC0uMDJjLS4wNS0uMDQtLjExLS4wNi0uMTctLjA4aC0uMDNhLjUuNSAwIDAgMC0uMTctLjAzaC0uMDNjLS4wNiAwLS4xMiAwLS4xOC4wMmgtLjA0Yy0uMDYuMDMtLjEyLjA1LS4xOC4wOGwtMS43NCAxYy0uNjcuMzktMS41LjM5LTIuMTggMGEyLjE5IDIuMTkgMCAwIDEtMS4wOS0xLjg4di0yLjAxYzAtLjA2IDAtLjEzLS4wMi0uMTl2LS4wNGMtLjAzLS4wNi0uMDUtLjExLS4wOC0uMTdsLS4wMi0uMDJzLS4wNi0uMDktLjEtLjEzTDguMjkgMTlzLS4wOS0uMDgtLjE1LS4xMWgtLjAxbC0zLjQ3LTIuMDJhLjgzLjgzIDAgMCAwLS44MSAwTC4zNyAxOC44OGEuODcuODcgMCAwIDAtLjM3LjcxdjQuMDFjMCAuMjkuMTUuNTUuNC43bDMuNDcgMi4wMWguMDJjLjA1LjA0LjExLjA2LjE3LjA4aC4wM2MuMDUuMDIuMTEuMDMuMTYuMDNoLjAzYy4wNiAwIC4xMiAwIC4xOC0uMDJoLjA0Yy4wNi0uMDMuMTItLjA1LjE4LS4wOGwxLjc0LTFjLjY3LS4zOSAxLjUtLjM5IDIuMTcgMHMxLjA5IDEuMTEgMS4wOSAxLjg4djIuMDFjMCAuMDcgMCAuMTMuMDIuMTl2LjA0Yy4wMy4wNi4wNS4xMS4wOC4xN2wuMDIuMDJzLjA2LjA5LjEuMTRsLjAyLjAycy4wOS4wOC4xNS4xMWguMDFsMy40OCAyLjAyYy4yNS4xNC41Ni4xNC44MSAwbDMuNDgtMi4wMWMuMjUtLjE0LjQtLjQxLjQtLjdWMjUuMmEuODEuODEgMCAwIDAtLjQtLjdaIiBzdHlsZT0iZmlsbDojNDI5M2Q5Ii8+PC9zdmc+
[deepwiki-link]: https://deepwiki.com/CherryHQ/cherry-studio
[twitter-shield]: https://img.shields.io/badge/Twitter-CherryStudioApp-0088CC?logo=x
[twitter-link]: https://twitter.com/CherryStudioHQ
[discord-shield]: https://img.shields.io/badge/Discord-@CherryStudio-0088CC?logo=discord
[discord-link]: https://discord.gg/wez8HtpxqQ
[telegram-shield]: https://img.shields.io/badge/Telegram-@CherryStudioAI-0088CC?logo=telegram
[telegram-link]: https://t.me/CherryStudioAI
<!-- Links & Images -->
[github-release-shield]: https://img.shields.io/github/v/release/CherryHQ/cherry-studio?logo=github
[github-release-link]: https://github.com/CherryHQ/cherry-studio/releases
[github-nightly-shield]: https://img.shields.io/github/actions/workflow/status/CherryHQ/cherry-studio/nightly-build.yml?label=nightly%20build&logo=github
[github-nightly-link]: https://github.com/CherryHQ/cherry-studio/actions/workflows/nightly-build.yml
[github-contributors-shield]: https://img.shields.io/github/contributors/CherryHQ/cherry-studio?logo=github
[github-contributors-link]: https://github.com/CherryHQ/cherry-studio/graphs/contributors
<!-- Links & Images -->
[license-shield]: https://img.shields.io/badge/License-AGPLv3-important.svg?logo=gnu
[license-link]: https://www.gnu.org/licenses/agpl-3.0
[commercial-shield]: https://img.shields.io/badge/License-Contact-white.svg?logoColor=white&logo=telegram&color=blue
[commercial-link]: mailto:[email protected]?subject=Commercial%20License%20Inquiry
[sponsor-shield]: https://img.shields.io/badge/Sponsor-FF6699.svg?logo=githubsponsors&logoColor=white
[sponsor-link]: https://github.com/CherryHQ/cherry-studio/blob/main/docs/sponsor.md
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/README.zh.md
|
CherryHQ__cherry-studio/docs/README.zh.md
| 16,221 | 1,758,202,168 |
en
|
<div align="right" >
<details>
<summary >🌐 Language</summary>
<div>
<div align="right">
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=en">English</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=zh-CN">简体中文</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=zh-TW">繁體中文</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ja">日本語</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ko">한국어</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=hi">हिन्दी</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=th">ไทย</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=fr">Français</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=de">Deutsch</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=es">Español</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=it">Italiano</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ru">Русский</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=pt">Português</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=nl">Nederlands</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=pl">Polski</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=ar">العربية</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=fa">فارسی</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=tr">Türkçe</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=vi">Tiếng Việt</a></p>
<p><a href="https://openaitx.github.io/view.html?user=CherryHQ&project=cherry-studio&lang=id">Bahasa Indonesia</a></p>
</div>
</div>
</details>
</div>
<h1 align="center">
<a href="https://github.com/CherryHQ/cherry-studio/releases">
<img src="https://github.com/CherryHQ/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" /><br>
</a>
</h1>
<p align="center">
<a href="https://github.com/CherryHQ/cherry-studio">English</a> | 中文 | <a href="https://cherry-ai.com">官方网站</a> | <a href="https://docs.cherry-ai.com/cherry-studio-wen-dang/zh-cn">文档</a> | <a href="./dev.md">开发</a> | <a href="https://github.com/CherryHQ/cherry-studio/issues">反馈</a><br>
</p>
<!-- 题头徽章组合 -->
<div align="center">
[![][deepwiki-shield]][deepwiki-link]
[![][twitter-shield]][twitter-link]
[![][discord-shield]][discord-link]
[![][telegram-shield]][telegram-link]
</div>
<div align="center">
[![][github-release-shield]][github-release-link]
[![][github-contributors-shield]][github-contributors-link]
[![][license-shield]][license-link]
[![][commercial-shield]][commercial-link]
[![][sponsor-shield]][sponsor-link]
</div>
<div align="center">
<a href="https://hellogithub.com/repository/1605492e1e2a4df3be07abfa4578dd37" target="_blank" style="text-decoration: none"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=1605492e1e2a4df3be07abfa4578dd37" alt="Featured|HelloGitHub" width="220" height="55" /></a>
<a href="https://trendshift.io/repositories/11772" target="_blank" style="text-decoration: none"><img src="https://trendshift.io/api/badge/repositories/11772" alt="kangfenmao%2Fcherry-studio | Trendshift" width="220" height="55" /></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry-studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry Studio - AI Chatbots, AI Desktop Client | Product Hunt" width="220" height="55" /></a>
</div>
# 🍒 Cherry Studio
Cherry Studio 是一款支持多个大语言模型(LLM)服务商的桌面客户端,兼容 Windows、Mac 和 Linux 系统。
👏 欢迎加入 [Telegram 群组](https://t.me/CherryStudioAI)|[Discord](https://discord.gg/wez8HtpxqQ) | [QQ群(575014769)](https://qm.qq.com/q/lo0D4qVZKi)
❤️ 喜欢 Cherry Studio? 点亮小星星 🌟 或 [赞助开发者](sponsor.md)! ❤️
# 📖 使用教程
https://docs.cherry-ai.com
# 🌠 界面



# 🌟 主要特性
1. **多样化 LLM 服务支持**:
- ☁️ 支持主流 LLM 云服务:OpenAI、Gemini、Anthropic、硅基流动等
- 🔗 集成流行 AI Web 服务:Claude、Perplexity、Poe、腾讯元宝、知乎直答等
- 💻 支持 Ollama、LM Studio 本地模型部署
2. **智能助手与对话**:
- 📚 内置 300+ 预配置 AI 助手
- 🤖 支持自定义创建专属助手
- 💬 多模型同时对话,获得多样化观点
3. **文档与数据处理**:
- 📄 支持文本、图片、Office、PDF 等多种格式
- ☁️ WebDAV 文件管理与数据备份
- 📊 Mermaid 图表可视化
- 💻 代码高亮显示
4. **实用工具集成**:
- 🔍 全局搜索功能
- 📝 话题管理系统
- 🔤 AI 驱动的翻译功能
- 🎯 拖拽排序
- 🔌 小程序支持
- ⚙️ MCP(模型上下文协议) 服务
5. **优质使用体验**:
- 🖥️ Windows、Mac、Linux 跨平台支持
- 📦 开箱即用,无需配置环境
- 🎨 支持明暗主题与透明窗口
- 📝 完整的 Markdown 渲染
- 🤲 便捷的内容分享功能
# 📝 开发计划
我们正在积极开发以下功能和改进:
1. 🎯 **核心功能**
- 选择助手 - 智能内容选择增强
- 深度研究 - 高级研究能力
- 全局记忆 - 全局上下文感知
- 文档预处理 - 改进文档处理能力
- MCP 市场 - 模型上下文协议生态系统
2. 🗂 **知识管理**
- 笔记与收藏功能
- 动态画布可视化
- OCR 光学字符识别
- TTS 文本转语音支持
3. 📱 **平台支持**
- 鸿蒙版本 (PC)
- Android 应用(第一期)
- iOS 应用(第一期)
- 多窗口支持
- 窗口置顶功能
4. 🔌 **高级特性**
- 插件系统
- ASR 语音识别
- 助手与话题交互重构
在我们的[项目面板](https://github.com/orgs/CherryHQ/projects/7)上跟踪进展并参与贡献。
想要影响开发计划?欢迎加入我们的 [GitHub 讨论区](https://github.com/CherryHQ/cherry-studio/discussions) 分享您的想法和反馈!
# 🌈 主题
- 主题库:https://cherrycss.com
- Aero 主题:https://github.com/hakadao/CherryStudio-Aero
- PaperMaterial 主题:https://github.com/rainoffallingstar/CherryStudio-PaperMaterial
- 仿 Claude 主题:https://github.com/bjl101501/CherryStudio-Claudestyle-dynamic
- 霓虹枫叶主题:https://github.com/BoningtonChen/CherryStudio_themes
欢迎 PR 更多主题
# 🤝 贡献
我们欢迎对 Cherry Studio 的贡献!您可以通过以下方式贡献:
1. **贡献代码**:开发新功能或优化现有代码
2. **修复错误**:提交您发现的错误修复
3. **维护问题**:帮助管理 GitHub 问题
4. **产品设计**:参与设计讨论
5. **撰写文档**:改进用户手册和指南
6. **社区参与**:加入讨论并帮助用户
7. **推广使用**:宣传 Cherry Studio
参考[分支策略](branching-strategy-zh.md)了解贡献指南
## 入门
1. **Fork 仓库**:Fork 并克隆到您的本地机器
2. **创建分支**:为您的更改创建分支
3. **提交更改**:提交并推送您的更改
4. **打开 Pull Request**:描述您的更改和原因
有关更详细的指南,请参阅我们的 [贡献指南](CONTRIBUTING.zh.md)
感谢您的支持和贡献!
# 🔧 开发者共创计划
我们正在启动 Cherry Studio 开发者共创计划,旨在为开源生态系统构建一个健康、正向反馈的循环。我们相信,优秀的软件是通过协作构建的,每一个合并的拉取请求都为项目注入新的生命力。
我们诚挚地邀请您加入我们的贡献者队伍,与我们一起塑造 Cherry Studio 的未来。
## 贡献者奖励计划
为了回馈我们的核心贡献者并创造良性循环,我们建立了以下长期激励计划。
**该计划的首个跟踪周期将是 2025 年第三季度(7月、8月、9月)。此周期的奖励将在 10月1日 发放。**
在任何跟踪周期内(例如,首个周期的 7月1日 至 9月30日),任何为 Cherry Studio 在 GitHub 上的开源项目贡献超过 **30 个有意义提交** 的开发者都有资格获得以下福利:
- **Cursor 订阅赞助**:获得 **70 美元** 的 [Cursor](https://cursor.sh/) 订阅积分或报销,让 AI 成为您最高效的编码伙伴。
- **无限模型访问**:获得 **DeepSeek** 和 **Qwen** 模型的 **无限次** API 调用。
- **前沿技术访问**:享受偶尔的特殊福利,包括 **Claude**、**Gemini** 和 **OpenAI** 等模型的 API 访问权限,让您始终站在技术前沿。
## 共同成长与未来规划
活跃的社区是任何可持续开源项目背后的推动力。随着 Cherry Studio 的发展,我们的奖励计划也将随之发展。我们致力于持续将我们的福利与行业内最优秀的工具和资源保持一致。这确保我们的核心贡献者获得有意义的支持,创造一个开发者、社区和项目共同成长的正向循环。
**展望未来,该项目还将采取越来越开放的态度来回馈整个开源社区。**
## 如何开始?
我们期待您的第一个拉取请求!
您可以从探索我们的仓库开始,选择一个 `good first issue`,或者提出您自己的改进建议。每一个提交都是开源精神的体现。
感谢您的关注和贡献。
让我们一起建设。
# 🏢 企业版
在社区版的基础上,我们自豪地推出 **Cherry Studio 企业版**——一个为现代团队和企业设计的私有部署 AI 生产力与管理平台。
企业版通过集中管理 AI 资源、知识和数据,解决了团队协作中的核心挑战。它赋能组织提升效率、促进创新并确保合规,同时在安全环境中保持对数据的 100% 控制。
## 核心优势
- **统一模型管理**:集中整合和管理各种基于云的大语言模型(如 OpenAI、Anthropic、Google Gemini)和本地部署的私有模型。员工可以开箱即用,无需单独配置。
- **企业级知识库**:构建、管理和分享全团队的知识库。确保知识得到保留且一致,使团队成员能够基于统一准确的信息与 AI 交互。
- **细粒度访问控制**:通过统一的管理后台轻松管理员工账户,并为不同模型、知识库和功能分配基于角色的权限。
- **完全私有部署**:在您的本地服务器或私有云上部署整个后端服务,确保您的数据 100% 私有且在您的控制之下,满足最严格的安全和合规标准。
- **可靠的后端服务**:提供稳定的 API 服务、企业级数据备份和恢复机制,确保业务连续性。
## ✨ 在线演示
> 🚧 **公开测试版通知**
>
> 企业版目前处于早期公开测试阶段,我们正在积极迭代和优化其功能。我们知道它可能还不够完全稳定。如果您在试用过程中遇到任何问题或有宝贵建议,我们非常感谢您能通过邮件联系我们提供反馈。
**🔗 [Cherry Studio 企业版](https://www.cherry-ai.com/enterprise)**
## 版本对比
| 功能 | 社区版 | 企业版 |
| :----------- | :---------------------- | :--------------------------------------------------------------------------------------------- |
| **开源** | ✅ 是 | ⭕️ 部分开源,对客户开放 |
| **成本** | 个人使用免费 / 商业授权 | 买断 / 订阅费用 |
| **管理后台** | — | ● 集中化**模型**访问<br>● **员工**管理<br>● 共享**知识库**<br>● **访问**控制<br>● **数据**备份 |
| **服务器** | — | ✅ 专用私有部署 |
## 获取企业版
我们相信企业版将成为您团队的 AI 生产力引擎。如果您对 Cherry Studio 企业版感兴趣,希望了解更多信息、请求报价或安排演示,请联系我们。
- **商业咨询与购买**:
**📧 [[email protected]](mailto:[email protected])**
# 🔗 相关项目
- [one-api](https://github.com/songquanpeng/one-api):LLM API 管理及分发系统,支持 OpenAI、Azure、Anthropic 等主流模型,统一 API 接口,可用于密钥管理与二次分发。
- [ublacklist](https://github.com/iorate/ublacklist):屏蔽特定网站在 Google 搜索结果中显示
# 🚀 贡献者
<a href="https://github.com/CherryHQ/cherry-studio/graphs/contributors">
<img src="https://contrib.rocks/image?repo=CherryHQ/cherry-studio" />
</a>
<br /><br />
# 📊 GitHub 统计

# ⭐️ Star 记录
<a href="https://www.star-history.com/#CherryHQ/cherry-studio&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Date" />
</picture>
</a>
<!-- Links & Images -->
[deepwiki-shield]: https://img.shields.io/badge/Deepwiki-CherryHQ-0088CC
[deepwiki-link]: https://deepwiki.com/CherryHQ/cherry-studio
[twitter-shield]: https://img.shields.io/badge/Twitter-CherryStudioApp-0088CC?logo=x
[twitter-link]: https://twitter.com/CherryStudioHQ
[discord-shield]: https://img.shields.io/badge/Discord-@CherryStudio-0088CC?logo=discord
[discord-link]: https://discord.gg/wez8HtpxqQ
[telegram-shield]: https://img.shields.io/badge/Telegram-@CherryStudioAI-0088CC?logo=telegram
[telegram-link]: https://t.me/CherryStudioAI
<!-- 项目统计徽章 -->
[github-release-shield]: https://img.shields.io/github/v/release/CherryHQ/cherry-studio
[github-release-link]: https://github.com/CherryHQ/cherry-studio/releases
[github-contributors-shield]: https://img.shields.io/github/contributors/CherryHQ/cherry-studio
[github-contributors-link]: https://github.com/CherryHQ/cherry-studio/graphs/contributors
<!-- 许可和赞助徽章 -->
[license-shield]: https://img.shields.io/badge/License-AGPLv3-important.svg?logo=gnu
[license-link]: https://www.gnu.org/licenses/agpl-3.0
[commercial-shield]: https://img.shields.io/badge/商用授权-联系-white.svg?logoColor=white&logo=telegram&color=blue
[commercial-link]: mailto:[email protected]?subject=商业授权咨询
[sponsor-shield]: https://img.shields.io/badge/赞助支持-FF6699.svg?logo=githubsponsors&logoColor=white
[sponsor-link]: https://github.com/CherryHQ/cherry-studio/blob/main/docs/sponsor.md
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/branching-strategy-zh.md
|
CherryHQ__cherry-studio/docs/branching-strategy-zh.md
| 2,362 | 1,758,202,168 |
en
|
# 🌿 分支策略
Cherry Studio 采用结构化的分支策略来维护代码质量并简化开发流程。
## 主要分支
- `main`:主开发分支
- 包含最新的开发代码
- 禁止直接提交 - 所有更改必须通过拉取请求(Pull Request)
- 此分支上的代码可能包含正在开发的功能,不一定完全稳定
- `release/*`:发布分支
- 从 `main` 分支创建
- 包含准备发布的稳定代码
- 只接受文档更新和 bug 修复
- 经过完整测试后可以发布到生产环境
关于测试计划所使用的`testplan`分支,请查阅[测试计划](testplan-zh.md)。
## 贡献分支
在为 Cherry Studio 贡献代码时,请遵循以下准则:
1. **功能开发分支:**
- 从 `main` 分支创建
- 命名格式:`feature/issue-number-brief-description`
- 完成后提交 PR 到 `main` 分支
2. **Bug 修复分支:**
- 从 `main` 分支创建
- 命名格式:`fix/issue-number-brief-description`
- 完成后提交 PR 到 `main` 分支
3. **文档更新分支:**
- 从 `main` 分支创建
- 命名格式:`docs/brief-description`
- 完成后提交 PR 到 `main` 分支
4. **紧急修复分支:**
- 从 `main` 分支创建
- 命名格式:`hotfix/issue-number-brief-description`
- 完成后需要同时合并到 `main` 和相关的 `release` 分支
5. **发布分支:**
- 从 `main` 分支创建
- 命名格式:`release/version-number`
- 用于版本发布前的最终准备工作
- 只允许合并 bug 修复和文档更新
- 完成测试和准备工作后,将代码合并回 `main` 分支并打上版本标签
## 工作流程

## 拉取请求(PR)指南
- 除非是修复生产环境的关键问题,否则所有 PR 都应该提交到 `main` 分支
- 提交 PR 前确保你的分支已经同步了最新的 `main` 分支内容
- 在 PR 描述中包含相关的 issue 编号
- 确保所有测试通过,且代码符合我们的质量标准
- 如果你添加了新功能或修改了 UI 组件,请附上更改前后的截图
## 版本标签管理
- 主要版本发布:v1.0.0、v2.0.0 等
- 功能更新发布:v1.1.0、v1.2.0 等
- 补丁修复发布:v1.0.1、v1.0.2 等
- 紧急修复发布:v1.0.1-hotfix 等
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/dev.md
|
CherryHQ__cherry-studio/docs/dev.md
| 893 | 1,758,202,168 |
en
|
# 🖥️ Develop
## IDE Setup
- Editor: [Cursor](https://www.cursor.com/), etc. Any VS Code compatible editor.
- Linter: [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
- Formatter: [Biome](https://marketplace.visualstudio.com/items?itemName=biomejs.biome)
## Project Setup
### Install
```bash
yarn
```
### Development
### Setup Node.js
Download and install [Node.js v20.x.x](https://nodejs.org/en/download)
### Setup Yarn
```bash
corepack enable
corepack prepare [email protected] --activate
```
### Install Dependencies
```bash
yarn install
```
### ENV
```bash
copy .env.example .env
```
### Start
```bash
yarn dev
```
### Debug
```bash
yarn debug
```
Then input chrome://inspect in browser
### Test
```bash
yarn test
```
### Build
```bash
# For windows
$ yarn build:win
# For macOS
$ yarn build:mac
# For Linux
$ yarn build:linux
```
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/branching-strategy-en.md
|
CherryHQ__cherry-studio/docs/branching-strategy-en.md
| 2,421 | 1,758,202,168 |
en
|
# 🌿 Branching Strategy
Cherry Studio implements a structured branching strategy to maintain code quality and streamline the development process.
## Main Branches
- `main`: Main development branch
- Contains the latest development code
- Direct commits are not allowed - changes must come through pull requests
- Code may contain features in development and might not be fully stable
- `release/*`: Release branches
- Created from `main` branch
- Contains stable code ready for release
- Only accepts documentation updates and bug fixes
- Thoroughly tested before production deployment
For details about the `testplan` branch used in the Test Plan, please refer to the [Test Plan](testplan-en.md).
## Contributing Branches
When contributing to Cherry Studio, please follow these guidelines:
1. **Feature Branches:**
- Create from `main` branch
- Naming format: `feature/issue-number-brief-description`
- Submit PR back to `main`
2. **Bug Fix Branches:**
- Create from `main` branch
- Naming format: `fix/issue-number-brief-description`
- Submit PR back to `main`
3. **Documentation Branches:**
- Create from `main` branch
- Naming format: `docs/brief-description`
- Submit PR back to `main`
4. **Hotfix Branches:**
- Create from `main` branch
- Naming format: `hotfix/issue-number-brief-description`
- Submit PR to both `main` and relevant `release` branches
5. **Release Branches:**
- Create from `main` branch
- Naming format: `release/version-number`
- Used for final preparation work before version release
- Only accepts bug fixes and documentation updates
- After testing and preparation, merge back to `main` and tag with version
## Workflow Diagram

## Pull Request Guidelines
- All PRs should be submitted to the `main` branch unless fixing a critical production issue
- Ensure your branch is up to date with the latest `main` changes before submitting
- Include relevant issue numbers in your PR description
- Make sure all tests pass and code meets our quality standards
- Add before/after screenshots if you add a new feature or modify a UI component
## Version Tag Management
- Major releases: v1.0.0, v2.0.0, etc.
- Feature releases: v1.1.0, v1.2.0, etc.
- Patch releases: v1.0.1, v1.0.2, etc.
- Hotfix releases: v1.0.1-hotfix, etc.
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/testplan-en.md
|
CherryHQ__cherry-studio/docs/testplan-en.md
| 5,872 | 1,758,202,168 |
en
|
# Test Plan
To provide users with a more stable application experience and faster iteration speed, Cherry Studio has launched the "Test Plan".
## User Guide
The Test Plan is divided into the RC channel and the Beta channel, with the following differences:
- **RC (Release Candidate)**: The features are stable, with fewer bugs, and it is close to the official release.
- **Beta**: Features may change at any time, and there may be more bugs, but users can experience future features earlier.
Users can enable the "Test Plan" and select the version channel in the software's `Settings` > `About`. Please note that the versions in the "Test Plan" cannot guarantee data consistency, so be sure to back up your data before using them.
Users are welcome to submit issues or provide feedback through other channels for any bugs encountered during testing. Your feedback is very important to us.
## Developer Guide
### Participating in the Test Plan
Developers should submit `PRs` according to the [Contributor Guide](../CONTRIBUTING.md) (and ensure the target branch is `main`). The repository maintainers will evaluate whether the `PR` should be included in the Test Plan based on factors such as the impact of the feature on the application, its importance, and whether broader testing is needed.
If the `PR` is added to the Test Plan, the repository maintainers will:
- Notify the `PR` submitter.
- Set the PR to `draft` status (to avoid accidental merging into `main` before testing is complete).
- Set the `milestone` to the specific Test Plan version.
- Modify the `PR` title.
During participation in the Test Plan, `PR` submitters should:
- Keep the `PR` branch synchronized with the latest `main` (i.e., the `PR` branch should always be based on the latest `main` code).
- Ensure the `PR` branch is conflict-free.
- Actively respond to comments & reviews and fix bugs.
- Enable maintainers to modify the `PR` branch to allow for bug fixes at any time.
Inclusion in the Test Plan does not guarantee the final merging of the `PR`. It may be shelved due to immature features or poor testing feedback.
### Test Plan Lead
A maintainer will be assigned as the lead for a specific version (e.g., `1.5.0-rc`). The responsibilities of the Test Plan lead include:
- Determining whether a `PR` meets the Test Plan requirements and deciding whether it should be included in the current Test Plan.
- Modifying the status of `PRs` added to the Test Plan and communicating relevant matters with the `PR` submitter.
- Before the Test Plan release, merging the branches of `PRs` added to the Test Plan (using squash merge) into the corresponding version branch of `testplan` and resolving conflicts.
- Ensuring the `testplan` branch is synchronized with the latest `main`.
- Overseeing the Test Plan release.
## In-Depth Understanding
### About `PRs`
A `PR` is a collection of a specific branch (and commits), comments, reviews, and other information, and it is the **smallest management unit** of the Test Plan.
Compared to submitting all features to a single branch, the Test Plan manages features through `PRs`, which offers greater flexibility and efficiency:
- Features can be added or removed between different versions of the Test Plan without cumbersome `revert` operations.
- Clear feature boundaries and responsibilities are established. Bug fixes are completed within their respective `PRs`, isolating cross-impact and better tracking progress.
- The `PR` submitter is responsible for resolving conflicts with the latest `main`. The Test Plan lead is responsible for resolving conflicts between `PR` branches. However, since features added to the Test Plan are relatively independent (in other words, if a feature has broad implications, it should be independently included in the Test Plan), conflicts are generally few or simple.
### The `testplan` Branch
The `testplan` branch is a **temporary** branch used for Test Plan releases.
Note:
- **Do not develop based on this branch**. It may change or even be deleted at any time, and there is no guarantee of commit completeness or order.
- **Do not submit `commits` or `PRs` to this branch**, as they will not be retained.
- The `testplan` branch is always based on the latest `main` branch (not on a released version), with features added on top.
#### RC Branch
Branch name: `testplan/rc/x.y.z`
Used for RC releases, where `x.y.z` is the target version number. Note that whether it is rc.1 or rc.5, as long as the major version number is `x.y.z`, it is completed in this branch.
Generally, the version number for releases from this branch is named `x.y.z-rc.n`.
#### Beta Branch
Branch name: `testplan/beta/x.y.z`
Used for Beta releases, where `x.y.z` is the target version number. Note that whether it is beta.1 or beta.5, as long as the major version number is `x.y.z`, it is completed in this branch.
Generally, the version number for releases from this branch is named `x.y.z-beta.n`.
### Version Rules
The application version number for the Test Plan is: `x.y.z-CHA.n`, where:
- `x.y.z` is the conventional version number, referred to here as the **target version number**.
- `CHA` is the channel code (Channel), currently divided into `rc` and `beta`.
- `n` is the release number, starting from `1`.
Examples of complete version numbers: `1.5.0-rc.3`, `1.5.1-beta.1`, `1.6.0-beta.6`.
The **target version number** of the Test Plan points to the official version number where these features are expected to be added. For example:
- `1.5.0-rc.3` means this is a preview of the `1.5.0` official release (the current latest official release is `1.4.9`, and `1.5.0` has not yet been officially released).
- `1.5.1-beta.1` means this is a beta version of the `1.5.1` official release (the current latest official release is `1.5.0`, and `1.5.1` has not yet been officially released).
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/testplan-zh.md
|
CherryHQ__cherry-studio/docs/testplan-zh.md
| 4,738 | 1,758,202,168 |
en
|
# 测试计划
为了给用户提供更稳定的应用体验,并提供更快的迭代速度,Cherry Studio推出“测试计划”。
## 用户指南
测试计划分为RC版通道和Beta版通道吗,区别在于:
- **RC版(预览版)**:RC即Release Candidate,功能已经稳定,BUG较少,接近正式版
- **Beta版(测试版)**:功能可能随时变化,BUG较多,可以较早体验未来功能
用户可以在软件的`设置`-`关于`中,开启“测试计划”并选择版本通道。请注意“测试计划”的版本无法保证数据的一致性,请使用前一定要备份数据。
用户在测试过程中发现的BUG,欢迎提交issue或通过其他渠道反馈。用户的反馈对我们非常重要。
## 开发者指南
### 参与测试计划
开发者按照[贡献者指南](CONTRIBUTING.zh.md)要求正常提交`PR`(并注意提交target为`main`)。仓库维护者会综合考虑(例如该功能对应用的影响程度,功能的重要性,是否需要更广泛的测试等),决定该`PR`是否应加入测试计划。
若该`PR`加入测试计划,仓库维护者会做如下操作:
- 通知`PR`提交人
- 设置PR为`draft`状态(避免在测试完成前意外并入`main`)
- `milestone`设置为具体测试计划版本
- 修改`PR`标题
`PR`提交人在参与测试计划过程中,应做到:
- 保持`PR`分支与最新`main`同步(即`PR`分支总是应基于最新`main`代码)
- 保持`PR`分支为无冲突状态
- 积极响应 comments & reviews,修复bug
- 开启维护者可以修改`PR`分支的权限,以便维护者能随时修改BUG
加入测试计划并不保证`PR`的最终合并,也有可能由于功能不成熟或测试反馈不佳而搁置
### 测试计划负责人
某个维护者会被指定为某个版本期间(例如`1.5.0-rc`)的测试计划负责人。测试计划负责人的工作为:
- 判断某个`PR`是否符合测试计划要求,并决定是否应合入当期测试计划
- 修改加入测试计划的`PR`状态,并与`PR`提交人沟通相关事宜
- 在测试计划发版前,将加入测试计划的`PR`分支逐一合并(采用squash merge)至`testplan`对应版本分支,并解决冲突
- 保证`testplan`分支与最新`main`同步
- 负责测试计划发版
## 深入理解
### 关于`PR`
`PR`是特定分支(及commits)、comments、reviews等各种信息的集合,也是测试计划的**最小管理单元**。
相比将所有功能都提交到某个分支,测试计划通过`PR`来管理功能,这可以带来极大的灵活度和效率:
- 测试计划的各个版本间,可以随意增减功能,而无需繁琐的`revert`操作
- 明确了功能边界和负责人,bug修复在各自`PR`中完成,隔离了交叉影响,也能更好观察进度
- `PR`提交人负责与最新`main`之间的冲突;测试计划负责人负责各`PR`分支之间的冲突,但因加入测试计划的各功能相对比较独立(话句话说,如果功能牵涉较广,则应独立上测试计划),冲突一般比较少或简单。
### `testplan`分支
`testplan`分支是用于测试计划发版所用的**临时**分支。
注意:
- **请勿基于该分支开发**。该分支随时会变化甚至删除,且并不保证commit的完整和顺序。
- **请勿向该分支提交`commit`及`PR`**,将不会得到保留
- `testplan`分支总是基于最新`main`分支(而不是基于已发布版本),在其之上添加功能
#### RC版分支
分支名称:`testplan/rc/x.y.z`
用于RC版的发版,x.y.z为目标版本号,注意无论是rc.1还是rc.5,只要主版本号为x.y.z,都在该分支完成。
一般而言,该分支发版的版本号命名为`x.y.z-rc.n`
#### Beta版分支
分支名称:`testplan/beta/x.y.z`
用于Beta版的发版,x.y.z为目标版本号,注意无论是beta.1还是beta.5,只要主版本号为x.y.z,都在该分支完成。
一般而言,该分支发版的版本号命名为`x.y.z-beta.n`
### 版本规则
测试计划的应用版本号为:`x.y.z-CHA.n`,其中:
- `x.y.z`为一般意义上的版本号,在这里称为**目标版本号**
- `CHA`为通道号(Channel),现在分为`rc`和`beta`
- `n`为发版编号,从`1`计数
完整的版本号举例:`1.5.0-rc.3`、`1.5.1-beta.1`、`1.6.0-beta.6`
测试计划的**目标版本号**指向希望添加这些功能的正式版版本号。例如:
- `1.5.0-rc.3`是指,这是`1.5.0`正式版的预览版(当前最新正式版是`1.4.9`,而`1.5.0`正式版还未发布)
- `1.5.1-beta.1`是指,这是`1.5.1`正式版的测试版(当前最新正式版是`1.5.0`,而`1.5.1`正式版还未发布)
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/CONTRIBUTING.zh.md
|
CherryHQ__cherry-studio/docs/CONTRIBUTING.zh.md
| 4,802 | 1,758,202,168 |
en
|
# Cherry Studio 贡献者指南
[**English**](../CONTRIBUTING.md) | [**中文**](CONTRIBUTING.zh.md)
欢迎来到 Cherry Studio 的贡献者社区!我们致力于将 Cherry Studio 打造成一个长期提供价值的项目,并希望邀请更多的开发者加入我们的行列。无论您是经验丰富的开发者还是刚刚起步的初学者,您的贡献都将帮助我们更好地服务用户,提升软件质量。
## 如何贡献
以下是您可以参与的几种方式:
1. **贡献代码**:帮助我们开发新功能或优化现有代码。请确保您的代码符合我们的编码标准,并通过所有测试。
2. **修复 BUG**:如果您发现了 BUG,欢迎提交修复方案。请在提交前确认问题已被解决,并附上相关测试。
3. **维护 Issue**:协助我们管理 GitHub 上的 issue,帮助标记、分类和解决问题。
4. **产品设计**:参与产品设计讨论,帮助我们改进用户体验和界面设计。
5. **编写文档**:帮助我们完善用户手册、API 文档和开发者指南。
6. **社区维护**:参与社区讨论,帮助解答用户问题,促进社区活跃。
7. **推广使用**:通过博客、社交媒体等渠道推广 Cherry Studio,吸引更多用户和开发者。
## 开始之前
请确保阅读了[行为准则](../CODE_OF_CONDUCT.md)和[LICENSE](../LICENSE)。
## 开始贡献
为了让您更熟悉代码,建议您处理一些标记有以下标签之一或多个的问题:[good-first-issue](https://github.com/CherryHQ/cherry-studio/labels/good%20first%20issue)、[help-wanted](https://github.com/CherryHQ/cherry-studio/labels/help%20wanted) 或 [kind/bug](https://github.com/CherryHQ/cherry-studio/labels/kind%2Fbug)。任何帮助都会收到欢迎。
### 测试
未经测试的功能等同于不存在。为确保代码真正有效,应通过单元测试和功能测试覆盖相关流程。因此,在考虑贡献时,也请考虑可测试性。所有测试均可本地运行,无需依赖 CI。请参阅[开发者指南](dev.md#test)中的“Test”部分。
### 拉取请求的自动化测试
自动化测试会在 Cherry Studio 组织成员开启的拉取请求(PR)上触发,草稿 PR 除外。新贡献者开启的 PR 最初会标记为 needs-ok-to-test 标签且不自动测试。待 Cherry Studio 组织成员在 PR 上添加 /ok-to-test 后,测试通道将被创建。
### 考虑将您的拉取请求作为草稿打开
并非所有拉取请求在创建时就准备好接受审查。这可能是因为作者想发起讨论,或者他们不完全确定更改是否朝着正确的方向发展,甚至可能是因为更改尚未完成。请考虑将这些 PR 创建为[草稿拉取请求](https://github.blog/2019-02-14-introducing-draft-pull-requests/)。草稿 PR 会被CI跳过,从而节省CI资源。这也意味着审阅者不会被自动分配,社区会理解此 PR 尚未准备好接受审阅。
在您将草稿拉取请求标记为准备审核后,审核人员将被分配
### 贡献者遵守项目条款
我们要求每位贡献者证明他们有权合法地为我们的项目做出贡献。贡献者通过有意识地签署他们的提交来表达这一点,并通过这一行为表明他们遵守许可证[LICENSE](LICENSE)。
签名提交是指提交信息中包含以下内容的提交:
```
Signed-off-by: Your Name <[email protected]>
```
您可以通过以下命令[git commit --signoff](https://git-scm.com/docs/git-commit#Documentation/git-commit.txt---signoff)生成签名提交:
```
git commit --signoff -m "Your commit message"
```
### 获取代码审查/合并
维护者在此帮助您在合理时间内实现您的用例。他们会尽力在合理时间内审查您的代码并提供建设性反馈。但如果您在审查过程中受阻,或认为您的 Pull Request 未得到应有的关注,请通过 Issue 中的评论或者[社群](README.zh.md#-community)联系我们
### 参与测试计划
测试计划旨在为用户提供更稳定的应用体验和更快的迭代速度,详细情况请参阅[测试计划](testplan-zh.md)。
### 其他建议
- **联系开发者**:在提交 PR 之前,您可以先和开发者进行联系,共同探讨或者获取帮助。
- **成为核心开发者**:如果您能够稳定为项目贡献,恭喜您可以成为项目核心开发者,获取到项目成员身份。请查看我们的[成员指南](https://github.com/CherryHQ/community/blob/main/membership.md)
## 联系我们
如果您有任何问题或建议,欢迎通过以下方式联系我们:
- 微信:kangfenmao
- [GitHub Issues](https://github.com/CherryHQ/cherry-studio/issues)
感谢您的支持和贡献!我们期待与您一起将 Cherry Studio 打造成更好的产品。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/sponsor.md
|
CherryHQ__cherry-studio/docs/sponsor.md
| 168 | 1,758,202,168 |
en
|
# Sponsor
<div align="center">
<img src="https://github.com/user-attachments/assets/4665f07f-5ecc-4bd8-8727-ae00f35d6d98" alt="Buy Me a Coffee" width="280"/>
</div>
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/features/memory-guide-zh.md
|
CherryHQ__cherry-studio/docs/features/memory-guide-zh.md
| 7,126 | 1,758,202,168 |
en
|
# Cherry Studio 记忆功能指南
## 功能介绍
Cherry Studio 的记忆功能是一个强大的工具,能够帮助 AI 助手记住对话中的重要信息、用户偏好和上下文。通过记忆功能,您的 AI 助手可以:
- 📝 **记住重要信息**:自动从对话中提取并存储关键事实和信息
- 🧠 **个性化响应**:基于存储的记忆提供更加个性化和相关的回答
- 🔍 **智能检索**:在需要时自动搜索相关记忆,增强对话的连贯性
- 👥 **多用户支持**:为不同用户维护独立的记忆上下文
记忆功能特别适用于需要长期保持上下文的场景,例如个人助手、客户服务、教育辅导等。
## 如何启用记忆功能
### 1. 全局配置(首次设置)
在使用记忆功能之前,您需要先进行全局配置:
1. 点击侧边栏的 **记忆** 图标(记忆棒图标)进入记忆管理页面
2. 点击右上角的 **更多** 按钮(三个点),选择 **设置**
3. 在设置弹窗中配置以下必要项:
- **LLM 模型**:选择用于处理记忆的语言模型(推荐使用 GPT-4 或 Claude 等高级模型)
- **嵌入模型**:选择用于生成向量嵌入的模型(如 text-embedding-3-small)
- **嵌入维度**:输入嵌入模型的维度(通常为 1536)
4. 点击 **确定** 保存配置
> ⚠️ **注意**:嵌入模型和维度一旦设置后无法更改,请谨慎选择。
### 2. 为助手启用记忆
完成全局配置后,您可以为特定助手启用记忆功能:
1. 进入 **助手** 页面
2. 选择要启用记忆的助手,点击 **编辑**
3. 在助手设置中找到 **记忆** 部分
4. 打开记忆功能开关
5. 保存助手设置
启用后,该助手将在对话过程中自动提取和使用记忆。
## 使用方法
### 查看记忆
1. 点击侧边栏的 **记忆** 图标进入记忆管理页面
2. 您可以看到所有存储的记忆卡片,包括:
- 记忆内容
- 创建时间
- 所属用户
### 添加记忆
手动添加记忆有两种方式:
**方式一:在记忆管理页面添加**
1. 点击右上角的 **添加记忆** 按钮
2. 在弹窗中输入记忆内容
3. 点击 **添加** 保存
**方式二:在对话中自动提取**
- 当助手启用记忆功能后,系统会自动从对话中提取重要信息并存储为记忆
### 编辑记忆
1. 在记忆卡片上点击 **更多** 按钮(三个点)
2. 选择 **编辑**
3. 修改记忆内容
4. 点击 **保存**
### 删除记忆
1. 在记忆卡片上点击 **更多** 按钮
2. 选择 **删除**
3. 确认删除操作
## 记忆搜索
记忆管理页面提供了强大的搜索功能:
1. 在页面顶部的搜索框中输入关键词
2. 系统会实时过滤显示匹配的记忆
3. 搜索支持模糊匹配,可以搜索记忆内容的任何部分
## 用户管理
记忆功能支持多用户,您可以为不同的用户维护独立的记忆库:
### 切换用户
1. 在记忆管理页面,点击右上角的用户选择器
2. 选择要切换到的用户
3. 页面会自动加载该用户的记忆
### 添加新用户
1. 点击用户选择器
2. 选择 **添加新用户**
3. 输入用户 ID(支持字母、数字、下划线和连字符)
4. 点击 **添加**
### 删除用户
1. 切换到要删除的用户
2. 点击右上角的 **更多** 按钮
3. 选择 **删除用户**
4. 确认删除(注意:这将删除该用户的所有记忆)
> 💡 **提示**:默认用户(default-user)无法删除。
## 设置说明
### LLM 模型
- 用于处理记忆提取和更新的语言模型
- 建议选择能力较强的模型以获得更好的记忆提取效果
- 可随时更改
### 嵌入模型
- 用于将文本转换为向量,支持语义搜索
- 一旦设置后无法更改(为了保证现有记忆的兼容性)
- 推荐使用 OpenAI 的 text-embedding 系列模型
### 嵌入维度
- 嵌入向量的维度,需要与选择的嵌入模型匹配
- 常见维度:
- text-embedding-3-small: 1536
- text-embedding-3-large: 3072
- text-embedding-ada-002: 1536
### 自定义提示词(可选)
- **事实提取提示词**:自定义如何从对话中提取信息
- **记忆更新提示词**:自定义如何更新现有记忆
## 最佳实践
### 1. 合理组织记忆
- 保持记忆简洁明了,每条记忆专注于一个具体信息
- 使用清晰的语言描述事实,避免模糊表达
- 定期审查和清理过时或不准确的记忆
### 2. 多用户场景
- 为不同的使用场景创建独立用户(如工作、个人、学习等)
- 使用有意义的用户 ID,便于识别和管理
- 定期备份重要用户的记忆数据
### 3. 模型选择建议
- **LLM 模型**:GPT-4、Claude 3 等高级模型能更准确地提取和理解信息
- **嵌入模型**:选择与您的主要使用语言匹配的模型
### 4. 性能优化
- 避免存储过多冗余记忆,这可能影响搜索性能
- 定期整理和合并相似的记忆
- 对于大量记忆的场景,考虑按主题或时间进行分类管理
## 常见问题
### Q: 为什么我无法启用记忆功能?
A: 请确保您已经完成全局配置,包括选择 LLM 模型和嵌入模型。
### Q: 记忆会自动同步到所有助手吗?
A: 不会。每个助手的记忆功能需要单独启用,且记忆是按用户隔离的。
### Q: 如何导出我的记忆数据?
A: 目前系统暂不支持直接导出功能,但所有记忆都存储在本地数据库中。
### Q: 删除的记忆可以恢复吗?
A: 删除操作是永久的,无法恢复。建议在删除前仔细确认。
### Q: 记忆功能会影响对话速度吗?
A: 记忆功能在后台异步处理,不会明显影响对话响应速度。但过多的记忆可能会略微增加搜索时间。
### Q: 如何清空所有记忆?
A: 您可以删除当前用户并重新创建,或者手动删除所有记忆条目。
## 注意事项
### 隐私保护
- 所有记忆数据都存储在您的本地设备上,不会上传到云端
- 请勿在记忆中存储敏感信息(如密码、私钥等)
- 定期审查记忆内容,确保没有意外存储的隐私信息
### 数据安全
- 记忆数据存储在本地数据库中
- 建议定期备份重要数据
- 更换设备时请注意迁移记忆数据
### 使用限制
- 单条记忆的长度建议不超过 500 字
- 每个用户的记忆数量建议控制在 1000 条以内
- 过多的记忆可能影响系统性能
## 技术细节
记忆功能使用了先进的 RAG(检索增强生成)技术:
1. **信息提取**:使用 LLM 从对话中智能提取关键信息
2. **向量化存储**:通过嵌入模型将文本转换为向量,支持语义搜索
3. **智能检索**:在对话时自动搜索相关记忆,提供给 AI 作为上下文
4. **持续学习**:随着对话进行,不断更新和完善记忆库
---
💡 **提示**:记忆功能是 Cherry Studio 的高级特性,合理使用可以大大提升 AI 助手的智能程度和用户体验。如有更多问题,欢迎查阅文档或联系支持团队。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/code-execution.md
|
CherryHQ__cherry-studio/docs/technical/code-execution.md
| 6,737 | 1,758,202,168 |
en
|
# 代码执行功能
本文档说明了代码块的 Python 代码执行功能。该实现利用 [Pyodide][pyodide-link] 在浏览器环境中直接运行 Python 代码,并将其置于 Web Worker 中,以避免阻塞主 UI 线程。
整个实现分为三个主要部分:UI 层、服务层和 Worker 层。
## 执行流程图
```mermaid
sequenceDiagram
participant 用户
participant CodeBlockView (UI)
participant PyodideService (服务)
participant PyodideWorker (Worker)
用户->>CodeBlockView (UI): 点击“运行”按钮
CodeBlockView (UI)->>PyodideService (服务): 调用 runScript(code)
PyodideService (服务)->>PyodideWorker (Worker): 发送 postMessage({ id, python: code })
PyodideWorker (Worker)->>PyodideWorker (Worker): 加载 Pyodide 和相关包
PyodideWorker (Worker)->>PyodideWorker (Worker): (按需)注入垫片并合并代码
PyodideWorker (Worker)->>PyodideWorker (Worker): 执行合并后的 Python 代码
PyodideWorker (Worker)-->>PyodideService (服务): 返回 postMessage({ id, output })
PyodideService (服务)-->>CodeBlockView (UI): 返回 { text, image } 对象
CodeBlockView (UI)->>用户: 在状态栏中显示文本和/或图像输出
```
## 1. UI 层
面向用户的代码执行组件是 [CodeBlockView][codeblock-view-link]。
### 关键机制:
- **运行按钮**:当代码块语言为 `python` 且 `codeExecution.enabled` 设置为 true 时,`CodeToolbar` 中会条件性地渲染一个“运行”按钮。
- **事件处理**:运行按钮的 `onClick` 事件会触发 `handleRunScript` 函数。
- **服务调用**:`handleRunScript` 调用 `pyodideService.runScript(code)`,将代码块中的 Python 代码传递给服务。
- **状态管理与输出显示**:使用 `executionResult` 来管理所有执行输出,只要有任何结果(文本或图像),[StatusBar][statusbar-link] 组件就会被渲染以统一显示。
```typescript
// src/renderer/src/components/CodeBlockView/view.tsx
const [executionResult, setExecutionResult] = useState<{ text: string; image?: string } | null>(null)
const handleRunScript = useCallback(() => {
setIsRunning(true)
setExecutionResult(null)
pyodideService
.runScript(children, {}, codeExecution.timeoutMinutes * 60000)
.then((result) => {
setExecutionResult(result)
})
.catch((error) => {
console.error('Unexpected error:', error)
setExecutionResult({
text: `Unexpected error: ${error.message || 'Unknown error'}`
})
})
.finally(() => {
setIsRunning(false)
})
}, [children, codeExecution.timeoutMinutes]);
// ... 在 JSX 中
{isExecutable && executionResult && (
<StatusBar>
{executionResult.text}
{executionResult.image && (
<ImageOutput>
<img src={executionResult.image} alt="Matplotlib plot" />
</ImageOutput>
)}
</StatusBar>
)}
```
## 2. 服务层
服务层充当 UI 组件和运行 Pyodide 的 Web Worker 之间的桥梁。其逻辑封装在位于单例类 [PyodideService][pyodide-service-link]。
### 主要职责:
- **Worker 管理**:初始化、管理并与 Pyodide Web Worker 通信。
- **请求处理**:使用 `resolvers` Map 管理并发请求,通过唯一 ID 匹配请求和响应。
- **为 UI 提供 API**:向 UI 提供 `runScript(script, context, timeout)` 方法。此方法的返回值已修改为 `Promise<{ text: string; image?: string }>`,以支持包括图像在内的多种输出类型。
- **输出处理**:从 Worker 接收包含文本、错误和可选图像数据的 `output` 对象。它将文本和错误格式化为对用户友好的单个字符串,然后连同图像数据一起包装成对象返回给 UI 层。
- **IPC 端点**:该服务还提供了一个 `python-execution-request` IPC 端点,允许主进程请求执行 Python 代码,展示了其灵活的架构。
## 3. Worker 层
核心的 Python 执行发生在 [pyodide.worker.ts][pyodide-worker-link] 中定义的 Web Worker 内部。这确保了计算密集的 Python 代码不会冻结用户界面。
### Worker 逻辑:
- **Pyodide 加载**:Worker 从 CDN 加载 Pyodide 引擎,并设置处理器以捕获 Python 的 `stdout` 和 `stderr`。
- **动态包安装**:使用 `pyodide.loadPackagesFromImports()` 自动分析并安装代码中导入的依赖包。
- **按需执行垫片代码**:Worker 会检查传入的代码中是否包含 "matplotlib" 字符串。如果是,它会先执行一段 Python“垫片”代码确保图像输出到全局命名空间。
- **结果序列化**:执行结果通过 `.toJs()` 等方法被递归转换为可序列化的标准 JavaScript 对象。
- **返回结构化输出**:执行后,Worker 将一个包含 `id` 和 `output` 对象的-消息发回服务层。`output` 对象是一个结构化对象,包含 `result`、`text`、`error` 以及一个可选的 `image` 字段(用于 Base64 图像数据)。
### 数据流
最终的数据流如下:
1. **UI 层 ([CodeBlockView][codeblock-view-link])**: 用户点击“运行”按钮。
2. **服务层 ([PyodideService][pyodide-service-link])**:
- 接收到代码执行请求。
- 调用 Web Worker ([pyodide.worker.ts][pyodide-worker-link]),传递用户代码。
3. **Worker 层 ([pyodide.worker.ts][pyodide-worker-link])**:
- 加载 Pyodide 运行时。
- 动态安装代码中 `import` 语句声明的依赖包。
- **注入 Matplotlib 垫片**: 如果代码中包含 `matplotlib`,则在用户代码前拼接垫片代码,强制使用 `AGG` 后端。
- **执行代码并捕获输出**: 在代码执行后,检查 `matplotlib.pyplot` 的所有 figure,如果存在图像,则将其保存到内存中的 `BytesIO` 对象,并编码为 Base64 字符串。
- **结构化返回**: 将捕获的文本输出和 Base64 图像数据封装在一个 JSON 对象中 (`{ "text": "...", "image": "data:image/png;base64,..." }`) 返回给主线程。
4. **服务层 ([PyodideService][pyodide-service-link])**:
- 接收来自 Worker 的结构化数据。
- 将数据原样传递给 UI 层。
5. **UI 层 ([CodeBlockView][codeblock-view-link])**:
- 接收包含文本和图像数据的对象。
- 使用一个 `useState` 来管理执行结果 (`executionResult`)。
- 在界面上分别渲染文本输出和图像(如果存在)。
<!-- Link Definitions -->
[pyodide-link]: https://pyodide.org/
[codeblock-view-link]: /src/renderer/src/components/CodeBlockView/view.tsx
[pyodide-service-link]: /src/renderer/src/services/PyodideService.ts
[pyodide-worker-link]: /src/renderer/src/workers/pyodide.worker.ts
[statusbar-link]: /src/renderer/src/components/CodeBlockView/StatusBar.tsx
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-i18n-zh.md
|
CherryHQ__cherry-studio/docs/technical/how-to-i18n-zh.md
| 4,804 | 1,758,202,168 |
en
|
# 如何优雅地做好 i18n
## 使用i18n ally插件提升开发体验
i18n ally是一个强大的VSCode插件,它能在开发阶段提供实时反馈,帮助开发者更早发现文案缺失和错译问题。
项目中已经配置好了插件设置,直接安装即可。
### 开发时优势
- **实时预览**:翻译文案会直接显示在编辑器中
- **错误检测**:自动追踪标记出缺失的翻译或未使用的key
- **快速跳转**:可通过key直接跳转到定义处(Ctrl/Cmd + click)
- **自动补全**:输入i18n key时提供自动补全建议
### 效果展示



## i18n 约定
### **绝对避免使用flat格式**
绝对避免使用flat格式,如`"add.button.tip": "添加"`。应采用清晰的嵌套结构:
```json
// 错误示例 - flat结构
{
"add.button.tip": "添加",
"delete.button.tip": "删除"
}
// 正确示例 - 嵌套结构
{
"add": {
"button": {
"tip": "添加"
}
},
"delete": {
"button": {
"tip": "删除"
}
}
}
```
#### 为什么要使用嵌套结构
1. **自然分组**:通过对象结构天然能将相关上下文的文案分到一个组别中
2. **插件要求**:i18n ally 插件需要嵌套或flat格式其一的文件才能正常分析
### **避免在`t()`中使用模板字符串**
**强烈建议避免使用模板字符串**进行动态插值。虽然模板字符串在JavaScript开发中非常方便,但在国际化场景下会带来一系列问题。
1. **插件无法跟踪**
i18n ally等工具无法解析模板字符串中的动态内容,导致:
- 无法正确显示实时预览
- 无法检测翻译缺失
- 无法提供跳转到定义的功能
```javascript
// 不推荐 - 插件无法解析
const message = t(`fruits.${fruit}`)
```
2. **编辑器无法实时渲染**
在IDE中,模板字符串会显示为原始代码而非最终翻译结果,降低了开发体验。
3. **更难以维护**
由于插件无法跟踪这样的文案,编辑器中也无法渲染,开发者必须人工确认语言文件中是否存在相应的文案。
### 推荐做法
为了避免键的缺失,所有需要动态翻译的文本都应当先维护一个`FooKeyMap`,再通过函数获取翻译文本。
例如:
```ts
// src/renderer/src/i18n/label.ts
const themeModeKeyMap = {
dark: 'settings.theme.dark',
light: 'settings.theme.light',
system: 'settings.theme.system'
} as const
export const getThemeModeLabel = (key: string): string => {
return themeModeKeyMap[key] ? t(themeModeKeyMap[key]) : key
}
```
通过避免模板字符串,可以获得更好的开发体验、更可靠的翻译检查以及更易维护的代码库。
## 自动化脚本
项目中有一系列脚本来自动化i18n相关任务:
### `check:i18n` - 检查i18n结构
此脚本会检查:
- 所有语言文件是否为嵌套结构
- 是否存在缺失的key
- 是否存在多余的key
- 是否已经有序
```bash
yarn check:i18n
```
### `sync:i18n` - 同步json结构与排序
此脚本以`zh-cn.json`文件为基准,将结构同步到其他语言文件,包括:
1. 添加缺失的键。缺少的翻译内容会以`[to be translated]`标记
2. 删除多余的键
3. 自动排序
```bash
yarn sync:i18n
```
### `auto:i18n` - 自动翻译待翻译文本
次脚本自动将标记为待翻译的文本通过机器翻译填充。
通常,在`zh-cn.json`中添加所需文案后,执行`sync:i18n`即可自动完成翻译。
使用该脚本前,需要配置环境变量,例如:
```bash
API_KEY="sk-xxx"
BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1/"
MODEL="qwen-plus-latest"
```
你也可以通过直接编辑`.env`文件来添加环境变量。
```bash
yarn auto:i18n
```
### `update:i18n` - 对象级别翻译更新
对`src/renderer/src/i18n/translate`中的语言文件进行对象级别的翻译更新,保留已有翻译,只更新新增内容。
**不建议**使用该脚本,更推荐使用`auto:i18n`进行翻译。
```bash
yarn update:i18n
```
### 工作流
1. 开发阶段,先在`zh-cn.json`中添加所需文案
2. 确认在中文环境下显示无误后,使用`yarn sync:i18n`将文案同步到其他语言文件
3. 使用`yarn auto:i18n`进行自动翻译
4. 喝杯咖啡,等翻译完成吧!
## 最佳实践
1. **以中文为源语言**:所有开发首先使用中文,再翻译为其他语言
2. **提交前运行检查脚本**:使用`yarn check:i18n`检查i18n是否有问题
3. **小步提交翻译**:避免积累大量未翻译文本
4. **保持key语义明确**:key应能清晰表达其用途,如`user.profile.avatar.upload.error`
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-use-logger-zh.md
|
CherryHQ__cherry-studio/docs/technical/how-to-use-logger-zh.md
| 10,841 | 1,758,202,168 |
en
|
# 如何使用日志 LoggerService
这是关于如何使用日志的开发者文档。
CherryStudio使用统一的日志服务来打印和记录日志,**若无特殊原因,请勿使用`console.xxx`来打印日志**。
以下是详细说明。
## 在`main`进程中使用
### 引入
```typescript
import { loggerService } from '@logger'
```
### 设置module信息(规范要求)
在import头之后,设置:
```typescript
const logger = loggerService.withContext('moduleName')
```
- `moduleName`是当前文件模块的名称,命名可以以文件名、主类名、主函数名等,原则是清晰明了
- `moduleName`会在终端中打印出来,也会在文件日志中体现,方便筛选
### 设置`CONTEXT`信息(可选)
在`withContext`中,也可以设置其他`CONTEXT`信息:
```typescript
const logger = loggerService.withContext('moduleName', CONTEXT)
```
- `CONTEXT`为`{ key: value, ... }`
- `CONTEXT`信息不会在终端中打印出来,但是会在文件日志中记录,方便筛选
### 记录日志
在代码中,可以随时调用 `logger` 来记录日志,支持的级别有:`error`, `warn`, `info`, `verbose`, `debug`, `silly`。
各级别的含义,请参考后面的章节。
以下支持的记录日志的参数(以 `logger.LEVEL` 举例如何使用,`LEVEL`指代为上述级别):
```typescript
logger.LEVEL(message)
logger.LEVEL(message, CONTEXT)
logger.LEVEL(message, error)
logger.LEVEL(message, error, CONTEXT)
```
**只支持上述四种调用方式**。
| 参数 | 类型 | 说明 |
| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message` | `string` | 必填项。这是日志的核心字段,记录的重点内容 |
| `CONTEXT` | `object` | 可选。其他需要再日志文件中记录的信息,建议为`{ key: value, ...}`格式 |
| `error` | `Error` | 可选。同时会打印错误堆栈信息。<br />注意`catch(error)`所捕获的`error`是`unknown`类型,按照`Typescript`最佳实践,请先用`instanceof`进行类型判断,如果确信一定是`Error`类型,也可用断言`as Error`。 |
#### 记录非`object`类型的上下文信息
```typescript
const foo = getFoo()
logger.debug(`foo ${foo}`)
```
### 记录级别
- 开发环境下,所有级别的日志都会打印到终端,并且记录到文件日志中
- 生产环境下,默认记录级别为`info`,日志只会记录到文件,不会打印到终端
更改日志记录级别:
- 可以通过 `logger.setLevel('newLevel')` 来更改日志记录级别
- `logger.resetLevel()` 可以重置为默认级别
- `logger.getLevel()` 可以获取当前记录记录级别
**注意** 更改日志记录级别是全局生效的,请不要在代码中随意更改,除非你非常清楚自己在做什么
## 在`renderer`进程中使用
在`renderer`进程中使用,_引入方法_、_设置`module`信息_、*设置`context`信息的方法*和`main`进程中是**完全一样**的。
下面着重讲一下不同之处。
### `initWindowSource`
`renderer`进程中,有不同的`window`,在开始使用`logger`之前,我们必须设置`window`信息:
```typescript
loggerService.initWindowSource('windowName')
```
原则上,我们将在`window`的`entryPoint.tsx`中进行设置,这可以保证`windowName`在开始使用前已经设置好了。
- 未设置`windowName`会报错,`logger`将不起作用
- `windowName`只能设置一次,重复设置将不生效
- `windowName`不会在`devTool`的`console`中打印出来,但是会在`main`进程的终端和文件日志中记录
- `initWindowSource`返回的是LoggerService的实例,因此可以做链式调用
### 记录级别
- 开发环境下,默认所有级别的日志都会打印到`devTool`的`console`
- 生产环境下,默认记录级别为`info`,日志会打印到`devTool`的`console`
- 在开发和生产环境下,默认`warn`和`error`级别的日志,会传输给`main`进程,并记录到文件日志
- 开发环境下,`main`进程终端中也会打印传输过来的日志
#### 更改日志记录级别
和`main`进程中一样,你可以通过`setLevel('level')`、`resetLevel()`和`getLevel()`来管理日志记录级别。
同样,该日志记录级别也是全局调整的。
#### 更改传输到`main`的级别
将`renderer`的日志发送到`main`,并由`main`统一管理和记录到文件(根据`main`的记录到文件的级别),默认只有`warn`和`error`级别的日志会传输到`main`
有以下两种方式,可以更改传输到`main`的日志级别:
##### 全局更改
以下方法可以分别设置、重置和获取传输到`main`的日志级别
```typescript
logger.setLogToMainLevel('newLevel')
logger.resetLogToMainLevel()
logger.getLogToMainLevel()
```
**注意** 该方法是全局生效的,请不要在代码中随意更改,除非你非常清楚自己在做什么
##### 单条更改
在日志记录的最末尾,加上`{ logToMain: true }`,即可将本条日志传输到`main`(不受全局日志级别限制),例如:
```typescript
logger.info('message', { logToMain: true })
```
## 关于`worker`线程
- 现在不支持`main`进程中的`worker`的日志。
- 支持`renderer`中起的`worker`的日志,但是现在该日志不会发送给`main`进行记录。
### 如何在`renderer`的`worker`中使用日志
由于`worker`线程是独立的,在其中使用LoggerService,等同于在一个新`renderer`窗口中使用。因此也必须先`initWindowSource`。
如果`worker`比较简单,只有一个文件,也可以使用链式语法直接使用:
```typescript
const logger = loggerService.initWindowSource('Worker').withContext('LetsWork')
```
## 使用环境变量来筛选要显示的日志
在开发环境中,可以通过环境变量的定义,来筛选要显示的日志的级别和module。开发者可以专注于自己的日志,提高开发效率。
环境变量可以在终端中自行设置,或者在开发根目录的`.env`文件中进行定义,可以定义的变量如下:
| 变量名 | 含义 |
| -------------------------------- | ----------------------------------------------------------------------------------------------- |
| `CSLOGGER_MAIN_LEVEL` | 用于`main`进程的日志级别,低于该级别的日志将不显示 |
| `CSLOGGER_MAIN_SHOW_MODULES` | 用于`main`进程的日志module筛选,用`,`分隔,区分大小写。只有在该列表中的module的日志才会显示 |
| `CSLOGGER_RENDERER_LEVEL` | 用于`renderer`进程的日志级别,低于该级别的日志将不显示 |
| `CSLOGGER_RENDERER_SHOW_MODULES` | 用于`renderer`进程的日志module筛选,用`,`分隔,区分大小写。只有在该列表中的module的日志才会显示 |
示例:
```bash
CSLOGGER_MAIN_LEVEL=verbose
CSLOGGER_MAIN_SHOW_MODULES=MCPService,SelectionService
```
注意:
- 环境变量仅在开发环境中生效
- 该变量仅会改变在终端或在devTools中显示的日志,不会影响文件日志和`logToMain`的记录逻辑
## 日志级别的使用规范
日志有很多级别,什么时候应该用哪个级别,下面是在CherryStudio中应该遵循的规范:
(按日志级别从高到低排列)
| 日志级别 | 核心定义与使用场景 | 示例 |
| :------------ | :------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`error`** | **严重错误,导致程序崩溃或核心功能无法使用。** <br> 这是最高优的日志,通常需要立即上报或提示用户。 | - 主进程或渲染进程崩溃。 <br> - 无法读写用户关键数据文件(如数据库、配置文件),导致应用无法运行。<br> - 所有未捕获的异常。 |
| **`warn`** | **潜在问题或非预期情况,但不影响程序核心功能。** <br> 程序可以从中恢复或使用备用方案。 | - 配置文件 `settings.json` 缺失,已使用默认配置启动。 <br> - 自动更新检查失败,但不影响当前版本使用。<br> - 某个非核心插件加载失败。 |
| **`info`** | **记录应用生命周期和关键用户行为。** <br> 这是发布版中默认应记录的级别,用于追踪用户的主要操作路径。 | - 应用启动、退出。<br> - 用户成功打开/保存文件。 <br> - 主窗口创建/关闭。<br> - 开始执行一项重要任务(如“开始导出视频”)。 |
| **`verbose`** | **比 `info` 更详细的流程信息,用于追踪特定功能。** <br> 在诊断特定功能问题时开启,帮助理解内部执行流程。 | - 正在加载 `Toolbar` 模块。 <br> - IPC 消息 `open-file-dialog` 已从渲染进程发送。<br> - 正在应用滤镜 'Sepia' 到图像。 |
| **`debug`** | **开发和调试时使用的详细诊断信息。** <br> **严禁在发布版中默认开启**,因为它可能包含敏感数据并影响性能。 | - 函数 `renderImage` 的入参: `{ width: 800, ... }`。<br> - IPC 消息 `save-file` 收到的具体数据内容。<br> - 渲染进程中 Redux/Vuex 的 state 变更详情。 |
| **`silly`** | **最详尽的底层信息,仅用于极限调试。** <br> 几乎不在常规开发中使用,仅为解决棘手问题。 | - 鼠标移动的实时坐标 `(x: 150, y: 320)`。<br> - 读取文件时每个数据块(chunk)的大小。<br> - 每一次渲染帧的耗时。 |
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/KnowledgeService.md
|
CherryHQ__cherry-studio/docs/technical/KnowledgeService.md
| 6,020 | 1,758,202,168 |
en
|
我来详细介绍 KnowledgeService 中控制并发处理的项目数量和工作负载的部分。
## 并发控制与工作负载管理机制
KnowledgeService 实现了一个精细的任务队列系统,用于控制并发处理的项目数量和工作负载。这个系统主要通过以下几个关键部分实现:
### 1. 关键变量和限制
```typescript
private workload = 0
private processingItemCount = 0
private knowledgeItemProcessingQueueMappingPromise: Map<LoaderTaskOfSet, () => void> = new Map()
private static MAXIMUM_WORKLOAD = 1024 * 1024 * 80 // 约80MB
private static MAXIMUM_PROCESSING_ITEM_COUNT = 30
```
- `workload`: 跟踪当前正在处理的总工作量(以字节为单位)
- `processingItemCount`: 跟踪当前正在处理的项目数量
- `MAXIMUM_WORKLOAD`: 设置最大工作负载为80MB
- `MAXIMUM_PROCESSING_ITEM_COUNT`: 设置最大并发处理项目数为30个
### 2. 工作负载评估
每个任务都有一个评估工作负载的机制,通过 `evaluateTaskWorkload` 属性来表示:
```typescript
interface EvaluateTaskWorkload {
workload: number
}
```
不同类型的任务有不同的工作负载评估方式:
- 文件任务:使用文件大小作为工作负载 `{ workload: file.size }`
- URL任务:使用固定值 `{ workload: 1024 * 1024 * 2 }` (约2MB)
- 网站地图任务:使用固定值 `{ workload: 1024 * 1024 * 20 }` (约20MB)
- 笔记任务:使用文本内容的字节长度 `{ workload: contentBytes.length }`
### 3. 任务状态管理
任务通过状态枚举来跟踪其生命周期:
```typescript
enum LoaderTaskItemState {
PENDING, // 等待处理
PROCESSING, // 正在处理
DONE // 已完成
}
```
### 4. 任务队列处理核心逻辑
核心的队列处理逻辑在 `processingQueueHandle` 方法中:
```typescript
private processingQueueHandle() {
const getSubtasksUntilMaximumLoad = (): QueueTaskItem[] => {
const queueTaskList: QueueTaskItem[] = []
that: for (const [task, resolve] of this.knowledgeItemProcessingQueueMappingPromise) {
for (const item of task.loaderTasks) {
if (this.maximumLoad()) {
break that
}
const { state, task: taskPromise, evaluateTaskWorkload } = item
if (state !== LoaderTaskItemState.PENDING) {
continue
}
const { workload } = evaluateTaskWorkload
this.workload += workload
this.processingItemCount += 1
item.state = LoaderTaskItemState.PROCESSING
queueTaskList.push({
taskPromise: () =>
taskPromise().then(() => {
this.workload -= workload
this.processingItemCount -= 1
task.loaderTasks.delete(item)
if (task.loaderTasks.size === 0) {
this.knowledgeItemProcessingQueueMappingPromise.delete(task)
resolve()
}
this.processingQueueHandle()
}),
resolve: () => {},
evaluateTaskWorkload
})
}
}
return queueTaskList
}
const subTasks = getSubtasksUntilMaximumLoad()
if (subTasks.length > 0) {
const subTaskPromises = subTasks.map(({ taskPromise }) => taskPromise())
Promise.all(subTaskPromises).then(() => {
subTasks.forEach(({ resolve }) => resolve())
})
}
}
```
这个方法的工作流程是:
1. 遍历所有待处理的任务集合
2. 对于每个任务集合中的每个子任务:
- 检查是否已达到最大负载(通过 `maximumLoad()` 方法)
- 如果任务状态为 PENDING,则:
- 增加当前工作负载和处理项目计数
- 将任务状态更新为 PROCESSING
- 将任务添加到待执行队列
3. 执行所有收集到的子任务
4. 当子任务完成时:
- 减少工作负载和处理项目计数
- 从任务集合中移除已完成的任务
- 如果任务集合为空,则解析相应的 Promise
- 递归调用 `processingQueueHandle()` 以处理更多任务
### 5. 负载检查
```typescript
private maximumLoad() {
return (
this.processingItemCount >= KnowledgeService.MAXIMUM_PROCESSING_ITEM_COUNT ||
this.workload >= KnowledgeService.MAXIMUM_WORKLOAD
)
}
```
这个方法检查当前是否已达到最大负载,通过两个条件:
- 处理项目数量达到上限(30个)
- 总工作负载达到上限(80MB)
### 6. 任务添加与执行流程
当添加新任务时,流程如下:
1. 创建任务(根据类型不同创建不同的任务)
2. 通过 `appendProcessingQueue` 将任务添加到队列
3. 调用 `processingQueueHandle` 开始处理队列中的任务
```typescript
private appendProcessingQueue(task: LoaderTask): Promise<LoaderReturn> {
return new Promise((resolve) => {
this.knowledgeItemProcessingQueueMappingPromise.set(loaderTaskIntoOfSet(task), () => {
resolve(task.loaderDoneReturn!)
})
})
}
```
## 并发控制的优势
这种并发控制机制有几个重要优势:
1. **资源使用优化**:通过限制同时处理的项目数量和总工作负载,避免系统资源过度使用
2. **自动调节**:当任务完成时,会自动从队列中获取新任务,保持资源的高效利用
3. **灵活性**:不同类型的任务有不同的工作负载评估,更准确地反映实际资源需求
4. **可靠性**:通过状态管理和Promise解析机制,确保任务正确完成并通知调用者
## 实际应用场景
这种并发控制在处理大量数据时特别有用,例如:
- 导入大型目录时,可能包含数百个文件
- 处理大型网站地图,可能包含大量URL
- 处理多个用户同时添加知识库项目的请求
通过这种机制,系统可以平滑地处理大量请求,避免资源耗尽,同时保持良好的响应性。
总结来说,KnowledgeService 实现了一个复杂而高效的任务队列系统,通过精确控制并发处理的项目数量和工作负载,确保系统在处理大量数据时保持稳定和高效。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/db.translate_languages.md
|
CherryHQ__cherry-studio/docs/technical/db.translate_languages.md
| 1,023 | 1,758,202,168 |
en
|
# `translate_languages` 表技术文档
## 📄 概述
`translate_languages` 记录用户自定义的的语言类型(`Language`)。
### 字段说明
| 字段名 | 类型 | 是否主键 | 索引 | 说明 |
| ---------- | ------ | -------- | ---- | ------------------------------------------------------------------------ |
| `id` | string | ✅ 是 | ✅ | 唯一标识符,主键 |
| `langCode` | string | ❌ 否 | ✅ | 语言代码(如:`zh-cn`, `en-us`, `ja-jp` 等,均为小写),支持普通索引查询 |
| `value` | string | ❌ 否 | ❌ | 语言的名称,用户输入 |
| `emoji` | string | ❌ 否 | ❌ | 语言的emoji,用户输入 |
> `langCode` 虽非主键,但在业务层应当避免重复插入相同语言代码。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-use-messageBlock.md
|
CherryHQ__cherry-studio/docs/technical/how-to-use-messageBlock.md
| 6,426 | 1,758,202,168 |
en
|
# messageBlock.ts 使用指南
该文件定义了用于管理应用程序中所有 `MessageBlock` 实体的 Redux Slice。它使用 Redux Toolkit 的 `createSlice` 和 `createEntityAdapter` 来高效地处理规范化的状态,并提供了一系列 actions 和 selectors 用于与消息块数据交互。
## 核心目标
- **状态管理**: 集中管理所有 `MessageBlock` 的状态。`MessageBlock` 代表消息中的不同内容单元(如文本、代码、图片、引用等)。
- **规范化**: 使用 `createEntityAdapter` 将 `MessageBlock` 数据存储在规范化的结构中(`{ ids: [], entities: {} }`),这有助于提高性能和简化更新逻辑。
- **可预测性**: 提供明确的 actions 来修改状态,并通过 selectors 安全地访问状态。
## 关键概念
- **Slice (`createSlice`)**: Redux Toolkit 的核心 API,用于创建包含 reducer 逻辑、action creators 和初始状态的 Redux 模块。
- **Entity Adapter (`createEntityAdapter`)**: Redux Toolkit 提供的工具,用于简化对规范化数据的 CRUD(创建、读取、更新、删除)操作。它会自动生成 reducer 函数和 selectors。
- **Selectors**: 用于从 Redux store 中派生和计算数据的函数。Selectors 可以被记忆化(memoized),以提高性能。
## State 结构
`messageBlocks` slice 的状态结构由 `createEntityAdapter` 定义,大致如下:
```typescript
{
ids: string[]; // 存储所有 MessageBlock ID 的有序列表
entities: { [id: string]: MessageBlock }; // 按 ID 存储 MessageBlock 对象的字典
loadingState: 'idle' | 'loading' | 'succeeded' | 'failed'; // (可选) 其他状态,如加载状态
error: string | null; // (可选) 错误信息
}
```
## Actions
该 slice 导出以下 actions (由 `createSlice` 和 `createEntityAdapter` 自动生成或自定义):
- **`upsertOneBlock(payload: MessageBlock)`**:
- 添加一个新的 `MessageBlock` 或更新一个已存在的 `MessageBlock`。如果 payload 中的 `id` 已存在,则执行更新;否则执行插入。
- **`upsertManyBlocks(payload: MessageBlock[])`**:
- 添加或更新多个 `MessageBlock`。常用于批量加载数据(例如,加载一个 Topic 的所有消息块)。
- **`removeOneBlock(payload: string)`**:
- 根据提供的 `id` (payload) 移除单个 `MessageBlock`。
- **`removeManyBlocks(payload: string[])`**:
- 根据提供的 `id` 数组 (payload) 移除多个 `MessageBlock`。常用于删除消息或清空 Topic 时清理相关的块。
- **`removeAllBlocks()`**:
- 移除 state 中的所有 `MessageBlock` 实体。
- **`updateOneBlock(payload: { id: string; changes: Partial<MessageBlock> })`**:
- 更新一个已存在的 `MessageBlock`。`payload` 需要包含块的 `id` 和一个包含要更改的字段的 `changes` 对象。
- **`setMessageBlocksLoading(payload: 'idle' | 'loading')`**:
- (自定义) 设置 `loadingState` 属性。
- **`setMessageBlocksError(payload: string)`**:
- (自定义) 设置 `loadingState` 为 `'failed'` 并记录错误信息。
**使用示例 (在 Thunk 或其他 Dispatch 的地方):**
```typescript
import { upsertOneBlock, removeManyBlocks, updateOneBlock } from './messageBlock'
import store from './store' // 假设这是你的 Redux store 实例
// 添加或更新一个块
const newBlock: MessageBlock = {
/* ... block data ... */
}
store.dispatch(upsertOneBlock(newBlock))
// 更新一个块的内容
store.dispatch(updateOneBlock({ id: blockId, changes: { content: 'New content' } }))
// 删除多个块
const blockIdsToRemove = ['id1', 'id2']
store.dispatch(removeManyBlocks(blockIdsToRemove))
```
## Selectors
该 slice 导出由 `createEntityAdapter` 生成的基础 selectors,并通过 `messageBlocksSelectors` 对象访问:
- **`messageBlocksSelectors.selectIds(state: RootState): string[]`**: 返回包含所有块 ID 的数组。
- **`messageBlocksSelectors.selectEntities(state: RootState): { [id: string]: MessageBlock }`**: 返回块 ID 到块对象的映射字典。
- **`messageBlocksSelectors.selectAll(state: RootState): MessageBlock[]`**: 返回包含所有块对象的数组。
- **`messageBlocksSelectors.selectTotal(state: RootState): number`**: 返回块的总数。
- **`messageBlocksSelectors.selectById(state: RootState, id: string): MessageBlock | undefined`**: 根据 ID 返回单个块对象,如果找不到则返回 `undefined`。
**此外,还提供了一个自定义的、记忆化的 selector:**
- **`selectFormattedCitationsByBlockId(state: RootState, blockId: string | undefined): Citation[]`**:
- 接收一个 `blockId`。
- 如果该 ID 对应的块是 `CITATION` 类型,则提取并格式化其包含的引用信息(来自网页搜索、知识库等),进行去重和重新编号,最后返回一个 `Citation[]` 数组,用于在 UI 中显示。
- 如果块不存在或类型不匹配,返回空数组 `[]`。
- 这个 selector 封装了处理不同引用来源(Gemini, OpenAI, OpenRouter, Zhipu 等)的复杂逻辑。
**使用示例 (在 React 组件或 `useSelector` 中):**
```typescript
import { useSelector } from 'react-redux'
import { messageBlocksSelectors, selectFormattedCitationsByBlockId } from './messageBlock'
import type { RootState } from './store'
// 获取所有块
const allBlocks = useSelector(messageBlocksSelectors.selectAll)
// 获取特定 ID 的块
const specificBlock = useSelector((state: RootState) => messageBlocksSelectors.selectById(state, someBlockId))
// 获取特定引用块格式化后的引用列表
const formattedCitations = useSelector((state: RootState) => selectFormattedCitationsByBlockId(state, citationBlockId))
// 在组件中使用引用数据
// {formattedCitations.map(citation => ...)}
```
## 集成
`messageBlock.ts` slice 通常与 `messageThunk.ts` 中的 Thunks 紧密协作。Thunks 负责处理异步逻辑(如 API 调用、数据库操作),并在需要时 dispatch `messageBlock` slice 的 actions 来更新状态。例如,当 `messageThunk` 接收到流式响应时,它会 dispatch `upsertOneBlock` 或 `updateOneBlock` 来实时更新对应的 `MessageBlock`。同样,删除消息的 Thunk 会 dispatch `removeManyBlocks`。
理解 `messageBlock.ts` 的职责是管理**状态本身**,而 `messageThunk.ts` 负责**触发状态变更**的异步流程,这对于维护清晰的应用架构至关重要。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/Message.md
|
CherryHQ__cherry-studio/docs/technical/Message.md
| 59 | 1,758,202,168 |
en
|
# 消息的生命周期

|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/CodeBlockView-zh.md
|
CherryHQ__cherry-studio/docs/technical/CodeBlockView-zh.md
| 4,524 | 1,758,202,168 |
en
|
# CodeBlockView 组件结构说明
## 概述
CodeBlockView 是 Cherry Studio 中用于显示和操作代码块的核心组件。它支持多种视图模式和特殊语言的可视化预览,提供丰富的交互工具。
## 组件结构
```mermaid
graph TD
A[CodeBlockView] --> B[CodeToolbar]
A --> C[SourceView]
A --> D[SpecialView]
A --> E[StatusBar]
B --> F[CodeToolButton]
C --> G[CodeEditor / CodeViewer]
D --> H[MermaidPreview]
D --> I[PlantUmlPreview]
D --> J[SvgPreview]
D --> K[GraphvizPreview]
F --> L[useCopyTool]
F --> M[useDownloadTool]
F --> N[useViewSourceTool]
F --> O[useSplitViewTool]
F --> P[useRunTool]
F --> Q[useExpandTool]
F --> R[useWrapTool]
F --> S[useSaveTool]
```
## 核心概念
### 视图类型
- **preview**: 预览视图,非源代码的是特殊视图
- **edit**: 编辑视图
### 视图模式
- **source**: 源代码视图模式
- **special**: 特殊视图模式(Mermaid、PlantUML、SVG)
- **split**: 分屏模式(源代码和特殊视图并排显示)
### 特殊视图语言
- mermaid
- plantuml
- svg
- dot
- graphviz
## 组件详细说明
### CodeBlockView 主组件
主要负责:
1. 管理视图模式状态
2. 协调源代码视图和特殊视图的显示
3. 管理工具栏工具
4. 处理代码执行状态
### 子组件
#### CodeToolbar 工具栏
- 显示在代码块右上角的工具栏
- 包含核心(core)和快捷(quick)两类工具
- 根据上下文动态显示相关工具
#### CodeEditor/CodeViewer 源代码视图
- 可编辑的代码编辑器或只读的代码查看器
- 根据设置决定使用哪个组件
- 支持多种编程语言高亮
#### 特殊视图组件
- **MermaidPreview**: Mermaid 图表预览
- **PlantUmlPreview**: PlantUML 图表预览
- **SvgPreview**: SVG 图像预览
- **GraphvizPreview**: Graphviz 图表预览
所有特殊视图组件共享通用架构,以确保一致的用户体验和功能。有关这些组件及其实现的详细信息,请参阅 [图像预览组件文档](./ImagePreview-zh.md)。
#### StatusBar 状态栏
- 显示 Python 代码执行结果
- 可显示文本和图像结果
## 工具系统
CodeBlockView 使用基于 hooks 的工具系统:
```mermaid
graph TD
A[CodeBlockView] --> B[useCopyTool]
A --> C[useDownloadTool]
A --> D[useViewSourceTool]
A --> E[useSplitViewTool]
A --> F[useRunTool]
A --> G[useExpandTool]
A --> H[useWrapTool]
A --> I[useSaveTool]
B --> J[ToolManager]
C --> J
D --> J
E --> J
F --> J
G --> J
H --> J
I --> J
J --> K[CodeToolbar]
```
每个工具 hook 负责注册特定功能的工具按钮到工具管理器,工具管理器再将这些工具传递给 CodeToolbar 组件进行渲染。
### 工具类型
- **core**: 核心工具,始终显示在工具栏
- **quick**: 快捷工具,当数量大于1时通过下拉菜单显示
### 工具列表
1. **复制(copy)**: 复制代码或图像
2. **下载(download)**: 下载代码或图像
3. **查看源码(view-source)**: 在特殊视图和源码视图间切换
4. **分屏(split-view)**: 切换分屏模式
5. **运行(run)**: 运行 Python 代码
6. **展开/折叠(expand)**: 控制代码块的展开/折叠
7. **换行(wrap)**: 控制代码的自动换行
8. **保存(save)**: 保存编辑的代码
## 状态管理
CodeBlockView 通过 React hooks 管理以下状态:
1. **viewMode**: 当前视图模式 ('source' | 'special' | 'split')
2. **isRunning**: Python 代码执行状态
3. **executionResult**: Python 代码执行结果
4. **tools**: 工具栏工具列表
5. **expandOverride/unwrapOverride**: 用户展开/换行的覆盖设置
6. **sourceScrollHeight**: 源代码视图滚动高度
## 交互流程
```mermaid
sequenceDiagram
participant U as User
participant CB as CodeBlockView
participant CT as CodeToolbar
participant SV as SpecialView
participant SE as SourceEditor
U->>CB: 查看代码块
CB->>CB: 初始化状态
CB->>CT: 注册工具
CB->>SV: 渲染特殊视图(如果适用)
CB->>SE: 渲染源码视图
U->>CT: 点击工具按钮
CT->>CB: 触发工具回调
CB->>CB: 更新状态
CB->>CT: 重新注册工具(如果需要)
```
## 特殊处理
### HTML 代码块
HTML 代码块会被特殊处理,使用 HtmlArtifactsCard 组件显示。
### Python 代码执行
支持执行 Python 代码并显示结果,使用 Pyodide 在浏览器中运行 Python 代码。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/CodeBlockView-en.md
|
CherryHQ__cherry-studio/docs/technical/CodeBlockView-en.md
| 4,733 | 1,758,202,168 |
en
|
# CodeBlockView Component Structure
## Overview
CodeBlockView is the core component in Cherry Studio for displaying and manipulating code blocks. It supports multiple view modes and visual previews for special languages, providing rich interactive tools.
## Component Structure
```mermaid
graph TD
A[CodeBlockView] --> B[CodeToolbar]
A --> C[SourceView]
A --> D[SpecialView]
A --> E[StatusBar]
B --> F[CodeToolButton]
C --> G[CodeEditor / CodeViewer]
D --> H[MermaidPreview]
D --> I[PlantUmlPreview]
D --> J[SvgPreview]
D --> K[GraphvizPreview]
F --> L[useCopyTool]
F --> M[useDownloadTool]
F --> N[useViewSourceTool]
F --> O[useSplitViewTool]
F --> P[useRunTool]
F --> Q[useExpandTool]
F --> R[useWrapTool]
F --> S[useSaveTool]
```
## Core Concepts
### View Types
- **preview**: Preview view, where non-source code is displayed as special views
- **edit**: Edit view
### View Modes
- **source**: Source code view mode
- **special**: Special view mode (Mermaid, PlantUML, SVG)
- **split**: Split view mode (source code and special view displayed side by side)
### Special View Languages
- mermaid
- plantuml
- svg
- dot
- graphviz
## Component Details
### CodeBlockView Main Component
Main responsibilities:
1. Managing view mode state
2. Coordinating the display of source code view and special view
3. Managing toolbar tools
4. Handling code execution state
### Subcomponents
#### CodeToolbar
- Toolbar displayed at the top-right corner of the code block
- Contains core and quick tools
- Dynamically displays relevant tools based on context
#### CodeEditor/CodeViewer Source View
- Editable code editor or read-only code viewer
- Uses either component based on settings
- Supports syntax highlighting for multiple programming languages
#### Special View Components
- **MermaidPreview**: Mermaid diagram preview
- **PlantUmlPreview**: PlantUML diagram preview
- **SvgPreview**: SVG image preview
- **GraphvizPreview**: Graphviz diagram preview
All special view components share a common architecture for consistent user experience and functionality. For detailed information about these components and their implementation, see [Image Preview Components Documentation](./ImagePreview-en.md).
#### StatusBar
- Displays Python code execution results
- Can show both text and image results
## Tool System
CodeBlockView uses a hook-based tool system:
```mermaid
graph TD
A[CodeBlockView] --> B[useCopyTool]
A --> C[useDownloadTool]
A --> D[useViewSourceTool]
A --> E[useSplitViewTool]
A --> F[useRunTool]
A --> G[useExpandTool]
A --> H[useWrapTool]
A --> I[useSaveTool]
B --> J[ToolManager]
C --> J
D --> J
E --> J
F --> J
G --> J
H --> J
I --> J
J --> K[CodeToolbar]
```
Each tool hook is responsible for registering specific function tool buttons to the tool manager, which then passes these tools to the CodeToolbar component for rendering.
### Tool Types
- **core**: Core tools, always displayed in the toolbar
- **quick**: Quick tools, displayed in a dropdown menu when there are more than one
### Tool List
1. **Copy**: Copy code or image
2. **Download**: Download code or image
3. **View Source**: Switch between special view and source code view
4. **Split View**: Toggle split view mode
5. **Run**: Run Python code
6. **Expand/Collapse**: Control code block expansion/collapse
7. **Wrap**: Control automatic line wrapping
8. **Save**: Save edited code
## State Management
CodeBlockView manages the following states through React hooks:
1. **viewMode**: Current view mode ('source' | 'special' | 'split')
2. **isRunning**: Python code execution status
3. **executionResult**: Python code execution result
4. **tools**: Toolbar tool list
5. **expandOverride/unwrapOverride**: User override settings for expand/wrap
6. **sourceScrollHeight**: Source code view scroll height
## Interaction Flow
```mermaid
sequenceDiagram
participant U as User
participant CB as CodeBlockView
participant CT as CodeToolbar
participant SV as SpecialView
participant SE as SourceEditor
U->>CB: View code block
CB->>CB: Initialize state
CB->>CT: Register tools
CB->>SV: Render special view (if applicable)
CB->>SE: Render source view
U->>CT: Click tool button
CT->>CB: Trigger tool callback
CB->>CB: Update state
CB->>CT: Re-register tools (if needed)
```
## Special Handling
### HTML Code Blocks
HTML code blocks are specially handled using the HtmlArtifactsCard component.
### Python Code Execution
Supports executing Python code and displaying results using Pyodide to run Python code in the browser.
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-use-useMessageOperations.md
|
CherryHQ__cherry-studio/docs/technical/how-to-use-useMessageOperations.md
| 6,600 | 1,758,202,168 |
en
|
# useMessageOperations.ts 使用指南
该文件定义了一个名为 `useMessageOperations` 的自定义 React Hook。这个 Hook 的主要目的是为 React 组件提供一个便捷的接口,用于执行与特定主题(Topic)相关的各种消息操作。它封装了调用 Redux Thunks (`messageThunk.ts`) 和 Actions (`newMessage.ts`, `messageBlock.ts`) 的逻辑,简化了组件与消息数据交互的代码。
## 核心目标
- **封装**: 将复杂的消息操作逻辑(如删除、重发、重新生成、编辑、翻译等)封装在易于使用的函数中。
- **简化**: 让组件可以直接调用这些操作函数,而无需直接与 Redux `dispatch` 或 Thunks 交互。
- **上下文关联**: 所有操作都与传入的 `topic` 对象相关联,确保操作作用于正确的主题。
## 如何使用
在你的 React 函数组件中,导入并调用 `useMessageOperations` Hook,并传入当前活动的 `Topic` 对象。
```typescript
import React from 'react';
import { useMessageOperations } from '@renderer/hooks/useMessageOperations';
import type { Topic, Message, Assistant, Model } from '@renderer/types';
interface MyComponentProps {
currentTopic: Topic;
currentAssistant: Assistant;
}
function MyComponent({ currentTopic, currentAssistant }: MyComponentProps) {
const {
deleteMessage,
resendMessage,
regenerateAssistantMessage,
appendAssistantResponse,
getTranslationUpdater,
createTopicBranch,
// ... 其他操作函数
} = useMessageOperations(currentTopic);
const handleDelete = (messageId: string) => {
deleteMessage(messageId);
};
const handleResend = (message: Message) => {
resendMessage(message, currentAssistant);
};
const handleAppend = (existingMsg: Message, newModel: Model) => {
appendAssistantResponse(existingMsg, newModel, currentAssistant);
}
// ... 在组件中使用其他操作函数
return (
<div>
{/* Component UI */}
<button onClick={() => handleDelete('some-message-id')}>Delete Message</button>
{/* ... */}
</div>
);
}
```
## 返回值
`useMessageOperations(topic)` Hook 返回一个包含以下函数和值的对象:
- **`deleteMessage(id: string)`**:
- 删除指定 `id` 的单个消息。
- 内部调用 `deleteSingleMessageThunk`。
- **`deleteGroupMessages(askId: string)`**:
- 删除与指定 `askId` 相关联的一组消息(通常是用户提问及其所有助手回答)。
- 内部调用 `deleteMessageGroupThunk`。
- **`editMessage(messageId: string, updates: Partial<Message>)`**:
- 更新指定 `messageId` 的消息的部分属性。
- **注意**: 目前主要用于更新 Redux 状态
- 内部调用 `newMessagesActions.updateMessage`。
- **`resendMessage(message: Message, assistant: Assistant)`**:
- 重新发送指定的用户消息 (`message`),这将触发其所有关联助手响应的重新生成。
- 内部调用 `resendMessageThunk`。
- **`resendUserMessageWithEdit(message: Message, editedContent: string, assistant: Assistant)`**:
- 在用户消息的主要文本块被编辑后,重新发送该消息。
- 会先查找消息的 `MAIN_TEXT` 块 ID,然后调用 `resendUserMessageWithEditThunk`。
- **`clearTopicMessages(_topicId?: string)`**:
- 清除当前主题(或可选的指定 `_topicId`)下的所有消息。
- 内部调用 `clearTopicMessagesThunk`。
- **`createNewContext()`**:
- 发出一个全局事件 (`EVENT_NAMES.NEW_CONTEXT`),通常用于通知 UI 清空显示,准备新的上下文。不直接修改 Redux 状态。
- **`displayCount`**:
- (非操作函数) 从 Redux store 中获取当前的 `displayCount` 值。
- **`pauseMessages()`**:
- 尝试中止当前主题中正在进行的消息生成(状态为 `processing` 或 `pending`)。
- 通过查找相关的 `askId` 并调用 `abortCompletion` 来实现。
- 同时会 dispatch `setTopicLoading` action 将加载状态设为 `false`。
- **`resumeMessage(message: Message, assistant: Assistant)`**:
- 恢复/重新发送一个用户消息。目前实现为直接调用 `resendMessage`。
- **`regenerateAssistantMessage(message: Message, assistant: Assistant)`**:
- 重新生成指定的**助手**消息 (`message`) 的响应。
- 内部调用 `regenerateAssistantResponseThunk`。
- **`appendAssistantResponse(existingAssistantMessage: Message, newModel: Model, assistant: Assistant)`**:
- 针对 `existingAssistantMessage` 所回复的**同一用户提问**,使用 `newModel` 追加一个新的助手响应。
- 内部调用 `appendAssistantResponseThunk`。
- **`getTranslationUpdater(messageId: string, targetLanguage: string, sourceBlockId?: string, sourceLanguage?: string)`**:
- **用途**: 获取一个用于逐步更新翻译块内容的函数。
- **流程**:
1. 内部调用 `initiateTranslationThunk` 来创建或获取一个 `TRANSLATION` 类型的 `MessageBlock`,并获取其 `blockId`。
2. 返回一个**异步更新函数**。
- **返回的更新函数 `(accumulatedText: string, isComplete?: boolean) => void`**:
- 接收累积的翻译文本和完成状态。
- 调用 `updateOneBlock` 更新 Redux 中的翻译块内容和状态 (`STREAMING` 或 `SUCCESS`)。
- 调用 `throttledBlockDbUpdate` 将更新(节流地)保存到数据库。
- 如果初始化失败(Thunk 返回 `undefined`),则此函数返回 `null`。
- **`createTopicBranch(sourceTopicId: string, branchPointIndex: number, newTopic: Topic)`**:
- 创建一个主题分支,将 `sourceTopicId` 主题中 `branchPointIndex` 索引之前的消息克隆到 `newTopic` 中。
- **注意**: `newTopic` 对象必须是调用此函数**之前**已经创建并添加到 Redux 和数据库中的。
- 内部调用 `cloneMessagesToNewTopicThunk`。
## 依赖
- **`topic: Topic`**: 必须传入当前操作上下文的主题对象。Hook 返回的操作函数将始终作用于这个主题的 `topic.id`。
- **Redux `dispatch`**: Hook 内部使用 `useAppDispatch` 获取 `dispatch` 函数来调用 actions 和 thunks。
## 相关 Hooks
在同一文件中还定义了两个辅助 Hook:
- **`useTopicMessages(topic: Topic)`**:
- 使用 `selectMessagesForTopic` selector 来获取并返回指定主题的消息列表。
- **`useTopicLoading(topic: Topic)`**:
- 使用 `selectNewTopicLoading` selector 来获取并返回指定主题的加载状态。
这些 Hook 可以与 `useMessageOperations` 结合使用,方便地在组件中获取消息数据、加载状态,并执行相关操作。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-write-middlewares.md
|
CherryHQ__cherry-studio/docs/technical/how-to-write-middlewares.md
| 13,069 | 1,758,202,168 |
en
|
# 如何为 AI Provider 编写中间件
本文档旨在指导开发者如何为我们的 AI Provider 框架创建和集成自定义中间件。中间件提供了一种强大而灵活的方式来增强、修改或观察 Provider 方法的调用过程,例如日志记录、缓存、请求/响应转换、错误处理等。
## 架构概览
我们的中间件架构借鉴了 Redux 的三段式设计,并结合了 JavaScript Proxy 来动态地将中间件应用于 Provider 的方法。
- **Proxy**: 拦截对 Provider 方法的调用,并将调用引导至中间件链。
- **中间件链**: 一系列按顺序执行的中间件函数。每个中间件都可以处理请求/响应,然后将控制权传递给链中的下一个中间件,或者在某些情况下提前终止链。
- **上下文 (Context)**: 一个在中间件之间传递的对象,携带了关于当前调用的信息(如方法名、原始参数、Provider 实例、以及中间件自定义的数据)。
## 中间件的类型
目前主要支持两种类型的中间件,它们共享相似的结构但针对不同的场景:
1. **`CompletionsMiddleware`**: 专门为 `completions` 方法设计。这是最常用的中间件类型,因为它允许对 AI 模型的核心聊天/文本生成功能进行精细控制。
2. **`ProviderMethodMiddleware`**: 通用中间件,可以应用于 Provider 上的任何其他方法(例如,`translate`, `summarize` 等,如果这些方法也通过中间件系统包装)。
## 编写一个 `CompletionsMiddleware`
`CompletionsMiddleware` 的基本签名(TypeScript 类型)如下:
```typescript
import { AiProviderMiddlewareCompletionsContext, CompletionsParams, MiddlewareAPI } from './AiProviderMiddlewareTypes' // 假设类型定义文件路径
export type CompletionsMiddleware = (
api: MiddlewareAPI<AiProviderMiddlewareCompletionsContext, [CompletionsParams]>
) => (
next: (context: AiProviderMiddlewareCompletionsContext, params: CompletionsParams) => Promise<any> // next 返回 Promise<any> 代表原始SDK响应或下游中间件的结果
) => (context: AiProviderMiddlewareCompletionsContext, params: CompletionsParams) => Promise<void> // 最内层函数通常返回 Promise<void>,因为结果通过 onChunk 或 context 副作用传递
```
让我们分解这个三段式结构:
1. **第一层函数 `(api) => { ... }`**:
- 接收一个 `api` 对象。
- `api` 对象提供了以下方法:
- `api.getContext()`: 获取当前调用的上下文对象 (`AiProviderMiddlewareCompletionsContext`)。
- `api.getOriginalArgs()`: 获取传递给 `completions` 方法的原始参数数组 (即 `[CompletionsParams]`)。
- `api.getProviderId()`: 获取当前 Provider 的 ID。
- `api.getProviderInstance()`: 获取原始的 Provider 实例。
- 此函数通常用于进行一次性的设置或获取所需的服务/配置。它返回第二层函数。
2. **第二层函数 `(next) => { ... }`**:
- 接收一个 `next` 函数。
- `next` 函数代表了中间件链中的下一个环节。调用 `next(context, params)` 会将控制权传递给下一个中间件,或者如果当前中间件是链中的最后一个,则会调用核心的 Provider 方法逻辑 (例如,实际的 SDK 调用)。
- `next` 函数接收当前的 `context` 和 `params` (这些可能已被上游中间件修改)。
- **重要的是**:`next` 的返回类型通常是 `Promise<any>`。对于 `completions` 方法,如果 `next` 调用了实际的 SDK,它将返回原始的 SDK 响应(例如,OpenAI 的流对象或 JSON 对象)。你需要处理这个响应。
- 此函数返回第三层(也是最核心的)函数。
3. **第三层函数 `(context, params) => { ... }`**:
- 这是执行中间件主要逻辑的地方。
- 它接收当前的 `context` (`AiProviderMiddlewareCompletionsContext`) 和 `params` (`CompletionsParams`)。
- 在此函数中,你可以:
- **在调用 `next` 之前**:
- 读取或修改 `params`。例如,添加默认参数、转换消息格式。
- 读取或修改 `context`。例如,设置一个时间戳用于后续计算延迟。
- 执行某些检查,如果不满足条件,可以不调用 `next` 而直接返回或抛出错误(例如,参数校验失败)。
- **调用 `await next(context, params)`**:
- 这是将控制权传递给下游的关键步骤。
- `next` 的返回值是原始的 SDK 响应或下游中间件的结果,你需要根据情况处理它(例如,如果是流,则开始消费流)。
- **在调用 `next` 之后**:
- 处理 `next` 的返回结果。例如,如果 `next` 返回了一个流,你可以在这里开始迭代处理这个流,并通过 `context.onChunk` 发送数据块。
- 基于 `context` 的变化或 `next` 的结果执行进一步操作。例如,计算总耗时、记录日志。
- 修改最终结果(尽管对于 `completions`,结果通常通过 `onChunk` 副作用发出)。
### 示例:一个简单的日志中间件
```typescript
import {
AiProviderMiddlewareCompletionsContext,
CompletionsParams,
MiddlewareAPI,
OnChunkFunction // 假设 OnChunkFunction 类型被导出
} from './AiProviderMiddlewareTypes' // 调整路径
import { ChunkType } from '@renderer/types' // 调整路径
export const createSimpleLoggingMiddleware = (): CompletionsMiddleware => {
return (api: MiddlewareAPI<AiProviderMiddlewareCompletionsContext, [CompletionsParams]>) => {
return (next: (context: AiProviderMiddlewareCompletionsContext, params: CompletionsParams) => Promise<any>) => {
return async (context: AiProviderMiddlewareCompletionsContext, params: CompletionsParams): Promise<void> => {
const startTime = Date.now()
// 从 context 中获取 onChunk (它最初来自 params.onChunk)
const onChunk = context.onChunk
logger.debug(
`[LoggingMiddleware] Request for ${context.methodName} with params:`,
params.messages?.[params.messages.length - 1]?.content
)
try {
// 调用下一个中间件或核心逻辑
// `rawSdkResponse` 是来自下游的原始响应 (例如 OpenAIStream 或 ChatCompletion 对象)
const rawSdkResponse = await next(context, params)
// 此处简单示例不处理 rawSdkResponse,假设下游中间件 (如 StreamingResponseHandler)
// 会处理它并通过 onChunk 发送数据。
// 如果这个日志中间件在 StreamingResponseHandler 之后,那么流已经被处理。
// 如果在之前,那么它需要自己处理 rawSdkResponse 或确保下游会处理。
const duration = Date.now() - startTime
logger.debug(`[LoggingMiddleware] Request for ${context.methodName} completed in ${duration}ms.`)
// 假设下游已经通过 onChunk 发送了所有数据。
// 如果这个中间件是链的末端,并且需要确保 BLOCK_COMPLETE 被发送,
// 它可能需要更复杂的逻辑来跟踪何时所有数据都已发送。
} catch (error) {
const duration = Date.now() - startTime
logger.error(`[LoggingMiddleware] Request for ${context.methodName} failed after ${duration}ms:`, error)
// 如果 onChunk 可用,可以尝试发送一个错误块
if (onChunk) {
onChunk({
type: ChunkType.ERROR,
error: { message: (error as Error).message, name: (error as Error).name, stack: (error as Error).stack }
})
// 考虑是否还需要发送 BLOCK_COMPLETE 来结束流
onChunk({ type: ChunkType.BLOCK_COMPLETE, response: {} })
}
throw error // 重新抛出错误,以便上层或全局错误处理器可以捕获
}
}
}
}
}
```
### `AiProviderMiddlewareCompletionsContext` 的重要性
`AiProviderMiddlewareCompletionsContext` 是在中间件之间传递状态和数据的核心。它通常包含:
- `methodName`: 当前调用的方法名 (总是 `'completions'`)。
- `originalArgs`: 传递给 `completions` 的原始参数数组。
- `providerId`: Provider 的 ID。
- `_providerInstance`: Provider 实例。
- `onChunk`: 从原始 `CompletionsParams` 传入的回调函数,用于流式发送数据块。**所有中间件都应该通过 `context.onChunk` 来发送数据。**
- `messages`, `model`, `assistant`, `mcpTools`: 从原始 `CompletionsParams` 中提取的常用字段,方便访问。
- **自定义字段**: 中间件可以向上下文中添加自定义字段,以供后续中间件使用。例如,一个缓存中间件可能会添加 `context.cacheHit = true`。
**关键**: 当你在中间件中修改 `params` 或 `context` 时,这些修改会向下游中间件传播(如果它们在 `next` 调用之前修改)。
### 中间件的顺序
中间件的执行顺序非常重要。它们在 `AiProviderMiddlewareConfig` 的数组中定义的顺序就是它们的执行顺序。
- 请求首先通过第一个中间件,然后是第二个,依此类推。
- 响应(或 `next` 的调用结果)则以相反的顺序"冒泡"回来。
例如,如果链是 `[AuthMiddleware, CacheMiddleware, LoggingMiddleware]`:
1. `AuthMiddleware` 先执行其 "调用 `next` 之前" 的逻辑。
2. 然后 `CacheMiddleware` 执行其 "调用 `next` 之前" 的逻辑。
3. 然后 `LoggingMiddleware` 执行其 "调用 `next` 之前" 的逻辑。
4. 核心SDK调用(或链的末端)。
5. `LoggingMiddleware` 先接收到结果,执行其 "调用 `next` 之后" 的逻辑。
6. 然后 `CacheMiddleware` 接收到结果(可能已被 LoggingMiddleware 修改的上下文),执行其 "调用 `next` 之后" 的逻辑(例如,存储结果)。
7. 最后 `AuthMiddleware` 接收到结果,执行其 "调用 `next` 之后" 的逻辑。
### 注册中间件
中间件在 `src/renderer/src/providers/middleware/register.ts` (或其他类似的配置文件) 中进行注册。
```typescript
// register.ts
import { AiProviderMiddlewareConfig } from './AiProviderMiddlewareTypes'
import { createSimpleLoggingMiddleware } from './common/SimpleLoggingMiddleware' // 假设你创建了这个文件
import { createCompletionsLoggingMiddleware } from './common/CompletionsLoggingMiddleware' // 已有的
const middlewareConfig: AiProviderMiddlewareConfig = {
completions: [
createSimpleLoggingMiddleware(), // 你新加的中间件
createCompletionsLoggingMiddleware() // 已有的日志中间件
// ... 其他 completions 中间件
],
methods: {
// translate: [createGenericLoggingMiddleware()],
// ... 其他方法的中间件
}
}
export default middlewareConfig
```
### 最佳实践
1. **单一职责**: 每个中间件应专注于一个特定的功能(例如,日志、缓存、转换特定数据)。
2. **无副作用 (尽可能)**: 除了通过 `context` 或 `onChunk` 明确的副作用外,尽量避免修改全局状态或产生其他隐蔽的副作用。
3. **错误处理**:
- 在中间件内部使用 `try...catch` 来处理可能发生的错误。
- 决定是自行处理错误(例如,通过 `onChunk` 发送错误块)还是将错误重新抛出给上游。
- 如果重新抛出,确保错误对象包含足够的信息。
4. **性能考虑**: 中间件会增加请求处理的开销。避免在中间件中执行非常耗时的同步操作。对于IO密集型操作,确保它们是异步的。
5. **可配置性**: 使中间件的行为可通过参数或配置进行调整。例如,日志中间件可以接受一个日志级别参数。
6. **上下文管理**:
- 谨慎地向 `context` 添加数据。避免污染 `context` 或添加过大的对象。
- 明确你添加到 `context` 的字段的用途和生命周期。
7. **`next` 的调用**:
- 除非你有充分的理由提前终止请求(例如,缓存命中、授权失败),否则**总是确保调用 `await next(context, params)`**。否则,下游的中间件和核心逻辑将不会执行。
- 理解 `next` 的返回值并正确处理它,特别是当它是一个流时。你需要负责消费这个流或将其传递给另一个能够消费它的组件/中间件。
8. **命名清晰**: 给你的中间件和它们创建的函数起描述性的名字。
9. **文档和注释**: 对复杂的中间件逻辑添加注释,解释其工作原理和目的。
### 调试技巧
- 在中间件的关键点使用 `logger.debug` 或调试器来检查 `params`、`context` 的状态以及 `next` 的返回值。
- 暂时简化中间件链,只保留你正在调试的中间件和最简单的核心逻辑,以隔离问题。
- 编写单元测试来独立验证每个中间件的行为。
通过遵循这些指南,你应该能够有效地为我们的系统创建强大且可维护的中间件。如果你有任何疑问或需要进一步的帮助,请咨询团队。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-i18n-en.md
|
CherryHQ__cherry-studio/docs/technical/how-to-i18n-en.md
| 5,398 | 1,758,202,168 |
en
|
# How to Do i18n Gracefully
> [!WARNING]
> This document is machine translated from Chinese. While we strive for accuracy, there may be some imperfections in the translation.
## Enhance Development Experience with the i18n Ally Plugin
i18n Ally is a powerful VSCode extension that provides real-time feedback during development, helping developers detect missing or incorrect translations earlier.
The plugin has already been configured in the project — simply install it to get started.
### Advantages During Development
- **Real-time Preview**: Translated texts are displayed directly in the editor.
- **Error Detection**: Automatically tracks and highlights missing translations or unused keys.
- **Quick Navigation**: Jump to key definitions with Ctrl/Cmd + click.
- **Auto-completion**: Provides suggestions when typing i18n keys.
### Demo



## i18n Conventions
### **Avoid Flat Structure at All Costs**
Never use flat structures like `"add.button.tip": "Add"`. Instead, adopt a clear nested structure:
```json
// Wrong - Flat structure
{
"add.button.tip": "Add",
"delete.button.tip": "Delete"
}
// Correct - Nested structure
{
"add": {
"button": {
"tip": "Add"
}
},
"delete": {
"button": {
"tip": "Delete"
}
}
}
```
#### Why Use Nested Structure?
1. **Natural Grouping**: Related texts are logically grouped by their context through object nesting.
2. **Plugin Requirement**: Tools like i18n Ally require either flat or nested format to properly analyze translation files.
### **Avoid Template Strings in `t()`**
**We strongly advise against using template strings for dynamic interpolation.** While convenient in general JavaScript development, they cause several issues in i18n scenarios.
#### 1. **Plugin Cannot Track Dynamic Keys**
Tools like i18n Ally cannot parse dynamic content within template strings, resulting in:
- No real-time preview
- No detection of missing translations
- No navigation to key definitions
```javascript
// Not recommended - Plugin cannot resolve
const message = t(`fruits.${fruit}`)
```
#### 2. **No Real-time Rendering in Editor**
Template strings appear as raw code instead of the final translated text in IDEs, degrading the development experience.
#### 3. **Harder to Maintain**
Since the plugin cannot track such usages, developers must manually verify the existence of corresponding keys in language files.
### Recommended Approach
To avoid missing keys, all dynamically translated texts should first maintain a `FooKeyMap`, then retrieve the translation text through a function.
For example:
```ts
// src/renderer/src/i18n/label.ts
const themeModeKeyMap = {
dark: 'settings.theme.dark',
light: 'settings.theme.light',
system: 'settings.theme.system'
} as const
export const getThemeModeLabel = (key: string): string => {
return themeModeKeyMap[key] ? t(themeModeKeyMap[key]) : key
}
```
By avoiding template strings, you gain better developer experience, more reliable translation checks, and a more maintainable codebase.
## Automation Scripts
The project includes several scripts to automate i18n-related tasks:
### `check:i18n` - Validate i18n Structure
This script checks:
- Whether all language files use nested structure
- For missing or unused keys
- Whether keys are properly sorted
```bash
yarn check:i18n
```
### `sync:i18n` - Synchronize JSON Structure and Sort Order
This script uses `zh-cn.json` as the source of truth to sync structure across all language files, including:
1. Adding missing keys, with placeholder `[to be translated]`
2. Removing obsolete keys
3. Sorting keys automatically
```bash
yarn sync:i18n
```
### `auto:i18n` - Automatically Translate Pending Texts
This script fills in texts marked as `[to be translated]` using machine translation.
Typically, after adding new texts in `zh-cn.json`, run `sync:i18n`, then `auto:i18n` to complete translations.
Before using this script, set the required environment variables:
```bash
API_KEY="sk-xxx"
BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1/"
MODEL="qwen-plus-latest"
```
Alternatively, add these variables directly to your `.env` file.
```bash
yarn auto:i18n
```
### `update:i18n` - Object-level Translation Update
Updates translations in language files under `src/renderer/src/i18n/translate` at the object level, preserving existing translations and only updating new content.
**Not recommended** — prefer `auto:i18n` for translation tasks.
```bash
yarn update:i18n
```
### Workflow
1. During development, first add the required text in `zh-cn.json`
2. Confirm it displays correctly in the Chinese environment
3. Run `yarn sync:i18n` to propagate the keys to other language files
4. Run `yarn auto:i18n` to perform machine translation
5. Grab a coffee and let the magic happen!
## Best Practices
1. **Use Chinese as Source Language**: All development starts in Chinese, then translates to other languages.
2. **Run Check Script Before Commit**: Use `yarn check:i18n` to catch i18n issues early.
3. **Translate in Small Increments**: Avoid accumulating a large backlog of untranslated content.
4. **Keep Keys Semantically Clear**: Keys should clearly express their purpose, e.g., `user.profile.avatar.upload.error`
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-use-logger-en.md
|
CherryHQ__cherry-studio/docs/technical/how-to-use-logger-en.md
| 13,295 | 1,758,202,168 |
en
|
# How to use the LoggerService
This is a developer document on how to use the logger.
CherryStudio uses a unified logging service to print and record logs. **Unless there is a special reason, do not use `console.xxx` to print logs**.
The following are detailed instructions.
## Usage in the `main` process
### Importing
```typescript
import { loggerService } from '@logger'
```
### Setting module information (Required by convention)
After the import statements, set it up as follows:
```typescript
const logger = loggerService.withContext('moduleName')
```
- `moduleName` is the name of the current file's module. It can be named after the filename, main class name, main function name, etc. The principle is to be clear and understandable.
- `moduleName` will be printed in the terminal and will also be present in the file log, making it easier to filter.
### Setting `CONTEXT` information (Optional)
In `withContext`, you can also set other `CONTEXT` information:
```typescript
const logger = loggerService.withContext('moduleName', CONTEXT)
```
- `CONTEXT` is an object of the form `{ key: value, ... }`.
- `CONTEXT` information will not be printed in the terminal, but it will be recorded in the file log, making it easier to filter.
### Logging
In your code, you can call `logger` at any time to record logs. The supported levels are: `error`, `warn`, `info`, `verbose`, `debug`, and `silly`.
For the meaning of each level, please refer to the subsequent sections.
The following are the supported parameters for logging (using `logger.LEVEL` as an example, where `LEVEL` represents one of the levels mentioned above):
```typescript
logger.LEVEL(message)
logger.LEVEL(message, CONTEXT)
logger.LEVEL(message, error)
logger.LEVEL(message, error, CONTEXT)
```
**Only the four calling methods above are supported**.
| Parameter | Type | Description |
| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message` | `string` | Required. This is the core field of the log, containing the main content to be recorded. |
| `CONTEXT` | `object` | Optional. Additional information to be recorded in the log file. It is recommended to use the `{ key: value, ...}` format. |
| `error` | `Error` | Optional. The error stack trace will also be printed.<br />Note that the `error` caught by `catch(error)` is of the `unknown` type. According to TypeScript best practices, you should first use `instanceof` for type checking. If you are certain it is an `Error` type, you can also use a type assertion like `as Error`. |
#### Recording non-`object` type context information
```typescript
const foo = getFoo()
logger.debug(`foo ${foo}`)
```
### Log Levels
- In the development environment, all log levels are printed to the terminal and recorded in the file log.
- In the production environment, the default log level is `info`. Logs are only recorded to the file and are not printed to the terminal.
Changing the log level:
- You can change the log level with `logger.setLevel('newLevel')`.
- `logger.resetLevel()` resets it to the default level.
- `logger.getLevel()` gets the current log level.
**Note:** Changing the log level has a global effect. Please do not change it arbitrarily in your code unless you are very clear about what you are doing.
## Usage in the `renderer` process
Usage in the `renderer` process for _importing_, _setting module information_, and _setting context information_ is **exactly the same** as in the `main` process.
The following section focuses on the differences.
### `initWindowSource`
In the `renderer` process, there are different `window`s. Before starting to use the `logger`, we must set the `window` information:
```typescript
loggerService.initWindowSource('windowName')
```
As a rule, we will set this in the `window`'s `entryPoint.tsx`. This ensures that `windowName` is set before it's used.
- An error will be thrown if `windowName` is not set, and the `logger` will not work.
- `windowName` can only be set once; subsequent attempts to set it will have no effect.
- `windowName` will not be printed in the `devTool`'s `console`, but it will be recorded in the `main` process terminal and the file log.
- `initWindowSource` returns the LoggerService instance, allowing for method chaining.
### Log Levels
- In the development environment, all log levels are printed to the `devTool`'s `console` by default.
- In the production environment, the default log level is `info`, and logs are printed to the `devTool`'s `console`.
- In both development and production environments, `warn` and `error` level logs are, by default, transmitted to the `main` process and recorded in the file log.
- In the development environment, the `main` process terminal will also print the logs transmitted from the renderer.
#### Changing the Log Level
Same as in the `main` process, you can manage the log level using `setLevel('level')`, `resetLevel()`, and `getLevel()`.
Similarly, changing the log level is a global adjustment.
#### Changing the Level Transmitted to `main`
Logs from the `renderer` are sent to `main` to be managed and recorded to a file centrally (according to `main`'s file logging level). By default, only `warn` and `error` level logs are transmitted to `main`.
There are two ways to change the log level for transmission to `main`:
##### Global Change
The following methods can be used to set, reset, and get the log level for transmission to `main`, respectively.
```typescript
logger.setLogToMainLevel('newLevel')
logger.resetLogToMainLevel()
logger.getLogToMainLevel()
```
**Note:** This method has a global effect. Please do not change it arbitrarily in your code unless you are very clear about what you are doing.
##### Per-log Change
By adding `{ logToMain: true }` at the end of the log call, you can force a single log entry to be transmitted to `main` (bypassing the global log level restriction), for example:
```typescript
logger.info('message', { logToMain: true })
```
## About `worker` Threads
- Currently, logging is not supported for workers in the `main` process.
- Logging is supported for workers started in the `renderer` process, but currently these logs are not sent to `main` for recording.
### How to Use Logging in `renderer` Workers
Since worker threads are independent, using LoggerService in them is equivalent to using it in a new `renderer` window. Therefore, you must first call `initWindowSource`.
If the worker is relatively simple (just one file), you can also use method chaining directly:
```typescript
const logger = loggerService.initWindowSource('Worker').withContext('LetsWork')
```
## Filtering Logs with Environment Variables
In a development environment, you can define environment variables to filter displayed logs by level and module. This helps developers focus on their specific logs and improves development efficiency.
Environment variables can be set in the terminal or defined in the `.env` file in the project's root directory. The available variables are as follows:
| Variable Name | Description |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CSLOGGER_MAIN_LEVEL` | Log level for the `main` process. Logs below this level will not be displayed. |
| `CSLOGGER_MAIN_SHOW_MODULES` | Filters log modules for the `main` process. Use a comma (`,`) to separate modules. The filter is case-sensitive. Only logs from modules in this list will be displayed. |
| `CSLOGGER_RENDERER_LEVEL` | Log level for the `renderer` process. Logs below this level will not be displayed. |
| `CSLOGGER_RENDERER_SHOW_MODULES` | Filters log modules for the `renderer` process. Use a comma (`,`) to separate modules. The filter is case-sensitive. Only logs from modules in this list will be displayed. |
Example:
```bash
CSLOGGER_MAIN_LEVEL=verbose
CSLOGGER_MAIN_SHOW_MODULES=MCPService,SelectionService
```
Note:
- Environment variables are only effective in the development environment.
- These variables only affect the logs displayed in the terminal or DevTools. They do not affect file logging or the `logToMain` recording logic.
## Log Level Usage Guidelines
There are many log levels. The following are the guidelines that should be followed in CherryStudio for when to use each level:
(Arranged from highest to lowest log level)
| Log Level | Core Definition & Use case | Example |
| :------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`error`** | **Critical error causing the program to crash or core functionality to become unusable.** <br> This is the highest-priority log, usually requiring immediate reporting or user notification. | - Main or renderer process crash. <br> - Failure to read/write critical user data files (e.g., database, configuration files), preventing the application from running. <br> - All unhandled exceptions. |
| **`warn`** | **Potential issue or unexpected situation that does not affect the program's core functionality.** <br> The program can recover or use a fallback. | - Configuration file `settings.json` is missing; started with default settings. <br> - Auto-update check failed, but does not affect the use of the current version. <br> - A non-essential plugin failed to load. |
| **`info`** | **Records application lifecycle events and key user actions.** <br> This is the default level that should be recorded in a production release to trace the user's main operational path. | - Application start, exit. <br> - User successfully opens/saves a file. <br> - Main window created/closed. <br> - Starting an important task (e.g., "Start video export"). |
| **`verbose`** | **More detailed flow information than `info`, used for tracing specific features.** <br> Enabled when diagnosing issues with a specific feature to help understand the internal execution flow. | - Loading `Toolbar` module. <br> - IPC message `open-file-dialog` sent from the renderer process. <br> - Applying filter 'Sepia' to the image. |
| **`debug`** | **Detailed diagnostic information used during development and debugging.** <br> **Must not be enabled by default in production releases**, as it may contain sensitive data and impact performance. | - Parameters for function `renderImage`: `{ width: 800, ... }`. <br> - Specific data content received by IPC message `save-file`. <br> - Details of Redux/Vuex state changes in the renderer process. |
| **`silly`** | **The most detailed, low-level information, used only for extreme debugging.** <br> Rarely used in regular development; only for solving very difficult problems. | - Real-time mouse coordinates `(x: 150, y: 320)`. <br> - Size of each data chunk when reading a file. <br> - Time taken for each rendered frame. |
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/db.settings.md
|
CherryHQ__cherry-studio/docs/technical/db.settings.md
| 527 | 1,758,202,168 |
en
|
# 数据库设置字段
此文档包含部分字段的数据类型说明。
## 字段
| 字段名 | 类型 | 说明 |
| ------------------------------ | ------------------------------ | ------------ |
| `translate:target:language` | `LanguageCode` | 翻译目标语言 |
| `translate:source:language` | `LanguageCode` | 翻译源语言 |
| `translate:bidirectional:pair` | `[LanguageCode, LanguageCode]` | 双向翻译对 |
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/ImagePreview-en.md
|
CherryHQ__cherry-studio/docs/technical/ImagePreview-en.md
| 5,564 | 1,758,202,168 |
en
|
# Image Preview Components
## Overview
Image Preview Components are a set of specialized components in Cherry Studio for rendering and displaying various diagram and image formats. They provide a consistent user experience across different preview types with shared functionality for loading states, error handling, and interactive controls.
## Supported Formats
- **Mermaid**: Interactive diagrams and flowcharts
- **PlantUML**: UML diagrams and system architecture
- **SVG**: Scalable vector graphics
- **Graphviz/DOT**: Graph visualization and network diagrams
## Architecture
```mermaid
graph TD
A[MermaidPreview] --> D[ImagePreviewLayout]
B[PlantUmlPreview] --> D
C[SvgPreview] --> D
E[GraphvizPreview] --> D
D --> F[ImageToolbar]
D --> G[useDebouncedRender]
F --> H[Pan Controls]
F --> I[Zoom Controls]
F --> J[Reset Function]
F --> K[Dialog Control]
G --> L[Debounced Rendering]
G --> M[Error Handling]
G --> N[Loading State]
G --> O[Dependency Management]
```
## Core Components
### ImagePreviewLayout
A common layout wrapper that provides the foundation for all image preview components.
**Features:**
- **Loading State Management**: Shows loading spinner during rendering
- **Error Display**: Displays error messages when rendering fails
- **Toolbar Integration**: Conditionally renders ImageToolbar when enabled
- **Container Management**: Wraps preview content with consistent styling
- **Responsive Design**: Adapts to different container sizes
**Props:**
- `children`: The preview content to be displayed
- `loading`: Boolean indicating if content is being rendered
- `error`: Error message to display if rendering fails
- `enableToolbar`: Whether to show the interactive toolbar
- `imageRef`: Reference to the container element for image manipulation
### ImageToolbar
Interactive toolbar component providing image manipulation controls.
**Features:**
- **Pan Controls**: 4-directional pan buttons (up, down, left, right)
- **Zoom Controls**: Zoom in/out functionality with configurable increments
- **Reset Function**: Restore original pan and zoom state
- **Dialog Control**: Open preview in expanded dialog view
- **Accessible Design**: Full keyboard navigation and screen reader support
**Layout:**
- 3x3 grid layout positioned at bottom-right of preview
- Responsive button sizing
- Tooltip support for all controls
### useDebouncedRender Hook
A specialized React hook for managing preview rendering with performance optimizations.
**Features:**
- **Debounced Rendering**: Prevents excessive re-renders during rapid content changes (default 300ms delay)
- **Automatic Dependency Management**: Handles dependencies for render and condition functions
- **Error Handling**: Catches and manages rendering errors with detailed error messages
- **Loading State**: Tracks rendering progress with automatic state updates
- **Conditional Rendering**: Supports pre-render condition checks
- **Manual Controls**: Provides trigger, cancel, and state management functions
**API:**
```typescript
const { containerRef, error, isLoading, triggerRender, cancelRender, clearError, setLoading } = useDebouncedRender(
value,
renderFunction,
options
)
```
**Options:**
- `debounceDelay`: Customize debounce timing
- `shouldRender`: Function for conditional rendering logic
## Component Implementations
### MermaidPreview
Renders Mermaid diagrams with special handling for visibility detection.
**Special Features:**
- Syntax validation before rendering
- Visibility detection to handle collapsed containers
- SVG coordinate fixing for edge cases
- Integration with mermaid.js library
### PlantUmlPreview
Renders PlantUML diagrams using the online PlantUML server.
**Special Features:**
- Network error handling and retry logic
- Diagram encoding using deflate compression
- Support for light/dark themes
- Server status monitoring
### SvgPreview
Renders SVG content using Shadow DOM for isolation.
**Special Features:**
- Shadow DOM rendering for style isolation
- Direct SVG content injection
- Minimal processing overhead
- Cross-browser compatibility
### GraphvizPreview
Renders Graphviz/DOT diagrams using the viz.js library.
**Special Features:**
- Client-side rendering with viz.js
- Lazy loading of viz.js library
- SVG element generation
- Memory-efficient processing
## Shared Functionality
### Error Handling
All preview components provide consistent error handling:
- Network errors (connection failures)
- Syntax errors (invalid diagram code)
- Server errors (external service failures)
- Rendering errors (library failures)
### Loading States
Standardized loading indicators across all components:
- Spinner animation during processing
- Progress feedback for long operations
- Smooth transitions between states
### Interactive Controls
Common interaction patterns:
- Pan and zoom functionality
- Reset to original view
- Full-screen dialog mode
- Keyboard accessibility
### Performance Optimizations
- Debounced rendering to prevent excessive updates
- Lazy loading of heavy libraries
- Memory management for large diagrams
- Efficient re-rendering strategies
## Integration with CodeBlockView
Image Preview Components integrate seamlessly with CodeBlockView:
- Automatic format detection based on language tags
- Consistent toolbar integration
- Shared state management
- Responsive layout adaptation
For more information about the overall CodeBlockView architecture, see [CodeBlockView Documentation](./CodeBlockView-en.md).
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/ImagePreview-zh.md
|
CherryHQ__cherry-studio/docs/technical/ImagePreview-zh.md
| 4,849 | 1,758,202,168 |
en
|
# 图像预览组件
## 概述
图像预览组件是 Cherry Studio 中用于渲染和显示各种图表和图像格式的专用组件集合。它们为不同预览类型提供一致的用户体验,具有共享的加载状态、错误处理和交互控制功能。
## 支持格式
- **Mermaid**: 交互式图表和流程图
- **PlantUML**: UML 图表和系统架构
- **SVG**: 可缩放矢量图形
- **Graphviz/DOT**: 图形可视化和网络图表
## 架构
```mermaid
graph TD
A[MermaidPreview] --> D[ImagePreviewLayout]
B[PlantUmlPreview] --> D
C[SvgPreview] --> D
E[GraphvizPreview] --> D
D --> F[ImageToolbar]
D --> G[useDebouncedRender]
F --> H[平移控制]
F --> I[缩放控制]
F --> J[重置功能]
F --> K[对话框控制]
G --> L[防抖渲染]
G --> M[错误处理]
G --> N[加载状态]
G --> O[依赖管理]
```
## 核心组件
### ImagePreviewLayout 图像预览布局
为所有图像预览组件提供基础的通用布局包装器。
**功能特性:**
- **加载状态管理**: 在渲染期间显示加载动画
- **错误显示**: 渲染失败时显示错误信息
- **工具栏集成**: 启用时有条件地渲染 ImageToolbar
- **容器管理**: 使用一致的样式包装预览内容
- **响应式设计**: 适应不同的容器尺寸
**属性:**
- `children`: 要显示的预览内容
- `loading`: 指示内容是否正在渲染的布尔值
- `error`: 渲染失败时显示的错误信息
- `enableToolbar`: 是否显示交互式工具栏
- `imageRef`: 用于图像操作的容器元素引用
### ImageToolbar 图像工具栏
提供图像操作控制的交互式工具栏组件。
**功能特性:**
- **平移控制**: 4方向平移按钮(上、下、左、右)
- **缩放控制**: 放大/缩小功能,支持可配置的增量
- **重置功能**: 恢复原始平移和缩放状态
- **对话框控制**: 在展开对话框中打开预览
- **无障碍设计**: 完整的键盘导航和屏幕阅读器支持
**布局:**
- 3x3 网格布局,位于预览右下角
- 响应式按钮尺寸
- 所有控件的工具提示支持
### useDebouncedRender Hook 防抖渲染钩子
用于管理预览渲染的专用 React Hook,具有性能优化功能。
**功能特性:**
- **防抖渲染**: 防止内容快速变化时的过度重新渲染(默认 300ms 延迟)
- **自动依赖管理**: 处理渲染和条件函数的依赖项
- **错误处理**: 捕获和管理渲染错误,提供详细的错误信息
- **加载状态**: 跟踪渲染进度并自动更新状态
- **条件渲染**: 支持预渲染条件检查
- **手动控制**: 提供触发、取消和状态管理功能
**API:**
```typescript
const { containerRef, error, isLoading, triggerRender, cancelRender, clearError, setLoading } = useDebouncedRender(
value,
renderFunction,
options
)
```
**选项:**
- `debounceDelay`: 自定义防抖时间
- `shouldRender`: 条件渲染逻辑函数
## 组件实现
### MermaidPreview Mermaid 预览
渲染 Mermaid 图表,具有可见性检测的特殊处理。
**特殊功能:**
- 渲染前语法验证
- 可见性检测以处理折叠的容器
- 边缘情况的 SVG 坐标修复
- 与 mermaid.js 库集成
### PlantUmlPreview PlantUML 预览
使用在线 PlantUML 服务器渲染 PlantUML 图表。
**特殊功能:**
- 网络错误处理和重试逻辑
- 使用 deflate 压缩的图表编码
- 支持明/暗主题
- 服务器状态监控
### SvgPreview SVG 预览
使用 Shadow DOM 隔离渲染 SVG 内容。
**特殊功能:**
- Shadow DOM 渲染实现样式隔离
- 直接 SVG 内容注入
- 最小化处理开销
- 跨浏览器兼容性
### GraphvizPreview Graphviz 预览
使用 viz.js 库渲染 Graphviz/DOT 图表。
**特殊功能:**
- 使用 viz.js 进行客户端渲染
- viz.js 库的懒加载
- SVG 元素生成
- 内存高效处理
## 共享功能
### 错误处理
所有预览组件提供一致的错误处理:
- 网络错误(连接失败)
- 语法错误(无效的图表代码)
- 服务器错误(外部服务失败)
- 渲染错误(库失败)
### 加载状态
所有组件的标准化加载指示器:
- 处理期间的动画
- 长时间操作的进度反馈
- 状态间的平滑过渡
### 交互控制
通用交互模式:
- 平移和缩放功能
- 重置到原始视图
- 全屏对话框模式
- 键盘无障碍访问
### 性能优化
- 防抖渲染以防止过度更新
- 重型库的懒加载
- 大型图表的内存管理
- 高效的重新渲染策略
## 与 CodeBlockView 的集成
图像预览组件与 CodeBlockView 无缝集成:
- 基于语言标签的自动格式检测
- 一致的工具栏集成
- 共享状态管理
- 响应式布局适应
有关整体 CodeBlockView 架构的更多信息,请参阅 [CodeBlockView 文档](./CodeBlockView-zh.md)。
|
2025-09-24T14:46:58.085215
|
CherryHQ
|
cherry-studio
|
CherryHQ__cherry-studio
|
docs/technical/how-to-use-messageThunk.md
|
CherryHQ__cherry-studio/docs/technical/how-to-use-messageThunk.md
| 7,604 | 1,758,202,168 |
en
|
# messageThunk.ts 使用指南
该文件包含用于管理应用程序中消息流、处理助手交互以及同步 Redux 状态与 IndexedDB 数据库的核心 Thunk Action Creators。主要围绕 `Message` 和 `MessageBlock` 对象进行操作。
## 核心功能
1. **发送/接收消息**: 处理用户消息的发送,触发助手响应,并流式处理返回的数据,将其解析为不同的 `MessageBlock`。
2. **状态管理**: 确保 Redux store 中的消息和消息块状态与 IndexedDB 中的持久化数据保持一致。
3. **消息操作**: 提供删除、重发、重新生成、编辑后重发、追加响应、克隆等消息生命周期管理功能。
4. **Block 处理**: 动态创建、更新和保存各种类型的 `MessageBlock`(文本、思考过程、工具调用、引用、图片、错误、翻译等)。
## 主要 Thunks
以下是一些关键的 Thunk 函数及其用途:
1. **`sendMessage(userMessage, userMessageBlocks, assistant, topicId)`**
- **用途**: 发送一条新的用户消息。
- **流程**:
- 保存用户消息 (`userMessage`) 及其块 (`userMessageBlocks`) 到 Redux 和 DB。
- 检查 `@mentions` 以确定是单模型响应还是多模型响应。
- 创建助手消息(们)的存根 (Stub)。
- 将存根添加到 Redux 和 DB。
- 将核心处理逻辑 `fetchAndProcessAssistantResponseImpl` 添加到该 `topicId` 的队列中以获取实际响应。
- **Block 相关**: 主要处理用户消息的初始 `MessageBlock` 保存。
2. **`fetchAndProcessAssistantResponseImpl(dispatch, getState, topicId, assistant, assistantMessage)`**
- **用途**: (内部函数) 获取并处理单个助手响应的核心逻辑,被 `sendMessage`, `resend...`, `regenerate...`, `append...` 等调用。
- **流程**:
- 设置 Topic 加载状态。
- 准备上下文消息。
- 调用 `fetchChatCompletion` API 服务。
- 使用 `createStreamProcessor` 处理流式响应。
- 通过各种回调 (`onTextChunk`, `onThinkingChunk`, `onToolCallComplete`, `onImageGenerated`, `onError`, `onComplete` 等) 处理不同类型的事件。
- **Block 相关**:
- 根据流事件创建初始 `UNKNOWN` 块。
- 实时创建和更新 `MAIN_TEXT` 和 `THINKING` 块,使用 `throttledBlockUpdate` 和 `throttledBlockDbUpdate` 进行节流更新。
- 创建 `TOOL`, `CITATION`, `IMAGE`, `ERROR` 等类型的块。
- 在事件完成时(如 `onTextComplete`, `onToolCallComplete`)将块状态标记为 `SUCCESS` 或 `ERROR`,并使用 `saveUpdatedBlockToDB` 保存最终状态。
- 使用 `handleBlockTransition` 管理非流式块(如 `TOOL`, `CITATION`)的添加和状态更新。
3. **`loadTopicMessagesThunk(topicId, forceReload)`**
- **用途**: 从数据库加载指定主题的所有消息及其关联的 `MessageBlock`。
- **流程**:
- 从 DB 获取 `Topic` 及其 `messages` 列表。
- 根据消息 ID 列表从 DB 获取所有相关的 `MessageBlock`。
- 使用 `upsertManyBlocks` 将块更新到 Redux。
- 将消息更新到 Redux。
- **Block 相关**: 负责将持久化的 `MessageBlock` 加载到 Redux 状态。
4. **删除 Thunks**
- `deleteSingleMessageThunk(topicId, messageId)`: 删除单个消息及其所有 `MessageBlock`。
- `deleteMessageGroupThunk(topicId, askId)`: 删除一个用户消息及其所有相关的助手响应消息和它们的所有 `MessageBlock`。
- `clearTopicMessagesThunk(topicId)`: 清空主题下的所有消息及其所有 `MessageBlock`。
- **Block 相关**: 从 Redux 和 DB 中移除指定的 `MessageBlock`。
5. **重发/重新生成 Thunks**
- `resendMessageThunk(topicId, userMessageToResend, assistant)`: 重发用户消息。会重置(清空 Block 并标记为 PENDING)所有与该用户消息关联的助手响应,然后重新请求生成。
- `resendUserMessageWithEditThunk(topicId, originalMessage, mainTextBlockId, editedContent, assistant)`: 用户编辑消息内容后重发。先更新用户消息的 `MAIN_TEXT` 块内容,然后调用 `resendMessageThunk`。
- `regenerateAssistantResponseThunk(topicId, assistantMessageToRegenerate, assistant)`: 重新生成单个助手响应。重置该助手消息(清空 Block 并标记为 PENDING),然后重新请求生成。
- **Block 相关**: 删除旧的 `MessageBlock`,并在重新生成过程中创建新的 `MessageBlock`。
6. **`appendAssistantResponseThunk(topicId, existingAssistantMessageId, newModel, assistant)`**
- **用途**: 在已有的对话上下文中,针对同一个用户问题,使用新选择的模型追加一个新的助手响应。
- **流程**:
- 找到现有助手消息以获取原始 `askId`。
- 创建使用 `newModel` 的新助手消息存根(使用相同的 `askId`)。
- 添加新存根到 Redux 和 DB。
- 将 `fetchAndProcessAssistantResponseImpl` 添加到队列以生成新响应。
- **Block 相关**: 为新的助手响应创建全新的 `MessageBlock`。
7. **`cloneMessagesToNewTopicThunk(sourceTopicId, branchPointIndex, newTopic)`**
- **用途**: 将源主题的部分消息(及其 Block)克隆到一个**已存在**的新主题中。
- **流程**:
- 复制指定索引前的消息。
- 为所有克隆的消息和 Block 生成新的 UUID。
- 正确映射克隆消息之间的 `askId` 关系。
- 复制 `MessageBlock` 内容,更新其 `messageId` 指向新的消息 ID。
- 更新文件引用计数(如果 Block 是文件或图片)。
- 将克隆的消息和 Block 保存到新主题的 Redux 状态和 DB 中。
- **Block 相关**: 创建 `MessageBlock` 的副本,并更新其 ID 和 `messageId`。
8. **`initiateTranslationThunk(messageId, topicId, targetLanguage, sourceBlockId?, sourceLanguage?)`**
- **用途**: 为指定消息启动翻译流程,创建一个初始的 `TRANSLATION` 类型的 `MessageBlock`。
- **流程**:
- 创建一个状态为 `STREAMING` 的 `TranslationMessageBlock`。
- 将其添加到 Redux 和 DB。
- 更新原消息的 `blocks` 列表以包含新的翻译块 ID。
- **Block 相关**: 创建并保存一个占位的 `TranslationMessageBlock`。实际翻译内容的获取和填充需要后续步骤。
## 内部机制和注意事项
- **数据库交互**: 通过 `saveMessageAndBlocksToDB`, `updateExistingMessageAndBlocksInDB`, `saveUpdatesToDB`, `saveUpdatedBlockToDB`, `throttledBlockDbUpdate` 等辅助函数与 IndexedDB (`db`) 交互,确保数据持久化。
- **状态同步**: Thunks 负责协调 Redux Store 和 IndexedDB 之间的数据一致性。
- **队列 (`getTopicQueue`)**: 使用 `AsyncQueue` 确保对同一主题的操作(尤其是 API 请求)按顺序执行,避免竞态条件。
- **节流 (`throttle`)**: 对流式响应中频繁的 Block 更新(文本、思考)使用 `lodash.throttle` 优化性能,减少 Redux dispatch 和 DB 写入次数。
- **错误处理**: `fetchAndProcessAssistantResponseImpl` 内的回调函数(特别是 `onError`)处理流处理和 API 调用中可能出现的错误,并创建 `ERROR` 类型的 `MessageBlock`。
开发者在使用这些 Thunks 时,通常需要提供 `dispatch`, `getState` (由 Redux Thunk 中间件注入),以及如 `topicId`, `assistant` 配置对象, 相关的 `Message` 或 `MessageBlock` 对象/ID 等参数。理解每个 Thunk 的职责和它如何影响消息及块的状态至关重要。
|
2025-09-24T14:46:58.085215
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 16