Compare commits
77 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0dd60cb129 | ||
|
|
04dae10d89 | ||
|
|
71ef0f319f | ||
|
|
58817ae82f | ||
|
|
7e477cb9c7 | ||
|
|
1063610c01 | ||
|
|
927670d3a3 | ||
|
|
2fea7659b1 | ||
|
|
43b9298329 | ||
|
|
fe2e3bfc36 | ||
|
|
bae80fda8d | ||
|
|
ab709b9c61 | ||
|
|
2c28e3bb76 | ||
|
|
d98020e12c | ||
|
|
25addc390f | ||
|
|
88d04a1a6e | ||
|
|
1f582c672d | ||
|
|
c913b2a6d0 | ||
|
|
267c60f24d | ||
|
|
a8ccaf6847 | ||
|
|
a3a005b946 | ||
|
|
2220a6016e | ||
|
|
3197390f1a | ||
|
|
5f04d1adb1 | ||
|
|
76b6593545 | ||
|
|
04ce641bf7 | ||
|
|
31e912aac3 | ||
|
|
832ec99d92 | ||
|
|
ef9fda6d0c | ||
|
|
624230411a | ||
|
|
14808649f8 | ||
|
|
3cc8cfb43b | ||
|
|
4055111ade | ||
|
|
dc98b27e3e | ||
|
|
90fec317e5 | ||
|
|
303a0e20a0 | ||
|
|
d69252a7da | ||
|
|
99f05383cb | ||
|
|
5ba6c9f882 | ||
|
|
27f64409d6 | ||
|
|
7237729ff6 | ||
|
|
d29cd3c657 | ||
|
|
8c87f59822 | ||
|
|
5780141df4 | ||
|
|
f5799ef47b | ||
|
|
6f502049f4 | ||
|
|
c68ad4febb | ||
|
|
2ebcec9f59 | ||
|
|
7bc74a5b86 | ||
|
|
75152421d9 | ||
|
|
3326074076 | ||
|
|
362d82bdcc | ||
|
|
fcce241c82 | ||
|
|
693b06c126 | ||
|
|
c310c71576 | ||
|
|
bea95fc52f | ||
|
|
969cf8ea21 | ||
|
|
5b357f14e5 | ||
|
|
de5db4f805 | ||
|
|
1ccb5edda7 | ||
|
|
97b8749dd1 | ||
|
|
a6d7ecae81 | ||
|
|
938efb5aef | ||
|
|
9baf0f772e | ||
|
|
ff5de3625e | ||
|
|
f1cfdb29f8 | ||
|
|
26e48f07fd | ||
|
|
8bb5fb9811 | ||
|
|
d41667b599 | ||
|
|
85152cbcd7 | ||
|
|
b80863111f | ||
|
|
6cd88fa51d | ||
|
|
3619e8f47b | ||
|
|
5b41dd24d4 | ||
|
|
91dd2f233a | ||
|
|
7e651f9abc | ||
|
|
e44f666c5c |
1
.github/workflows/release.yml
vendored
1
.github/workflows/release.yml
vendored
@@ -71,5 +71,6 @@ jobs:
|
||||
dist/*.rpm
|
||||
dist/*.tar.gz
|
||||
dist/latest*.yml
|
||||
dist/*.blockmap
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -19,12 +19,6 @@ lerna-debug.log*
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# NPM
|
||||
npm/*/*
|
||||
!npm/*/dist
|
||||
!npm/*/package.json
|
||||
!npm/*/*.js
|
||||
|
||||
# Yarn
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
|
||||
32
CODE_OF_CONDUCT.md
Normal file
32
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,32 @@
|
||||
This software is licensed under the **Apache License 2.0**. In addition to the terms of the Apache License 2.0, the following additional terms apply to the use of Cherry Studio:
|
||||
|
||||
**I. Commercial Use License**
|
||||
|
||||
1. **Free Commercial Use**: Users can use the software for commercial purposes without modifying the code.
|
||||
2. **Commercial License Required**: A commercial license is required if any of the following conditions are met:
|
||||
1. You modify, develop, or alter the software, including but not limited to changes to the application name, logo, code, or functionality.
|
||||
2. You provide multi-tenant services to enterprise customers with 10 or more users.
|
||||
3. You pre-install or integrate the software into hardware devices or products and bundle it for sale.
|
||||
4. You are engaging in large-scale procurement for government or educational institutions, especially involving security, data privacy, or other sensitive requirements.
|
||||
|
||||
**II. Contributor Agreement**
|
||||
|
||||
As a contributor to Cherry Studio, you agree to the following:
|
||||
|
||||
1. **License Adjustment**: The producer reserves the right to adjust the open-source license as needed, making it stricter or more lenient.
|
||||
2. **Commercial Use**: Any code you contribute may be used for commercial purposes, including but not limited to cloud business operations.
|
||||
|
||||
**III. Other Terms**
|
||||
|
||||
1. The interpretation of these terms is subject to the discretion of Cherry Studio developers.
|
||||
2. These terms may be updated, and users will be notified through the software when changes occur.
|
||||
|
||||
For any questions or to request a commercial license, please contact the Cherry Studio development team.
|
||||
|
||||
Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at http://www.apache.org/licenses/LICENSE-2.0.
|
||||
|
||||
---
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
||||
72
CONTRIBUTING.md
Normal file
72
CONTRIBUTING.md
Normal file
@@ -0,0 +1,72 @@
|
||||
## Cherry Studio目录结构和功能
|
||||
|
||||
### 1. `/src`: 主要源代码目录
|
||||
- ** `/main`**: Electron主进程相关代码
|
||||
- 负责应用的生命周期管理、窗口创建、IPC通信等
|
||||
- ** `/renderer`**: Electron渲染进程相关代码
|
||||
- 包含用户界面的实现,使用TypeScript和SCSS
|
||||
- ** `/preload`**: 预加载脚本
|
||||
- 用于在渲染进程中安全地暴露主进程功能
|
||||
- ** `/components`**: React组件
|
||||
- 可复用的UI组件,如对话框、输入框等
|
||||
- ** `/pages`**: 应用的主要页面
|
||||
- 如聊天界面、设置页面等
|
||||
- ** `/store`**: 状态管理
|
||||
- 可能使用Redux或MobX来管理应用状态
|
||||
- ** `/utils`**: 工具函数
|
||||
- 包含各种辅助函数和工具类
|
||||
- ** `/styles`**: 全局样式文件
|
||||
- 包含SCSS文件,定义全局样式和主题
|
||||
|
||||
### 2. `/public`: 静态资源目录
|
||||
- 包含图标、字体等静态文件
|
||||
|
||||
### 3. `/electron`: Electron相关配置
|
||||
- 包含Electron的构建和打包配置
|
||||
|
||||
### 4. `/scripts`: 构建和开发脚本
|
||||
- 包含npm脚本,用于开发、构建和部署
|
||||
|
||||
### 5. `/types`: TypeScript类型定义
|
||||
- 包含自定义的类型定义文件
|
||||
|
||||
### 6. `/tests`: 测试文件目录
|
||||
- 包含单元测试和集成测试
|
||||
|
||||
### 7. `/docs`: 文档目录
|
||||
- 包含项目文档、API文档等
|
||||
|
||||
### 8. `/config`: 配置文件目录
|
||||
- 包含各种配置文件,如webpack配置、环境变量等
|
||||
|
||||
### 9. `/migrations`: 数据库迁移文件
|
||||
- 由于使用了Sequelize,这里可能包含数据库结构的变更记录
|
||||
|
||||
### 10. `/models`: 数据模型
|
||||
- 定义Sequelize的数据模型,对应数据库表结构
|
||||
|
||||
## 主要功能实现
|
||||
|
||||
### 1. LLM提供商集成
|
||||
- 可能在`/src/utils`或`/src/services`中实现与不同LLM API的集成
|
||||
|
||||
### 2. 多助手和多主题支持
|
||||
- 在`/src/store`中管理助手和主题的状态
|
||||
- 在`/src/components`中实现相关的UI组件
|
||||
|
||||
### 3. 多模型对话
|
||||
- 在`/src/pages`的聊天界面中实现
|
||||
- 可能使用`/src/store`来管理对话状态
|
||||
|
||||
### 4. 拖放排序
|
||||
- 在`/src/components`中实现相关的可拖拽组件
|
||||
|
||||
### 5. 代码高亮
|
||||
- 可能使用第三方库,如Prism.js,集成在`/src/components`中
|
||||
|
||||
### 6. Mermaid图表支持
|
||||
- 在`/src/components`中集成Mermaid库
|
||||
|
||||
### 7. 数据持久化
|
||||
- 使用Sequelize在`/models`中定义数据模型
|
||||
- 在`/migrations`中管理数据库结构变更
|
||||
136
LICENSE
136
LICENSE
@@ -1,101 +1,79 @@
|
||||
### Cherry Studio 商业许可协议
|
||||
## Cherry Studio 用户协议
|
||||
|
||||
欢迎使用 Cherry Studio 桌面 AI 客户端工具。请仔细阅读以下协议条款,继续使用本软件即表示您同意本协议内容。
|
||||
|
||||
**许可协议**
|
||||
|
||||
本软件采用 Apache License 2.0 许可。除 Apache License 2.0 规定的条款外,您在使用 Cherry Studio 时还应遵守以下附加条款:
|
||||
|
||||
**一. 商用许可**
|
||||
|
||||
1. **免费商用**:用户在不修改代码的情况下,可以免费用于商业目的。
|
||||
2. **商业授权**:如果您满足以下任意条件之一,需取得商业授权:
|
||||
1. 对本软件进行二次修改、开发(包括但不限于修改应用名称、logo、代码以及功能)。
|
||||
2. 为企业客户提供多租户服务,且该服务支持 10 人或以上的使用。
|
||||
3. 预装或集成到硬件设备或产品中进行捆绑销售。
|
||||
4. 政府或教育机构的大规模采购项目,特别是涉及安全、数据隐私等敏感需求时。
|
||||
|
||||
**二. 贡献者协议**
|
||||
|
||||
作为 Cherry Studio 的贡献者,您应当同意以下条款:
|
||||
|
||||
1. **许可调整**:生产者有权根据需要对开源协议进行调整,使其更加严格或宽松。
|
||||
2. **商业用途**:您贡献的代码可能会被用于商业用途,包括但不限于云业务运营。
|
||||
|
||||
**三. 其他条款**
|
||||
|
||||
1. 本协议条款的解释权归 Cherry Studio 开发者所有。
|
||||
2. 本协议可能根据实际情况进行更新,更新时将通过本软件通知用户。
|
||||
|
||||
如有任何问题或需申请商业授权,请联系 Cherry Studio 开发团队。
|
||||
|
||||
除上述特定条件外,其他所有权利和限制均遵循 Apache License 2.0。有关 Apache License 2.0 的详细信息,请访问 http://www.apache.org/licenses/LICENSE-2.0。
|
||||
|
||||
---
|
||||
|
||||
#### 中文版
|
||||
根据 Apache 许可证 2.0 版(“许可证”)进行许可;除非符合许可证,否则您不得使用此文件。您可以在以下网址获取许可证副本:
|
||||
|
||||
**Cherry Studio 商业许可协议**
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
本协议(以下简称“协议”)由以下双方签订:
|
||||
除非适用法律要求或书面同意,软件根据许可证分发的内容以“原样”分发,不附带任何明示或暗示的保证或条件。请参阅特定语言管理权限的许可证和许可证下的限制。
|
||||
|
||||
- 许可方:王谦(kangfenmao@qq.com)
|
||||
- 被许可方:[被许可方名称]
|
||||
## Cherry Studio User Agreement
|
||||
|
||||
**1. 定义**
|
||||
Welcome to Cherry Studio, a desktop AI client tool. Please read the following agreement carefully. By continuing to use this software, you agree to the terms outlined below.
|
||||
|
||||
- “软件”指 Cherry Studio 软件,网址为 https://cherry-ai.com。
|
||||
- “商业用途”指任何以盈利为目的的使用。
|
||||
**License Agreement**
|
||||
|
||||
**2. 许可**
|
||||
This software is licensed under the **Apache License 2.0**. In addition to the terms of the Apache License 2.0, the following additional terms apply to the use of Cherry Studio:
|
||||
|
||||
- 未经许可方明确书面许可,被许可方不得将软件用于商业用途。
|
||||
- 未经许可方事先书面同意,被许可方不得将软件全部或部分用于商业用途分发。
|
||||
- 未经许可方明确授权,被许可方不得再许可、租赁、销售、出租或以其他方式将软件转让给任何第三方用于商业用途。
|
||||
**I. Commercial Use License**
|
||||
|
||||
**3. 责任限制**
|
||||
1. **Free Commercial Use**: Users can use the software for commercial purposes without modifying the code.
|
||||
2. **Commercial License Required**: A commercial license is required if any of the following conditions are met:
|
||||
1. You modify, develop, or alter the software, including but not limited to changes to the application name, logo, code, or functionality.
|
||||
2. You provide multi-tenant services to enterprise customers with 10 or more users.
|
||||
3. You pre-install or integrate the software into hardware devices or products and bundle it for sale.
|
||||
4. You are engaging in large-scale procurement for government or educational institutions, especially involving security, data privacy, or other sensitive requirements.
|
||||
|
||||
开发者不对因使用本软件而产生的任何直接或间接损失承担责任。用户应自行承担使用本软件的风险。
|
||||
**II. Contributor Agreement**
|
||||
|
||||
**4. 许可协议生效日期**
|
||||
As a contributor to Cherry Studio, you agree to the following:
|
||||
|
||||
本许可协议自用户首次下载或使用本软件之日起生效。
|
||||
1. **License Adjustment**: The producer reserves the right to adjust the open-source license as needed, making it stricter or more lenient.
|
||||
2. **Commercial Use**: Any code you contribute may be used for commercial purposes, including but not limited to cloud business operations.
|
||||
|
||||
**5. 许可终止**
|
||||
**III. Other Terms**
|
||||
|
||||
如发现用户违反上述条款,开发者有权随时终止本许可,并要求用户停止使用本软件及删除所有相关副本。
|
||||
1. The interpretation of these terms is subject to the discretion of Cherry Studio developers.
|
||||
2. These terms may be updated, and users will be notified through the software when changes occur.
|
||||
|
||||
**6. 其他**
|
||||
For any questions or to request a commercial license, please contact the Cherry Studio development team.
|
||||
|
||||
本协议的解释、效力及争议的解决,均适用中华人民共和国法律。
|
||||
|
||||
**7. 联系信息**
|
||||
|
||||
- 许可方联系方式:
|
||||
- 手机号:18539907620
|
||||
- 邮箱:kangfenmao@qq.com
|
||||
|
||||
**许可方(签字):**
|
||||
**日期:**
|
||||
|
||||
**被许可方(签字):**
|
||||
**日期:**
|
||||
Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at http://www.apache.org/licenses/LICENSE-2.0.
|
||||
|
||||
---
|
||||
|
||||
#### English Version
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
**Cherry Studio Commercial License Agreement**
|
||||
|
||||
This Agreement ("Agreement") is entered into by and between:
|
||||
|
||||
- Licensor: Wang Qian (kangfenmao)
|
||||
- Licensee: [Licensee Name]
|
||||
|
||||
**1. Definitions**
|
||||
|
||||
- "Software" refers to the Cherry Studio software, available at https://cherry-ai.com.
|
||||
- "Commercial Use" refers to any use for profit.
|
||||
|
||||
**2. License**
|
||||
|
||||
- The Licensee may not use the Software for Commercial Use without the Licensor's explicit written permission.
|
||||
- The Licensee may not distribute the Software in whole or in part for Commercial Use without the Licensor's prior written consent.
|
||||
- The Licensee may not sublicense, lease, sell, rent, or otherwise transfer the Software to any third party for Commercial Use without the Licensor's explicit authorization.
|
||||
|
||||
**3. Termination of License**
|
||||
|
||||
The developer reserves the right to terminate this license at any time if the terms are violated, and may require the user to cease using the software and delete all related copies.
|
||||
|
||||
**4. Effective Date of License Agreement**
|
||||
|
||||
This license agreement becomes effective from the date the user first downloads or uses the software.
|
||||
|
||||
**5. Termination of License**
|
||||
|
||||
The developer reserves the right to terminate this license at any time if the terms are violated, and may require the user to cease using the software and delete all related copies.
|
||||
|
||||
**6. Miscellaneous**
|
||||
|
||||
This Agreement shall be governed by and construed in accordance with the laws of the People's Republic of China.
|
||||
|
||||
**7. Contact Information**
|
||||
|
||||
- Licensor's Contact Details:
|
||||
- Phone: 18539907620
|
||||
- Email: kangfenmao@qq.com
|
||||
|
||||
**Licensor (Signature):**
|
||||
**Date:**
|
||||
|
||||
**Licensee (Signature):**
|
||||
**Date:**
|
||||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
||||
|
||||
22
README.md
22
README.md
@@ -1,14 +1,20 @@
|
||||
<div align="center">
|
||||
<a href="https://github.com/kangfenmao/cherry-studio/releases">
|
||||
<img src="https://github.com/user-attachments/assets/7b4f2f78-5cbe-4be8-9aec-f98d8405a505" alt="banner" />
|
||||
<img src="https://github.com/kangfenmao/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" />
|
||||
</a>
|
||||
English | <a href="./docs/README.zh.md">中文</a>
|
||||
</div>
|
||||
<div align="center">
|
||||
English | <a href="./README.zh.md">中文</a>
|
||||
</div>
|
||||
|
||||
# 🍒 Cherry Studio
|
||||
|
||||

|
||||
|
||||
Cherry Studio is a desktop client that supports for multiple LLM providers, available on Windows, Mac and Linux.
|
||||
|
||||
👏 Join [Telegram Group](https://t.me/CherryStudioAI)
|
||||
|
||||
# 🌠 Screenshot
|
||||
|
||||

|
||||
@@ -17,6 +23,10 @@ Cherry Studio is a desktop client that supports for multiple LLM providers, avai
|
||||
|
||||
# 🌟 Features
|
||||
|
||||
<div align="center">
|
||||
<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" style="width: 250px; height: 54px;" width="250" height="54" /></a>
|
||||
</div>
|
||||
|
||||
1. Support for Multiple LLM Providers.
|
||||
2. Allows creation of multiple Assistants.
|
||||
3. Enables creation of multiple topics.
|
||||
@@ -27,9 +37,9 @@ Cherry Studio is a desktop client that supports for multiple LLM providers, avai
|
||||
|
||||
# 🖥️ Develop
|
||||
|
||||
## Recommended IDE Setup
|
||||
## IDE Setup
|
||||
|
||||
- [VSCode](https://code.visualstudio.com/) + [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) + [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
|
||||
[VSCode](https://code.visualstudio.com/) + [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) + [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
|
||||
|
||||
## Project Setup
|
||||
|
||||
@@ -68,6 +78,10 @@ $ yarn build:linux
|
||||
<img src="https://contrib.rocks/image?repo=kangfenmao/cherry-studio" />
|
||||
</a>
|
||||
|
||||
# Community
|
||||
|
||||
[Telegram](https://t.me/CherryStudioAI)
|
||||
|
||||
# Sponsor
|
||||
|
||||
[Buy Me a Coffee](docs/sponsor.md)
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
<div align="center">
|
||||
<a href="https://github.com/kangfenmao/cherry-studio/releases">
|
||||
<img src="https://github.com/user-attachments/assets/995910f3-177a-4d1e-97ea-04e3b009ba36" alt="banner"/>
|
||||
<img src="https://github.com/kangfenmao/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" />
|
||||
</a>
|
||||
English / <a href="https://github.com/kangfenmao/cherry-studio">中文</a>
|
||||
</div>
|
||||
<div align="center">
|
||||
中文 / <a href="https://github.com/kangfenmao/cherry-studio">English</a>
|
||||
</div>
|
||||
|
||||
# 🍒 Cherry Studio
|
||||
|
||||

|
||||
|
||||
Cherry Studio 是一款跨平台桌面客户端,支持多个大语言模型(LLM)服务商,兼容 Windows、Mac 和 Linux 系统,并拥丰富的个性化选项与领先的功能设计。
|
||||
|
||||
👏 欢迎加入 [Telegram 群组](https://t.me/CherryStudioAI)
|
||||
|
||||
# 🌠 界面
|
||||
|
||||
<img width="1582" alt="Xnip2024-09-23_15-01-53" src="https://github.com/user-attachments/assets/554aa31b-87b6-49fe-877d-af313e1608b0">
|
||||
@@ -20,6 +26,10 @@ Cherry Studio 是一款跨平台桌面客户端,支持多个大语言模型(
|
||||
|
||||
# 🌟 特性
|
||||
|
||||
<div align="center">
|
||||
<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" style="width: 250px; height: 54px;" width="250" height="54" /></a>
|
||||
</div>
|
||||
|
||||
## 😌 轻松上手
|
||||
|
||||
🍏Windows,Mac,Linux跨平台支持
|
||||
@@ -52,9 +62,9 @@ Cherry Studio 是一款跨平台桌面客户端,支持多个大语言模型(
|
||||
|
||||
# 🖥️ 开发指南
|
||||
|
||||
## 推荐的开发环境
|
||||
## 开发环境
|
||||
|
||||
- [VSCode](https://code.visualstudio.com/) + [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) + [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
|
||||
[VSCode](https://code.visualstudio.com/) + [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) + [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
|
||||
|
||||
## 项目设置
|
||||
|
||||
@@ -87,6 +97,10 @@ $ yarn build:linux
|
||||
|
||||
[](https://star-history.com/#kangfenmao/cherry-studio&Timeline)
|
||||
|
||||
# 社区
|
||||
|
||||
[Telegram](https://t.me/CherryStudioAI)
|
||||
|
||||
# 赞助
|
||||
|
||||
[微信赞赏码](docs/sponsor.md)
|
||||
@@ -1,5 +0,0 @@
|
||||
# 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>
|
||||
@@ -1,95 +0,0 @@
|
||||
# FAQ 文档
|
||||
本文档适用于:产品手册、官网页面、课程测验、现场 Q&A。
|
||||
|
||||
## 问题1:Cherry Studio 支持哪些操作系统?
|
||||
- **答案**:Cherry Studio 支持 Windows、Mac 和 Linux 操作系统。
|
||||
|
||||
## 问题2:Cherry Studio 的主要功能有哪些?
|
||||
- **答案**:Cherry Studio 的主要功能包括:
|
||||
1. 支持多个 LLM 提供商
|
||||
2. 允许创建多个助手
|
||||
3. 支持创建多个主题
|
||||
4. 允许在同一对话中使用多个模型来回答问题
|
||||
5. 支持拖放排序
|
||||
6. 代码高亮
|
||||
7. Mermaid 图表支持
|
||||
|
||||
## 问题3:Cherry Studio 的主要目录结构是怎样的?
|
||||
- **答案**:Cherry Studio 的主要目录结构如下:
|
||||
- `/src`: 主要源代码目录
|
||||
- `/build`: 构建相关文件
|
||||
- `/docs`: 文档目录
|
||||
- `/resources`: 资源文件目录
|
||||
- `/scripts`: 脚本文件目录
|
||||
|
||||
## 问题4:如何在 Windows 环境下 fork Cherry Studio 并修改部分功能?
|
||||
- **答案**:在 Windows 环境下 fork Cherry Studio 并修改部分功能的步骤如下:
|
||||
1. 在 GitHub 上 fork Cherry Studio 仓库
|
||||
2. 克隆 fork 的仓库到本地:`git clone https://github.com/your-username/cherry-studio.git`
|
||||
3. 进入项目目录:`cd cherry-studio`
|
||||
4. 安装依赖:`yarn install`
|
||||
5. 修改所需的功能代码
|
||||
6. 测试修改:`yarn dev`
|
||||
7. 提交修改:`git add .` 和 `git commit -m "描述你的修改"`
|
||||
8. 推送到你的 fork 仓库:`git push origin main`
|
||||
|
||||
## 问题5:Cherry Studio 使用了哪些主要技术栈?
|
||||
- **答案**:Cherry Studio 主要使用了以下技术栈:
|
||||
- TypeScript
|
||||
- SCSS
|
||||
- Electron
|
||||
- Vite
|
||||
- Sequelize
|
||||
|
||||
## 问题6:如何贡献代码到 Cherry Studio 项目?
|
||||
- **答案**:贡献代码到 Cherry Studio 项目的步骤如下:
|
||||
1. Fork 项目仓库
|
||||
2. 创建你的特性分支:`git checkout -b feature/AmazingFeature`
|
||||
3. 提交你的修改:`git commit -m 'Add some AmazingFeature'`
|
||||
4. 推送到分支:`git push origin feature/AmazingFeature`
|
||||
5. 打开一个 Pull Request
|
||||
|
||||
## 问题7:Cherry Studio 的 `/src` 目录主要包含哪些内容?
|
||||
- **答案**:Cherry Studio 的 `/src` 目录主要包含以下内容:
|
||||
- 主进程代码(Electron 主进程)
|
||||
- 渲染进程代码(用户界面)
|
||||
- 组件
|
||||
- 工具函数
|
||||
- 状态管理
|
||||
- 样式文件
|
||||
|
||||
## 问题8:如何在 Cherry Studio 中添加新的 LLM 提供商?
|
||||
- **答案**:要在 Cherry Studio 中添加新的 LLM 提供商,你需要:
|
||||
1. 在 `/src/services` 或类似目录下创建新的服务文件
|
||||
2. 实现与新 LLM 提供商 API 的集成
|
||||
3. 在用户界面中添加新提供商的选项
|
||||
4. 更新配置和状态管理以支持新提供商
|
||||
|
||||
## 问题9:Cherry Studio 的构建过程是怎样的?
|
||||
- **答案**:Cherry Studio 的构建过程主要包括:
|
||||
1. 使用 Vite 构建前端资源
|
||||
2. 使用 Electron Builder 打包桌面应用
|
||||
3. 根据不同平台(Windows、Mac、Linux)生成相应的安装包
|
||||
|
||||
## 问题10:如何在 Cherry Studio 中实现新的 UI 主题?
|
||||
- **答案**:在 Cherry Studio 中实现新的 UI 主题的步骤:
|
||||
1. 在 `/src/styles` 目录下创建新的主题 SCSS 文件
|
||||
2. 定义新主题的颜色变量和样式
|
||||
3. 在主样式文件中导入新主题
|
||||
4. 更新主题切换逻辑以包含新主题
|
||||
5. 在用户界面中添加新主题的选项
|
||||
|
||||
## 问题11:Cherry Studio 如何处理多语言支持?
|
||||
- **答案**:Cherry Studio 可能通过以下方式处理多语言支持:
|
||||
1. 使用 i18n 库进行国际化
|
||||
2. 在 `/src/locales` 或类似目录下存储不同语言的翻译文件
|
||||
3. 实现语言切换功能
|
||||
4. 在组件中使用翻译函数或组件来显示多语言文本
|
||||
|
||||
## 问题12:如何为 Cherry Studio 编写单元测试?
|
||||
- **答案**:为 Cherry Studio 编写单元测试的步骤:
|
||||
1. 在 `/tests` 目录下创建测试文件
|
||||
2. 使用测试框架(如 Jest)编写测试用例
|
||||
3. 模拟 Electron 环境和其他依赖
|
||||
4. 运行测试命令:`yarn test`
|
||||
5. 确保测试覆盖主要功能和组件
|
||||
@@ -9,9 +9,8 @@ files:
|
||||
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
|
||||
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
|
||||
- '!src'
|
||||
- '!local'
|
||||
- '!scripts'
|
||||
- '!resources'
|
||||
- '!local'
|
||||
asarUnpack:
|
||||
- resources/**
|
||||
win:
|
||||
@@ -62,12 +61,3 @@ publish:
|
||||
electronDownload:
|
||||
mirror: https://npmmirror.com/mirrors/electron/
|
||||
afterSign: scripts/notarize.js
|
||||
releaseInfo:
|
||||
releaseNotes: |
|
||||
本次更新:
|
||||
增加 Azure OpenAI 服务商
|
||||
修复表格换行问题
|
||||
近期更新:
|
||||
增加 WebDAV 备份功能 by @DrayChou
|
||||
增加话题历史记录
|
||||
增加消息搜索功能
|
||||
|
||||
1
npm/artifacts/README.md
Normal file
1
npm/artifacts/README.md
Normal file
@@ -0,0 +1 @@
|
||||
# Cherry Studio Artifacts
|
||||
19
npm/artifacts/package.json
Normal file
19
npm/artifacts/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@cherry-studio/artifacts",
|
||||
"version": "0.1.0",
|
||||
"description": "Cherry Studio Artifacts",
|
||||
"main": "index.js",
|
||||
"homepage": "https://github.com/kangfenmao/cherry-studio/blob/main/npm/artifacts",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org/"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [
|
||||
"artifacts"
|
||||
],
|
||||
"author": "kangfenmao",
|
||||
"license": "ISC"
|
||||
}
|
||||
108
npm/artifacts/statics/word-explanation-card.css
Normal file
108
npm/artifacts/statics/word-explanation-card.css
Normal file
@@ -0,0 +1,108 @@
|
||||
:root {
|
||||
/* 莫兰迪色系:使用柔和、低饱和度的颜色 */
|
||||
--primary-color: #b6b5a7; /* 莫兰迪灰褐色,用于背景文字 */
|
||||
--secondary-color: #9a8f8f; /* 莫兰迪灰棕色,用于标题背景 */
|
||||
--accent-color: #c5b4a0; /* 莫兰迪淡棕色,用于强调元素 */
|
||||
--background-color: #e8e3de; /* 莫兰迪米色,用于页面背景 */
|
||||
--text-color: #5b5b5b; /* 莫兰迪深灰色,用于主要文字 */
|
||||
--light-text-color: #8c8c8c; /* 莫兰迪中灰色,用于次要文字 */
|
||||
--divider-color: #d1cbc3; /* 莫兰迪浅灰色,用于分隔线 */
|
||||
}
|
||||
body,
|
||||
html {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background-color: var(--background-color); /* 使用莫兰迪米色作为页面背景 */
|
||||
font-family: 'Noto Sans SC', sans-serif;
|
||||
color: var(--text-color); /* 使用莫兰迪深灰色作为主要文字颜色 */
|
||||
}
|
||||
.card {
|
||||
width: 300px;
|
||||
height: 500px;
|
||||
background-color: #f2ede9; /* 莫兰迪浅米色,用于卡片背景 */
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.header {
|
||||
background-color: var(--secondary-color); /* 使用莫兰迪灰棕色作为标题背景 */
|
||||
color: #f2ede9; /* 浅色文字与深色背景形成对比 */
|
||||
padding: 20px;
|
||||
text-align: left;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
h1 {
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 20px;
|
||||
margin: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
.content {
|
||||
padding: 30px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-grow: 1;
|
||||
}
|
||||
.word {
|
||||
text-align: left;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.word-main {
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 36px;
|
||||
color: var(--text-color); /* 使用莫兰迪深灰色作为主要词汇颜色 */
|
||||
margin-bottom: 10px;
|
||||
position: relative;
|
||||
}
|
||||
.word-main::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: -5px;
|
||||
width: 50px;
|
||||
height: 3px;
|
||||
background-color: var(--accent-color); /* 使用莫兰迪淡棕色作为下划线 */
|
||||
}
|
||||
.word-sub {
|
||||
font-size: 14px;
|
||||
color: var(--light-text-color); /* 使用莫兰迪中灰色作为次要文字颜色 */
|
||||
margin: 5px 0;
|
||||
}
|
||||
.divider {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background-color: var(--divider-color); /* 使用莫兰迪浅灰色作为分隔线 */
|
||||
margin: 20px 0;
|
||||
}
|
||||
.explanation {
|
||||
font-size: 18px;
|
||||
line-height: 1.6;
|
||||
text-align: left;
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
.quote {
|
||||
position: relative;
|
||||
padding-left: 20px;
|
||||
border-left: 3px solid var(--accent-color); /* 使用莫兰迪淡棕色作为引用边框 */
|
||||
}
|
||||
.background-text {
|
||||
position: absolute;
|
||||
font-size: 150px;
|
||||
color: rgba(182, 181, 167, 0.15); /* 使用莫兰迪灰褐色的透明版本作为背景文字 */
|
||||
z-index: 0;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
font-weight: bold;
|
||||
}
|
||||
11
package.json
11
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "CherryStudio",
|
||||
"version": "0.7.13",
|
||||
"version": "0.8.2",
|
||||
"private": true,
|
||||
"description": "A powerful AI assistant for producer.",
|
||||
"main": "./out/main/index.js",
|
||||
@@ -8,7 +8,8 @@
|
||||
"homepage": "https://github.com/kangfenmao/cherry-studio",
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
"local"
|
||||
"local",
|
||||
"npm/*"
|
||||
]
|
||||
},
|
||||
"scripts": {
|
||||
@@ -27,6 +28,7 @@
|
||||
"build:linux": "dotenv electron-vite build && electron-builder --linux --publish never",
|
||||
"release": "node scripts/version.js",
|
||||
"publish": "yarn release patch push",
|
||||
"pulish:artifacts": "cd npm/artifacts && npm publish && cd -",
|
||||
"generate:icons": "electron-icon-builder --input=./build/logo.png --output=build"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -35,10 +37,11 @@
|
||||
"archiver": "^7.0.1",
|
||||
"electron-log": "^5.1.5",
|
||||
"electron-store": "^8.2.0",
|
||||
"electron-updater": "^6.1.7",
|
||||
"electron-updater": "^6.3.9",
|
||||
"electron-window-state": "^5.0.3",
|
||||
"fs-extra": "^11.2.0",
|
||||
"html2canvas": "^1.4.1",
|
||||
"officeparser": "^4.1.1",
|
||||
"unzipper": "^0.12.3",
|
||||
"webdav": "4.11.4"
|
||||
},
|
||||
@@ -96,7 +99,7 @@
|
||||
"react-syntax-highlighter": "^15.5.0",
|
||||
"redux": "^5.0.1",
|
||||
"redux-persist": "^6.0.0",
|
||||
"rehype-katex": "^7.0.0",
|
||||
"rehype-mathjax": "^6.0.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"remark-math": "^6.0.0",
|
||||
|
||||
118
resources/cherry-studio/license.html
Normal file
118
resources/cherry-studio/license.html
Normal file
@@ -0,0 +1,118 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CherryStudio 许可协议-ZH/EN</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
|
||||
<body class="bg-gray-100 p-8">
|
||||
<div class="container mx-auto bg-white p-6 rounded shadow-lg">
|
||||
<h1 class="text-3xl font-bold mb-6 text-center">Cherry Studio 许可协议</h1>
|
||||
<div class="mb-8">
|
||||
<h2 class="text-2xl font-semibold mb-4">许可协议</h2>
|
||||
<p class="mb-4">
|
||||
本软件采用 <strong>Apache License 2.0</strong> 许可。除 Apache License 2.0 规定的条款外,您在使用 Cherry
|
||||
Studio 时还应遵守以下附加条款:
|
||||
</p>
|
||||
<h3 class="text-xl font-semibold mb-2">一. 商用许可</h3>
|
||||
<ol class="list-decimal list-inside mb-4">
|
||||
<li><strong>免费商用</strong>:用户在不修改代码的情况下,可以免费用于商业目的。</li>
|
||||
<li>
|
||||
<strong>商业授权</strong>:如果您满足以下任意条件之一,需取得商业授权:
|
||||
<ol class="list-decimal list-inside ml-4">
|
||||
<li>对本软件进行二次修改、开发(包括但不限于修改应用名称、logo、代码以及功能)。</li>
|
||||
<li>为企业客户提供多租户服务,且该服务支持 10 人或以上的使用。</li>
|
||||
<li>预装或集成到硬件设备或产品中进行捆绑销售。</li>
|
||||
<li>政府或教育机构的大规模采购项目,特别是涉及安全、数据隐私等敏感需求时。</li>
|
||||
</ol>
|
||||
</li>
|
||||
</ol>
|
||||
<h3 class="text-xl font-semibold mb-2">二. 贡献者协议</h3>
|
||||
<ol class="list-decimal list-inside mb-4">
|
||||
<li><strong>许可调整</strong>:生产者有权根据需要对开源协议进行调整,使其更加严格或宽松。</li>
|
||||
<li><strong>商业用途</strong>:您贡献的代码可能会被用于商业用途,包括但不限于云业务运营。</li>
|
||||
</ol>
|
||||
<h3 class="text-xl font-semibold mb-2">三. 其他条款</h3>
|
||||
<ol class="list-decimal list-inside mb-4">
|
||||
<li>本协议条款的解释权归 Cherry Studio 开发者所有。</li>
|
||||
<li>本协议可能根据实际情况进行更新,更新时将通过本软件通知用户。</li>
|
||||
</ol>
|
||||
<p class="mb-4">如有任何问题或需申请商业授权,请联系 Cherry Studio 开发团队。</p>
|
||||
<p>
|
||||
除上述特定条件外,其他所有权利和限制均遵循 Apache License 2.0。有关 Apache License 2.0 的详细信息,请访问
|
||||
<a href="http://www.apache.org/licenses/LICENSE-2.0"
|
||||
class="text-blue-500 underline">http://www.apache.org/licenses/LICENSE-2.0</a>
|
||||
</p>
|
||||
</div>
|
||||
<h1 class="text-3xl font-bold mb-6 text-center">Cherry Studio License</h1>
|
||||
<div class="mb-8">
|
||||
<h2 class="text-2xl font-semibold mb-4">License Agreement</h2>
|
||||
<p class="mb-4">
|
||||
This software is licensed under the <strong>Apache License 2.0</strong>. In addition to the terms of the
|
||||
Apache License 2.0, the following additional terms apply to the use of Cherry Studio:
|
||||
</p>
|
||||
<h3 class="text-xl font-semibold mb-2">I. Commercial Use License</h3>
|
||||
<ol class="list-decimal list-inside mb-4">
|
||||
<li>
|
||||
<strong>Free Commercial Use</strong>: Users can use the software for commercial purposes without
|
||||
modifying
|
||||
the code.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Commercial License Required</strong>: A commercial license is required if any of the
|
||||
following
|
||||
conditions are met:
|
||||
<ol class="list-decimal list-inside ml-4">
|
||||
<li>
|
||||
You modify, develop, or alter the software, including but not limited to changes to the
|
||||
application
|
||||
name, logo, code, or functionality.
|
||||
</li>
|
||||
<li>You provide multi-tenant services to enterprise customers with 10 or more users.</li>
|
||||
<li>
|
||||
You pre-install or integrate the software into hardware devices or products and bundle it
|
||||
for sale.
|
||||
</li>
|
||||
<li>
|
||||
You are engaging in large-scale procurement for government or educational institutions,
|
||||
especially
|
||||
involving security, data privacy, or other sensitive requirements.
|
||||
</li>
|
||||
</ol>
|
||||
</li>
|
||||
</ol>
|
||||
<h3 class="text-xl font-semibold mb-2">II. Contributor Agreement</h3>
|
||||
<ol class="list-decimal list-inside mb-4">
|
||||
<li>
|
||||
<strong>License Adjustment</strong>: The producer reserves the right to adjust the open-source
|
||||
license as
|
||||
needed, making it stricter or more lenient.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Commercial Use</strong>: Any code you contribute may be used for commercial purposes,
|
||||
including but
|
||||
not limited to cloud business operations.
|
||||
</li>
|
||||
</ol>
|
||||
<h3 class="text-xl font-semibold mb-2">III. Other Terms</h3>
|
||||
<ol class="list-decimal list-inside mb-4">
|
||||
<li>The interpretation of these terms is subject to the discretion of Cherry Studio developers.</li>
|
||||
<li>These terms may be updated, and users will be notified through the software when changes occur.</li>
|
||||
</ol>
|
||||
<p class="mb-4">
|
||||
For any questions or to request a commercial license, please contact the Cherry Studio development team.
|
||||
</p>
|
||||
<p>
|
||||
Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache
|
||||
License 2.0. Detailed information about the Apache License 2.0 can be found at
|
||||
<a href="http://www.apache.org/licenses/LICENSE-2.0"
|
||||
class="text-blue-500 underline">http://www.apache.org/licenses/LICENSE-2.0</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
91
src/main/constant.ts
Normal file
91
src/main/constant.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
export const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
|
||||
export const videoExts = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv']
|
||||
export const audioExts = ['.mp3', '.wav', '.ogg', '.flac', '.aac']
|
||||
export const documentExts = ['.pdf', '.docx', '.pptx', '.xlsx', '.odt', '.odp', '.ods']
|
||||
export const textExts = [
|
||||
'.txt', // 普通文本文件
|
||||
'.md', // Markdown 文件
|
||||
'.mdx', // Markdown 文件
|
||||
'.html', // HTML 文件
|
||||
'.htm', // HTML 文件的另一种扩展名
|
||||
'.xml', // XML 文件
|
||||
'.json', // JSON 文件
|
||||
'.yaml', // YAML 文件
|
||||
'.yml', // YAML 文件的另一种扩展名
|
||||
'.csv', // 逗号分隔值文件
|
||||
'.tsv', // 制表符分隔值文件
|
||||
'.ini', // 配置文件
|
||||
'.log', // 日志文件
|
||||
'.rtf', // 富文本格式文件
|
||||
'.tex', // LaTeX 文件
|
||||
'.srt', // 字幕文件
|
||||
'.xhtml', // XHTML 文件
|
||||
'.nfo', // 信息文件(主要用于场景发布)
|
||||
'.conf', // 配置文件
|
||||
'.config', // 配置文件
|
||||
'.env', // 环境变量文件
|
||||
'.rst', // reStructuredText 文件
|
||||
'.php', // PHP 脚本文件,包含嵌入的 HTML
|
||||
'.js', // JavaScript 文件(部分是文本,部分可能包含代码)
|
||||
'.ts', // TypeScript 文件
|
||||
'.jsp', // JavaServer Pages 文件
|
||||
'.aspx', // ASP.NET 文件
|
||||
'.bat', // Windows 批处理文件
|
||||
'.sh', // Unix/Linux Shell 脚本文件
|
||||
'.py', // Python 脚本文件
|
||||
'.rb', // Ruby 脚本文件
|
||||
'.pl', // Perl 脚本文件
|
||||
'.sql', // SQL 脚本文件
|
||||
'.css', // Cascading Style Sheets 文件
|
||||
'.less', // Less CSS 预处理器文件
|
||||
'.scss', // Sass CSS 预处理器文件
|
||||
'.sass', // Sass 文件
|
||||
'.styl', // Stylus CSS 预处理器文件
|
||||
'.coffee', // CoffeeScript 文件
|
||||
'.ino', // Arduino 代码文件
|
||||
'.asm', // Assembly 语言文件
|
||||
'.go', // Go 语言文件
|
||||
'.scala', // Scala 语言文件
|
||||
'.swift', // Swift 语言文件
|
||||
'.kt', // Kotlin 语言文件
|
||||
'.rs', // Rust 语言文件
|
||||
'.lua', // Lua 语言文件
|
||||
'.groovy', // Groovy 语言文件
|
||||
'.dart', // Dart 语言文件
|
||||
'.hs', // Haskell 语言文件
|
||||
'.clj', // Clojure 语言文件
|
||||
'.cljs', // ClojureScript 语言文件
|
||||
'.elm', // Elm 语言文件
|
||||
'.erl', // Erlang 语言文件
|
||||
'.ex', // Elixir 语言文件
|
||||
'.exs', // Elixir 脚本文件
|
||||
'.pug', // Pug (formerly Jade) 模板文件
|
||||
'.haml', // Haml 模板文件
|
||||
'.slim', // Slim 模板文件
|
||||
'.tpl', // 模板文件(通用)
|
||||
'.ejs', // Embedded JavaScript 模板文件
|
||||
'.hbs', // Handlebars 模板文件
|
||||
'.mustache', // Mustache 模板文件
|
||||
'.jade', // Jade 模板文件 (已重命名为 Pug)
|
||||
'.twig', // Twig 模板文件
|
||||
'.blade', // Blade 模板文件 (Laravel)
|
||||
'.vue', // Vue.js 单文件组件
|
||||
'.jsx', // React JSX 文件
|
||||
'.tsx', // React TSX 文件
|
||||
'.graphql', // GraphQL 查询语言文件
|
||||
'.gql', // GraphQL 查询语言文件
|
||||
'.proto', // Protocol Buffers 文件
|
||||
'.thrift', // Thrift 文件
|
||||
'.toml', // TOML 配置文件
|
||||
'.edn', // Clojure 数据表示文件
|
||||
'.cake', // CakePHP 配置文件
|
||||
'.ctp', // CakePHP 视图文件
|
||||
'.cfm', // ColdFusion 标记语言文件
|
||||
'.cfc', // ColdFusion 组件文件
|
||||
'.m', // Objective-C 源文件
|
||||
'.mm', // Objective-C++ 源文件
|
||||
'.gradle', // Gradle 构建文件
|
||||
'.groovy', // Gradle 构建文件
|
||||
'.kts', // Kotlin Script 文件
|
||||
'.java' // Java 代码文件
|
||||
]
|
||||
@@ -4,6 +4,7 @@ import { appConfig, titleBarOverlayDark, titleBarOverlayLight } from './config'
|
||||
import AppUpdater from './services/AppUpdater'
|
||||
import BackupManager from './services/BackupManager'
|
||||
import FileManager from './services/FileManager'
|
||||
import { compress, decompress } from './utils/zip'
|
||||
import { createMinappWindow } from './window'
|
||||
|
||||
const fileManager = new FileManager()
|
||||
@@ -29,6 +30,8 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
|
||||
|
||||
ipcMain.handle('reload', () => mainWindow.reload())
|
||||
|
||||
ipcMain.handle('zip:compress', (_, text: string) => compress(text))
|
||||
ipcMain.handle('zip:decompress', (_, text: Buffer) => decompress(text))
|
||||
ipcMain.handle('backup:backup', backupManager.backup)
|
||||
ipcMain.handle('backup:restore', backupManager.restore)
|
||||
ipcMain.handle('backup:backupToWebdav', backupManager.backupToWebdav)
|
||||
|
||||
@@ -20,8 +20,10 @@ export default class AppUpdater {
|
||||
autoUpdater.on('update-available', (releaseInfo: UpdateInfo) => {
|
||||
autoUpdater.logger?.info('检测到新版本,确认是否下载')
|
||||
mainWindow.webContents.send('update-available', releaseInfo)
|
||||
|
||||
const releaseNotes = releaseInfo.releaseNotes
|
||||
let releaseContent = ''
|
||||
|
||||
if (releaseNotes) {
|
||||
if (typeof releaseNotes === 'string') {
|
||||
releaseContent = <string>releaseNotes
|
||||
|
||||
@@ -102,7 +102,13 @@ class BackupManager {
|
||||
const webdavClient = new WebDav(webdavConfig)
|
||||
const retrievedFile = await webdavClient.getFileContents(filename)
|
||||
const backupedFilePath = path.join(this.backupDir, filename)
|
||||
|
||||
if (!fs.existsSync(this.backupDir)) {
|
||||
fs.mkdirSync(this.backupDir, { recursive: true })
|
||||
}
|
||||
|
||||
await fs.writeFileSync(backupedFilePath, retrievedFile as Buffer)
|
||||
|
||||
return await this.restore(_, backupedFilePath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { documentExts } from '@main/constant'
|
||||
import { getFileType } from '@main/utils/file'
|
||||
import { FileType } from '@types'
|
||||
import * as crypto from 'crypto'
|
||||
@@ -13,11 +14,14 @@ import logger from 'electron-log'
|
||||
import * as fs from 'fs'
|
||||
import { writeFileSync } from 'fs'
|
||||
import { readFile } from 'fs/promises'
|
||||
import officeParser from 'officeparser'
|
||||
import * as path from 'path'
|
||||
import { chdir } from 'process'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
|
||||
class FileManager {
|
||||
private storageDir = path.join(app.getPath('userData'), 'Data', 'Files')
|
||||
private tempDir = path.join(app.getPath('temp'), 'CherryStudio')
|
||||
|
||||
constructor() {
|
||||
this.initStorageDir()
|
||||
@@ -27,6 +31,9 @@ class FileManager {
|
||||
if (!fs.existsSync(this.storageDir)) {
|
||||
fs.mkdirSync(this.storageDir, { recursive: true })
|
||||
}
|
||||
if (!fs.existsSync(this.tempDir)) {
|
||||
fs.mkdirSync(this.tempDir, { recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
private getFileHash = async (filePath: string): Promise<string> => {
|
||||
@@ -173,15 +180,29 @@ class FileManager {
|
||||
|
||||
public readFile = async (_: Electron.IpcMainInvokeEvent, id: string): Promise<string> => {
|
||||
const filePath = path.join(this.storageDir, id)
|
||||
|
||||
if (documentExts.includes(path.extname(filePath))) {
|
||||
const originalCwd = process.cwd()
|
||||
try {
|
||||
chdir(this.tempDir)
|
||||
const data = await officeParser.parseOfficeAsync(filePath)
|
||||
chdir(originalCwd)
|
||||
return data
|
||||
} catch (error) {
|
||||
chdir(originalCwd)
|
||||
logger.error(error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return fs.readFileSync(filePath, 'utf8')
|
||||
}
|
||||
|
||||
public createTempFile = async (_: Electron.IpcMainInvokeEvent, fileName: string): Promise<string> => {
|
||||
const tempDir = path.join(app.getPath('temp'), 'CherryStudio')
|
||||
if (!fs.existsSync(tempDir)) {
|
||||
fs.mkdirSync(tempDir, { recursive: true })
|
||||
if (!fs.existsSync(this.tempDir)) {
|
||||
fs.mkdirSync(this.tempDir, { recursive: true })
|
||||
}
|
||||
const tempFilePath = path.join(tempDir, `temp_file_${uuidv4()}_${fileName}`)
|
||||
const tempFilePath = path.join(this.tempDir, `temp_file_${uuidv4()}_${fileName}`)
|
||||
return tempFilePath
|
||||
}
|
||||
|
||||
|
||||
@@ -1,101 +1,8 @@
|
||||
import { audioExts, documentExts, imageExts, textExts, videoExts } from '@main/constant'
|
||||
|
||||
import { FileTypes } from '../../renderer/src/types'
|
||||
|
||||
export function getFileType(ext: string): FileTypes {
|
||||
const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
|
||||
const videoExts = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv']
|
||||
const audioExts = ['.mp3', '.wav', '.ogg', '.flac', '.aac']
|
||||
const documentExts = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']
|
||||
const textExts = [
|
||||
'.txt', // 普通文本文件
|
||||
'.md', // Markdown 文件
|
||||
'.mdx', // Markdown 文件
|
||||
'.html', // HTML 文件
|
||||
'.htm', // HTML 文件的另一种扩展名
|
||||
'.xml', // XML 文件
|
||||
'.json', // JSON 文件
|
||||
'.yaml', // YAML 文件
|
||||
'.yml', // YAML 文件的另一种扩展名
|
||||
'.csv', // 逗号分隔值文件
|
||||
'.tsv', // 制表符分隔值文件
|
||||
'.ini', // 配置文件
|
||||
'.log', // 日志文件
|
||||
'.rtf', // 富文本格式文件
|
||||
'.tex', // LaTeX 文件
|
||||
'.srt', // 字幕文件
|
||||
'.xhtml', // XHTML 文件
|
||||
'.nfo', // 信息文件(主要用于场景发布)
|
||||
'.conf', // 配置文件
|
||||
'.config', // 配置文件
|
||||
'.env', // 环境变量文件
|
||||
'.properties', // 配置属性文件
|
||||
'.latex', // LaTeX 文档文件
|
||||
'.rst', // reStructuredText 文件
|
||||
'.php', // PHP 脚本文件,包含嵌入的 HTML
|
||||
'.js', // JavaScript 文件(部分是文本,部分可能包含代码)
|
||||
'.ts', // TypeScript 文件
|
||||
'.jsp', // JavaServer Pages 文件
|
||||
'.aspx', // ASP.NET 文件
|
||||
'.bat', // Windows 批处理文件
|
||||
'.sh', // Unix/Linux Shell 脚本文件
|
||||
'.py', // Python 脚本文件
|
||||
'.rb', // Ruby 脚本文件
|
||||
'.pl', // Perl 脚本文件
|
||||
'.sql', // SQL 脚本文件
|
||||
'.css', // Cascading Style Sheets 文件
|
||||
'.less', // Less CSS 预处理器文件
|
||||
'.scss', // Sass CSS 预处理器文件
|
||||
'.sass', // Sass 文件
|
||||
'.styl', // Stylus CSS 预处理器文件
|
||||
'.coffee', // CoffeeScript 文件
|
||||
'.ino', // Arduino 代码文件
|
||||
'.ino', // Arduino 代码文件
|
||||
'.asm', // Assembly 语言文件
|
||||
'.go', // Go 语言文件
|
||||
'.scala', // Scala 语言文件
|
||||
'.swift', // Swift 语言文件
|
||||
'.kt', // Kotlin 语言文件
|
||||
'.rs', // Rust 语言文件
|
||||
'.lua', // Lua 语言文件
|
||||
'.groovy', // Groovy 语言文件
|
||||
'.dart', // Dart 语言文件
|
||||
'.hs', // Haskell 语言文件
|
||||
'.clj', // Clojure 语言文件
|
||||
'.cljs', // ClojureScript 语言文件
|
||||
'.elm', // Elm 语言文件
|
||||
'.erl', // Erlang 语言文件
|
||||
'.ex', // Elixir 语言文件
|
||||
'.exs', // Elixir 脚本文件
|
||||
'.pug', // Pug (formerly Jade) 模板文件
|
||||
'.haml', // Haml 模板文件
|
||||
'.slim', // Slim 模板文件
|
||||
'.tpl', // 模板文件(通用)
|
||||
'.ejs', // Embedded JavaScript 模板文件
|
||||
'.hbs', // Handlebars 模板文件
|
||||
'.mustache', // Mustache 模板文件
|
||||
'.jade', // Jade 模板文件 (已重命名为 Pug)
|
||||
'.twig', // Twig 模板文件
|
||||
'.blade', // Blade 模板文件 (Laravel)
|
||||
'.vue', // Vue.js 单文件组件
|
||||
'.jsx', // React JSX 文件
|
||||
'.tsx', // React TSX 文件
|
||||
'.graphql', // GraphQL 查询语言文件
|
||||
'.gql', // GraphQL 查询语言文件
|
||||
'.proto', // Protocol Buffers 文件
|
||||
'.thrift', // Thrift 文件
|
||||
'.toml', // TOML 配置文件
|
||||
'.edn', // Clojure 数据表示文件
|
||||
'.cake', // CakePHP 配置文件
|
||||
'.ctp', // CakePHP 视图文件
|
||||
'.cfm', // ColdFusion 标记语言文件
|
||||
'.cfc', // ColdFusion 组件文件
|
||||
'.m', // Objective-C 源文件
|
||||
'.mm', // Objective-C++ 源文件
|
||||
'.gradle', // Gradle 构建文件
|
||||
'.groovy', // Gradle 构建文件
|
||||
'.gradle', // Gradle 构建文件
|
||||
'.kts' // Kotlin Script 文件
|
||||
]
|
||||
|
||||
ext = ext.toLowerCase()
|
||||
if (imageExts.includes(ext)) return FileTypes.IMAGE
|
||||
if (videoExts.includes(ext)) return FileTypes.VIDEO
|
||||
|
||||
39
src/main/utils/zip.ts
Normal file
39
src/main/utils/zip.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import util from 'node:util'
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
import logger from 'electron-log'
|
||||
|
||||
// 将 zlib 的 gzip 和 gunzip 方法转换为 Promise 版本
|
||||
const gzipPromise = util.promisify(zlib.gzip)
|
||||
const gunzipPromise = util.promisify(zlib.gunzip)
|
||||
|
||||
/**
|
||||
* 压缩字符串
|
||||
* @param {string} string - 要压缩的 JSON 字符串
|
||||
* @returns {Promise<Buffer>} 压缩后的 Buffer
|
||||
*/
|
||||
export async function compress(str) {
|
||||
try {
|
||||
const buffer = Buffer.from(str, 'utf-8')
|
||||
const compressedBuffer = await gzipPromise(buffer)
|
||||
return compressedBuffer
|
||||
} catch (error) {
|
||||
logger.error('Compression failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压缩 Buffer 到 JSON 字符串
|
||||
* @param {Buffer} compressedBuffer - 压缩的 Buffer
|
||||
* @returns {Promise<string>} 解压缩后的 JSON 字符串
|
||||
*/
|
||||
export async function decompress(compressedBuffer) {
|
||||
try {
|
||||
const buffer = await gunzipPromise(compressedBuffer)
|
||||
return buffer.toString('utf-8')
|
||||
} catch (error) {
|
||||
logger.error('Decompression failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export function createMainWindow() {
|
||||
const theme = appConfig.get('theme') || 'light'
|
||||
|
||||
// Create the browser window.
|
||||
const isMac = process.platform === 'darwin'
|
||||
|
||||
const mainWindow = new BrowserWindow({
|
||||
x: mainWindowState.x,
|
||||
y: mainWindowState.y,
|
||||
@@ -25,11 +27,12 @@ export function createMainWindow() {
|
||||
minHeight: 600,
|
||||
show: true,
|
||||
autoHideMenuBar: true,
|
||||
transparent: process.platform === 'darwin',
|
||||
transparent: isMac,
|
||||
vibrancy: 'fullscreen-ui',
|
||||
visualEffectState: 'active',
|
||||
titleBarStyle: 'hidden',
|
||||
titleBarOverlay: theme === 'dark' ? titleBarOverlayDark : titleBarOverlayLight,
|
||||
backgroundColor: isMac ? undefined : theme === 'dark' ? '#181818' : '#FFFFFF',
|
||||
trafficLightPosition: { x: 8, y: 12 },
|
||||
...(process.platform === 'linux' ? { icon } : {}),
|
||||
webPreferences: {
|
||||
@@ -45,11 +48,9 @@ export function createMainWindow() {
|
||||
|
||||
mainWindow.webContents.on('context-menu', () => {
|
||||
const menu = new Menu()
|
||||
menu.append(new MenuItem({ label: '复制', role: 'copy', sublabel: '⌘ + C' }))
|
||||
menu.append(new MenuItem({ label: '粘贴', role: 'paste', sublabel: '⌘ + V' }))
|
||||
menu.append(new MenuItem({ label: '剪切', role: 'cut', sublabel: '⌘ + X' }))
|
||||
menu.append(new MenuItem({ type: 'separator' }))
|
||||
menu.append(new MenuItem({ label: '全选', role: 'selectAll', sublabel: '⌘ + A' }))
|
||||
menu.append(new MenuItem({ label: '复制', role: 'copy' }))
|
||||
menu.append(new MenuItem({ label: '粘贴', role: 'paste' }))
|
||||
menu.append(new MenuItem({ label: '剪切', role: 'cut' }))
|
||||
menu.popup()
|
||||
})
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ const api = {
|
||||
setTheme: (theme: 'light' | 'dark') => ipcRenderer.invoke('set-theme', theme),
|
||||
minApp: (url: string) => ipcRenderer.invoke('minapp', url),
|
||||
reload: () => ipcRenderer.invoke('reload'),
|
||||
compress: (text: string) => ipcRenderer.invoke('zip:compress', text),
|
||||
decompress: (text: Buffer) => ipcRenderer.invoke('zip:decompress', text),
|
||||
backup: {
|
||||
backup: (fileName: string, data: string, destinationPath?: string) =>
|
||||
ipcRenderer.invoke('backup:backup', fileName, data, destinationPath),
|
||||
|
||||
@@ -1,36 +1,40 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="initial-scale=1, width=device-width" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; connect-src *; script-src 'self' *; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' *; font-src 'self' data: *; img-src 'self' data: file: *; frame-src * file:" />
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
#spinner {
|
||||
position: fixed;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
#spinner img {
|
||||
width: 100px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<div id="spinner">
|
||||
<img src="/src/assets/images/logo/cherry-text.svg" />
|
||||
</div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="initial-scale=1, width=device-width" />
|
||||
<meta http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; connect-src *; script-src 'self' *; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' *; font-src 'self' data: *; img-src 'self' data: file: *; frame-src * file:" />
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#spinner {
|
||||
position: fixed;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#spinner img {
|
||||
width: 100px;
|
||||
border-radius: 50px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<div id="spinner">
|
||||
<img src="/src/assets/images/logo.png" />
|
||||
</div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
18
src/renderer/src/assets/images/apps/bolt.svg
Normal file
18
src/renderer/src/assets/images/apps/bolt.svg
Normal file
@@ -0,0 +1,18 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="16" height="16" rx="4" fill="black"/>
|
||||
<g filter="url(#filter0_i_2119_154)">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.64368 11.7731C7.91976 11.7731 7.20901 11.5147 6.80099 10.9591L6.65707 11.6143L4 13L4.28684 11.6143L6.22186 3H8.59103L7.9066 6.03634C8.45941 5.44199 8.97273 5.22234 9.63083 5.22234C11.0523 5.22234 12 6.1397 12 7.81938C12 9.55074 10.9076 11.7731 8.64368 11.7731ZM9.55186 8.31036C9.55186 9.11144 8.97273 9.71871 8.22249 9.71871C7.8013 9.71871 7.4196 9.56366 7.16952 9.29233L7.53806 7.70309C7.81447 7.43176 8.13036 7.27671 8.49889 7.27671C9.06486 7.27671 9.55186 7.69017 9.55186 8.31036Z" fill="white"/>
|
||||
</g>
|
||||
<defs>
|
||||
<filter id="filter0_i_2119_154" x="4" y="3" width="8" height="10" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
||||
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
|
||||
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
|
||||
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
|
||||
<feOffset/>
|
||||
<feGaussianBlur stdDeviation="0.0192413"/>
|
||||
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1"/>
|
||||
<feColorMatrix type="matrix" values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.95 0"/>
|
||||
<feBlend mode="normal" in2="shape" result="effect1_innerShadow_2119_154"/>
|
||||
</filter>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
BIN
src/renderer/src/assets/images/providers/bailian.png
Normal file
BIN
src/renderer/src/assets/images/providers/bailian.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -2,10 +2,8 @@
|
||||
resize: none;
|
||||
}
|
||||
|
||||
.chat-nav-dropdown {
|
||||
.ant-dropdown-menu {
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
.ant-btn:not(:disabled):focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.ant-segmented-group {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
@import './markdown.scss';
|
||||
@import './scrollbar.scss';
|
||||
@import './ant.scss';
|
||||
@import '../fonts/icon-fonts/iconfont.css';
|
||||
@import '../fonts/ubuntu/ubuntu.css';
|
||||
@@ -39,6 +38,7 @@
|
||||
--color-code-background: #323232;
|
||||
--color-scrollbar-thumb: rgba(255, 255, 255, 0.08);
|
||||
--color-scrollbar-thumb-hover: rgba(255, 255, 255, 0.15);
|
||||
--color-scrollbar-thumb-active: rgba(255, 255, 255, 0.2);
|
||||
--color-hover: rgba(40, 40, 40, 1);
|
||||
--color-active: rgba(55, 55, 55, 1);
|
||||
|
||||
@@ -90,6 +90,7 @@ body[theme-mode='light'] {
|
||||
--color-code-background: #e3e3e3;
|
||||
--color-scrollbar-thumb: rgba(0, 0, 0, 0.08);
|
||||
--color-scrollbar-thumb-hover: rgba(0, 0, 0, 0.15);
|
||||
--color-scrollbar-thumb-active: rgba(0, 0, 0, 0.2);
|
||||
--color-hover: var(--color-white-mute);
|
||||
--color-active: var(--color-white-soft);
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
|
||||
p {
|
||||
margin: 1em 0;
|
||||
white-space: pre-wrap;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
@@ -97,7 +99,6 @@
|
||||
}
|
||||
|
||||
code {
|
||||
white-space: pre-wrap !important;
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
}
|
||||
|
||||
@@ -109,7 +110,6 @@
|
||||
}
|
||||
|
||||
pre {
|
||||
white-space: pre-wrap !important;
|
||||
border-radius: 5px;
|
||||
overflow-x: auto;
|
||||
font-family: 'Fira Code', 'Courier New', Courier, monospace;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* 全局初始化滚动条样式 */
|
||||
::-webkit-scrollbar {
|
||||
width: 2px;
|
||||
width: 4px;
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
|
||||
import { Assistant, AssistantMessage, AssistantSettings } from '@renderer/types'
|
||||
import { Button, Card, Col, Divider, Form as FormAntd, FormInstance, Row, Space, Switch } from 'antd'
|
||||
import TextArea from 'antd/es/input/TextArea'
|
||||
import { FC, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
updateAssistant: (assistant: Assistant) => void
|
||||
updateAssistantSettings: (settings: Partial<AssistantSettings>) => void
|
||||
}
|
||||
|
||||
const AssistantMessagesSettings: FC<Props> = ({ assistant, updateAssistant, updateAssistantSettings }) => {
|
||||
const { t } = useTranslation()
|
||||
const [form] = Form.useForm()
|
||||
const formRef = useRef<FormInstance>(null)
|
||||
const [messages, setMessagess] = useState<AssistantMessage[]>(assistant?.messages || [])
|
||||
const [hideMessages, setHideMessages] = useState(assistant?.settings?.hideMessages || false)
|
||||
|
||||
const onSave = () => {
|
||||
// 检查是否有空对话组
|
||||
for (let i = 0; i < messages.length; i += 2) {
|
||||
const userContent = messages[i].content.trim()
|
||||
const assistantContent = messages[i + 1]?.content.trim()
|
||||
if (userContent === '' || assistantContent === '') {
|
||||
window.modal.error({
|
||||
centered: true,
|
||||
content: t('agents.edit.message.empty.content')
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤掉空消息并将消息分组
|
||||
const filteredMessagess = messages.reduce((acc, conv, index) => {
|
||||
if (index % 2 === 0) {
|
||||
const userContent = conv.content.trim()
|
||||
const assistantContent = messages[index + 1]?.content.trim()
|
||||
if (userContent !== '' || assistantContent !== '') {
|
||||
acc.push({ role: 'user', content: userContent }, { role: 'assistant', content: assistantContent })
|
||||
}
|
||||
}
|
||||
return acc
|
||||
}, [] as AssistantMessage[])
|
||||
|
||||
updateAssistant({
|
||||
...assistant,
|
||||
messages: filteredMessagess
|
||||
})
|
||||
|
||||
window.message.success({ content: t('message.save.success.title'), key: 'save-messages' })
|
||||
}
|
||||
|
||||
const addMessages = () => {
|
||||
setMessagess([...messages, { role: 'user', content: '' }, { role: 'assistant', content: '' }])
|
||||
}
|
||||
|
||||
const updateMessages = (index: number, role: 'user' | 'assistant', content: string) => {
|
||||
const newMessagess = [...messages]
|
||||
newMessagess[index] = { role, content }
|
||||
setMessagess(newMessagess)
|
||||
}
|
||||
|
||||
const deleteMessages = (index: number) => {
|
||||
const newMessagess = [...messages]
|
||||
newMessagess.splice(index, 2) // 删除用户和助手的对话
|
||||
setMessagess(newMessagess)
|
||||
}
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Form ref={formRef} layout="vertical" form={form} labelAlign="right" colon={false}>
|
||||
<Form.Item label={t('agents.edit.settings.hide_preset_messages')}>
|
||||
<Switch
|
||||
checked={hideMessages}
|
||||
onChange={(checked) => {
|
||||
setHideMessages(checked)
|
||||
updateAssistantSettings({ hideMessages: checked })
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Divider style={{ marginBottom: 15 }} />
|
||||
<Form.Item label={t('agents.edit.message.group.title')}>
|
||||
{messages.map(
|
||||
(_, index) =>
|
||||
index % 2 === 0 && (
|
||||
<Card
|
||||
size="small"
|
||||
key={index}
|
||||
style={{ marginBottom: 16 }}
|
||||
title={`${t('agents.edit.message.group.title')} #${index / 2 + 1}`}
|
||||
extra={<Button icon={<DeleteOutlined />} type="text" danger onClick={() => deleteMessages(index)} />}>
|
||||
<Row gutter={16} align="middle" style={{ marginBottom: 16 }}>
|
||||
<Col span={3}>
|
||||
<label>{t('agents.edit.message.user.title')}</label>
|
||||
</Col>
|
||||
<Col span={21}>
|
||||
<TextArea
|
||||
value={messages[index].content}
|
||||
onChange={(e) => updateMessages(index, 'user', e.target.value)}
|
||||
placeholder={t('agents.edit.message.user.placeholder')}
|
||||
rows={1}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
<Row gutter={16} align="top">
|
||||
<Col span={3}>
|
||||
<label>{t('agents.edit.message.assistant.title')}</label>
|
||||
</Col>
|
||||
<Col span={21}>
|
||||
<TextArea
|
||||
value={messages[index + 1]?.content || ''}
|
||||
onChange={(e) => updateMessages(index + 1, 'assistant', e.target.value)}
|
||||
placeholder={t('agents.edit.message.assistant.placeholder')}
|
||||
rows={3}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
)
|
||||
)}
|
||||
<Space>
|
||||
<Button icon={<PlusOutlined />} onClick={addMessages}>
|
||||
{t('agents.edit.message.add.title')}
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
<Divider style={{ marginBottom: 15 }} />
|
||||
<Form.Item>
|
||||
{messages.length > 0 && (
|
||||
<Button type="primary" onClick={onSave}>
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
)}
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<div style={{ minHeight: 50 }} />
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
padding-top: 10px;
|
||||
`
|
||||
|
||||
const Form = styled(FormAntd)`
|
||||
.ant-form-item-no-colon {
|
||||
font-weight: 500;
|
||||
}
|
||||
`
|
||||
|
||||
export default AssistantMessagesSettings
|
||||
@@ -1,81 +1,107 @@
|
||||
import { QuestionCircleOutlined } from '@ant-design/icons'
|
||||
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons'
|
||||
import { HStack } from '@renderer/components/Layout'
|
||||
import { DEFAULT_CONEXTCOUNT, DEFAULT_MAX_TOKENS, DEFAULT_TEMPERATURE } from '@renderer/config/constant'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { SettingRow, SettingRowTitle } from '@renderer/pages/settings'
|
||||
import { DEFAULT_CONEXTCOUNT, DEFAULT_TEMPERATURE } from '@renderer/config/constant'
|
||||
import { SettingRow } from '@renderer/pages/settings'
|
||||
import { Assistant, AssistantSettings } from '@renderer/types'
|
||||
import { Button, Col, Row, Slider, Switch, Tooltip } from 'antd'
|
||||
import { FC, useEffect, useState } from 'react'
|
||||
import { Button, Col, Divider, Row, Slider, Switch, Tooltip } from 'antd'
|
||||
import { FC, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import ModelAvatar from '../Avatar/ModelAvatar'
|
||||
import SelectModelPopup from '../Popups/SelectModelPopup'
|
||||
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
updateAssistant: (assistant: Assistant) => void
|
||||
updateAssistantSettings: (settings: Partial<AssistantSettings>) => void
|
||||
}
|
||||
|
||||
const AssistantModelSettings: FC<Props> = (props) => {
|
||||
const { assistant, updateAssistantSettings, updateAssistant } = useAssistant(props.assistant.id)
|
||||
const AssistantModelSettings: FC<Props> = ({ assistant, updateAssistant, updateAssistantSettings }) => {
|
||||
const [temperature, setTemperature] = useState(assistant?.settings?.temperature ?? DEFAULT_TEMPERATURE)
|
||||
const [contextCount, setConextCount] = useState(assistant?.settings?.contextCount ?? DEFAULT_CONEXTCOUNT)
|
||||
const [enableMaxTokens, setEnableMaxTokens] = useState(assistant?.settings?.enableMaxTokens ?? false)
|
||||
const [maxTokens, setMaxTokens] = useState(assistant?.settings?.maxTokens ?? 0)
|
||||
const [autoResetModel, setAutoResetModel] = useState(assistant?.settings?.autoResetModel ?? false)
|
||||
const [streamOutput, setStreamOutput] = useState(assistant?.settings?.streamOutput ?? true)
|
||||
const [defaultModel, setDefaultModel] = useState(assistant?.defaultModel)
|
||||
const { t } = useTranslation()
|
||||
|
||||
const onUpdateAssistantSettings = (settings: Partial<AssistantSettings>) => {
|
||||
updateAssistantSettings({
|
||||
temperature: settings.temperature ?? temperature,
|
||||
contextCount: settings.contextCount ?? contextCount,
|
||||
enableMaxTokens: settings.enableMaxTokens ?? enableMaxTokens,
|
||||
maxTokens: settings.maxTokens ?? maxTokens,
|
||||
streamOutput: settings.streamOutput ?? streamOutput
|
||||
})
|
||||
}
|
||||
|
||||
const onTemperatureChange = (value) => {
|
||||
if (!isNaN(value as number)) {
|
||||
onUpdateAssistantSettings({ temperature: value })
|
||||
updateAssistantSettings({ temperature: value })
|
||||
}
|
||||
}
|
||||
|
||||
const onConextCountChange = (value) => {
|
||||
if (!isNaN(value as number)) {
|
||||
onUpdateAssistantSettings({ contextCount: value })
|
||||
updateAssistantSettings({ contextCount: value })
|
||||
}
|
||||
}
|
||||
|
||||
const onMaxTokensChange = (value) => {
|
||||
if (!isNaN(value as number)) {
|
||||
onUpdateAssistantSettings({ maxTokens: value })
|
||||
updateAssistantSettings({ maxTokens: value })
|
||||
}
|
||||
}
|
||||
|
||||
const onReset = () => {
|
||||
setTemperature(DEFAULT_TEMPERATURE)
|
||||
setConextCount(DEFAULT_CONEXTCOUNT)
|
||||
updateAssistant({
|
||||
...assistant,
|
||||
settings: {
|
||||
...assistant.settings,
|
||||
temperature: DEFAULT_TEMPERATURE,
|
||||
contextCount: DEFAULT_CONEXTCOUNT,
|
||||
enableMaxTokens: false,
|
||||
maxTokens: DEFAULT_MAX_TOKENS,
|
||||
streamOutput: true
|
||||
}
|
||||
setEnableMaxTokens(false)
|
||||
setMaxTokens(0)
|
||||
setStreamOutput(true)
|
||||
updateAssistantSettings({
|
||||
temperature: DEFAULT_TEMPERATURE,
|
||||
contextCount: DEFAULT_CONEXTCOUNT,
|
||||
enableMaxTokens: false,
|
||||
maxTokens: 0,
|
||||
streamOutput: true
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setTemperature(assistant?.settings?.temperature ?? DEFAULT_TEMPERATURE)
|
||||
setConextCount(assistant?.settings?.contextCount ?? DEFAULT_CONEXTCOUNT)
|
||||
setEnableMaxTokens(assistant?.settings?.enableMaxTokens ?? false)
|
||||
setMaxTokens(assistant?.settings?.maxTokens ?? DEFAULT_MAX_TOKENS)
|
||||
setStreamOutput(assistant?.settings?.streamOutput ?? true)
|
||||
}, [assistant])
|
||||
const onSelectModel = async () => {
|
||||
const selectedModel = await SelectModelPopup.show({ model: assistant?.model })
|
||||
if (selectedModel) {
|
||||
setDefaultModel(selectedModel)
|
||||
updateAssistant({
|
||||
...assistant,
|
||||
defaultModel: selectedModel
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Row align="middle" style={{ marginBottom: 10 }}>
|
||||
<Label style={{ marginBottom: 10 }}>{t('assistants.settings.default_model')}</Label>
|
||||
<Col span={24}>
|
||||
<HStack alignItems="center">
|
||||
<Button
|
||||
icon={defaultModel ? <ModelAvatar model={defaultModel} size={20} /> : <PlusOutlined />}
|
||||
onClick={onSelectModel}>
|
||||
{defaultModel ? defaultModel.name : t('agents.edit.model.select.title')}
|
||||
</Button>
|
||||
</HStack>
|
||||
</Col>
|
||||
</Row>
|
||||
<Divider style={{ margin: '10px 0' }} />
|
||||
<SettingRow style={{ minHeight: 30 }}>
|
||||
<Label>
|
||||
{t('assistants.settings.auto_reset_model')}{' '}
|
||||
<Tooltip title={t('assistants.settings.auto_reset_model.tip')}>
|
||||
<QuestionIcon />
|
||||
</Tooltip>
|
||||
</Label>
|
||||
<Switch
|
||||
value={autoResetModel}
|
||||
onChange={(checked) => {
|
||||
setAutoResetModel(checked)
|
||||
updateAssistantSettings({ autoResetModel: checked })
|
||||
}}
|
||||
/>
|
||||
</SettingRow>
|
||||
<Divider style={{ margin: '10px 0' }} />
|
||||
<Row align="middle">
|
||||
<Label>{t('chat.settings.temperature')}</Label>
|
||||
<Tooltip title={t('chat.settings.temperature.tip')}>
|
||||
@@ -95,10 +121,12 @@ const AssistantModelSettings: FC<Props> = (props) => {
|
||||
</Col>
|
||||
</Row>
|
||||
<Row align="middle">
|
||||
<Label>{t('chat.settings.conext_count')}</Label>
|
||||
<Tooltip title={t('chat.settings.conext_count.tip')}>
|
||||
<QuestionIcon />
|
||||
</Tooltip>
|
||||
<Label>
|
||||
{t('chat.settings.conext_count')}{' '}
|
||||
<Tooltip title={t('chat.settings.conext_count.tip')}>
|
||||
<QuestionIcon />
|
||||
</Tooltip>
|
||||
</Label>
|
||||
</Row>
|
||||
<Row align="middle" gutter={10}>
|
||||
<Col span={24}>
|
||||
@@ -123,7 +151,7 @@ const AssistantModelSettings: FC<Props> = (props) => {
|
||||
checked={enableMaxTokens}
|
||||
onChange={(enabled) => {
|
||||
setEnableMaxTokens(enabled)
|
||||
onUpdateAssistantSettings({ enableMaxTokens: enabled })
|
||||
updateAssistantSettings({ enableMaxTokens: enabled })
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
@@ -141,18 +169,17 @@ const AssistantModelSettings: FC<Props> = (props) => {
|
||||
</Col>
|
||||
</Row>
|
||||
<SettingRow>
|
||||
<SettingRowTitleSmall>{t('model.stream_output')}</SettingRowTitleSmall>
|
||||
<Label>{t('model.stream_output')}</Label>
|
||||
<Switch
|
||||
checked={streamOutput}
|
||||
onChange={(checked) => {
|
||||
setStreamOutput(checked)
|
||||
onUpdateAssistantSettings({ streamOutput: checked })
|
||||
updateAssistantSettings({ streamOutput: checked })
|
||||
}}
|
||||
/>
|
||||
</SettingRow>
|
||||
<HStack
|
||||
justifyContent="flex-end"
|
||||
style={{ marginTop: 20, padding: '10px 0', borderTop: '0.5px solid var(--color-border)' }}>
|
||||
<Divider style={{ margin: '15px 0' }} />
|
||||
<HStack justifyContent="flex-end">
|
||||
<Button onClick={onReset} style={{ width: 80 }} danger type="primary">
|
||||
{t('chat.settings.reset')}
|
||||
</Button>
|
||||
@@ -166,12 +193,12 @@ const Container = styled.div`
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding-bottom: 10px;
|
||||
padding: 5px;
|
||||
`
|
||||
|
||||
const Label = styled.p`
|
||||
margin: 0;
|
||||
margin-right: 5px;
|
||||
font-weight: 500;
|
||||
`
|
||||
|
||||
const QuestionIcon = styled(QuestionCircleOutlined)`
|
||||
@@ -180,8 +207,4 @@ const QuestionIcon = styled(QuestionCircleOutlined)`
|
||||
color: var(--color-text-3);
|
||||
`
|
||||
|
||||
const SettingRowTitleSmall = styled(SettingRowTitle)`
|
||||
font-size: 13px;
|
||||
`
|
||||
|
||||
export default AssistantModelSettings
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { syncAsistantToAgent } from '@renderer/services/assistant'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import { Input } from 'antd'
|
||||
import { Assistant, AssistantSettings } from '@renderer/types'
|
||||
import { Button, Input } from 'antd'
|
||||
import TextArea from 'antd/es/input/TextArea'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import { Box, VStack } from '../Layout'
|
||||
import { Box, HStack } from '../Layout'
|
||||
|
||||
const AssistantPromptSettings: React.FC<{ assistant: Assistant }> = (props) => {
|
||||
const { assistant, updateAssistant } = useAssistant(props.assistant.id)
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
updateAssistant: (assistant: Assistant) => void
|
||||
updateAssistantSettings: (settings: AssistantSettings) => void
|
||||
onOk: () => void
|
||||
}
|
||||
|
||||
const AssistantPromptSettings: React.FC<Props> = ({ assistant, updateAssistant, onOk }) => {
|
||||
const [name, setName] = useState(assistant.name)
|
||||
const [prompt, setPrompt] = useState(assistant.prompt)
|
||||
const { t } = useTranslation()
|
||||
@@ -17,19 +22,20 @@ const AssistantPromptSettings: React.FC<{ assistant: Assistant }> = (props) => {
|
||||
const onUpdate = () => {
|
||||
const _assistant = { ...assistant, name, prompt }
|
||||
updateAssistant(_assistant)
|
||||
syncAsistantToAgent(_assistant)
|
||||
}
|
||||
|
||||
return (
|
||||
<VStack flex={1}>
|
||||
<Box mb={8}>{t('common.name')}</Box>
|
||||
<Container>
|
||||
<Box mb={8} style={{ fontWeight: 'bold' }}>
|
||||
{t('common.name')}
|
||||
</Box>
|
||||
<Input
|
||||
placeholder={t('common.assistant') + t('common.name')}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={onUpdate}
|
||||
/>
|
||||
<Box mt={8} mb={8}>
|
||||
<Box mt={8} mb={8} style={{ fontWeight: 'bold' }}>
|
||||
{t('common.prompt')}
|
||||
</Box>
|
||||
<TextArea
|
||||
@@ -38,10 +44,23 @@ const AssistantPromptSettings: React.FC<{ assistant: Assistant }> = (props) => {
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
onBlur={onUpdate}
|
||||
style={{ minHeight: 'calc(80vh - 150px)', maxHeight: 'calc(80vh - 150px)' }}
|
||||
style={{ minHeight: 'calc(80vh - 200px)', maxHeight: 'calc(80vh - 150px)' }}
|
||||
/>
|
||||
</VStack>
|
||||
<HStack width="100%" justifyContent="flex-end" mt="10px">
|
||||
<Button type="primary" onClick={onOk}>
|
||||
{t('common.close')}
|
||||
</Button>
|
||||
</HStack>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding: 5px;
|
||||
`
|
||||
|
||||
export default AssistantPromptSettings
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useTheme } from '@renderer/context/ThemeProvider'
|
||||
import { useAgent } from '@renderer/hooks/useAgents'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import { Menu, Modal } from 'antd'
|
||||
import { useState } from 'react'
|
||||
@@ -7,6 +8,7 @@ import styled from 'styled-components'
|
||||
|
||||
import { HStack } from '../Layout'
|
||||
import { TopView } from '../TopView'
|
||||
import AssistantMessagesSettings from './AssistantMessagesSettings'
|
||||
import AssistantModelSettings from './AssistantModelSettings'
|
||||
import AssistantPromptSettings from './AssistantPromptSettings'
|
||||
|
||||
@@ -18,32 +20,43 @@ interface Props extends AssistantSettingPopupShowParams {
|
||||
resolve: (assistant: Assistant) => void
|
||||
}
|
||||
|
||||
const AssistantSettingPopupContainer: React.FC<Props> = ({ assistant, resolve }) => {
|
||||
const AssistantSettingPopupContainer: React.FC<Props> = ({ resolve, ...props }) => {
|
||||
const [open, setOpen] = useState(true)
|
||||
const { t } = useTranslation()
|
||||
const [menu, setMenu] = useState('prompt')
|
||||
const { theme } = useTheme()
|
||||
|
||||
const _useAssistant = useAssistant(props.assistant.id)
|
||||
const _useAgent = useAgent(props.assistant.id)
|
||||
const isAgent = props.assistant.type === 'agent'
|
||||
|
||||
const assistant = isAgent ? _useAgent.agent : _useAssistant.assistant
|
||||
const updateAssistant = isAgent ? _useAgent.updateAgent : _useAssistant.updateAssistant
|
||||
const updateAssistantSettings = isAgent ? _useAgent.updateAgentSettings : _useAssistant.updateAssistantSettings
|
||||
|
||||
const onOk = () => {
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
const onCancel = () => {
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const onClose = () => {
|
||||
const afterClose = () => {
|
||||
resolve(assistant)
|
||||
}
|
||||
|
||||
const items = [
|
||||
{
|
||||
key: 'prompt',
|
||||
label: t('assistants.prompt_settings')
|
||||
label: t('assistants.settings.prompt')
|
||||
},
|
||||
{
|
||||
key: 'model',
|
||||
label: t('assistants.model_settings')
|
||||
label: t('assistants.settings.model')
|
||||
},
|
||||
{
|
||||
key: 'messages',
|
||||
label: t('assistants.settings.preset_messages')
|
||||
}
|
||||
]
|
||||
|
||||
@@ -51,21 +64,19 @@ const AssistantSettingPopupContainer: React.FC<Props> = ({ assistant, resolve })
|
||||
<StyledModal
|
||||
open={open}
|
||||
onOk={onOk}
|
||||
onCancel={handleCancel}
|
||||
afterClose={onClose}
|
||||
transitionName="ant-move-down"
|
||||
maskTransitionName="ant-fade"
|
||||
onClose={onCancel}
|
||||
onCancel={onCancel}
|
||||
afterClose={afterClose}
|
||||
footer={null}
|
||||
title={assistant.name}
|
||||
transitionName="ant-move-down"
|
||||
styles={{
|
||||
content: {
|
||||
padding: 0,
|
||||
overflow: 'hidden',
|
||||
border: '1px solid var(--color-border)',
|
||||
background: 'var(--color-background)'
|
||||
},
|
||||
header: { padding: '10px 15px', borderBottom: '0.5px solid var(--color-border)', margin: 0 },
|
||||
mask: { background: theme === 'light' ? 'rgba(255,255,255, 0.8)' : 'rgba(0,0,0, 0.8)' }
|
||||
header: { padding: '10px 15px', borderBottom: '0.5px solid var(--color-border)', margin: 0 }
|
||||
}}
|
||||
width="70vw"
|
||||
height="80vh"
|
||||
@@ -81,8 +92,28 @@ const AssistantSettingPopupContainer: React.FC<Props> = ({ assistant, resolve })
|
||||
/>
|
||||
</LeftMenu>
|
||||
<Settings>
|
||||
{menu === 'prompt' && <AssistantPromptSettings assistant={assistant} />}
|
||||
{menu === 'model' && <AssistantModelSettings assistant={assistant} />}
|
||||
{menu === 'prompt' && (
|
||||
<AssistantPromptSettings
|
||||
assistant={assistant}
|
||||
updateAssistant={updateAssistant}
|
||||
updateAssistantSettings={updateAssistantSettings}
|
||||
onOk={onOk}
|
||||
/>
|
||||
)}
|
||||
{menu === 'model' && (
|
||||
<AssistantModelSettings
|
||||
assistant={assistant}
|
||||
updateAssistant={updateAssistant}
|
||||
updateAssistantSettings={updateAssistantSettings}
|
||||
/>
|
||||
)}
|
||||
{menu === 'messages' && (
|
||||
<AssistantMessagesSettings
|
||||
assistant={assistant}
|
||||
updateAssistant={updateAssistant}
|
||||
updateAssistantSettings={updateAssistantSettings}
|
||||
/>
|
||||
)}
|
||||
</Settings>
|
||||
</HStack>
|
||||
</StyledModal>
|
||||
@@ -111,7 +142,7 @@ const StyledModal = styled(Modal)`
|
||||
}
|
||||
.ant-menu-item {
|
||||
height: 36px;
|
||||
border-radius: 4px;
|
||||
border-radius: 6px;
|
||||
color: var(--color-text-2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -132,11 +163,7 @@ const StyledModal = styled(Modal)`
|
||||
}
|
||||
`
|
||||
|
||||
export default class AssistantSettingPopup {
|
||||
static topviewId = 0
|
||||
static hide() {
|
||||
TopView.hide('AssistantSettingPopup')
|
||||
}
|
||||
export default class AssistantSettingsPopup {
|
||||
static show(props: AssistantSettingPopupShowParams) {
|
||||
return new Promise<Assistant>((resolve) => {
|
||||
TopView.show(
|
||||
@@ -144,10 +171,10 @@ export default class AssistantSettingPopup {
|
||||
{...props}
|
||||
resolve={(v) => {
|
||||
resolve(v)
|
||||
this.hide()
|
||||
TopView.hide('AssistantSettingsPopup')
|
||||
}}
|
||||
/>,
|
||||
'AssistantSettingPopup'
|
||||
'AssistantSettingsPopup'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { TopView } from '@renderer/components/TopView'
|
||||
import systemAgents from '@renderer/config/agents.json'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { useAssistants, useDefaultAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { covertAgentToAssistant } from '@renderer/services/assistant'
|
||||
import { createAssistantFromAgent } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { Agent, Assistant } from '@renderer/types'
|
||||
import { Divider, Input, InputRef, Modal, Tag } from 'antd'
|
||||
@@ -26,35 +26,22 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
|
||||
const { assistants, addAssistant } = useAssistants()
|
||||
const inputRef = useRef<InputRef>(null)
|
||||
|
||||
const defaultAgent: Agent = useMemo(
|
||||
() => ({
|
||||
id: defaultAssistant.id,
|
||||
name: defaultAssistant.name,
|
||||
emoji: defaultAssistant.emoji || '',
|
||||
prompt: defaultAssistant.prompt,
|
||||
group: 'system'
|
||||
}),
|
||||
[defaultAssistant.emoji, defaultAssistant.id, defaultAssistant.name, defaultAssistant.prompt]
|
||||
)
|
||||
|
||||
const agents = useMemo(() => {
|
||||
const allAgents = [...userAgents, ...systemAgents] as Agent[]
|
||||
const list = [defaultAgent, ...allAgents.filter((agent) => !assistants.map((a) => a.id).includes(agent.id))]
|
||||
const list = [defaultAssistant, ...allAgents.filter((agent) => !assistants.map((a) => a.id).includes(agent.id))]
|
||||
return searchText
|
||||
? list.filter((agent) => agent.name.toLowerCase().includes(searchText.trim().toLocaleLowerCase()))
|
||||
: list
|
||||
}, [assistants, defaultAgent, searchText, userAgents])
|
||||
}, [assistants, defaultAssistant, searchText, userAgents])
|
||||
|
||||
const onCreateAssistant = (agent: Agent) => {
|
||||
if (agent.id !== 'default') {
|
||||
if (assistants.map((a) => a.id).includes(String(agent.id))) {
|
||||
return
|
||||
}
|
||||
const onCreateAssistant = async (agent: Agent) => {
|
||||
if (agent.id === 'default') {
|
||||
addAssistant(agent)
|
||||
return
|
||||
}
|
||||
|
||||
const assistant = covertAgentToAssistant(agent)
|
||||
const assistant = await createAssistantFromAgent(agent)
|
||||
|
||||
addAssistant(assistant)
|
||||
setTimeout(() => EventEmitter.emit(EVENT_NAMES.SHOW_ASSISTANTS), 0)
|
||||
resolve(assistant)
|
||||
setOpen(false)
|
||||
@@ -102,7 +89,7 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
|
||||
size="middle"
|
||||
/>
|
||||
</HStack>
|
||||
<Divider style={{ margin: 0 }} />
|
||||
<Divider style={{ margin: 0, borderBlockStartWidth: 0.5 }} />
|
||||
<Container>
|
||||
{agents.map((agent) => (
|
||||
<AgentItem
|
||||
@@ -112,8 +99,8 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
|
||||
<HStack alignItems="center" gap={5}>
|
||||
{agent.emoji} {agent.name}
|
||||
</HStack>
|
||||
{agent.group === 'system' && <Tag color="green">{t('agents.tag.system')}</Tag>}
|
||||
{agent.group === 'user' && <Tag color="orange">{t('agents.tag.user')}</Tag>}
|
||||
{agent.id === 'default' && <Tag color="green">{t('agents.tag.system')}</Tag>}
|
||||
{agent.type === 'agent' && <Tag color="orange">{t('agents.tag.agent')}</Tag>}
|
||||
</AgentItem>
|
||||
))}
|
||||
</Container>
|
||||
|
||||
181
src/renderer/src/components/Popups/SelectModelPopup.tsx
Normal file
181
src/renderer/src/components/Popups/SelectModelPopup.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
import { SearchOutlined } from '@ant-design/icons'
|
||||
import VisionIcon from '@renderer/components/Icons/VisionIcon'
|
||||
import { TopView } from '@renderer/components/TopView'
|
||||
import { getModelLogo, isVisionModel } from '@renderer/config/models'
|
||||
import { useProviders } from '@renderer/hooks/useProvider'
|
||||
import { getModelUniqId } from '@renderer/services/model'
|
||||
import { Model } from '@renderer/types'
|
||||
import { Avatar, Divider, Empty, Input, InputRef, Menu, MenuProps, Modal } from 'antd'
|
||||
import { first, reverse, sortBy } from 'lodash'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import { HStack } from '../Layout'
|
||||
|
||||
type MenuItem = Required<MenuProps>['items'][number]
|
||||
|
||||
interface Props {
|
||||
model?: Model
|
||||
}
|
||||
|
||||
interface PopupContainerProps extends Props {
|
||||
resolve: (value: Model | undefined) => void
|
||||
}
|
||||
|
||||
const PopupContainer: React.FC<PopupContainerProps> = ({ model, resolve }) => {
|
||||
const [open, setOpen] = useState(true)
|
||||
const { t } = useTranslation()
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const inputRef = useRef<InputRef>(null)
|
||||
const { providers } = useProviders()
|
||||
|
||||
const filteredItems: MenuItem[] = providers
|
||||
.filter((p) => p.models && p.models.length > 0)
|
||||
.map((p) => ({
|
||||
key: p.id,
|
||||
label: p.isSystem ? t(`provider.${p.id}`) : p.name,
|
||||
type: 'group',
|
||||
children: reverse(sortBy(p.models, 'name'))
|
||||
.filter((m) =>
|
||||
[m.name + m.provider + t('provider.' + p.id)].join('').toLowerCase().includes(searchText.toLowerCase())
|
||||
)
|
||||
.map((m) => ({
|
||||
key: getModelUniqId(m),
|
||||
label: (
|
||||
<ModelItem>
|
||||
{m?.name} {isVisionModel(m) && <VisionIcon />}
|
||||
</ModelItem>
|
||||
),
|
||||
icon: (
|
||||
<Avatar src={getModelLogo(m?.id || '')} size={24}>
|
||||
{first(m?.name)}
|
||||
</Avatar>
|
||||
),
|
||||
onClick: () => {
|
||||
resolve(m)
|
||||
setOpen(false)
|
||||
}
|
||||
}))
|
||||
}))
|
||||
.filter((item) => item.children && item.children.length > 0) as MenuItem[]
|
||||
|
||||
const onCancel = () => {
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const onClose = async () => {
|
||||
resolve(undefined)
|
||||
SelectModelPopup.hide()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
open && setTimeout(() => inputRef.current?.focus(), 0)
|
||||
}, [open])
|
||||
|
||||
return (
|
||||
<Modal
|
||||
centered
|
||||
open={open}
|
||||
onCancel={onCancel}
|
||||
afterClose={onClose}
|
||||
transitionName="ant-move-down"
|
||||
styles={{ content: { borderRadius: 20, padding: 0, overflow: 'hidden', paddingBottom: 20 } }}
|
||||
closeIcon={null}
|
||||
footer={null}>
|
||||
<HStack style={{ padding: '0 12px', marginTop: 5 }}>
|
||||
<Input
|
||||
prefix={
|
||||
<SearchIcon>
|
||||
<SearchOutlined />
|
||||
</SearchIcon>
|
||||
}
|
||||
ref={inputRef}
|
||||
placeholder={t('model.search')}
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
allowClear
|
||||
autoFocus
|
||||
style={{ paddingLeft: 0 }}
|
||||
bordered={false}
|
||||
size="middle"
|
||||
/>
|
||||
</HStack>
|
||||
<Divider style={{ margin: 0, borderBlockStartWidth: 0.5 }} />
|
||||
<Container>
|
||||
{filteredItems.length > 0 ? (
|
||||
<StyledMenu
|
||||
items={filteredItems}
|
||||
selectedKeys={model ? [getModelUniqId(model)] : []}
|
||||
mode="inline"
|
||||
inlineIndent={6}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState>
|
||||
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
|
||||
</EmptyState>
|
||||
)}
|
||||
</Container>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
height: 50vh;
|
||||
margin-top: 10px;
|
||||
overflow-y: auto;
|
||||
`
|
||||
|
||||
const StyledMenu = styled(Menu)`
|
||||
background-color: transparent;
|
||||
padding: 5px;
|
||||
margin-top: -10px;
|
||||
max-height: calc(60vh - 50px);
|
||||
|
||||
.ant-menu-item-group-title {
|
||||
padding: 5px 10px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.ant-menu-item {
|
||||
height: 36px;
|
||||
line-height: 36px;
|
||||
}
|
||||
`
|
||||
|
||||
const ModelItem = styled.div`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 14px;
|
||||
`
|
||||
|
||||
const EmptyState = styled.div`
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 200px;
|
||||
`
|
||||
|
||||
const SearchIcon = styled.div`
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background-color: var(--color-background-soft);
|
||||
margin-right: 2px;
|
||||
`
|
||||
|
||||
export default class SelectModelPopup {
|
||||
static topviewId = 0
|
||||
static hide() {
|
||||
TopView.hide('SelectModelPopup')
|
||||
}
|
||||
static show(params: Props) {
|
||||
return new Promise<Model | undefined>((resolve) => {
|
||||
TopView.show(<PopupContainer {...params} resolve={resolve} />, 'SelectModelPopup')
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ const Sidebar: FC = () => {
|
||||
</Icon>
|
||||
</StyledLink>
|
||||
<StyledLink onClick={() => to('/agents')}>
|
||||
<Icon className={isRoute('/agents')}>
|
||||
<Icon className={isRoutes('/agents')}>
|
||||
<i className="iconfont icon-business-smart-assistant" />
|
||||
</Icon>
|
||||
</StyledLink>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -9,6 +9,7 @@ export const isWindows = platform === 'win32' || platform === 'win64'
|
||||
export const isLinux = platform === 'linux'
|
||||
|
||||
export const imageExts = ['.jpg', '.png', '.jpeg']
|
||||
export const documentExts = ['.pdf', '.docx', '.pptx', '.xlsx', '.odt', '.odp', '.ods']
|
||||
export const textExts = [
|
||||
'.txt', // 普通文本文件
|
||||
'.md', // Markdown 文件
|
||||
@@ -31,8 +32,6 @@ export const textExts = [
|
||||
'.conf', // 配置文件
|
||||
'.config', // 配置文件
|
||||
'.env', // 环境变量文件
|
||||
'.properties', // 配置属性文件
|
||||
'.latex', // LaTeX 文档文件
|
||||
'.rst', // reStructuredText 文件
|
||||
'.php', // PHP 脚本文件,包含嵌入的 HTML
|
||||
'.js', // JavaScript 文件(部分是文本,部分可能包含代码)
|
||||
@@ -52,7 +51,6 @@ export const textExts = [
|
||||
'.styl', // Stylus CSS 预处理器文件
|
||||
'.coffee', // CoffeeScript 文件
|
||||
'.ino', // Arduino 代码文件
|
||||
'.ino', // Arduino 代码文件
|
||||
'.asm', // Assembly 语言文件
|
||||
'.go', // Go 语言文件
|
||||
'.scala', // Scala 语言文件
|
||||
@@ -96,6 +94,6 @@ export const textExts = [
|
||||
'.mm', // Objective-C++ 源文件
|
||||
'.gradle', // Gradle 构建文件
|
||||
'.groovy', // Gradle 构建文件
|
||||
'.gradle', // Gradle 构建文件
|
||||
'.kts' // Kotlin Script 文件
|
||||
'.kts', // Kotlin Script 文件
|
||||
'.java' // Java 代码文件
|
||||
]
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import AiAssistantAppLogo from '@renderer/assets/images/apps/360-ai.png'
|
||||
import AiSearchAppLogo from '@renderer/assets/images/apps/ai-search.png'
|
||||
import BaiduAiAppLogo from '@renderer/assets/images/apps/baidu-ai.png'
|
||||
import FeloAppLogo from '@renderer/assets/images/apps/felo.png'
|
||||
import BaicuanAppLogo from '@renderer/assets/images/apps/baixiaoying.webp'
|
||||
import BoltAppLogo from '@renderer/assets/images/apps/bolt.svg'
|
||||
import DevvAppLogo from '@renderer/assets/images/apps/devv.png'
|
||||
import DoubaoAppLogo from '@renderer/assets/images/apps/doubao.png'
|
||||
import FeloAppLogo from '@renderer/assets/images/apps/felo.png'
|
||||
import GeminiAppLogo from '@renderer/assets/images/apps/gemini.png'
|
||||
import HuggingChatLogo from '@renderer/assets/images/apps/huggingchat.svg'
|
||||
import KimiAppLogo from '@renderer/assets/images/apps/kimi.jpg'
|
||||
@@ -207,6 +208,13 @@ const _apps: MinAppType[] = [
|
||||
logo: FeloAppLogo,
|
||||
url: 'https://felo.ai/',
|
||||
bodered: true
|
||||
},
|
||||
{
|
||||
id: 'bolt',
|
||||
name: 'bolt',
|
||||
logo: BoltAppLogo,
|
||||
url: 'https://bolt.new/',
|
||||
bodered: true
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ import YiModelLogoDark from '@renderer/assets/images/models/yi_dark.png'
|
||||
import { Model } from '@renderer/types'
|
||||
import OpenAI from 'openai'
|
||||
|
||||
const allowedModels = [
|
||||
const visionAllowedModels = [
|
||||
'llava',
|
||||
'moondream',
|
||||
'minicpm',
|
||||
@@ -129,11 +129,19 @@ const allowedModels = [
|
||||
'vision',
|
||||
'glm-4v',
|
||||
'qwen-vl',
|
||||
'qwen2-vl',
|
||||
'internvl2',
|
||||
'gpt-4(?:-[\\w-]+)',
|
||||
'gpt-4o(?:-[\\w-]+)?'
|
||||
]
|
||||
const excludedModels = ['gpt-4-\\d+-preview', 'gpt-4-turbo-preview', 'gpt-4-32k', 'gpt-4-\\d+']
|
||||
const VISION_REGEX = new RegExp(`\\b(?!(?:${excludedModels.join('|')})\\b)(${allowedModels.join('|')})\\b`, 'i')
|
||||
|
||||
const visionExcludedModels = ['gpt-4-\\d+-preview', 'gpt-4-turbo-preview', 'gpt-4-32k', 'gpt-4-\\d+']
|
||||
|
||||
const VISION_REGEX = new RegExp(
|
||||
`\\b(?!(?:${visionExcludedModels.join('|')})\\b)(${visionAllowedModels.join('|')})\\b`,
|
||||
'i'
|
||||
)
|
||||
|
||||
const TEXT_TO_IMAGE_REGEX = /flux|diffusion|stabilityai|sd-|dall|cogview/i
|
||||
const EMBEDDING_REGEX = /(?:^text-|embed|rerank|davinci|babbage|bge-|base|retrieval|uae-)/i
|
||||
const NOT_SUPPORTED_REGEX = /(?:^text-|embed|tts|rerank|whisper|speech|davinci|babbage|bge-|base|retrieval|uae-)/i
|
||||
@@ -346,13 +354,13 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
|
||||
'azure-openai': [
|
||||
{
|
||||
id: 'gpt-4o',
|
||||
provider: 'openai',
|
||||
provider: 'azure-openai',
|
||||
name: ' GPT-4o',
|
||||
group: 'GPT 4o'
|
||||
},
|
||||
{
|
||||
id: 'gpt-4o-mini',
|
||||
provider: 'openai',
|
||||
provider: 'azure-openai',
|
||||
name: ' GPT-4o-mini',
|
||||
group: 'GPT 4o'
|
||||
}
|
||||
@@ -695,7 +703,7 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
|
||||
group: 'Baichuan3'
|
||||
}
|
||||
],
|
||||
dashscope: [
|
||||
bailian: [
|
||||
{
|
||||
id: 'qwen-turbo',
|
||||
provider: 'dashscope',
|
||||
@@ -798,6 +806,56 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
|
||||
group: '360Gpt'
|
||||
}
|
||||
],
|
||||
hunyuan: [
|
||||
{
|
||||
id: 'hunyuan-pro',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-pro',
|
||||
group: 'Hunyuan'
|
||||
},
|
||||
{
|
||||
id: 'hunyuan-standard',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-standard',
|
||||
group: 'Hunyuan'
|
||||
},
|
||||
{
|
||||
id: 'hunyuan-lite',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-lite',
|
||||
group: 'Hunyuan'
|
||||
},
|
||||
{
|
||||
id: 'hunyuan-standard-256k',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-standard-256k',
|
||||
group: 'Hunyuan'
|
||||
},
|
||||
{
|
||||
id: 'hunyuan-vision',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-vision',
|
||||
group: 'Hunyuan'
|
||||
},
|
||||
{
|
||||
id: 'hunyuan-code',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-code',
|
||||
group: 'Hunyuan'
|
||||
},
|
||||
{
|
||||
id: 'hunyuan-role',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-role',
|
||||
group: 'Hunyuan'
|
||||
},
|
||||
{
|
||||
id: 'hunyuan-turbo',
|
||||
provider: 'hunyuan',
|
||||
name: 'hunyuan-turbo',
|
||||
group: 'Hunyuan'
|
||||
}
|
||||
],
|
||||
nvidia: [
|
||||
{
|
||||
id: '01-ai/yi-large',
|
||||
|
||||
48
src/renderer/src/config/prompts.ts
Normal file
48
src/renderer/src/config/prompts.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
export const AGENT_PROMPT = `
|
||||
你是一个 Prompt 生成器。你会将用户输入的信息整合成一个 Markdown 语法的结构化的 Prompt。请务必不要使用代码块输出,而是直接显示!
|
||||
|
||||
## Role :
|
||||
[请填写你想定义的角色名称]
|
||||
|
||||
## Background :
|
||||
[请描述角色的背景信息,例如其历史、来源或特定的知识背景]
|
||||
|
||||
## Preferences :
|
||||
[请描述角色的偏好或特定风格,例如对某种设计或文化的偏好]
|
||||
|
||||
## Profile :
|
||||
- version: 0.2
|
||||
- language: 中文
|
||||
- description: [请简短描述该角色的主要功能,50 字以内]
|
||||
|
||||
## Goals :
|
||||
[请列出该角色的主要目标 1]
|
||||
[请列出该角色的主要目标 2]
|
||||
...
|
||||
|
||||
## Constrains :
|
||||
[请列出该角色在互动中必须遵循的限制条件 1]
|
||||
[请列出该角色在互动中必须遵循的限制条件 2]
|
||||
...
|
||||
|
||||
## Skills :
|
||||
[为了在限制条件下实现目标,该角色需要拥有的技能 1]
|
||||
[为了在限制条件下实现目标,该角色需要拥有的技能 2]
|
||||
...
|
||||
|
||||
## Examples :
|
||||
[提供一个输出示例 1,展示角色的可能回答或行为]
|
||||
[提供一个输出示例 2]
|
||||
...
|
||||
|
||||
## OutputFormat :
|
||||
[请描述该角色的工作流程的第一步]
|
||||
[请描述该角色的工作流程的第二步]
|
||||
...
|
||||
|
||||
## Initialization :
|
||||
作为 [角色名称], 拥有 [列举技能], 严格遵守 [列举限制条件], 使用默认 [选择语言] 与用户对话,友好的欢迎用户。然后介绍自己,并提示用户输入.
|
||||
`
|
||||
|
||||
export const SUMMARIZE_PROMPT =
|
||||
'你是一名擅长会话的助理,你需要将用户的会话总结为 10 个字以内的标题,不要使用标点符号和其他特殊符号。'
|
||||
@@ -1,10 +1,11 @@
|
||||
import ZhinaoProviderLogo from '@renderer/assets/images/models/360.png'
|
||||
import HunyuanProviderLogo from '@renderer/assets/images/models/hunyuan.png'
|
||||
import AzureProviderLogo from '@renderer/assets/images/models/microsoft.png'
|
||||
import AiHubMixProviderLogo from '@renderer/assets/images/providers/aihubmix.jpg'
|
||||
import AnthropicProviderLogo from '@renderer/assets/images/providers/anthropic.png'
|
||||
import BaichuanProviderLogo from '@renderer/assets/images/providers/baichuan.png'
|
||||
import BailianProviderLogo from '@renderer/assets/images/providers/bailian.png'
|
||||
import BytedanceProviderLogo from '@renderer/assets/images/providers/bytedance.png'
|
||||
import DashScopeProviderLogo from '@renderer/assets/images/providers/dashscope.png'
|
||||
import DeepSeekProviderLogo from '@renderer/assets/images/providers/deepseek.png'
|
||||
import FireworksProviderLogo from '@renderer/assets/images/providers/fireworks.png'
|
||||
import GithubProviderLogo from '@renderer/assets/images/providers/github.png'
|
||||
@@ -47,7 +48,7 @@ export function getProviderLogo(providerId: string) {
|
||||
case 'baichuan':
|
||||
return BaichuanProviderLogo
|
||||
case 'dashscope':
|
||||
return DashScopeProviderLogo
|
||||
return BailianProviderLogo
|
||||
case 'anthropic':
|
||||
return AnthropicProviderLogo
|
||||
case 'aihubmix':
|
||||
@@ -76,6 +77,8 @@ export function getProviderLogo(providerId: string) {
|
||||
return NvidiaProviderLogo
|
||||
case 'azure-openai':
|
||||
return AzureProviderLogo
|
||||
case 'hunyuan':
|
||||
return HunyuanProviderLogo
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
@@ -208,10 +211,10 @@ export const PROVIDER_CONFIG = {
|
||||
url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://dashscope.aliyun.com/',
|
||||
apiKey: 'https://help.aliyun.com/zh/dashscope/developer-reference/acquisition-and-configuration-of-api-key',
|
||||
docs: 'https://help.aliyun.com/zh/dashscope/',
|
||||
models: 'https://dashscope.console.aliyun.com/model'
|
||||
official: 'https://www.aliyun.com/product/bailian',
|
||||
apiKey: 'https://bailian.console.aliyun.com/?apiKey=1#/api-key',
|
||||
docs: 'https://help.aliyun.com/zh/model-studio/getting-started/',
|
||||
models: 'https://bailian.console.aliyun.com/model-market#/model-market'
|
||||
}
|
||||
},
|
||||
stepfun: {
|
||||
@@ -328,6 +331,17 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://ai.360.com/platform/limit'
|
||||
}
|
||||
},
|
||||
hunyuan: {
|
||||
api: {
|
||||
url: 'https://api.hunyuan.cloud.tencent.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://cloud.tencent.com/product/hunyuan',
|
||||
apiKey: 'https://console.cloud.tencent.com/hunyuan/api-key',
|
||||
docs: 'https://cloud.tencent.com/document/product/1729/111007',
|
||||
models: 'https://cloud.tencent.com/document/product/1729/104753'
|
||||
}
|
||||
},
|
||||
nvidia: {
|
||||
api: {
|
||||
url: 'https://integrate.api.nvidia.com'
|
||||
|
||||
@@ -1,17 +1,28 @@
|
||||
import { RootState } from '@renderer/store'
|
||||
import { addAgent, removeAgent, updateAgent, updateAgents } from '@renderer/store/agents'
|
||||
import { Agent } from '@renderer/types'
|
||||
import { useDispatch, useSelector } from 'react-redux'
|
||||
import { useAppDispatch, useAppSelector } from '@renderer/store'
|
||||
import { addAgent, removeAgent, updateAgent, updateAgents, updateAgentSettings } from '@renderer/store/agents'
|
||||
import { Agent, AssistantSettings } from '@renderer/types'
|
||||
|
||||
export function useAgents() {
|
||||
const agents = useSelector((state: RootState) => state.agents.agents)
|
||||
const dispatch = useDispatch()
|
||||
const agents = useAppSelector((state) => state.agents.agents)
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
return {
|
||||
agents,
|
||||
updateAgents: (agents: Agent[]) => dispatch(updateAgents(agents)),
|
||||
addAgent: (agent: Agent) => dispatch(addAgent(agent)),
|
||||
removeAgent: (agent: Agent) => dispatch(removeAgent(agent)),
|
||||
updateAgent: (agent: Agent) => dispatch(updateAgent(agent)),
|
||||
updateAgents: (agents: Agent[]) => dispatch(updateAgents(agents))
|
||||
removeAgent: (id: string) => dispatch(removeAgent({ id }))
|
||||
}
|
||||
}
|
||||
|
||||
export function useAgent(id: string) {
|
||||
const agent = useAppSelector((state) => state.agents.agents.find((a) => a.id === id) as Agent)
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
return {
|
||||
agent,
|
||||
updateAgent: (agent: Agent) => dispatch(updateAgent(agent)),
|
||||
updateAgentSettings: (settings: Partial<AssistantSettings>) => {
|
||||
dispatch(updateAgentSettings({ assistantId: agent.id, settings }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ export function useAppInit() {
|
||||
useEffect(() => {
|
||||
const transparentWindow = windowStyle === 'transparent' && isMac && !minappShow
|
||||
window.root.style.background = transparentWindow ? 'var(--navbar-background-mac)' : 'var(--navbar-background)'
|
||||
!isMac && import('@renderer/assets/styles/scrollbar.scss')
|
||||
}, [windowStyle, minappShow])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -58,7 +58,7 @@ export function useAssistant(id: string) {
|
||||
removeAllTopics: () => dispatch(removeAllTopics({ assistantId: assistant.id })),
|
||||
setModel: (model: Model) => dispatch(setModel({ assistantId: assistant.id, model })),
|
||||
updateAssistant: (assistant: Assistant) => dispatch(updateAssistant(assistant)),
|
||||
updateAssistantSettings: (settings: AssistantSettings) => {
|
||||
updateAssistantSettings: (settings: Partial<AssistantSettings>) => {
|
||||
dispatch(updateAssistantSettings({ assistantId: assistant.id, settings }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export function useProviders() {
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
return {
|
||||
providers,
|
||||
providers: providers || {},
|
||||
addProvider: (provider: Provider) => dispatch(addProvider(provider)),
|
||||
removeProvider: (provider: Provider) => dispatch(removeProvider(provider)),
|
||||
updateProvider: (provider: Provider) => dispatch(updateProvider(provider)),
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
"default": "Default",
|
||||
"warning": "Warning",
|
||||
"back": "Back",
|
||||
"chat": "Chat"
|
||||
"chat": "Chat",
|
||||
"close": "Close",
|
||||
"cancel": "Cancel"
|
||||
},
|
||||
"button": {
|
||||
"add": "Add",
|
||||
@@ -60,7 +62,8 @@
|
||||
"upgrade.success.title": "Upgrade successfully",
|
||||
"upgrade.success.content": "Please restart the application to complete the upgrade",
|
||||
"upgrade.success.button": "Restart",
|
||||
"topic.added": "New topic added"
|
||||
"topic.added": "New topic added",
|
||||
"save.success.title": "Saved successfully"
|
||||
},
|
||||
"chat": {
|
||||
"save": "Save",
|
||||
@@ -71,12 +74,12 @@
|
||||
"topics.auto_rename": "Auto Rename",
|
||||
"topics.edit.title": "Edit Name",
|
||||
"topics.edit.placeholder": "Enter new name",
|
||||
"topics.delete.all.title": "Delete all topics",
|
||||
"topics.delete.all.content": "Are you sure you want to delete all topics?",
|
||||
"topics.clear.title": "Clear Messages",
|
||||
"topics.move_to": "Move to",
|
||||
"topics.list": "Topic List",
|
||||
"topics.export.title": "Export",
|
||||
"topics.export.image": "Export as image",
|
||||
"topics.export.md": "Export as markdown",
|
||||
"input.new_topic": "New Topic",
|
||||
"input.topics": " Topics ",
|
||||
"input.clear": "Clear",
|
||||
@@ -89,7 +92,7 @@
|
||||
"input.send": "Send",
|
||||
"input.pause": "Pause",
|
||||
"input.settings": "Settings",
|
||||
"input.upload": "Upload image or text file",
|
||||
"input.upload": "Upload image or document file",
|
||||
"input.context_count.tip": "Context Count",
|
||||
"input.estimated_tokens.tip": "Estimated tokens",
|
||||
"settings.temperature": "Temperature",
|
||||
@@ -101,21 +104,38 @@
|
||||
"settings.reset": "Reset",
|
||||
"settings.set_as_default": "Apply to default assistant",
|
||||
"settings.max": "Max",
|
||||
"settings.show_line_numbers": "Show Line Numbers in Code",
|
||||
"suggestions.title": "Suggested Questions",
|
||||
"add.assistant.title": "Add Assistant",
|
||||
"message.new.context": "New Context",
|
||||
"message.new.branch": "New Branch",
|
||||
"assistant.search.placeholder": "Search"
|
||||
"message.new.branch.created": "New Branch Created",
|
||||
"assistant.search.placeholder": "Search",
|
||||
"artifacts.button.preview": "Preview",
|
||||
"artifacts.button.download": "Download"
|
||||
},
|
||||
"assistants": {
|
||||
"title": "Assistants",
|
||||
"abbr": "Assistant",
|
||||
"search": "Search assistants...",
|
||||
"prompt_settings": "Prompt Settings",
|
||||
"model_settings": "Model Settings"
|
||||
"settings.prompt": "Prompt Settings",
|
||||
"settings.model": "Model Settings",
|
||||
"settings.preset_messages": "Preset Messages",
|
||||
"settings.default_model": "Default Model",
|
||||
"settings.auto_reset_model": "Auto Reset Model",
|
||||
"settings.auto_reset_model.tip": "Automatically reset the model when a new topic is created.",
|
||||
"edit.title": "Edit Assistant",
|
||||
"copy.title": "Copy Assistant",
|
||||
"clear.title": "Clear topics",
|
||||
"clear.content": "Clearing the topic will delete all topics and files in the assistant. Are you sure you want to continue?",
|
||||
"save.title": "Save to agent",
|
||||
"save.success": "Saved successfully",
|
||||
"delete.title": "Delete Assistant",
|
||||
"delete.content": "Deleting an assistant will delete all topics and files under the assistant. Are you sure you want to delete it?"
|
||||
},
|
||||
"model": {
|
||||
"stream_output": "Stream Output"
|
||||
"stream_output": "Stream Output",
|
||||
"search": "Search models..."
|
||||
},
|
||||
"files": {
|
||||
"title": "Files",
|
||||
@@ -128,18 +148,28 @@
|
||||
"agents": {
|
||||
"title": "Agents",
|
||||
"my_agents": "My Agents",
|
||||
"add.title": "Add Agent",
|
||||
"add.title": "Create Agent",
|
||||
"edit.title": "Edit Agent",
|
||||
"add.name": "Name",
|
||||
"add.name.placeholder": "Enter name",
|
||||
"add.prompt": "Prompt",
|
||||
"add.prompt.placeholder": "Enter prompt",
|
||||
"add.button": "Add",
|
||||
"add.button": "Add to Assistant",
|
||||
"manage.title": "Manage Agents",
|
||||
"delete.popup.content": "Are you sure you want to delete this agent?",
|
||||
"tag.default": "Default",
|
||||
"tag.system": "System",
|
||||
"tag.user": "Mine"
|
||||
"tag.agent": "Agent",
|
||||
"edit.message.title": "Preset messages",
|
||||
"edit.message.add.title": "Add",
|
||||
"edit.message.group.title": "Message Group",
|
||||
"edit.message.assistant.title": "Assistant",
|
||||
"edit.message.assistant.placeholder": "Enter assistant message",
|
||||
"edit.message.user.title": "User",
|
||||
"edit.message.user.placeholder": "Enter user message",
|
||||
"edit.message.empty.content": "Conversation input content cannot be empty",
|
||||
"edit.model.select.title": "Select Model",
|
||||
"edit.settings.hide_preset_messages": "Hide Preset Message"
|
||||
},
|
||||
"minapp": {
|
||||
"title": "MinApp"
|
||||
@@ -153,6 +183,7 @@
|
||||
},
|
||||
"provider": {
|
||||
"nvidia": "Nvidia",
|
||||
"hunyuan": "Tencent Hunyuan",
|
||||
"zhinao": "360AI",
|
||||
"fireworks": "Fireworks",
|
||||
"together": "Together",
|
||||
@@ -167,7 +198,7 @@
|
||||
"groq": "Groq",
|
||||
"ollama": "Ollama",
|
||||
"baichuan": "Baichuan",
|
||||
"dashscope": "DashScope",
|
||||
"dashscope": "Alibaba Cloud",
|
||||
"anthropic": "Anthropic",
|
||||
"aihubmix": "AiHubMix",
|
||||
"stepfun": "StepFun",
|
||||
@@ -181,6 +212,7 @@
|
||||
"settings": {
|
||||
"title": "Settings",
|
||||
"general": "General Settings",
|
||||
"data": "Data Settings",
|
||||
"provider": "Model Provider",
|
||||
"model": "Default Model",
|
||||
"assistant": "Default Assistant",
|
||||
@@ -201,20 +233,18 @@
|
||||
"general.backup.button": "Backup",
|
||||
"general.restore.button": "Restore",
|
||||
"general.view_webdav_settings": "View WebDAV settings",
|
||||
"general.webdav.title": "WebDAV",
|
||||
"general.webdav.host": "WebDAV Host",
|
||||
"general.webdav.host.placeholder": "http://localhost:8080",
|
||||
"general.webdav.user": "WebDAV User",
|
||||
"general.webdav.password": "WebDAV Password",
|
||||
"general.webdav.path": "WebDAV Path",
|
||||
"general.webdav.path.placeholder": "/backup",
|
||||
"general.webdav.backup.button": "Backup to WebDAV",
|
||||
"general.webdav.restore.button": "Restore from WebDAV",
|
||||
"general.reset.title": "Data Reset",
|
||||
"general.reset.button": "Reset",
|
||||
"general.check_update_setting": "Check for updates",
|
||||
"general.manual_update_check": "Check for updates manually",
|
||||
"general.auto_update_check": "Check for updates automatically",
|
||||
"general.manually_check_update.title": "Turn off update checking",
|
||||
"data.webdav.title": "WebDAV",
|
||||
"data.webdav.host": "WebDAV Host",
|
||||
"data.webdav.host.placeholder": "http://localhost:8080",
|
||||
"data.webdav.user": "WebDAV User",
|
||||
"data.webdav.password": "WebDAV Password",
|
||||
"data.webdav.path": "WebDAV Path",
|
||||
"data.webdav.path.placeholder": "/backup",
|
||||
"data.webdav.backup.button": "Backup to WebDAV",
|
||||
"data.webdav.restore.button": "Restore from WebDAV",
|
||||
"advanced.title": "Advanced Settings",
|
||||
"advanced.click_assistant_switch_to_topics": "Auto switch to topic",
|
||||
"provider.api_key": "API Key",
|
||||
@@ -226,6 +256,8 @@
|
||||
"provider.docs_more_details": "for more details",
|
||||
"provider.search_placeholder": "Search model id or name",
|
||||
"provider.api.url.reset": "Reset",
|
||||
"provider.api.url.preview": "Preview: {{url}}",
|
||||
"provider.api.url.tip": "Add / at the end to force using the input address",
|
||||
"models.default_assistant_model": "Default Assistant Model",
|
||||
"models.topic_naming_model": "Topic Naming Model",
|
||||
"models.translate_model": "Translate Model",
|
||||
@@ -273,7 +305,8 @@
|
||||
"font_size.title": "Message Font Size",
|
||||
"topic.position": "Topic Position",
|
||||
"topic.position.left": "Left",
|
||||
"topic.position.right": "Right"
|
||||
"topic.position.right": "Right",
|
||||
"topic.show.time": "Show Topic Time"
|
||||
},
|
||||
"translate": {
|
||||
"title": "Translation",
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
"default": "默认",
|
||||
"warning": "警告",
|
||||
"back": "返回",
|
||||
"chat": "聊天"
|
||||
"chat": "聊天",
|
||||
"close": "关闭",
|
||||
"cancel": "取消"
|
||||
},
|
||||
"button": {
|
||||
"add": "添加",
|
||||
@@ -60,7 +62,8 @@
|
||||
"upgrade.success.title": "升级成功",
|
||||
"upgrade.success.content": "重启应用以完成升级",
|
||||
"upgrade.success.button": "重启",
|
||||
"topic.added": "话题添加成功"
|
||||
"topic.added": "话题添加成功",
|
||||
"save.success.title": "保存成功"
|
||||
},
|
||||
"chat": {
|
||||
"save": "保存",
|
||||
@@ -71,25 +74,25 @@
|
||||
"topics.auto_rename": "生成话题名",
|
||||
"topics.edit.title": "编辑话题名",
|
||||
"topics.edit.placeholder": "输入新名称",
|
||||
"topics.delete.all.title": "删除所有话题",
|
||||
"topics.delete.all.content": "确定要删除所有话题吗?",
|
||||
"topics.clear.title": "清空消息",
|
||||
"topics.move_to": "移动到",
|
||||
"topics.list": "话题列表",
|
||||
"topics.export.title": "导出",
|
||||
"topics.export.image": "导出为图片",
|
||||
"topics.export.md": "导出为 Markdown",
|
||||
"input.new_topic": "新话题",
|
||||
"input.topics": " 话题 ",
|
||||
"input.clear": "清除会话消息",
|
||||
"input.clear": "清空消息",
|
||||
"input.new.context": "清除上下文",
|
||||
"input.expand": "展开",
|
||||
"input.collapse": "收起",
|
||||
"input.clear.title": "清除消息?",
|
||||
"input.clear.title": "清空消息",
|
||||
"input.clear.content": "确定要清除当前会话所有消息吗?",
|
||||
"input.placeholder": "在这里输入消息...",
|
||||
"input.send": "发送",
|
||||
"input.pause": "暂停",
|
||||
"input.settings": "设置",
|
||||
"input.upload": "上传图片或纯文本文件",
|
||||
"input.upload": "上传图片或文档",
|
||||
"input.context_count.tip": "上下文数",
|
||||
"input.estimated_tokens.tip": "预估 token 数",
|
||||
"settings.temperature": "模型温度",
|
||||
@@ -101,21 +104,38 @@
|
||||
"settings.reset": "重置",
|
||||
"settings.set_as_default": "应用到默认助手",
|
||||
"settings.max": "不限",
|
||||
"settings.show_line_numbers": "代码显示行号",
|
||||
"suggestions.title": "建议的问题",
|
||||
"add.assistant.title": "添加助手",
|
||||
"message.new.context": "清除上下文",
|
||||
"message.new.branch": "新分支",
|
||||
"assistant.search.placeholder": "搜索"
|
||||
"message.new.branch.created": "新分支已创建",
|
||||
"assistant.search.placeholder": "搜索",
|
||||
"artifacts.button.preview": "预览",
|
||||
"artifacts.button.download": "下载"
|
||||
},
|
||||
"assistants": {
|
||||
"title": "助手",
|
||||
"abbr": "助手",
|
||||
"search": "搜索助手",
|
||||
"prompt_settings": "提示词设置",
|
||||
"model_settings": "模型设置"
|
||||
"settings.prompt": "提示词设置",
|
||||
"settings.model": "模型设置",
|
||||
"settings.preset_messages": "预设消息",
|
||||
"settings.default_model": "默认模型",
|
||||
"settings.auto_reset_model": "自动重置模型",
|
||||
"settings.auto_reset_model.tip": "创建新话题时自动重置模型",
|
||||
"edit.title": "编辑助手",
|
||||
"copy.title": "复制助手",
|
||||
"clear.title": "清空话题",
|
||||
"clear.content": "清空话题会删除助手下所有话题和文件,确定要继续吗?",
|
||||
"save.title": "保存到智能体",
|
||||
"save.success": "保存成功",
|
||||
"delete.title": "删除助手",
|
||||
"delete.content": "删除助手会删除所有该助手下的话题和文件,确定要继续吗?"
|
||||
},
|
||||
"model": {
|
||||
"stream_output": "流式输出"
|
||||
"stream_output": "流式输出",
|
||||
"search": "搜索模型..."
|
||||
},
|
||||
"files": {
|
||||
"title": "文件",
|
||||
@@ -128,18 +148,28 @@
|
||||
"agents": {
|
||||
"title": "智能体",
|
||||
"my_agents": "我的智能体",
|
||||
"add.title": "添加智能体",
|
||||
"add.title": "创建智能体",
|
||||
"edit.title": "编辑智能体",
|
||||
"add.name": "名称",
|
||||
"add.name.placeholder": "输入名称",
|
||||
"add.prompt": "提示词",
|
||||
"add.prompt.placeholder": "输入提示词",
|
||||
"add.button": "添加",
|
||||
"add.button": "添加到助手",
|
||||
"manage.title": "管理智能体",
|
||||
"delete.popup.content": "确定要删除此智能体吗?",
|
||||
"tag.default": "默认",
|
||||
"tag.system": "系统",
|
||||
"tag.user": "我的"
|
||||
"tag.agent": "智能体",
|
||||
"edit.message.title": "预设消息",
|
||||
"edit.message.add.title": "添加",
|
||||
"edit.message.group.title": "消息组",
|
||||
"edit.message.assistant.title": "助手",
|
||||
"edit.message.assistant.placeholder": "输入助手消息",
|
||||
"edit.message.user.title": "用户",
|
||||
"edit.message.user.placeholder": "输入用户消息",
|
||||
"edit.message.empty.content": "会话输入内容不能为空",
|
||||
"edit.model.select.title": "选择模型",
|
||||
"edit.settings.hide_preset_messages": "隐藏预设消息"
|
||||
},
|
||||
"minapp": {
|
||||
"title": "小程序"
|
||||
@@ -153,6 +183,7 @@
|
||||
},
|
||||
"provider": {
|
||||
"nvidia": "英伟达",
|
||||
"hunyuan": "腾讯混元",
|
||||
"zhinao": "360智脑",
|
||||
"fireworks": "Fireworks",
|
||||
"together": "Together",
|
||||
@@ -167,7 +198,7 @@
|
||||
"groq": "Groq",
|
||||
"ollama": "Ollama",
|
||||
"baichuan": "百川",
|
||||
"dashscope": "阿里云灵积",
|
||||
"dashscope": "阿里云百炼",
|
||||
"anthropic": "Anthropic",
|
||||
"aihubmix": "AiHubMix",
|
||||
"stepfun": "阶跃星辰",
|
||||
@@ -181,6 +212,7 @@
|
||||
"settings": {
|
||||
"title": "设置",
|
||||
"general": "常规设置",
|
||||
"data": "数据设置",
|
||||
"provider": "模型服务",
|
||||
"model": "默认模型",
|
||||
"assistant": "默认助手",
|
||||
@@ -203,18 +235,16 @@
|
||||
"general.reset.title": "重置数据",
|
||||
"general.reset.button": "重置",
|
||||
"general.view_webdav_settings": "查看 WebDAV 设置",
|
||||
"general.webdav.title": "WebDAV",
|
||||
"general.webdav.host": "WebDAV 地址",
|
||||
"general.webdav.host.placeholder": "http://localhost:8080",
|
||||
"general.webdav.user": "WebDAV 用户名",
|
||||
"general.webdav.password": "WebDAV 密码",
|
||||
"general.webdav.path": "WebDAV 路径",
|
||||
"general.webdav.path.placeholder": "/backup",
|
||||
"general.webdav.backup.button": "备份到 WebDAV",
|
||||
"general.webdav.restore.button": "从 WebDAV 恢复",
|
||||
"general.check_update_setting": "更新设置",
|
||||
"general.manual_update_check": "手动检查更新",
|
||||
"general.auto_update_check": "自动检查更新",
|
||||
"general.manually_check_update.title": "关闭更新检测",
|
||||
"data.webdav.title": "WebDAV",
|
||||
"data.webdav.host": "WebDAV 地址",
|
||||
"data.webdav.host.placeholder": "http://localhost:8080",
|
||||
"data.webdav.user": "WebDAV 用户名",
|
||||
"data.webdav.password": "WebDAV 密码",
|
||||
"data.webdav.path": "WebDAV 路径",
|
||||
"data.webdav.path.placeholder": "/backup",
|
||||
"data.webdav.backup.button": "备份到 WebDAV",
|
||||
"data.webdav.restore.button": "从 WebDAV 恢复",
|
||||
"advanced.title": "高级设置",
|
||||
"advanced.click_assistant_switch_to_topics": "点击助手切换到话题",
|
||||
"provider.api_key": "API 密钥",
|
||||
@@ -226,6 +256,8 @@
|
||||
"provider.docs_more_details": "获取更多详情",
|
||||
"provider.search_placeholder": "搜索模型 ID 或名称",
|
||||
"provider.api.url.reset": "重置",
|
||||
"provider.api.url.preview": "预览: {{url}}",
|
||||
"provider.api.url.tip": "结尾添加 / 强制使用输入地址",
|
||||
"models.default_assistant_model": "默认助手模型",
|
||||
"models.topic_naming_model": "话题命名模型",
|
||||
"models.translate_model": "翻译模型",
|
||||
@@ -273,7 +305,8 @@
|
||||
"font_size.title": "消息字体大小",
|
||||
"topic.position": "话题位置",
|
||||
"topic.position.left": "左侧",
|
||||
"topic.position.right": "右侧"
|
||||
"topic.position.right": "右侧",
|
||||
"topic.show.time": "显示话题时间"
|
||||
},
|
||||
"translate": {
|
||||
"title": "翻译",
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
"default": "預設",
|
||||
"warning": "警告",
|
||||
"back": "返回",
|
||||
"chat": "聊天"
|
||||
"chat": "聊天",
|
||||
"close": "關閉",
|
||||
"cancel": "取消"
|
||||
},
|
||||
"button": {
|
||||
"add": "添加",
|
||||
@@ -60,7 +62,8 @@
|
||||
"upgrade.success.title": "升級成功",
|
||||
"upgrade.success.content": "請重新啟動應用以完成升級",
|
||||
"upgrade.success.button": "重新啟動",
|
||||
"topic.added": "新話題已添加"
|
||||
"topic.added": "新話題已添加",
|
||||
"save.success.title": "保存成功"
|
||||
},
|
||||
"chat": {
|
||||
"save": "保存",
|
||||
@@ -71,12 +74,12 @@
|
||||
"topics.auto_rename": "自動重新命名",
|
||||
"topics.edit.title": "編輯名稱",
|
||||
"topics.edit.placeholder": "輸入新名稱",
|
||||
"topics.delete.all.title": "刪除所有話題",
|
||||
"topics.delete.all.content": "確定要刪除所有話題嗎?",
|
||||
"topics.clear.title": "清空消息",
|
||||
"topics.move_to": "移動到",
|
||||
"topics.list": "話題列表",
|
||||
"topics.export.title": "匯出",
|
||||
"topics.export.image": "匯出為圖片",
|
||||
"topics.export.md": "匯出為 Markdown",
|
||||
"input.new_topic": "新話題",
|
||||
"input.topics": " 話題 ",
|
||||
"input.clear": "清除",
|
||||
@@ -89,7 +92,7 @@
|
||||
"input.send": "發送",
|
||||
"input.pause": "暫停",
|
||||
"input.settings": "設定",
|
||||
"input.upload": "上傳圖片或文字檔",
|
||||
"input.upload": "上傳圖片或文檔",
|
||||
"input.context_count.tip": "上下文數量",
|
||||
"input.estimated_tokens.tip": "預估 Token 數",
|
||||
"settings.temperature": "溫度",
|
||||
@@ -101,21 +104,38 @@
|
||||
"settings.reset": "重置",
|
||||
"settings.set_as_default": "設為預設助手",
|
||||
"settings.max": "最大",
|
||||
"settings.show_line_numbers": "代码顯示行號",
|
||||
"suggestions.title": "建議的問題",
|
||||
"add.assistant.title": "添加助手",
|
||||
"message.new.context": "新上下文",
|
||||
"message.new.branch": "新分支",
|
||||
"assistant.search.placeholder": "搜尋"
|
||||
"message.new.branch.created": "新分支已建立",
|
||||
"assistant.search.placeholder": "搜尋",
|
||||
"artifacts.button.preview": "預覽",
|
||||
"artifacts.button.download": "下載"
|
||||
},
|
||||
"assistants": {
|
||||
"title": "助手",
|
||||
"abbr": "助",
|
||||
"search": "搜尋助手...",
|
||||
"prompt_settings": "提示詞設定",
|
||||
"model_settings": "模型設定"
|
||||
"settings.prompt": "提示詞設定",
|
||||
"settings.model": "模型設定",
|
||||
"settings.preset_messages": "預設訊息",
|
||||
"settings.default_model": "預設模型",
|
||||
"settings.auto_reset_model": "自動重置模型",
|
||||
"settings.auto_reset_model.tip": "每次新的話題時自動重置模型",
|
||||
"edit.title": "編輯助手",
|
||||
"copy.title": "複製助手",
|
||||
"clear.title": "清空話題",
|
||||
"clear.content": "清空話題會刪除助手下所有主題和文件,確定要繼續嗎?",
|
||||
"save.title": "儲存到智能體",
|
||||
"save.success": "儲存成功",
|
||||
"delete.title": "删除助手",
|
||||
"delete.content": "删除助手会删除所有该助手下的话题和文件,确定要繼續吗?"
|
||||
},
|
||||
"model": {
|
||||
"stream_output": "串流輸出"
|
||||
"stream_output": "串流輸出",
|
||||
"search": "搜尋模型..."
|
||||
},
|
||||
"files": {
|
||||
"title": "檔案",
|
||||
@@ -128,18 +148,28 @@
|
||||
"agents": {
|
||||
"title": "智能體",
|
||||
"my_agents": "我的智能體",
|
||||
"add.title": "添加智能體",
|
||||
"add.title": "创建智能體",
|
||||
"edit.title": "編輯智能體",
|
||||
"add.name": "名稱",
|
||||
"add.name.placeholder": "輸入名稱",
|
||||
"add.prompt": "提示詞",
|
||||
"add.prompt.placeholder": "輸入提示詞",
|
||||
"add.button": "添加",
|
||||
"add.button": "添加到助手",
|
||||
"manage.title": "管理智能體",
|
||||
"delete.popup.content": "確定要刪除此智能體嗎?",
|
||||
"tag.default": "預設",
|
||||
"tag.system": "系統",
|
||||
"tag.user": "我的"
|
||||
"tag.agent": "智能体",
|
||||
"edit.message.title": "預設訊息",
|
||||
"edit.message.add.title": "添加",
|
||||
"edit.message.group.title": "訊息組",
|
||||
"edit.message.assistant.title": "助手",
|
||||
"edit.message.assistant.placeholder": "輸入助手消息",
|
||||
"edit.message.user.title": "用戶",
|
||||
"edit.message.user.placeholder": "輸入用戶消息",
|
||||
"edit.message.empty.content": "會話輸入內容不能為空",
|
||||
"edit.model.select.title": "選擇模型",
|
||||
"edit.settings.hide_preset_messages": "隱藏預設消息"
|
||||
},
|
||||
"minapp": {
|
||||
"title": "小程序"
|
||||
@@ -154,6 +184,7 @@
|
||||
"provider": {
|
||||
"nvidia": "輝達",
|
||||
"zhinao": "360智腦",
|
||||
"hunyuan": "騰訊混元",
|
||||
"fireworks": "Fireworks",
|
||||
"together": "Together",
|
||||
"openai": "OpenAI",
|
||||
@@ -162,12 +193,12 @@
|
||||
"moonshot": "月之暗面",
|
||||
"silicon": "SiliconFlow",
|
||||
"openrouter": "OpenRouter",
|
||||
"yi": "零一万物",
|
||||
"zhipu": "智谱AI",
|
||||
"yi": "零一萬物",
|
||||
"zhipu": "智譜AI",
|
||||
"groq": "Groq",
|
||||
"ollama": "Ollama",
|
||||
"baichuan": "百川",
|
||||
"dashscope": "DashScope",
|
||||
"dashscope": "阿里雲百鍊",
|
||||
"anthropic": "Anthropic",
|
||||
"aihubmix": "AiHubMix",
|
||||
"stepfun": "StepFun",
|
||||
@@ -181,6 +212,7 @@
|
||||
"settings": {
|
||||
"title": "設定",
|
||||
"general": "一般設定",
|
||||
"data": "數據設定",
|
||||
"provider": "模型提供者",
|
||||
"model": "預設模型",
|
||||
"assistant": "預設助手",
|
||||
@@ -201,20 +233,18 @@
|
||||
"general.backup.button": "備份",
|
||||
"general.restore.button": "復原",
|
||||
"general.view_webdav_settings": "查看 WebDAV 設定",
|
||||
"general.webdav.title": "WebDAV",
|
||||
"general.webdav.host": "WebDAV 主機位址",
|
||||
"general.webdav.host.placeholder": "http://localhost:8080",
|
||||
"general.webdav.user": "WebDAV 使用者名稱",
|
||||
"general.webdav.password": "WebDAV 密碼",
|
||||
"general.webdav.path": "WebDAV Path",
|
||||
"general.webdav.path.placeholder": "/backup",
|
||||
"general.webdav.backup.button": "從 WebDAV 備份",
|
||||
"general.webdav.restore.button": "從 WebDAV 恢復",
|
||||
"general.reset.title": "資料重置",
|
||||
"general.reset.button": "重置",
|
||||
"general.check_update_setting": "更新設定",
|
||||
"general.manual_update_check": "手動檢查更新",
|
||||
"general.auto_update_check": "自動檢查更新",
|
||||
"general.manually_check_update.title": "關閉更新檢查",
|
||||
"data.webdav.title": "WebDAV",
|
||||
"data.webdav.host": "WebDAV 主機位址",
|
||||
"data.webdav.host.placeholder": "http://localhost:8080",
|
||||
"data.webdav.user": "WebDAV 使用者名稱",
|
||||
"data.webdav.password": "WebDAV 密碼",
|
||||
"data.webdav.path": "WebDAV Path",
|
||||
"data.webdav.path.placeholder": "/backup",
|
||||
"data.webdav.backup.button": "從 WebDAV 備份",
|
||||
"data.webdav.restore.button": "從 WebDAV 恢復",
|
||||
"advanced.title": "進階設定",
|
||||
"advanced.click_assistant_switch_to_topics": "點擊助手切換到話題",
|
||||
"provider.api_key": "API 密鑰",
|
||||
@@ -226,6 +256,8 @@
|
||||
"provider.docs_more_details": "查看更多細節",
|
||||
"provider.search_placeholder": "搜尋模型 ID 或名稱",
|
||||
"provider.api.url.reset": "重置",
|
||||
"provider.api.url.preview": "預覽: {{url}}",
|
||||
"provider.api.url.tip": "結尾新增 / 強制使用輸入地址",
|
||||
"models.default_assistant_model": "預設助手模型",
|
||||
"models.topic_naming_model": "話題命名模型",
|
||||
"models.translate_model": "翻譯模型",
|
||||
@@ -273,7 +305,8 @@
|
||||
"font_size.title": "訊息字體大小",
|
||||
"topic.position": "話題位置",
|
||||
"topic.position.left": "左側",
|
||||
"topic.position.right": "右側"
|
||||
"topic.position.right": "右側",
|
||||
"topic.show.time": "顯示話題時間"
|
||||
},
|
||||
"translate": {
|
||||
"title": "翻譯",
|
||||
|
||||
159
src/renderer/src/pages/agents/Agents.tsx
Normal file
159
src/renderer/src/pages/agents/Agents.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import { DeleteOutlined, EditOutlined, MoreOutlined, PlusOutlined } from '@ant-design/icons'
|
||||
import AssistantSettingsPopup from '@renderer/components/AssistantSettings'
|
||||
import DragableList from '@renderer/components/DragableList'
|
||||
import { HStack } from '@renderer/components/Layout'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { createAssistantFromAgent } from '@renderer/services/assistant'
|
||||
import { Agent } from '@renderer/types'
|
||||
import { Button, Dropdown } from 'antd'
|
||||
import { ItemType } from 'antd/es/menu/interface'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import AddAgentPopup from './components/AddAgentPopup'
|
||||
|
||||
interface Props {
|
||||
onClick: (agent: Agent) => void
|
||||
}
|
||||
|
||||
const Agents: React.FC<Props> = ({ onClick }) => {
|
||||
const { t } = useTranslation()
|
||||
const { agents, removeAgent, updateAgents } = useAgents()
|
||||
const [dragging, setDragging] = useState(false)
|
||||
|
||||
const getMenuItems = useCallback(
|
||||
(agent: Agent) =>
|
||||
[
|
||||
{
|
||||
label: t('agents.edit.title'),
|
||||
key: 'edit',
|
||||
icon: <EditOutlined />,
|
||||
onClick: () => AssistantSettingsPopup.show({ assistant: agent })
|
||||
},
|
||||
{
|
||||
label: t('agents.add.button'),
|
||||
key: 'create',
|
||||
icon: <PlusOutlined />,
|
||||
onClick: () => createAssistantFromAgent(agent)
|
||||
},
|
||||
{ type: 'divider' },
|
||||
{
|
||||
label: t('common.delete'),
|
||||
key: 'delete',
|
||||
icon: <DeleteOutlined />,
|
||||
danger: true,
|
||||
onClick: () => {
|
||||
window.modal.confirm({
|
||||
centered: true,
|
||||
content: t('agents.delete.popup.content'),
|
||||
onOk: () => removeAgent(agent.id)
|
||||
})
|
||||
}
|
||||
}
|
||||
] as ItemType[],
|
||||
[removeAgent, t]
|
||||
)
|
||||
|
||||
return (
|
||||
<Container style={{ paddingBottom: dragging ? 30 : 0 }}>
|
||||
{agents.length > 0 && (
|
||||
<DragableList
|
||||
list={agents}
|
||||
onUpdate={updateAgents}
|
||||
onDragStart={() => setDragging(true)}
|
||||
onDragEnd={() => setDragging(false)}>
|
||||
{(agent: Agent) => (
|
||||
<Dropdown menu={{ items: getMenuItems(agent) }} trigger={['contextMenu']}>
|
||||
<AgentItem onClick={() => onClick(agent)}>
|
||||
<HStack alignItems="center" justifyContent="space-between" h="36px">
|
||||
<AgentItemName className="text-nowrap">
|
||||
{agent.emoji} {agent.name}
|
||||
</AgentItemName>
|
||||
<ActionButton className="actions" gap="15px" onClick={(e) => e.stopPropagation()}>
|
||||
<Dropdown menu={{ items: getMenuItems(agent) }} trigger={['hover']}>
|
||||
<MoreOutlined style={{ cursor: 'pointer' }} />
|
||||
</Dropdown>
|
||||
</ActionButton>
|
||||
</HStack>
|
||||
<AgentItemPrompt>{agent.prompt}</AgentItemPrompt>
|
||||
</AgentItem>
|
||||
</Dropdown>
|
||||
)}
|
||||
</DragableList>
|
||||
)}
|
||||
{!dragging && (
|
||||
<Button
|
||||
type="dashed"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => AddAgentPopup.show()}
|
||||
style={{ borderRadius: 20, height: 34 }}>
|
||||
{t('agents.add.title')}
|
||||
</Button>
|
||||
)}
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
padding: 15px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 280px;
|
||||
height: calc(100vh - var(--navbar-height));
|
||||
border-right: 0.5px solid var(--color-border);
|
||||
overflow-y: scroll;
|
||||
`
|
||||
|
||||
const AgentItem = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0 12px;
|
||||
min-height: 38px;
|
||||
border-radius: 10px;
|
||||
user-select: none;
|
||||
margin-bottom: 12px;
|
||||
padding-bottom: 12px;
|
||||
border: 0.5px solid var(--color-border);
|
||||
transition: all 0.2s ease-in-out;
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
.actions {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
&:hover {
|
||||
border: 0.5px solid var(--color-primary);
|
||||
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
`
|
||||
|
||||
const AgentItemName = styled.div`
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
`
|
||||
|
||||
const AgentItemPrompt = styled.div`
|
||||
font-size: 12px;
|
||||
color: var(--color-text-soft);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-top: -5px;
|
||||
color: var(--color-text-3);
|
||||
`
|
||||
|
||||
const ActionButton = styled(HStack)`
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
display: none;
|
||||
background-color: var(--color-background-soft);
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 12px;
|
||||
font-size: 16px;
|
||||
color: var(--color-icon);
|
||||
`
|
||||
|
||||
export default Agents
|
||||
@@ -1,52 +1,56 @@
|
||||
import { UnorderedListOutlined } from '@ant-design/icons'
|
||||
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
|
||||
import { HStack } from '@renderer/components/Layout'
|
||||
import Agents from '@renderer/config/agents.json'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { useAssistants } from '@renderer/hooks/useAssistant'
|
||||
import { covertAgentToAssistant } from '@renderer/services/assistant'
|
||||
import { VStack } from '@renderer/components/Layout'
|
||||
import SystemAgents from '@renderer/config/agents.json'
|
||||
import { createAssistantFromAgent } from '@renderer/services/assistant'
|
||||
import { Agent } from '@renderer/types'
|
||||
import { uuid } from '@renderer/utils'
|
||||
import { Col, Row, Typography } from 'antd'
|
||||
import { find, groupBy } from 'lodash'
|
||||
import { groupBy, omit } from 'lodash'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import Agents from './Agents'
|
||||
import AgentCard from './components/AgentCard'
|
||||
import ManageAgentsPopup from './components/ManageAgentsPopup'
|
||||
import UserAgents from './components/UserAgents'
|
||||
|
||||
const { Title } = Typography
|
||||
|
||||
const AppsPage: FC = () => {
|
||||
const { assistants, addAssistant } = useAssistants()
|
||||
const { agents } = useAgents()
|
||||
const agentGroups = groupBy(Agents, 'group')
|
||||
const AgentsPage: FC = () => {
|
||||
const agentGroups = groupBy(SystemAgents, 'group')
|
||||
const { t } = useTranslation()
|
||||
|
||||
const onAddAgentConfirm = (agent: Agent) => {
|
||||
const added = find(assistants, { id: agent.id })
|
||||
const getAgentName = (agent: Agent) => {
|
||||
return agent.emoji ? agent.emoji + ' ' + agent.name : agent.name
|
||||
}
|
||||
|
||||
const onAddAgentConfirm = (agent: Agent) => {
|
||||
window.modal.confirm({
|
||||
title: agent.emoji + ' ' + agent.name,
|
||||
content: (agent.description || agent.prompt).substring(0, 1000) + '...',
|
||||
title: getAgentName(agent),
|
||||
content: (
|
||||
<AgentPrompt>
|
||||
<ReactMarkdown className="markdown">{agent.description || agent.prompt}</ReactMarkdown>
|
||||
</AgentPrompt>
|
||||
),
|
||||
width: 600,
|
||||
icon: null,
|
||||
closable: true,
|
||||
maskClosable: true,
|
||||
centered: true,
|
||||
okButtonProps: { type: 'primary', disabled: Boolean(added) },
|
||||
okText: added ? t('button.added') : t('button.add'),
|
||||
onOk: () => onAddAgent(agent)
|
||||
okButtonProps: { type: 'primary' },
|
||||
okText: t('agents.add.button'),
|
||||
onOk: () => createAssistantFromAgent(agent)
|
||||
})
|
||||
}
|
||||
|
||||
const onAddAgent = (agent: Agent) => {
|
||||
addAssistant(covertAgentToAssistant(agent))
|
||||
window.message.success({
|
||||
content: t('message.assistant.added.content'),
|
||||
key: 'agent-added',
|
||||
style: { marginTop: '5vh' }
|
||||
})
|
||||
const getAgentFromSystemAgent = (agent: (typeof SystemAgents)[number]) => {
|
||||
return {
|
||||
...omit(agent, 'group'),
|
||||
name: agent.name,
|
||||
id: uuid(),
|
||||
topics: [],
|
||||
type: 'agent'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -55,29 +59,32 @@ const AppsPage: FC = () => {
|
||||
<NavbarCenter style={{ borderRight: 'none' }}>{t('agents.title')}</NavbarCenter>
|
||||
</Navbar>
|
||||
<ContentContainer id="content-container">
|
||||
<Agents onClick={onAddAgentConfirm} />
|
||||
<AssistantsContainer>
|
||||
<HStack alignItems="center" style={{ marginBottom: 16 }}>
|
||||
<Title level={4}>{t('agents.my_agents')}</Title>
|
||||
{agents.length > 0 && <ManageIcon onClick={ManageAgentsPopup.show} />}
|
||||
</HStack>
|
||||
<UserAgents onAdd={onAddAgentConfirm} />
|
||||
{Object.keys(agentGroups).map((group) => (
|
||||
<div key={group}>
|
||||
<Title level={4} key={group} style={{ marginBottom: 16 }}>
|
||||
{group}
|
||||
</Title>
|
||||
<Row gutter={16}>
|
||||
{agentGroups[group].map((agent, index) => {
|
||||
return (
|
||||
<Col span={8} key={group + index}>
|
||||
<AgentCard onClick={() => onAddAgentConfirm(agent)} agent={agent as any} />
|
||||
</Col>
|
||||
)
|
||||
})}
|
||||
</Row>
|
||||
</div>
|
||||
))}
|
||||
<div style={{ minHeight: 20 }} />
|
||||
<VStack style={{ flex: 1 }}>
|
||||
{Object.keys(agentGroups)
|
||||
.reverse()
|
||||
.map((group) => (
|
||||
<div key={group}>
|
||||
<Title level={5} key={group} style={{ marginBottom: 16 }}>
|
||||
{group}
|
||||
</Title>
|
||||
<Row gutter={16}>
|
||||
{agentGroups[group].map((agent, index) => {
|
||||
return (
|
||||
<Col span={8} key={group + index}>
|
||||
<AgentCard
|
||||
onClick={() => onAddAgentConfirm(getAgentFromSystemAgent(agent))}
|
||||
agent={agent as any}
|
||||
/>
|
||||
</Col>
|
||||
)
|
||||
})}
|
||||
</Row>
|
||||
</div>
|
||||
))}
|
||||
<div style={{ minHeight: 20 }} />
|
||||
</VStack>
|
||||
</AssistantsContainer>
|
||||
</ContentContainer>
|
||||
</Container>
|
||||
@@ -97,24 +104,21 @@ const ContentContainer = styled.div`
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
overflow-y: scroll;
|
||||
`
|
||||
|
||||
const AssistantsContainer = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
flex-direction: row;
|
||||
height: calc(100vh - var(--navbar-height));
|
||||
padding: 20px;
|
||||
max-width: 1000px;
|
||||
padding: 15px 20px;
|
||||
overflow-y: scroll;
|
||||
`
|
||||
|
||||
const ManageIcon = styled(UnorderedListOutlined)`
|
||||
font-size: 18px;
|
||||
color: var(--color-icon);
|
||||
cursor: pointer;
|
||||
margin-bottom: 0.5em;
|
||||
margin-left: 0.5em;
|
||||
const AgentPrompt = styled.div`
|
||||
max-height: 60vh;
|
||||
overflow-y: scroll;
|
||||
max-width: 560px;
|
||||
`
|
||||
|
||||
export default AppsPage
|
||||
export default AgentsPage
|
||||
|
||||
@@ -3,18 +3,18 @@ import 'emoji-picker-element'
|
||||
import { LoadingOutlined, ThunderboltOutlined } from '@ant-design/icons'
|
||||
import EmojiPicker from '@renderer/components/EmojiPicker'
|
||||
import { TopView } from '@renderer/components/TopView'
|
||||
import { AGENT_PROMPT } from '@renderer/config/prompts'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { fetchGenerate } from '@renderer/services/api'
|
||||
import { syncAgentToAssistant } from '@renderer/services/assistant'
|
||||
import { getDefaultModel } from '@renderer/services/assistant'
|
||||
import { Agent } from '@renderer/types'
|
||||
import { getLeadingEmoji, uuid } from '@renderer/utils'
|
||||
import { Button, Form, FormInstance, Input, Modal, Popover } from 'antd'
|
||||
import TextArea from 'antd/es/input/TextArea'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
interface Props {
|
||||
agent?: Agent
|
||||
resolve: (data: Agent | null) => void
|
||||
}
|
||||
|
||||
@@ -24,13 +24,13 @@ type FieldType = {
|
||||
prompt: string
|
||||
}
|
||||
|
||||
const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
const PopupContainer: React.FC<Props> = ({ resolve }) => {
|
||||
const [open, setOpen] = useState(true)
|
||||
const [form] = Form.useForm()
|
||||
const { t } = useTranslation()
|
||||
const { addAgent, updateAgent } = useAgents()
|
||||
const { addAgent } = useAgents()
|
||||
const formRef = useRef<FormInstance>(null)
|
||||
const [emoji, setEmoji] = useState(agent?.emoji)
|
||||
const [emoji, setEmoji] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const onFinish = (values: FieldType) => {
|
||||
@@ -40,26 +40,15 @@ const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
return
|
||||
}
|
||||
|
||||
if (agent) {
|
||||
const _agent = {
|
||||
...agent,
|
||||
name: values.name,
|
||||
emoji: _emoji,
|
||||
prompt: values.prompt
|
||||
}
|
||||
updateAgent(_agent)
|
||||
syncAgentToAssistant(_agent)
|
||||
resolve(_agent)
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
|
||||
const _agent = {
|
||||
const _agent: Agent = {
|
||||
id: uuid(),
|
||||
name: values.name,
|
||||
emoji: _emoji,
|
||||
prompt: values.prompt,
|
||||
group: 'user'
|
||||
defaultModel: getDefaultModel(),
|
||||
type: 'agent',
|
||||
topics: [],
|
||||
messages: []
|
||||
}
|
||||
|
||||
addAgent(_agent)
|
||||
@@ -75,18 +64,7 @@ const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
resolve(null)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (agent) {
|
||||
form.setFieldsValue({
|
||||
name: agent.name,
|
||||
prompt: agent.prompt
|
||||
})
|
||||
}
|
||||
}, [agent, form])
|
||||
|
||||
const handleButtonClick = async () => {
|
||||
const prompt = `你是一个专业的 prompt 优化助手,我会给你一段prompt,你需要帮我优化它,仅回复优化后的 prompt 不要添加任何解释,使用 [CRISPE提示框架] 回复。`
|
||||
|
||||
const name = formRef.current?.getFieldValue('name')
|
||||
const content = formRef.current?.getFieldValue('prompt')
|
||||
const promptText = content || name
|
||||
@@ -102,8 +80,10 @@ const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const prefixedContent = `请帮我优化下面这段 prompt,使用 CRISPE 提示框架,请使用 Markdown 格式回复,不要使用 codeblock: ${promptText}`
|
||||
const generatedText = await fetchGenerate({ prompt, content: prefixedContent })
|
||||
const generatedText = await fetchGenerate({
|
||||
prompt: AGENT_PROMPT,
|
||||
content: promptText
|
||||
})
|
||||
formRef.current?.setFieldValue('prompt', generatedText)
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error)
|
||||
@@ -114,13 +94,13 @@ const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={agent ? t('agents.edit.title') : t('agents.add.title')}
|
||||
title={t('agents.add.title')}
|
||||
open={open}
|
||||
onOk={() => formRef.current?.submit()}
|
||||
onCancel={onCancel}
|
||||
maskClosable={false}
|
||||
afterClose={onClose}
|
||||
okText={agent ? t('common.save') : t('agents.add.button')}
|
||||
okText={t('agents.add.title')}
|
||||
centered>
|
||||
<Form
|
||||
ref={formRef}
|
||||
@@ -163,11 +143,10 @@ export default class AddAgentPopup {
|
||||
static hide() {
|
||||
TopView.hide('AddAgentPopup')
|
||||
}
|
||||
static show(agent?: Agent) {
|
||||
static show() {
|
||||
return new Promise<Agent | null>((resolve) => {
|
||||
TopView.show(
|
||||
<PopupContainer
|
||||
agent={agent}
|
||||
resolve={(v) => {
|
||||
resolve(v)
|
||||
this.hide()
|
||||
|
||||
@@ -32,7 +32,8 @@ const Container = styled.div`
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease-in-out;
|
||||
&:hover {
|
||||
background-color: var(--color-background-mute);
|
||||
border: 0.5px solid var(--color-primary);
|
||||
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
`
|
||||
const EmojiHeader = styled.div`
|
||||
@@ -69,6 +70,7 @@ const AgentCardPrompt = styled.div`
|
||||
-webkit-line-clamp: 1;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
white-space: pre-wrap;
|
||||
font-size: 12px;
|
||||
`
|
||||
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import { DeleteOutlined, EditOutlined, MenuOutlined } from '@ant-design/icons'
|
||||
import DragableList from '@renderer/components/DragableList'
|
||||
import { Box, HStack } from '@renderer/components/Layout'
|
||||
import { TopView } from '@renderer/components/TopView'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { Empty, Modal, Popconfirm } from 'antd'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import AddAgentPopup from './AddAgentPopup'
|
||||
|
||||
const PopupContainer: React.FC = () => {
|
||||
const [open, setOpen] = useState(true)
|
||||
const { t } = useTranslation()
|
||||
const { agents, removeAgent, updateAgents } = useAgents()
|
||||
|
||||
const onOk = () => {
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const onCancel = () => {
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const onClose = async () => {
|
||||
ManageAgentsPopup.hide()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (agents.length === 0) {
|
||||
setOpen(false)
|
||||
}
|
||||
}, [agents])
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('agents.manage.title')}
|
||||
open={open}
|
||||
onOk={onOk}
|
||||
onCancel={onCancel}
|
||||
afterClose={onClose}
|
||||
footer={null}
|
||||
centered>
|
||||
<Container>
|
||||
{agents.length > 0 && (
|
||||
<DragableList list={agents} onUpdate={updateAgents}>
|
||||
{(item) => (
|
||||
<AgentItem>
|
||||
<Box mr={8}>
|
||||
{item.emoji} {item.name}
|
||||
</Box>
|
||||
<HStack gap="15px">
|
||||
<Popconfirm
|
||||
title={t('agents.delete.popup.content')}
|
||||
okButtonProps={{ danger: true }}
|
||||
onConfirm={() => removeAgent(item)}>
|
||||
<DeleteOutlined style={{ color: 'var(--color-error)' }} />
|
||||
</Popconfirm>
|
||||
<EditOutlined style={{ cursor: 'pointer' }} onClick={() => AddAgentPopup.show(item)} />
|
||||
<MenuOutlined style={{ cursor: 'move' }} />
|
||||
</HStack>
|
||||
</AgentItem>
|
||||
)}
|
||||
</DragableList>
|
||||
)}
|
||||
{agents.length === 0 && <Empty description="" />}
|
||||
</Container>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
padding: 12px 0;
|
||||
height: 50vh;
|
||||
overflow-y: auto;
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
`
|
||||
|
||||
const AgentItem = styled.div`
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px;
|
||||
border-radius: 8px;
|
||||
user-select: none;
|
||||
background-color: var(--color-background-soft);
|
||||
margin-bottom: 8px;
|
||||
.anticon {
|
||||
font-size: 16px;
|
||||
color: var(--color-icon);
|
||||
}
|
||||
&:hover {
|
||||
background-color: var(--color-background-mute);
|
||||
}
|
||||
`
|
||||
|
||||
export default class ManageAgentsPopup {
|
||||
static topviewId = 0
|
||||
static hide() {
|
||||
TopView.hide('ManageAgentsPopup')
|
||||
}
|
||||
static show() {
|
||||
TopView.show(<PopupContainer />, 'ManageAgentsPopup')
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { PlusOutlined } from '@ant-design/icons'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { Agent } from '@renderer/types'
|
||||
import { Col, Row } from 'antd'
|
||||
import { FC } from 'react'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import AddAssistantPopup from './AddAgentPopup'
|
||||
import AgentCard from './AgentCard'
|
||||
|
||||
interface Props {
|
||||
onAdd: (agent: Agent) => void
|
||||
}
|
||||
|
||||
const UserAgents: FC<Props> = ({ onAdd }) => {
|
||||
const { agents } = useAgents()
|
||||
|
||||
const onAddMyAgentClick = () => {
|
||||
AddAssistantPopup.show()
|
||||
}
|
||||
|
||||
return (
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
{agents.map((agent) => (
|
||||
<Col span={8} key={agent.id}>
|
||||
<AgentCard agent={agent} onClick={() => onAdd(agent)} />
|
||||
</Col>
|
||||
))}
|
||||
<Col span={8}>
|
||||
<AssistantCardContainer style={{ borderStyle: 'dashed' }} onClick={onAddMyAgentClick}>
|
||||
<PlusOutlined />
|
||||
</AssistantCardContainer>
|
||||
</Col>
|
||||
</Row>
|
||||
)
|
||||
}
|
||||
|
||||
const AssistantCardContainer = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
border: 1px dashed var(--color-border-soft);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
min-height: 72px;
|
||||
.anticon {
|
||||
font-size: 16px;
|
||||
color: var(--color-icon);
|
||||
}
|
||||
&:hover {
|
||||
background-color: var(--color-background-soft);
|
||||
}
|
||||
`
|
||||
|
||||
export default UserAgents
|
||||
@@ -3,6 +3,7 @@ import { VStack } from '@renderer/components/Layout'
|
||||
import db from '@renderer/databases'
|
||||
import FileManager from '@renderer/services/file'
|
||||
import { FileType, FileTypes } from '@renderer/types'
|
||||
import { formatFileSize } from '@renderer/utils'
|
||||
import { Image, Table } from 'antd'
|
||||
import dayjs from 'dayjs'
|
||||
import { useLiveQuery } from 'dexie-react-hooks'
|
||||
@@ -12,7 +13,7 @@ import styled from 'styled-components'
|
||||
|
||||
const FilesPage: FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const files = useLiveQuery<FileType[]>(() => db.files.orderBy('ext').reverse().toArray())
|
||||
const files = useLiveQuery<FileType[]>(() => db.files.orderBy('count').reverse().toArray())
|
||||
|
||||
const dataSource = files?.map((file) => {
|
||||
const isImage = file.type === FileTypes.IMAGE
|
||||
@@ -21,7 +22,7 @@ const FilesPage: FC = () => {
|
||||
key: file.id,
|
||||
file: isImage ? ImageView : <FileNameText className="text-nowrap">{file.origin_name}</FileNameText>,
|
||||
name: <a href={'file://' + FileManager.getSafePath(file)}>{file.origin_name}</a>,
|
||||
size: `${(file.size / 1024 / 1024).toFixed(2)} MB`,
|
||||
size: formatFileSize(file),
|
||||
count: file.count,
|
||||
created_at: dayjs(file.created_at).format('MM-DD HH:mm')
|
||||
}
|
||||
@@ -71,7 +72,7 @@ const FilesPage: FC = () => {
|
||||
columns={columns}
|
||||
style={{ width: '100%', marginBottom: 20 }}
|
||||
size="small"
|
||||
pagination={{ pageSize: 15 }}
|
||||
pagination={{ pageSize: 100 }}
|
||||
/>
|
||||
</VStack>
|
||||
</ContentContainer>
|
||||
|
||||
@@ -118,6 +118,7 @@ const Header = styled.div`
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 8px 20px;
|
||||
padding-top: 10px;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
`
|
||||
|
||||
@@ -8,7 +8,7 @@ import styled from 'styled-components'
|
||||
|
||||
import Inputbar from './Inputbar/Inputbar'
|
||||
import Messages from './Messages/Messages'
|
||||
import RightSidebar from './RightSidebar'
|
||||
import Tabs from './Tabs'
|
||||
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
@@ -29,7 +29,7 @@ const Chat: FC<Props> = (props) => {
|
||||
<Inputbar assistant={assistant} setActiveTopic={props.setActiveTopic} />
|
||||
</Main>
|
||||
{topicPosition === 'right' && showTopics && (
|
||||
<RightSidebar
|
||||
<Tabs
|
||||
activeAssistant={assistant}
|
||||
activeTopic={props.activeTopic}
|
||||
setActiveAssistant={props.setActiveAssistant}
|
||||
|
||||
@@ -8,7 +8,7 @@ import styled from 'styled-components'
|
||||
|
||||
import Chat from './Chat'
|
||||
import Navbar from './Navbar'
|
||||
import RightSidebar from './RightSidebar'
|
||||
import HomeTabs from './Tabs'
|
||||
|
||||
let _activeAssistant: Assistant
|
||||
|
||||
@@ -29,7 +29,7 @@ const HomePage: FC = () => {
|
||||
<Navbar activeAssistant={activeAssistant} activeTopic={activeTopic} setActiveTopic={setActiveTopic} />
|
||||
<ContentContainer id="content-container">
|
||||
{showAssistants && (
|
||||
<RightSidebar
|
||||
<HomeTabs
|
||||
activeAssistant={activeAssistant}
|
||||
activeTopic={activeTopic}
|
||||
setActiveAssistant={setActiveAssistant}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { PaperClipOutlined } from '@ant-design/icons'
|
||||
import { imageExts, textExts } from '@renderer/config/constant'
|
||||
import { documentExts, imageExts, textExts } from '@renderer/config/constant'
|
||||
import { isVisionModel } from '@renderer/config/models'
|
||||
import { FileType, Model } from '@renderer/types'
|
||||
import { Tooltip } from 'antd'
|
||||
@@ -15,7 +15,9 @@ interface Props {
|
||||
|
||||
const AttachmentButton: FC<Props> = ({ model, files, setFiles, ToolbarButton }) => {
|
||||
const { t } = useTranslation()
|
||||
const extensions = isVisionModel(model) ? [...imageExts, ...textExts] : [...textExts]
|
||||
const extensions = isVisionModel(model)
|
||||
? [...imageExts, ...documentExts, ...textExts]
|
||||
: [...documentExts, ...textExts]
|
||||
|
||||
const onSelectFile = async () => {
|
||||
if (files.length > 0) {
|
||||
@@ -23,6 +25,7 @@ const AttachmentButton: FC<Props> = ({ model, files, setFiles, ToolbarButton })
|
||||
}
|
||||
|
||||
const _files = await window.api.file.select({
|
||||
properties: ['openFile', 'multiSelections'],
|
||||
filters: [
|
||||
{
|
||||
name: 'Files',
|
||||
|
||||
@@ -7,16 +7,16 @@ import {
|
||||
PauseCircleOutlined,
|
||||
QuestionCircleOutlined
|
||||
} from '@ant-design/icons'
|
||||
import { imageExts, textExts } from '@renderer/config/constant'
|
||||
import { documentExts, imageExts, textExts } from '@renderer/config/constant'
|
||||
import { isVisionModel } from '@renderer/config/models'
|
||||
import db from '@renderer/databases'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { useRuntime, useShowTopics } from '@renderer/hooks/useStore'
|
||||
import { getDefaultTopic } from '@renderer/services/assistant'
|
||||
import { addAssistantMessagesToTopic, getDefaultTopic } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import FileManager from '@renderer/services/file'
|
||||
import { estimateTextTokens } from '@renderer/services/tokens'
|
||||
import { estimateTextTokens as estimateTxtTokens } from '@renderer/services/tokens'
|
||||
import store, { useAppDispatch, useAppSelector } from '@renderer/store'
|
||||
import { setGenerating, setSearching } from '@renderer/store/runtime'
|
||||
import { Assistant, FileType, Message, Topic } from '@renderer/types'
|
||||
@@ -45,8 +45,8 @@ let _files: FileType[] = []
|
||||
const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
const [text, setText] = useState(_text)
|
||||
const [inputFocus, setInputFocus] = useState(false)
|
||||
const { addTopic, model } = useAssistant(assistant.id)
|
||||
const { sendMessageShortcut, fontSize, pasteLongTextAsFile } = useSettings()
|
||||
const { addTopic, model, setModel } = useAssistant(assistant.id)
|
||||
const { sendMessageShortcut, fontSize, pasteLongTextAsFile, showInputEstimatedTokens } = useSettings()
|
||||
const [expended, setExpend] = useState(false)
|
||||
const [estimateTokenCount, setEstimateTokenCount] = useState(0)
|
||||
const [contextCount, setContextCount] = useState(0)
|
||||
@@ -60,8 +60,13 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
const isVision = useMemo(() => isVisionModel(model), [model])
|
||||
const supportExts = useMemo(() => [...textExts, ...(isVision ? imageExts : [])], [isVision])
|
||||
const inputTokenCount = useMemo(() => estimateTextTokens(text), [text])
|
||||
const supportExts = useMemo(() => [...textExts, ...documentExts, ...(isVision ? imageExts : [])], [isVision])
|
||||
|
||||
const estimateTextTokens = useCallback(debounce(estimateTxtTokens, 1000), [])
|
||||
const inputTokenCount = useMemo(
|
||||
() => (showInputEstimatedTokens ? estimateTextTokens(text) || 0 : 0),
|
||||
[estimateTextTokens, showInputEstimatedTokens, text]
|
||||
)
|
||||
|
||||
_text = text
|
||||
_files = files
|
||||
@@ -78,7 +83,7 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
const message: Message = {
|
||||
id: uuid(),
|
||||
role: 'user',
|
||||
content: text.replace(/\n/g, ' \n'),
|
||||
content: text,
|
||||
assistantId: assistant.id,
|
||||
topicId: assistant.topics[0].id || uuid(),
|
||||
createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
|
||||
@@ -122,12 +127,20 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
}
|
||||
}
|
||||
|
||||
const addNewTopic = useCallback(() => {
|
||||
const addNewTopic = useCallback(async () => {
|
||||
const topic = getDefaultTopic(assistant.id)
|
||||
|
||||
await db.topics.add({ id: topic.id, messages: [] })
|
||||
await addAssistantMessagesToTopic({ assistant, topic })
|
||||
|
||||
// Reset to assistant default model
|
||||
if (assistant.settings?.autoResetModel) {
|
||||
assistant.defaultModel && setModel(assistant.defaultModel)
|
||||
}
|
||||
|
||||
addTopic(topic)
|
||||
setActiveTopic(topic)
|
||||
db.topics.add({ id: topic.id, messages: [] })
|
||||
}, [addTopic, assistant.id, setActiveTopic])
|
||||
}, [addTopic, assistant, setActiveTopic, setModel])
|
||||
|
||||
const clearTopic = async () => {
|
||||
if (generating) {
|
||||
@@ -207,16 +220,35 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
await window.api.file.write(tempFilePath, pasteText)
|
||||
const selectedFile = await window.api.file.get(tempFilePath)
|
||||
selectedFile && setFiles((prevFiles) => [...prevFiles, selectedFile])
|
||||
setText((prevText) => prevText.replace(pasteText, ''))
|
||||
setText(text)
|
||||
setTimeout(() => resizeTextArea(), 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
[pasteLongTextAsFile, supportExts]
|
||||
[pasteLongTextAsFile, supportExts, text]
|
||||
)
|
||||
|
||||
const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
const files = Array.from(e.dataTransfer.files)
|
||||
|
||||
files.forEach(async (file) => {
|
||||
if (supportExts.includes(getFileExtension(file.path))) {
|
||||
const selectedFile = await window.api.file.get(file.path)
|
||||
selectedFile && setFiles((prevFiles) => [...prevFiles, selectedFile])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Command or Ctrl + N create new topic
|
||||
useEffect(() => {
|
||||
const onKeydown = (e) => {
|
||||
@@ -243,17 +275,18 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
EventEmitter.on(EVENT_NAMES.ESTIMATED_TOKEN_COUNT, ({ tokensCount, contextCount }) => {
|
||||
_setEstimateTokenCount(tokensCount)
|
||||
setContextCount(contextCount)
|
||||
})
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.ADD_NEW_TOPIC, addNewTopic)
|
||||
]
|
||||
return () => unsubscribes.forEach((unsub) => unsub())
|
||||
}, [])
|
||||
}, [addNewTopic])
|
||||
|
||||
useEffect(() => {
|
||||
textareaRef.current?.focus()
|
||||
}, [assistant])
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Container onDragOver={handleDragOver} onDrop={handleDrop}>
|
||||
<AttachmentPreview files={files} setFiles={setFiles} />
|
||||
<InputBarContainer id="inputbar" className={inputFocus ? 'focus' : ''} ref={containerRef}>
|
||||
<Textarea
|
||||
|
||||
51
src/renderer/src/pages/home/Markdown/Artifacts.tsx
Normal file
51
src/renderer/src/pages/home/Markdown/Artifacts.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import MinApp from '@renderer/components/MinApp'
|
||||
import { AppLogo } from '@renderer/config/env'
|
||||
import { extractTitle } from '@renderer/utils/formula'
|
||||
import { Button } from 'antd'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
interface Props {
|
||||
html: string
|
||||
}
|
||||
|
||||
const Artifacts: FC<Props> = ({ html }) => {
|
||||
const { t } = useTranslation()
|
||||
const title = extractTitle(html) || 'Artifacts' + ' ' + t('chat.artifacts.button.preview')
|
||||
|
||||
const onPreview = async () => {
|
||||
const path = await window.api.file.create('artifacts-preview.html')
|
||||
await window.api.file.write(path, html)
|
||||
|
||||
MinApp.start({
|
||||
name: title,
|
||||
logo: AppLogo,
|
||||
url: `file://${path}`
|
||||
})
|
||||
}
|
||||
|
||||
const onDownload = () => {
|
||||
window.api.file.save(`${title}.html`, html)
|
||||
}
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Button type="primary" size="middle" onClick={onPreview}>
|
||||
{t('chat.artifacts.button.preview')}
|
||||
</Button>
|
||||
<Button size="middle" onClick={onDownload}>
|
||||
{t('chat.artifacts.button.download')}
|
||||
</Button>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
margin: 10px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
`
|
||||
|
||||
export default Artifacts
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CheckOutlined } from '@ant-design/icons'
|
||||
import CopyIcon from '@renderer/components/Icons/CopyIcon'
|
||||
import { useTheme } from '@renderer/context/ThemeProvider'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { initMermaid } from '@renderer/init'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
import React, { memo, useState } from 'react'
|
||||
@@ -9,6 +10,7 @@ import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
|
||||
import { atomDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import Artifacts from './Artifacts'
|
||||
import Mermaid from './Mermaid'
|
||||
|
||||
interface CodeBlockProps {
|
||||
@@ -20,9 +22,11 @@ interface CodeBlockProps {
|
||||
const CodeBlock: React.FC<CodeBlockProps> = ({ children, className }) => {
|
||||
const match = /language-(\w+)/.exec(className || '')
|
||||
const showFooterCopyButton = children && children.length > 500
|
||||
const { codeShowLineNumbers, fontSize } = useSettings()
|
||||
const { theme } = useTheme()
|
||||
const language = match?.[1]
|
||||
|
||||
if (match && match[1] === 'mermaid') {
|
||||
if (language === 'mermaid') {
|
||||
initMermaid(theme)
|
||||
return <Mermaid chart={children} />
|
||||
}
|
||||
@@ -36,12 +40,14 @@ const CodeBlock: React.FC<CodeBlockProps> = ({ children, className }) => {
|
||||
<SyntaxHighlighter
|
||||
language={match[1]}
|
||||
style={theme === ThemeMode.dark ? atomDark : oneLight}
|
||||
wrapLongLines={true}
|
||||
wrapLongLines={false}
|
||||
showLineNumbers={codeShowLineNumbers}
|
||||
customStyle={{
|
||||
border: '0.5px solid var(--color-code-background)',
|
||||
borderTopLeftRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
marginTop: 0
|
||||
marginTop: 0,
|
||||
fontSize
|
||||
}}>
|
||||
{String(children).replace(/\n$/, '')}
|
||||
</SyntaxHighlighter>
|
||||
@@ -50,6 +56,7 @@ const CodeBlock: React.FC<CodeBlockProps> = ({ children, className }) => {
|
||||
<CopyButton text={children} style={{ marginTop: -40, marginRight: 10 }} />
|
||||
</CodeFooter>
|
||||
)}
|
||||
{language === 'html' && children?.includes('</html>') && <Artifacts html={children} />}
|
||||
</div>
|
||||
) : (
|
||||
<code className={className}>{children}</code>
|
||||
@@ -82,7 +89,7 @@ const CodeHeader = styled.div`
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
/* background-color: var(--color-code-background); */
|
||||
height: 36px;
|
||||
height: 34px;
|
||||
padding: 0 10px;
|
||||
border-top-left-radius: 8px;
|
||||
border-top-right-radius: 8px;
|
||||
|
||||
62
src/renderer/src/pages/home/Markdown/ImagePreview.tsx
Normal file
62
src/renderer/src/pages/home/Markdown/ImagePreview.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
DownloadOutlined,
|
||||
RotateLeftOutlined,
|
||||
RotateRightOutlined,
|
||||
SwapOutlined,
|
||||
UndoOutlined,
|
||||
ZoomInOutlined,
|
||||
ZoomOutOutlined
|
||||
} from '@ant-design/icons'
|
||||
import { download } from '@renderer/utils/download'
|
||||
import { Image, Space } from 'antd'
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
|
||||
interface ImagePreviewProps extends React.ImgHTMLAttributes<HTMLImageElement> {
|
||||
src: string
|
||||
}
|
||||
|
||||
const ImagePreview: React.FC<ImagePreviewProps> = ({ src }) => {
|
||||
return (
|
||||
<Image
|
||||
src={src}
|
||||
preview={{
|
||||
toolbarRender: (
|
||||
_,
|
||||
{
|
||||
transform: { scale },
|
||||
actions: { onFlipY, onFlipX, onRotateLeft, onRotateRight, onZoomOut, onZoomIn, onReset }
|
||||
}
|
||||
) => (
|
||||
<ToobarWrapper size={12} className="toolbar-wrapper">
|
||||
<SwapOutlined rotate={90} onClick={onFlipY} />
|
||||
<SwapOutlined onClick={onFlipX} />
|
||||
<RotateLeftOutlined onClick={onRotateLeft} />
|
||||
<RotateRightOutlined onClick={onRotateRight} />
|
||||
<ZoomOutOutlined disabled={scale === 1} onClick={onZoomOut} />
|
||||
<ZoomInOutlined disabled={scale === 50} onClick={onZoomIn} />
|
||||
<UndoOutlined onClick={onReset} />
|
||||
<DownloadOutlined onClick={() => download(src)} />
|
||||
</ToobarWrapper>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const ToobarWrapper = styled(Space)`
|
||||
padding: 0px 24px;
|
||||
color: #fff;
|
||||
font-size: 20px;
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
border-radius: 100px;
|
||||
.anticon {
|
||||
padding: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.anticon:hover {
|
||||
opacity: 0.3;
|
||||
}
|
||||
`
|
||||
|
||||
export default ImagePreview
|
||||
@@ -7,26 +7,20 @@ import { isEmpty } from 'lodash'
|
||||
import { FC, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import ReactMarkdown, { Components } from 'react-markdown'
|
||||
import rehypeKatex from 'rehype-katex'
|
||||
// @ts-ignore next-line
|
||||
import rehypeMathjax from 'rehype-mathjax'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import remarkMath from 'remark-math'
|
||||
|
||||
import CodeBlock from './CodeBlock'
|
||||
import ImagePreview from './ImagePreview'
|
||||
import Link from './Link'
|
||||
|
||||
interface Props {
|
||||
message: Message
|
||||
}
|
||||
|
||||
const rehypePlugins = [rehypeRaw, rehypeKatex]
|
||||
const remarkPlugins = [remarkMath, remarkGfm]
|
||||
|
||||
const components = {
|
||||
code: CodeBlock,
|
||||
a: Link
|
||||
}
|
||||
|
||||
const Markdown: FC<Props> = ({ message }) => {
|
||||
const { t } = useTranslation()
|
||||
const { renderInputMessageAsMarkdown } = useSettings()
|
||||
@@ -38,6 +32,11 @@ const Markdown: FC<Props> = ({ message }) => {
|
||||
return escapeBrackets(content)
|
||||
}, [message.content, message.status, t])
|
||||
|
||||
const rehypePlugins = useMemo(() => {
|
||||
const hasUnsafeElements = /<(input|textarea|select)/i.test(messageContent)
|
||||
return hasUnsafeElements ? [rehypeMathjax] : [rehypeRaw, rehypeMathjax]
|
||||
}, [messageContent])
|
||||
|
||||
if (message.role === 'user' && !renderInputMessageAsMarkdown) {
|
||||
return <p style={{ marginBottom: 5, whiteSpace: 'pre-wrap' }}>{messageContent}</p>
|
||||
}
|
||||
@@ -46,8 +45,15 @@ const Markdown: FC<Props> = ({ message }) => {
|
||||
<ReactMarkdown
|
||||
className="markdown"
|
||||
rehypePlugins={rehypePlugins}
|
||||
remarkPlugins={remarkPlugins}
|
||||
components={components as Partial<Components>}
|
||||
remarkPlugins={[remarkMath, remarkGfm]}
|
||||
disallowedElements={['style']}
|
||||
components={
|
||||
{
|
||||
a: Link,
|
||||
code: CodeBlock,
|
||||
img: ImagePreview
|
||||
} as Partial<Components>
|
||||
}
|
||||
remarkRehypeOptions={{
|
||||
footnoteLabel: t('common.footnotes'),
|
||||
footnoteLabelTagName: 'h4',
|
||||
|
||||
@@ -20,11 +20,20 @@ interface Props {
|
||||
total?: number
|
||||
lastMessage?: boolean
|
||||
showMenu?: boolean
|
||||
hidePresetMessages?: boolean
|
||||
onEditMessage?: (message: Message) => void
|
||||
onDeleteMessage?: (message: Message) => void
|
||||
}
|
||||
|
||||
const MessageItem: FC<Props> = ({ message, index, lastMessage, showMenu = true, onEditMessage, onDeleteMessage }) => {
|
||||
const MessageItem: FC<Props> = ({
|
||||
message,
|
||||
index,
|
||||
lastMessage,
|
||||
showMenu = true,
|
||||
hidePresetMessages,
|
||||
onEditMessage,
|
||||
onDeleteMessage
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const { assistant, setModel } = useAssistant(message.assistantId)
|
||||
const model = useModel(message.modelId)
|
||||
@@ -42,21 +51,27 @@ const MessageItem: FC<Props> = ({ message, index, lastMessage, showMenu = true,
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribes = [
|
||||
EventEmitter.on(EVENT_NAMES.LOCATE_MESSAGE + ':' + message.id, () => {
|
||||
EventEmitter.on(EVENT_NAMES.LOCATE_MESSAGE + ':' + message.id, (highlight: boolean = true) => {
|
||||
if (messageRef.current) {
|
||||
messageRef.current.scrollIntoView({ behavior: 'smooth' })
|
||||
setTimeout(() => {
|
||||
messageRef.current?.classList.add('message-highlight')
|
||||
if (highlight) {
|
||||
setTimeout(() => {
|
||||
messageRef.current?.classList.remove('message-highlight')
|
||||
}, 2500)
|
||||
}, 500)
|
||||
messageRef.current?.classList.add('message-highlight')
|
||||
setTimeout(() => {
|
||||
messageRef.current?.classList.remove('message-highlight')
|
||||
}, 2500)
|
||||
}, 500)
|
||||
}
|
||||
}
|
||||
})
|
||||
]
|
||||
return () => unsubscribes.forEach((unsub) => unsub())
|
||||
}, [message])
|
||||
|
||||
if (hidePresetMessages && message.isPreset) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (message.type === 'clear') {
|
||||
return (
|
||||
<Divider dashed style={{ padding: '0 20px' }} plain>
|
||||
@@ -72,7 +87,7 @@ const MessageItem: FC<Props> = ({ message, index, lastMessage, showMenu = true,
|
||||
<MessageContent message={message} model={model} />
|
||||
{!lastMessage && showMenu && (
|
||||
<MessageFooter style={{ border: messageBorder, flexDirection: isLastMessage ? 'row-reverse' : undefined }}>
|
||||
<MessgeTokens message={message} />
|
||||
<MessgeTokens message={message} isLastMessage={isLastMessage} />
|
||||
<MessageMenubar
|
||||
message={message}
|
||||
model={model}
|
||||
|
||||
@@ -9,7 +9,6 @@ import { Assistant, Message, Model } from '@renderer/types'
|
||||
import { firstLetter, removeLeadingEmoji } from '@renderer/utils'
|
||||
import { Avatar } from 'antd'
|
||||
import dayjs from 'dayjs'
|
||||
import { upperFirst } from 'lodash'
|
||||
import { FC, useCallback, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
@@ -36,7 +35,7 @@ const MessageHeader: FC<Props> = ({ assistant, model, message }) => {
|
||||
|
||||
const getUserName = useCallback(() => {
|
||||
if (isLocalAi && message.role !== 'user') return APP_NAME
|
||||
if (message.role === 'assistant') return upperFirst(model?.name || model?.id)
|
||||
if (message.role === 'assistant') return model?.name || model?.id || ''
|
||||
return userName || t('common.you')
|
||||
}, [message.role, model?.id, model?.name, t, userName])
|
||||
|
||||
|
||||
@@ -8,17 +8,17 @@ import {
|
||||
SaveOutlined,
|
||||
SyncOutlined
|
||||
} from '@ant-design/icons'
|
||||
import SelectModelPopup from '@renderer/components/Popups/SelectModelPopup'
|
||||
import TextEditPopup from '@renderer/components/Popups/TextEditPopup'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { Message, Model } from '@renderer/types'
|
||||
import { removeTrailingDoubleSpaces } from '@renderer/utils'
|
||||
import { Dropdown, Popconfirm, Tooltip } from 'antd'
|
||||
import dayjs from 'dayjs'
|
||||
import { FC, useCallback, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import SelectModelDropdown from '../components/SelectModelDropdown'
|
||||
|
||||
interface Props {
|
||||
message: Message
|
||||
model?: Model
|
||||
@@ -55,7 +55,11 @@ const MessageMenubar: FC<Props> = (props) => {
|
||||
|
||||
const onNewBranch = useCallback(() => {
|
||||
EventEmitter.emit(EVENT_NAMES.NEW_BRANCH, index)
|
||||
}, [index])
|
||||
window.message.success({
|
||||
content: t('chat.message.new.branch.created'),
|
||||
key: 'new-branch'
|
||||
})
|
||||
}, [index, t])
|
||||
|
||||
const onEdit = useCallback(async () => {
|
||||
const editedText = await TextEditPopup.show({ text: message.content })
|
||||
@@ -69,7 +73,7 @@ const MessageMenubar: FC<Props> = (props) => {
|
||||
key: 'save',
|
||||
icon: <SaveOutlined />,
|
||||
onClick: () => {
|
||||
const fileName = message.createdAt + '.md'
|
||||
const fileName = dayjs(message.createdAt).format('YYYYMMDDHHmm') + '.md'
|
||||
window.api.file.save(fileName, message.content)
|
||||
}
|
||||
},
|
||||
@@ -83,6 +87,11 @@ const MessageMenubar: FC<Props> = (props) => {
|
||||
[message.content, message.createdAt, onEdit, t]
|
||||
)
|
||||
|
||||
const onSelectModel = async () => {
|
||||
const selectedModel = await SelectModelPopup.show({ model })
|
||||
selectedModel && onRegenerate(selectedModel)
|
||||
}
|
||||
|
||||
return (
|
||||
<MenusBar className={`menubar ${isLastMessage && 'show'}`}>
|
||||
{message.role === 'user' && (
|
||||
@@ -99,13 +108,11 @@ const MessageMenubar: FC<Props> = (props) => {
|
||||
</ActionButton>
|
||||
</Tooltip>
|
||||
{canRegenerate && (
|
||||
<SelectModelDropdown model={model} onSelect={onRegenerate} placement="topLeft">
|
||||
<Tooltip title={t('common.regenerate')} mouseEnterDelay={0.8}>
|
||||
<ActionButton>
|
||||
<SyncOutlined />
|
||||
</ActionButton>
|
||||
</Tooltip>
|
||||
</SelectModelDropdown>
|
||||
<Tooltip title={t('common.regenerate')} mouseEnterDelay={0.8}>
|
||||
<ActionButton onClick={onSelectModel}>
|
||||
<SyncOutlined />
|
||||
</ActionButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{isAssistantMessage && (
|
||||
<Tooltip title={t('chat.message.new.branch')} mouseEnterDelay={0.8}>
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
import { useRuntime } from '@renderer/hooks/useStore'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { Message } from '@renderer/types'
|
||||
import styled from 'styled-components'
|
||||
|
||||
const MessgeTokens: React.FC<{ message: Message }> = ({ message }) => {
|
||||
const MessgeTokens: React.FC<{ message: Message; isLastMessage: boolean }> = ({ message, isLastMessage }) => {
|
||||
const { generating } = useRuntime()
|
||||
|
||||
const locateMessage = () => {
|
||||
EventEmitter.emit(EVENT_NAMES.LOCATE_MESSAGE + ':' + message.id, false)
|
||||
}
|
||||
|
||||
if (!message.usage) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (message.role === 'user') {
|
||||
return <MessageMetadata>Tokens: {message?.usage?.total_tokens}</MessageMetadata>
|
||||
return <MessageMetadata onClick={locateMessage}>Tokens: {message?.usage?.total_tokens}</MessageMetadata>
|
||||
}
|
||||
|
||||
if (generating) {
|
||||
if (isLastMessage && generating) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (message.role === 'assistant') {
|
||||
return (
|
||||
<MessageMetadata>
|
||||
<MessageMetadata onClick={locateMessage}>
|
||||
Tokens: {message?.usage?.total_tokens} | ↑{message?.usage?.prompt_tokens} | ↓{message?.usage?.completion_tokens}
|
||||
</MessageMetadata>
|
||||
)
|
||||
@@ -33,6 +38,7 @@ const MessageMetadata = styled.div`
|
||||
color: var(--color-text-2);
|
||||
user-select: text;
|
||||
margin: 2px 0;
|
||||
cursor: pointer;
|
||||
`
|
||||
|
||||
export default MessgeTokens
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWindows } from '@renderer/config/constant'
|
||||
import db from '@renderer/databases'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
@@ -8,7 +9,7 @@ import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { deleteMessageFiles, filterMessages, getContextCount } from '@renderer/services/messages'
|
||||
import { estimateHistoryTokens, estimateMessageUsage } from '@renderer/services/tokens'
|
||||
import { Assistant, Message, Model, Topic } from '@renderer/types'
|
||||
import { captureScrollableDiv, runAsyncFunction, uuid } from '@renderer/utils'
|
||||
import { captureScrollableDiv, classNames, runAsyncFunction, uuid } from '@renderer/utils'
|
||||
import { t } from 'i18next'
|
||||
import { flatten, last, reverse, take } from 'lodash'
|
||||
import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
@@ -87,16 +88,17 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
[messages, topic.id]
|
||||
)
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
setTimeout(() => containerRef.current?.scrollTo({ top: containerRef.current.scrollHeight, behavior: 'auto' }), 10)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribes = [
|
||||
EventEmitter.on(EVENT_NAMES.SEND_MESSAGE, async (msg: Message) => {
|
||||
await onSendMessage(msg)
|
||||
|
||||
// Scroll to bottom
|
||||
setTimeout(
|
||||
() => containerRef.current?.scrollTo({ top: containerRef.current.scrollHeight, behavior: 'auto' }),
|
||||
10
|
||||
)
|
||||
scrollToBottom()
|
||||
|
||||
// Fetch completion
|
||||
fetchChatCompletion({
|
||||
@@ -131,7 +133,8 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
EventEmitter.on(EVENT_NAMES.AI_AUTO_RENAME, autoRenameTopic),
|
||||
EventEmitter.on(EVENT_NAMES.CLEAR_MESSAGES, () => {
|
||||
setMessages([])
|
||||
updateTopic({ ...topic, messages: [] })
|
||||
const defaultTopic = getDefaultTopic(assistant.id)
|
||||
updateTopic({ ...topic, name: defaultTopic.name, messages: [] })
|
||||
TopicManager.clearTopicMessages(topic.id)
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.EXPORT_TOPIC_IMAGE, async () => {
|
||||
@@ -145,6 +148,7 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
|
||||
if (lastMessage && lastMessage.type === 'clear') {
|
||||
onDeleteMessage(lastMessage)
|
||||
scrollToBottom()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -162,6 +166,8 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
status: 'success',
|
||||
type: 'clear'
|
||||
} as Message)
|
||||
|
||||
scrollToBottom()
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.NEW_BRANCH, async (index: number) => {
|
||||
const newTopic = getDefaultTopic(assistant.id)
|
||||
@@ -191,6 +197,7 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
messages,
|
||||
onDeleteMessage,
|
||||
onSendMessage,
|
||||
scrollToBottom,
|
||||
setActiveTopic,
|
||||
topic,
|
||||
updateTopic
|
||||
@@ -213,7 +220,12 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
}, [assistant, messages])
|
||||
|
||||
return (
|
||||
<Container id="messages" style={{ maxWidth }} key={assistant.id} ref={containerRef}>
|
||||
<Container
|
||||
id="messages"
|
||||
className={classNames(isWindows && 'scrollbar')}
|
||||
style={{ maxWidth }}
|
||||
key={assistant.id}
|
||||
ref={containerRef}>
|
||||
<Suggestions assistant={assistant} messages={messages} lastMessage={lastMessage} />
|
||||
{lastMessage && <MessageItem key={lastMessage.id} message={lastMessage} lastMessage />}
|
||||
{reverse([...messages]).map((message, index) => (
|
||||
@@ -221,6 +233,7 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
key={message.id}
|
||||
message={message}
|
||||
index={index}
|
||||
hidePresetMessages={assistant.settings?.hideMessages}
|
||||
onEditMessage={onEditMessage}
|
||||
onDeleteMessage={onDeleteMessage}
|
||||
/>
|
||||
@@ -241,6 +254,11 @@ const Container = styled.div`
|
||||
background-color: var(--color-background);
|
||||
padding-bottom: 20px;
|
||||
overflow-x: hidden;
|
||||
&.scrollbar {
|
||||
&::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default Messages
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import AssistantSettingPopup from '@renderer/components/AssistantSettings'
|
||||
import AssistantSettingsPopup from '@renderer/components/AssistantSettings'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
@@ -18,7 +18,7 @@ const Prompt: FC<Props> = ({ assistant }) => {
|
||||
}
|
||||
|
||||
return (
|
||||
<Container onClick={() => AssistantSettingPopup.show({ assistant })}>
|
||||
<Container onClick={() => AssistantSettingsPopup.show({ assistant })}>
|
||||
<Text>{prompt}</Text>
|
||||
</Container>
|
||||
)
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { FormOutlined } from '@ant-design/icons'
|
||||
import { Navbar, NavbarLeft, NavbarRight } from '@renderer/components/app/Navbar'
|
||||
import AssistantSettingPopup from '@renderer/components/AssistantSettings'
|
||||
import AssistantSettingsPopup from '@renderer/components/AssistantSettings'
|
||||
import { HStack } from '@renderer/components/Layout'
|
||||
import { isMac, isWindows } from '@renderer/config/constant'
|
||||
import { useTheme } from '@renderer/context/ThemeProvider'
|
||||
import db from '@renderer/databases'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { useShowAssistants, useShowTopics } from '@renderer/hooks/useStore'
|
||||
import { getDefaultTopic } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { Assistant, Topic } from '@renderer/types'
|
||||
import { Switch } from 'antd'
|
||||
import { FC, useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import SelectModelButton from './components/SelectModelButton'
|
||||
@@ -24,22 +21,17 @@ interface Props {
|
||||
setActiveTopic: (topic: Topic) => void
|
||||
}
|
||||
|
||||
const HeaderNavbar: FC<Props> = ({ activeAssistant, setActiveTopic }) => {
|
||||
const { assistant, addTopic } = useAssistant(activeAssistant.id)
|
||||
const HeaderNavbar: FC<Props> = ({ activeAssistant }) => {
|
||||
const { assistant } = useAssistant(activeAssistant.id)
|
||||
const { showAssistants, toggleShowAssistants } = useShowAssistants()
|
||||
const { theme, toggleTheme } = useTheme()
|
||||
const { topicPosition } = useSettings()
|
||||
const { showTopics, toggleShowTopics } = useShowTopics()
|
||||
const { t } = useTranslation()
|
||||
|
||||
const addNewTopic = useCallback(() => {
|
||||
const topic = getDefaultTopic(assistant.id)
|
||||
addTopic(topic)
|
||||
setActiveTopic(topic)
|
||||
db.topics.add({ id: topic.id, messages: [] })
|
||||
window.message.success({ content: t('message.topic.added'), key: 'topic-added' })
|
||||
EventEmitter.emit(EVENT_NAMES.ADD_NEW_TOPIC)
|
||||
setTimeout(() => EventEmitter.emit(EVENT_NAMES.SHOW_TOPIC_SIDEBAR), 0)
|
||||
}, [addTopic, assistant.id, setActiveTopic, t])
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Navbar>
|
||||
@@ -65,7 +57,7 @@ const HeaderNavbar: FC<Props> = ({ activeAssistant, setActiveTopic }) => {
|
||||
<TitleText
|
||||
style={{ marginRight: 10, cursor: 'pointer' }}
|
||||
className="nodrag"
|
||||
onClick={() => AssistantSettingPopup.show({ assistant })}>
|
||||
onClick={() => AssistantSettingsPopup.show({ assistant })}>
|
||||
{assistant.name}
|
||||
</TitleText>
|
||||
<SelectModelButton assistant={assistant} />
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { DeleteOutlined, EditOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'
|
||||
import AssistantSettingPopup from '@renderer/components/AssistantSettings'
|
||||
import { DeleteOutlined, EditOutlined, MinusCircleOutlined, PlusOutlined, SaveOutlined } from '@ant-design/icons'
|
||||
import AssistantSettingsPopup from '@renderer/components/AssistantSettings'
|
||||
import DragableList from '@renderer/components/DragableList'
|
||||
import CopyIcon from '@renderer/components/Icons/CopyIcon'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { useAssistant, useAssistants } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { getDefaultTopic } from '@renderer/services/assistant'
|
||||
@@ -12,7 +13,7 @@ import { Assistant } from '@renderer/types'
|
||||
import { uuid } from '@renderer/utils'
|
||||
import { Dropdown, Input, InputRef } from 'antd'
|
||||
import { ItemType } from 'antd/es/menu/interface'
|
||||
import { isEmpty, last } from 'lodash'
|
||||
import { isEmpty, last, omit } from 'lodash'
|
||||
import { FC, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
@@ -39,6 +40,7 @@ const Assistants: FC<Props> = ({
|
||||
const searchRef = useRef<InputRef>(null)
|
||||
const { t } = useTranslation()
|
||||
const dispatch = useAppDispatch()
|
||||
const { addAgent } = useAgents()
|
||||
|
||||
const onDelete = useCallback(
|
||||
(assistant: Assistant) => {
|
||||
@@ -53,13 +55,13 @@ const Assistants: FC<Props> = ({
|
||||
(assistant: Assistant) =>
|
||||
[
|
||||
{
|
||||
label: t('common.edit'),
|
||||
label: t('assistants.edit.title'),
|
||||
key: 'edit',
|
||||
icon: <EditOutlined />,
|
||||
onClick: () => AssistantSettingPopup.show({ assistant })
|
||||
onClick: () => AssistantSettingsPopup.show({ assistant })
|
||||
},
|
||||
{
|
||||
label: t('common.duplicate'),
|
||||
label: t('assistants.copy.title'),
|
||||
key: 'duplicate',
|
||||
icon: <CopyIcon />,
|
||||
onClick: async () => {
|
||||
@@ -69,29 +71,52 @@ const Assistants: FC<Props> = ({
|
||||
}
|
||||
},
|
||||
{
|
||||
label: t('chat.topics.delete.all.title'),
|
||||
key: 'delete-all',
|
||||
label: t('assistants.clear.title'),
|
||||
key: 'clear',
|
||||
icon: <MinusCircleOutlined />,
|
||||
onClick: () => {
|
||||
window.modal.confirm({
|
||||
title: t('chat.topics.delete.all.title'),
|
||||
content: t('chat.topics.delete.all.content'),
|
||||
title: t('assistants.clear.title'),
|
||||
content: t('assistants.clear.content'),
|
||||
centered: true,
|
||||
okButtonProps: { danger: true },
|
||||
onOk: removeAllTopics
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
label: t('assistants.save.title'),
|
||||
key: 'save-to-agent',
|
||||
icon: <SaveOutlined />,
|
||||
onClick: async () => {
|
||||
const agent = omit(assistant, ['model', 'emoji'])
|
||||
agent.id = uuid()
|
||||
agent.type = 'agent'
|
||||
addAgent(agent)
|
||||
window.message.success({
|
||||
content: t('assistants.save.success'),
|
||||
key: 'save-to-agent'
|
||||
})
|
||||
}
|
||||
},
|
||||
{ type: 'divider' },
|
||||
{
|
||||
label: t('common.delete'),
|
||||
key: 'delete',
|
||||
icon: <DeleteOutlined />,
|
||||
danger: true,
|
||||
onClick: () => onDelete(assistant)
|
||||
onClick: () => {
|
||||
window.modal.confirm({
|
||||
title: t('assistants.delete.title'),
|
||||
content: t('assistants.delete.content'),
|
||||
centered: true,
|
||||
okButtonProps: { danger: true },
|
||||
onOk: () => onDelete(assistant)
|
||||
})
|
||||
}
|
||||
}
|
||||
] as ItemType[],
|
||||
[addAssistant, onDelete, removeAllTopics, setActiveAssistant, t]
|
||||
[addAgent, addAssistant, onDelete, removeAllTopics, setActiveAssistant, t]
|
||||
)
|
||||
|
||||
const onSwitchAssistant = useCallback(
|
||||
@@ -161,7 +186,7 @@ const Assistants: FC<Props> = ({
|
||||
suffix={<CommandKey>⌘+K</CommandKey>}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
style={{ borderRadius: 4, borderWidth: 0.5 }}
|
||||
style={{ borderRadius: 16, borderWidth: 0.5 }}
|
||||
onKeyDown={onSearch}
|
||||
ref={searchRef}
|
||||
onFocus={() => dispatch(setSearching(true))}
|
||||
@@ -6,6 +6,7 @@ import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { SettingDivider, SettingRow, SettingRowTitle, SettingSubtitle } from '@renderer/pages/settings'
|
||||
import { useAppDispatch } from '@renderer/store'
|
||||
import {
|
||||
setCodeShowLineNumbers,
|
||||
setFontSize,
|
||||
setMessageFont,
|
||||
setPasteLongTextAsFile,
|
||||
@@ -43,17 +44,12 @@ const SettingsTab: FC<Props> = (props) => {
|
||||
sendMessageShortcut,
|
||||
setSendMessageShortcut,
|
||||
pasteLongTextAsFile,
|
||||
renderInputMessageAsMarkdown
|
||||
renderInputMessageAsMarkdown,
|
||||
codeShowLineNumbers
|
||||
} = useSettings()
|
||||
|
||||
const onUpdateAssistantSettings = (settings: Partial<AssistantSettings>) => {
|
||||
updateAssistantSettings({
|
||||
temperature: settings.temperature ?? temperature,
|
||||
contextCount: settings.contextCount ?? contextCount,
|
||||
enableMaxTokens: settings.enableMaxTokens ?? enableMaxTokens,
|
||||
maxTokens: settings.maxTokens ?? maxTokens,
|
||||
streamOutput: settings.streamOutput ?? streamOutput
|
||||
})
|
||||
updateAssistantSettings(settings)
|
||||
}
|
||||
|
||||
const onTemperatureChange = (value) => {
|
||||
@@ -85,7 +81,9 @@ const SettingsTab: FC<Props> = (props) => {
|
||||
contextCount: DEFAULT_CONEXTCOUNT,
|
||||
enableMaxTokens: false,
|
||||
maxTokens: DEFAULT_MAX_TOKENS,
|
||||
streamOutput: true
|
||||
streamOutput: true,
|
||||
hideMessages: false,
|
||||
autoResetModel: false
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -204,6 +202,15 @@ const SettingsTab: FC<Props> = (props) => {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitleSmall>{t('chat.settings.show_line_numbers')}</SettingRowTitleSmall>
|
||||
<Switch
|
||||
size="small"
|
||||
checked={codeShowLineNumbers}
|
||||
onChange={(checked) => dispatch(setCodeShowLineNumbers(checked))}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitleSmall>{t('settings.font_size.title')}</SettingRowTitleSmall>
|
||||
</SettingRow>
|
||||
@@ -214,12 +221,12 @@ const SettingsTab: FC<Props> = (props) => {
|
||||
onChange={(value) => setFontSizeValue(value)}
|
||||
onChangeComplete={(value) => dispatch(setFontSize(value))}
|
||||
min={12}
|
||||
max={18}
|
||||
max={22}
|
||||
step={1}
|
||||
marks={{
|
||||
12: <span style={{ fontSize: '12px' }}>A</span>,
|
||||
14: <span style={{ fontSize: '14px' }}>{t('common.default')}</span>,
|
||||
18: <span style={{ fontSize: '18px' }}>A</span>
|
||||
22: <span style={{ fontSize: '18px' }}>A</span>
|
||||
}}
|
||||
/>
|
||||
</Col>
|
||||
@@ -274,7 +281,6 @@ const Container = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding-bottom: 10px;
|
||||
padding: 10px 15px;
|
||||
`
|
||||
@@ -1,13 +1,24 @@
|
||||
import { CloseOutlined, DeleteOutlined, EditOutlined, FolderOutlined, UploadOutlined } from '@ant-design/icons'
|
||||
import {
|
||||
ClearOutlined,
|
||||
CloseOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
FolderOutlined,
|
||||
UploadOutlined
|
||||
} from '@ant-design/icons'
|
||||
import DragableList from '@renderer/components/DragableList'
|
||||
import PromptPopup from '@renderer/components/Popups/PromptPopup'
|
||||
import { useAssistant, useAssistants } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { TopicManager } from '@renderer/hooks/useTopic'
|
||||
import { fetchMessagesSummary } from '@renderer/services/api'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { useAppSelector } from '@renderer/store'
|
||||
import store, { useAppSelector } from '@renderer/store'
|
||||
import { setGenerating } from '@renderer/store/runtime'
|
||||
import { Assistant, Topic } from '@renderer/types'
|
||||
import { exportTopicAsMarkdown } from '@renderer/utils/export'
|
||||
import { Dropdown, MenuProps } from 'antd'
|
||||
import dayjs from 'dayjs'
|
||||
import { findIndex } from 'lodash'
|
||||
import { FC, useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
@@ -24,6 +35,9 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
const { assistant, removeTopic, moveTopic, updateTopic, updateTopics } = useAssistant(_assistant.id)
|
||||
const { t } = useTranslation()
|
||||
const generating = useAppSelector((state) => state.runtime.generating)
|
||||
const { showTopicTime } = useSettings()
|
||||
|
||||
const borderRadius = showTopicTime ? 12 : 17
|
||||
|
||||
const onDeleteTopic = useCallback(
|
||||
(topic: Topic) => {
|
||||
@@ -31,11 +45,9 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
window.message.warning({ content: t('message.switch.disabled'), key: 'generating' })
|
||||
return
|
||||
}
|
||||
if (assistant.topics.length > 1) {
|
||||
const index = findIndex(assistant.topics, (t) => t.id === topic.id)
|
||||
setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? 0 : index + 1])
|
||||
removeTopic(topic)
|
||||
}
|
||||
const index = findIndex(assistant.topics, (t) => t.id === topic.id)
|
||||
setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? 0 : index + 1])
|
||||
removeTopic(topic)
|
||||
},
|
||||
[assistant.topics, generating, removeTopic, setActiveTopic, t]
|
||||
)
|
||||
@@ -64,6 +76,12 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
[generating, setActiveTopic, t]
|
||||
)
|
||||
|
||||
const onClearMessages = useCallback(() => {
|
||||
window.keyv.set(EVENT_NAMES.CHAT_COMPLETION_PAUSED, true)
|
||||
store.dispatch(setGenerating(false))
|
||||
EventEmitter.emit(EVENT_NAMES.CLEAR_MESSAGES)
|
||||
}, [])
|
||||
|
||||
const getTopicMenuItems = useCallback(
|
||||
(topic: Topic) => {
|
||||
const menus: MenuProps['items'] = [
|
||||
@@ -96,6 +114,18 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
label: t('chat.topics.clear.title'),
|
||||
key: 'clear-messages',
|
||||
icon: <ClearOutlined />,
|
||||
async onClick() {
|
||||
window.modal.confirm({
|
||||
title: t('chat.input.clear.content'),
|
||||
centered: true,
|
||||
onOk: onClearMessages
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
label: t('chat.topics.export.title'),
|
||||
key: 'export',
|
||||
@@ -105,6 +135,11 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
label: t('chat.topics.export.image'),
|
||||
key: 'image',
|
||||
onClick: () => EventEmitter.emit(EVENT_NAMES.EXPORT_TOPIC_IMAGE, topic)
|
||||
},
|
||||
{
|
||||
label: t('chat.topics.export.md'),
|
||||
key: 'markdown',
|
||||
onClick: () => exportTopicAsMarkdown(topic)
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -138,7 +173,7 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
|
||||
return menus
|
||||
},
|
||||
[assistant, assistants, onDeleteTopic, onMoveTopic, t, updateTopic]
|
||||
[assistant, assistants, onClearMessages, onDeleteTopic, onMoveTopic, t, updateTopic]
|
||||
)
|
||||
|
||||
return (
|
||||
@@ -148,13 +183,20 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
const isActive = topic.id === activeTopic?.id
|
||||
return (
|
||||
<Dropdown menu={{ items: getTopicMenuItems(topic) }} trigger={['contextMenu']} key={topic.id}>
|
||||
<TopicListItem className={isActive ? 'active' : ''} onClick={() => onSwitchTopic(topic)}>
|
||||
<TopicListItem
|
||||
className={isActive ? 'active' : ''}
|
||||
style={{ borderRadius }}
|
||||
onClick={() => onSwitchTopic(topic)}>
|
||||
<TopicName className="name">{topic.name.replace('`', '')}</TopicName>
|
||||
{assistant.topics.length > 1 && isActive && (
|
||||
{showTopicTime && <TopicTime>{dayjs(topic.createdAt).format('MM/DD HH:mm')}</TopicTime>}
|
||||
{isActive && (
|
||||
<MenuButton
|
||||
className="menu"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (assistant.topics.length === 1) {
|
||||
return onClearMessages()
|
||||
}
|
||||
onDeleteTopic(topic)
|
||||
}}>
|
||||
<CloseOutlined />
|
||||
@@ -165,20 +207,16 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
)
|
||||
}}
|
||||
</DragableList>
|
||||
<div style={{ minHeight: '10px' }}></div>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
padding-top: 10px;
|
||||
overflow-y: scroll;
|
||||
max-height: calc(100vh - var(--navbar-height) - 70px);
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
`
|
||||
|
||||
const TopicListItem = styled.div`
|
||||
@@ -188,9 +226,8 @@ const TopicListItem = styled.div`
|
||||
font-family: Ubuntu;
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
font-family: Ubuntu;
|
||||
cursor: pointer;
|
||||
@@ -225,7 +262,11 @@ const TopicName = styled.div`
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
font-size: 13px;
|
||||
opacity: 0.6;
|
||||
`
|
||||
|
||||
const TopicTime = styled.div`
|
||||
color: var(--color-text-3);
|
||||
font-size: 11px;
|
||||
`
|
||||
|
||||
const MenuButton = styled.div`
|
||||
@@ -27,7 +27,7 @@ type Tab = 'assistants' | 'topic' | 'settings'
|
||||
|
||||
let _tab: any = ''
|
||||
|
||||
const RightSidebar: FC<Props> = ({ activeAssistant, activeTopic, setActiveAssistant, setActiveTopic, position }) => {
|
||||
const HomeTabs: FC<Props> = ({ activeAssistant, activeTopic, setActiveAssistant, setActiveTopic, position }) => {
|
||||
const { addAssistant } = useAssistants()
|
||||
const [tab, setTab] = useState<Tab>(position === 'left' ? _tab || 'assistants' : 'topic')
|
||||
const { topicPosition } = useSettings()
|
||||
@@ -164,4 +164,4 @@ const TabContent = styled.div`
|
||||
overflow-x: hidden;
|
||||
`
|
||||
|
||||
export default RightSidebar
|
||||
export default HomeTabs
|
||||
@@ -1,17 +1,15 @@
|
||||
import ModelAvatar from '@renderer/components/Avatar/ModelAvatar'
|
||||
import VisionIcon from '@renderer/components/Icons/VisionIcon'
|
||||
import SelectModelPopup from '@renderer/components/Popups/SelectModelPopup'
|
||||
import { isLocalAi } from '@renderer/config/env'
|
||||
import { isVisionModel } from '@renderer/config/models'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import { Button } from 'antd'
|
||||
import { upperFirst } from 'lodash'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import SelectModelDropdown from './SelectModelDropdown'
|
||||
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
}
|
||||
@@ -24,14 +22,20 @@ const SelectModelButton: FC<Props> = ({ assistant }) => {
|
||||
return null
|
||||
}
|
||||
|
||||
const onSelectModel = async (event: React.MouseEvent<HTMLElement>) => {
|
||||
event.currentTarget.blur()
|
||||
const selectedModel = await SelectModelPopup.show({ model })
|
||||
if (selectedModel) {
|
||||
setModel(selectedModel)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SelectModelDropdown model={model} onSelect={setModel} placement="top">
|
||||
<DropdownButton size="small" type="default">
|
||||
<ModelAvatar model={model} size={20} />
|
||||
<ModelName>{model ? upperFirst(model.name) : t('button.select_model')}</ModelName>
|
||||
{isVisionModel(model) && <VisionIcon style={{ marginLeft: 0 }} />}
|
||||
</DropdownButton>
|
||||
</SelectModelDropdown>
|
||||
<DropdownButton size="small" type="default" onClick={onSelectModel}>
|
||||
<ModelAvatar model={model} size={20} />
|
||||
<ModelName>{model ? model.name : t('button.select_model')}</ModelName>
|
||||
{isVisionModel(model) && <VisionIcon style={{ marginLeft: 0 }} />}
|
||||
</DropdownButton>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -39,6 +43,7 @@ const DropdownButton = styled(Button)`
|
||||
font-size: 11px;
|
||||
border-radius: 15px;
|
||||
padding: 12px 8px 12px 3px;
|
||||
-webkit-app-region: none;
|
||||
`
|
||||
|
||||
const ModelName = styled.span`
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
import VisionIcon from '@renderer/components/Icons/VisionIcon'
|
||||
import { getModelLogo, isVisionModel } from '@renderer/config/models'
|
||||
import { useProviders } from '@renderer/hooks/useProvider'
|
||||
import { getModelUniqId } from '@renderer/services/model'
|
||||
import { Model } from '@renderer/types'
|
||||
import { Avatar, Dropdown, DropdownProps, MenuProps } from 'antd'
|
||||
import { first, reverse, sortBy, upperFirst } from 'lodash'
|
||||
import { FC, PropsWithChildren } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
interface Props extends DropdownProps {
|
||||
model?: Model
|
||||
onSelect: (model: Model) => void
|
||||
}
|
||||
|
||||
const SelectModelDropdown: FC<Props & PropsWithChildren> = ({ children, model, onSelect, ...props }) => {
|
||||
const { t } = useTranslation()
|
||||
const { providers } = useProviders()
|
||||
|
||||
const items: MenuProps['items'] = (providers || [])
|
||||
.filter((p) => p.models && p.models.length > 0)
|
||||
.map((p) => ({
|
||||
key: p.id,
|
||||
label: p.isSystem ? t(`provider.${p.id}`) : p.name,
|
||||
type: 'group',
|
||||
children: reverse(sortBy(p.models, 'name')).map((m) => ({
|
||||
key: getModelUniqId(m),
|
||||
label: (
|
||||
<div>
|
||||
{upperFirst(m?.name)} {isVisionModel(m) && <VisionIcon />}
|
||||
</div>
|
||||
),
|
||||
icon: (
|
||||
<Avatar src={getModelLogo(m?.id || '')} size={24}>
|
||||
{first(m?.name)}
|
||||
</Avatar>
|
||||
),
|
||||
onClick: () => m && onSelect(m)
|
||||
}))
|
||||
}))
|
||||
|
||||
return (
|
||||
<DropdownMenu
|
||||
menu={{
|
||||
items,
|
||||
style: { maxHeight: '55vh', overflow: 'auto' },
|
||||
selectedKeys: model ? [getModelUniqId(model)] : []
|
||||
}}
|
||||
trigger={['click']}
|
||||
arrow
|
||||
placement="bottom"
|
||||
overlayClassName="chat-nav-dropdown"
|
||||
{...props}>
|
||||
{children}
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
const DropdownMenu = styled(Dropdown)`
|
||||
-webkit-app-region: none;
|
||||
`
|
||||
|
||||
export default SelectModelDropdown
|
||||
@@ -3,8 +3,11 @@ import { FileProtectOutlined, GlobalOutlined, MailOutlined, SoundOutlined } from
|
||||
import { HStack } from '@renderer/components/Layout'
|
||||
import MinApp from '@renderer/components/MinApp'
|
||||
import { APP_NAME, AppLogo } from '@renderer/config/env'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { useAppDispatch } from '@renderer/store'
|
||||
import { setManualUpdateCheck } from '@renderer/store/settings'
|
||||
import { runAsyncFunction } from '@renderer/utils'
|
||||
import { Avatar, Button, Progress, Row, Tag } from 'antd'
|
||||
import { Avatar, Button, Progress, Row, Switch, Tag } from 'antd'
|
||||
import { ProgressInfo } from 'electron-updater'
|
||||
import { debounce } from 'lodash'
|
||||
import { FC, useEffect, useState } from 'react'
|
||||
@@ -20,6 +23,8 @@ const AboutSettings: FC = () => {
|
||||
const [percent, setPercent] = useState(0)
|
||||
const [checkUpdateLoading, setCheckUpdateLoading] = useState(false)
|
||||
const [downloading, setDownloading] = useState(false)
|
||||
const { manualUpdateCheck } = useSettings()
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
const onCheckUpdate = debounce(
|
||||
async () => {
|
||||
@@ -29,7 +34,7 @@ const AboutSettings: FC = () => {
|
||||
try {
|
||||
await window.api.checkForUpdate()
|
||||
} catch (error) {
|
||||
setCheckUpdateLoading(false)
|
||||
window.message.error(t('settings.about.updateError'))
|
||||
}
|
||||
|
||||
setCheckUpdateLoading(false)
|
||||
@@ -51,10 +56,11 @@ const AboutSettings: FC = () => {
|
||||
onOpenWebsite(url)
|
||||
}
|
||||
|
||||
const showLicense = () => {
|
||||
const showLicense = async () => {
|
||||
const { appPath } = await window.api.getAppInfo()
|
||||
MinApp.start({
|
||||
name: t('settings.about.releases.title'),
|
||||
url: 'https://raw.githubusercontent.com/kangfenmao/cherry-studio/main/LICENSE',
|
||||
name: t('settings.about.license.title'),
|
||||
url: `file://${appPath}/resources/cherry-studio/license.html`,
|
||||
logo: AppLogo
|
||||
})
|
||||
}
|
||||
@@ -139,6 +145,11 @@ const AboutSettings: FC = () => {
|
||||
</CheckUpdateButton>
|
||||
</AboutHeader>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.manually_check_update.title')}</SettingRowTitle>
|
||||
<Switch value={manualUpdateCheck} onChange={(v) => dispatch(setManualUpdateCheck(v))} />
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>
|
||||
<SoundOutlined />
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { FolderOpenOutlined, SaveOutlined } from '@ant-design/icons'
|
||||
import { HStack, VStack } from '@renderer/components/Layout'
|
||||
import { backup, reset, restore } from '@renderer/services/backup'
|
||||
import { Button } from 'antd'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link, Route, Routes } from 'react-router-dom'
|
||||
|
||||
import { SettingContainer, SettingDivider, SettingRow, SettingRowTitle, SettingTitle } from '..'
|
||||
import WebDavSettings from './WebDavSettings'
|
||||
|
||||
const DataSettings: FC = () => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<SettingContainer>
|
||||
<SettingTitle>{t('settings.data')}</SettingTitle>
|
||||
<SettingDivider />
|
||||
<SettingRow style={{ minHeight: 32 }}>
|
||||
<SettingRowTitle>{t('settings.data.webdav.title')}</SettingRowTitle>
|
||||
<VStack gap="5px">
|
||||
<Link to="/settings/data/webdav" style={{ color: 'var(--color-text-2)' }}>
|
||||
<Button>{t('settings.general.view_webdav_settings')}</Button>
|
||||
</Link>
|
||||
</VStack>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.backup.title')}</SettingRowTitle>
|
||||
<HStack gap="5px" justifyContent="space-between">
|
||||
<Button onClick={backup} icon={<SaveOutlined />}>
|
||||
{t('settings.general.backup.button')}
|
||||
</Button>
|
||||
<Button onClick={restore} icon={<FolderOpenOutlined />}>
|
||||
{t('settings.general.restore.button')}
|
||||
</Button>
|
||||
</HStack>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.reset.title')}</SettingRowTitle>
|
||||
<HStack gap="5px">
|
||||
<Button onClick={reset} danger>
|
||||
{t('settings.general.reset.button')}
|
||||
</Button>
|
||||
</HStack>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
</SettingContainer>
|
||||
}
|
||||
/>
|
||||
<Route path="webdav" element={<WebDavSettings />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
export default DataSettings
|
||||
@@ -62,20 +62,20 @@ const WebDavSettings: FC = () => {
|
||||
<Breadcrumb
|
||||
items={[
|
||||
{
|
||||
title: t('settings.general.title'),
|
||||
href: '#/settings/general'
|
||||
title: t('settings.data'),
|
||||
href: '#/settings/data'
|
||||
},
|
||||
{
|
||||
title: t('settings.general.webdav.title')
|
||||
title: t('settings.data.webdav.title')
|
||||
}
|
||||
]}
|
||||
/>
|
||||
<SettingTitle style={{ marginTop: 20 }}>{t('settings.general.webdav.title')}</SettingTitle>
|
||||
<SettingTitle style={{ marginTop: 20 }}>{t('settings.data.webdav.title')}</SettingTitle>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.webdav.host')}</SettingRowTitle>
|
||||
<SettingRowTitle>{t('settings.data.webdav.host')}</SettingRowTitle>
|
||||
<Input
|
||||
placeholder={t('settings.general.webdav.host.placeholder')}
|
||||
placeholder={t('settings.data.webdav.host.placeholder')}
|
||||
value={webdavHost}
|
||||
onChange={(e) => setWebdavHost(e.target.value)}
|
||||
style={{ width: 250 }}
|
||||
@@ -85,9 +85,9 @@ const WebDavSettings: FC = () => {
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.webdav.user')}</SettingRowTitle>
|
||||
<SettingRowTitle>{t('settings.data.webdav.user')}</SettingRowTitle>
|
||||
<Input
|
||||
placeholder={t('settings.general.webdav.user')}
|
||||
placeholder={t('settings.data.webdav.user')}
|
||||
value={webdavUser}
|
||||
onChange={(e) => setWebdavUser(e.target.value)}
|
||||
style={{ width: 250 }}
|
||||
@@ -96,9 +96,9 @@ const WebDavSettings: FC = () => {
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.webdav.password')}</SettingRowTitle>
|
||||
<SettingRowTitle>{t('settings.data.webdav.password')}</SettingRowTitle>
|
||||
<Input.Password
|
||||
placeholder={t('settings.general.webdav.password')}
|
||||
placeholder={t('settings.data.webdav.password')}
|
||||
value={webdavPass}
|
||||
onChange={(e) => setWebdavPass(e.target.value)}
|
||||
style={{ width: 250 }}
|
||||
@@ -107,9 +107,9 @@ const WebDavSettings: FC = () => {
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.webdav.path')}</SettingRowTitle>
|
||||
<SettingRowTitle>{t('settings.data.webdav.path')}</SettingRowTitle>
|
||||
<Input
|
||||
placeholder={t('settings.general.webdav.path.placeholder')}
|
||||
placeholder={t('settings.data.webdav.path.placeholder')}
|
||||
value={webdavPath}
|
||||
onChange={(e) => setWebdavPath(e.target.value)}
|
||||
style={{ width: 250 }}
|
||||
@@ -122,10 +122,10 @@ const WebDavSettings: FC = () => {
|
||||
<HStack gap="5px" justifyContent="space-between">
|
||||
{/* 添加 在线备份 在线还原 按钮 */}
|
||||
<Button onClick={onBackup} icon={<SaveOutlined />} loading={backuping}>
|
||||
{t('settings.general.webdav.backup.button')}
|
||||
{t('settings.data.webdav.backup.button')}
|
||||
</Button>
|
||||
<Button onClick={onRestore} icon={<FolderOpenOutlined />} loading={restoring}>
|
||||
{t('settings.general.webdav.restore.button')}
|
||||
{t('settings.data.webdav.restore.button')}
|
||||
</Button>
|
||||
</HStack>
|
||||
</SettingRow>
|
||||
144
src/renderer/src/pages/settings/GeneralSettings.tsx
Normal file
144
src/renderer/src/pages/settings/GeneralSettings.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import { isMac } from '@renderer/config/constant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import i18n from '@renderer/i18n'
|
||||
import { useAppDispatch } from '@renderer/store'
|
||||
import { setClickAssistantToShowTopic, setLanguage, setShowTopicTime } from '@renderer/store/settings'
|
||||
import { setProxyUrl as _setProxyUrl } from '@renderer/store/settings'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
import { isValidProxyUrl } from '@renderer/utils'
|
||||
import { Input, Select, Switch } from 'antd'
|
||||
import { FC, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { SettingContainer, SettingDivider, SettingRow, SettingRowTitle, SettingTitle } from '.'
|
||||
|
||||
const GeneralSettings: FC = () => {
|
||||
const {
|
||||
language,
|
||||
proxyUrl: storeProxyUrl,
|
||||
theme,
|
||||
windowStyle,
|
||||
topicPosition,
|
||||
showTopicTime,
|
||||
clickAssistantToShowTopic,
|
||||
setTheme,
|
||||
setWindowStyle,
|
||||
setTopicPosition
|
||||
} = useSettings()
|
||||
const [proxyUrl, setProxyUrl] = useState<string | undefined>(storeProxyUrl)
|
||||
|
||||
const dispatch = useAppDispatch()
|
||||
const { t } = useTranslation()
|
||||
|
||||
const onSelectLanguage = (value: string) => {
|
||||
dispatch(setLanguage(value))
|
||||
localStorage.setItem('language', value)
|
||||
i18n.changeLanguage(value)
|
||||
}
|
||||
|
||||
const onSetProxyUrl = () => {
|
||||
if (proxyUrl && !isValidProxyUrl(proxyUrl)) {
|
||||
window.message.error({ content: t('message.error.invalid.proxy.url'), key: 'proxy-error' })
|
||||
return
|
||||
}
|
||||
|
||||
dispatch(_setProxyUrl(proxyUrl))
|
||||
window.api.setProxy(proxyUrl)
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingContainer>
|
||||
<SettingTitle>{t('settings.general.title')}</SettingTitle>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('common.language')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={language || 'en-US'}
|
||||
style={{ width: 180 }}
|
||||
onChange={onSelectLanguage}
|
||||
options={[
|
||||
{ value: 'zh-CN', label: '中文' },
|
||||
{ value: 'zh-TW', label: '中文(繁体)' },
|
||||
{ value: 'en-US', label: 'English' }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.theme.title')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={theme}
|
||||
style={{ width: 180 }}
|
||||
onChange={setTheme}
|
||||
options={[
|
||||
{ value: ThemeMode.light, label: t('settings.theme.light') },
|
||||
{ value: ThemeMode.dark, label: t('settings.theme.dark') },
|
||||
{ value: ThemeMode.auto, label: t('settings.theme.auto') }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
{isMac && (
|
||||
<>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.theme.window.style.title')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={windowStyle || 'opaque'}
|
||||
style={{ width: 180 }}
|
||||
onChange={setWindowStyle}
|
||||
options={[
|
||||
{ value: 'transparent', label: t('settings.theme.window.style.transparent') },
|
||||
{ value: 'opaque', label: t('settings.theme.window.style.opaque') }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
</>
|
||||
)}
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.proxy.title')}</SettingRowTitle>
|
||||
<Input
|
||||
placeholder="socks5://127.0.0.1:6153"
|
||||
value={proxyUrl}
|
||||
onChange={(e) => setProxyUrl(e.target.value)}
|
||||
style={{ width: 180 }}
|
||||
onBlur={() => onSetProxyUrl()}
|
||||
type="url"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.topic.position')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={topicPosition || 'right'}
|
||||
style={{ width: 180 }}
|
||||
onChange={setTopicPosition}
|
||||
options={[
|
||||
{ value: 'left', label: t('settings.topic.position.left') },
|
||||
{ value: 'right', label: t('settings.topic.position.right') }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
{topicPosition === 'left' && (
|
||||
<>
|
||||
<SettingRow style={{ minHeight: 32 }}>
|
||||
<SettingRowTitle>{t('settings.advanced.click_assistant_switch_to_topics')}</SettingRowTitle>
|
||||
<Switch
|
||||
checked={clickAssistantToShowTopic}
|
||||
onChange={(checked) => dispatch(setClickAssistantToShowTopic(checked))}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
</>
|
||||
)}
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.topic.show.time')}</SettingRowTitle>
|
||||
<Switch checked={showTopicTime} onChange={(checked) => dispatch(setShowTopicTime(checked))} />
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
</SettingContainer>
|
||||
)
|
||||
}
|
||||
|
||||
export default GeneralSettings
|
||||
@@ -1,195 +0,0 @@
|
||||
import { FolderOpenOutlined, SaveOutlined } from '@ant-design/icons'
|
||||
import { HStack, VStack } from '@renderer/components/Layout'
|
||||
import { isMac } from '@renderer/config/constant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import i18n from '@renderer/i18n'
|
||||
import { backup, reset, restore } from '@renderer/services/backup'
|
||||
import { useAppDispatch } from '@renderer/store'
|
||||
import { setClickAssistantToShowTopic, setLanguage, setManualUpdateCheck } from '@renderer/store/settings'
|
||||
import { setProxyUrl as _setProxyUrl } from '@renderer/store/settings'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
import { isValidProxyUrl } from '@renderer/utils'
|
||||
import { Button, Input, Select, Switch } from 'antd'
|
||||
import { FC, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link, Route, Routes } from 'react-router-dom'
|
||||
|
||||
import { SettingContainer, SettingDivider, SettingRow, SettingRowTitle, SettingTitle } from '..'
|
||||
import WebDavSettings from './WebDavSettings'
|
||||
|
||||
const GeneralSettings: FC = () => {
|
||||
const {
|
||||
language,
|
||||
proxyUrl: storeProxyUrl,
|
||||
theme,
|
||||
windowStyle,
|
||||
topicPosition,
|
||||
clickAssistantToShowTopic,
|
||||
manualUpdateCheck,
|
||||
setTheme,
|
||||
setWindowStyle,
|
||||
setTopicPosition
|
||||
} = useSettings()
|
||||
const [proxyUrl, setProxyUrl] = useState<string | undefined>(storeProxyUrl)
|
||||
|
||||
const dispatch = useAppDispatch()
|
||||
const { t } = useTranslation()
|
||||
|
||||
const onSelectLanguage = (value: string) => {
|
||||
dispatch(setLanguage(value))
|
||||
localStorage.setItem('language', value)
|
||||
i18n.changeLanguage(value)
|
||||
}
|
||||
|
||||
const onSetProxyUrl = () => {
|
||||
if (proxyUrl && !isValidProxyUrl(proxyUrl)) {
|
||||
window.message.error({ content: t('message.error.invalid.proxy.url'), key: 'proxy-error' })
|
||||
return
|
||||
}
|
||||
|
||||
dispatch(_setProxyUrl(proxyUrl))
|
||||
window.api.setProxy(proxyUrl)
|
||||
}
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<SettingContainer>
|
||||
<SettingTitle>{t('settings.general.title')}</SettingTitle>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('common.language')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={language || 'en-US'}
|
||||
style={{ width: 180 }}
|
||||
onChange={onSelectLanguage}
|
||||
options={[
|
||||
{ value: 'zh-CN', label: '中文' },
|
||||
{ value: 'zh-TW', label: '中文(繁体)' },
|
||||
{ value: 'en-US', label: 'English' }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.theme.title')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={theme}
|
||||
style={{ width: 180 }}
|
||||
onChange={setTheme}
|
||||
options={[
|
||||
{ value: ThemeMode.light, label: t('settings.theme.light') },
|
||||
{ value: ThemeMode.dark, label: t('settings.theme.dark') },
|
||||
{ value: ThemeMode.auto, label: t('settings.theme.auto') }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
{isMac && (
|
||||
<>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.theme.window.style.title')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={windowStyle || 'opaque'}
|
||||
style={{ width: 180 }}
|
||||
onChange={setWindowStyle}
|
||||
options={[
|
||||
{ value: 'transparent', label: t('settings.theme.window.style.transparent') },
|
||||
{ value: 'opaque', label: t('settings.theme.window.style.opaque') }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
</>
|
||||
)}
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.topic.position')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={topicPosition || 'right'}
|
||||
style={{ width: 180 }}
|
||||
onChange={setTopicPosition}
|
||||
options={[
|
||||
{ value: 'left', label: t('settings.topic.position.left') },
|
||||
{ value: 'right', label: t('settings.topic.position.right') }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
{topicPosition === 'left' && (
|
||||
<>
|
||||
<SettingRow style={{ minHeight: 32 }}>
|
||||
<SettingRowTitle>{t('settings.advanced.click_assistant_switch_to_topics')}</SettingRowTitle>
|
||||
<Switch
|
||||
checked={clickAssistantToShowTopic}
|
||||
onChange={(checked) => dispatch(setClickAssistantToShowTopic(checked))}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
</>
|
||||
)}
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.check_update_setting')}</SettingRowTitle>
|
||||
<Select
|
||||
defaultValue={manualUpdateCheck ?? false}
|
||||
style={{ width: 180 }}
|
||||
onChange={(v) => dispatch(setManualUpdateCheck(v))}
|
||||
options={[
|
||||
{ value: false, label: t('settings.general.auto_update_check') },
|
||||
{ value: true, label: t('settings.general.manual_update_check') }
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.proxy.title')}</SettingRowTitle>
|
||||
<Input
|
||||
placeholder="socks5://127.0.0.1:6153"
|
||||
value={proxyUrl}
|
||||
onChange={(e) => setProxyUrl(e.target.value)}
|
||||
style={{ width: 180 }}
|
||||
onBlur={() => onSetProxyUrl()}
|
||||
type="url"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow style={{ minHeight: 32 }}>
|
||||
<SettingRowTitle>{t('settings.general.webdav.title')}</SettingRowTitle>
|
||||
<VStack gap="5px">
|
||||
<Link to="/settings/general/webdav" style={{ color: 'var(--color-text-2)' }}>
|
||||
{t('settings.general.view_webdav_settings')}
|
||||
</Link>
|
||||
</VStack>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.backup.title')}</SettingRowTitle>
|
||||
<HStack gap="5px" justifyContent="space-between">
|
||||
<Button onClick={backup} icon={<SaveOutlined />}>
|
||||
{t('settings.general.backup.button')}
|
||||
</Button>
|
||||
<Button onClick={restore} icon={<FolderOpenOutlined />}>
|
||||
{t('settings.general.restore.button')}
|
||||
</Button>
|
||||
</HStack>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.general.reset.title')}</SettingRowTitle>
|
||||
<HStack gap="5px">
|
||||
<Button onClick={reset} danger>
|
||||
{t('settings.general.reset.button')}
|
||||
</Button>
|
||||
</HStack>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
</SettingContainer>
|
||||
}
|
||||
/>
|
||||
<Route path="webdav" element={<WebDavSettings />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
export default GeneralSettings
|
||||
@@ -4,7 +4,7 @@ import { useProviders } from '@renderer/hooks/useProvider'
|
||||
import { getModelUniqId, hasModel } from '@renderer/services/model'
|
||||
import { Model } from '@renderer/types'
|
||||
import { Select } from 'antd'
|
||||
import { find, sortBy, upperFirst } from 'lodash'
|
||||
import { find, sortBy } from 'lodash'
|
||||
import { FC, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
@@ -23,7 +23,7 @@ const ModelSettings: FC = () => {
|
||||
label: p.isSystem ? t(`provider.${p.id}`) : p.name,
|
||||
title: p.name,
|
||||
options: sortBy(p.models, 'name').map((m) => ({
|
||||
label: upperFirst(m.name),
|
||||
label: m.name,
|
||||
value: getModelUniqId(m)
|
||||
}))
|
||||
}))
|
||||
|
||||
@@ -11,6 +11,7 @@ import { getModelLogo, isVisionModel } from '@renderer/config/models'
|
||||
import { PROVIDER_CONFIG } from '@renderer/config/providers'
|
||||
import { useTheme } from '@renderer/context/ThemeProvider'
|
||||
import { useProvider } from '@renderer/hooks/useProvider'
|
||||
import { isOpenAIProvider } from '@renderer/providers/ProviderFactory'
|
||||
import { checkApi } from '@renderer/services/api'
|
||||
import { Provider } from '@renderer/types'
|
||||
import { Avatar, Button, Card, Divider, Flex, Input, Space, Switch } from 'antd'
|
||||
@@ -81,6 +82,8 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
|
||||
updateProvider({ ...provider, apiHost: configedApiHost })
|
||||
}
|
||||
|
||||
const hostPreview = (apiHost.endsWith('/') ? apiHost : `${apiHost}/v1/`) + 'chat/completions'
|
||||
|
||||
return (
|
||||
<SettingContainer
|
||||
style={
|
||||
@@ -138,6 +141,12 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
|
||||
<Button onClick={onReset}>{t('settings.provider.api.url.reset')}</Button>
|
||||
)}
|
||||
</Space.Compact>
|
||||
{isOpenAIProvider(provider) && (
|
||||
<SettingHelpTextRow style={{ justifyContent: 'space-between' }}>
|
||||
<SettingHelpText style={{ marginLeft: 6 }}>{hostPreview}</SettingHelpText>
|
||||
<SettingHelpText>{t('settings.provider.api.url.tip')}</SettingHelpText>
|
||||
</SettingHelpTextRow>
|
||||
)}
|
||||
{provider.id === 'azure-openai' && (
|
||||
<>
|
||||
<SettingSubtitle>{t('settings.provider.api_version')}</SettingSubtitle>
|
||||
|
||||
@@ -116,7 +116,7 @@ const ProvidersList: FC = () => {
|
||||
{getFirstCharacter(provider.name)}
|
||||
</ProviderLogo>
|
||||
)}
|
||||
<ProviderItemName>
|
||||
<ProviderItemName className="text-nowrap">
|
||||
{provider.isSystem ? t(`provider.${provider.id}`) : provider.name}
|
||||
</ProviderItemName>
|
||||
{provider.enabled && (
|
||||
@@ -196,9 +196,6 @@ const ProviderLogo = styled(Avatar)`
|
||||
|
||||
const ProviderItemName = styled.div`
|
||||
margin-left: 10px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
font-weight: 500;
|
||||
font-family: Ubuntu;
|
||||
`
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CloudOutlined, InfoCircleOutlined, MessageOutlined, SettingOutlined } from '@ant-design/icons'
|
||||
import { CloudOutlined, InfoCircleOutlined, MessageOutlined, SaveOutlined, SettingOutlined } from '@ant-design/icons'
|
||||
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
|
||||
import { isLocalAi } from '@renderer/config/env'
|
||||
import { FC } from 'react'
|
||||
@@ -8,7 +8,8 @@ import styled from 'styled-components'
|
||||
|
||||
import AboutSettings from './AboutSettings'
|
||||
import AssistantSettings from './AssistantSettings'
|
||||
import GeneralSettings from './GeneralSettings/GeneralSettings'
|
||||
import DataSettings from './DataSettings/DataSettings'
|
||||
import GeneralSettings from './GeneralSettings'
|
||||
import ModelSettings from './ModelSettings'
|
||||
import ProvidersList from './ProviderSettings'
|
||||
|
||||
@@ -53,6 +54,12 @@ const SettingsPage: FC = () => {
|
||||
{t('settings.general')}
|
||||
</MenuItem>
|
||||
</MenuItemLink>
|
||||
<MenuItemLink to="/settings/data">
|
||||
<MenuItem className={isRoute('/settings/data')}>
|
||||
<SaveOutlined />
|
||||
{t('settings.data')}
|
||||
</MenuItem>
|
||||
</MenuItemLink>
|
||||
<MenuItemLink to="/settings/about">
|
||||
<MenuItem className={isRoute('/settings/about')}>
|
||||
<InfoCircleOutlined />
|
||||
@@ -66,6 +73,7 @@ const SettingsPage: FC = () => {
|
||||
<Route path="model" element={<ModelSettings />} />
|
||||
<Route path="assistant" element={<AssistantSettings />} />
|
||||
<Route path="general/*" element={<GeneralSettings />} />
|
||||
<Route path="data/*" element={<DataSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Routes>
|
||||
</SettingContent>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import Anthropic from '@anthropic-ai/sdk'
|
||||
import { MessageCreateParamsNonStreaming, MessageParam } from '@anthropic-ai/sdk/resources'
|
||||
import { DEFAULT_MAX_TOKENS } from '@renderer/config/constant'
|
||||
import { SUMMARIZE_PROMPT } from '@renderer/config/prompts'
|
||||
import { getAssistantSettings, getDefaultModel, getTopNamingModel } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES } from '@renderer/services/event'
|
||||
import { filterContextMessages } from '@renderer/services/messages'
|
||||
@@ -37,7 +38,7 @@ export default class AnthropicProvider extends BaseProvider {
|
||||
}
|
||||
})
|
||||
}
|
||||
if (file.type === FileTypes.TEXT) {
|
||||
if ([FileTypes.TEXT, FileTypes.DOCUMENT].includes(file.type)) {
|
||||
const fileContent = await (await window.api.file.read(file.id + file.ext)).trim()
|
||||
parts.push({
|
||||
type: 'text',
|
||||
@@ -136,22 +137,34 @@ export default class AnthropicProvider extends BaseProvider {
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string> {
|
||||
const model = getTopNamingModel() || assistant.model || getDefaultModel()
|
||||
|
||||
const userMessages = takeRight(messages, 5).map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}))
|
||||
const userMessages = takeRight(messages, 5)
|
||||
.filter((message) => !message.isPreset)
|
||||
.map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}))
|
||||
|
||||
if (first(userMessages)?.role === 'assistant') {
|
||||
userMessages.shift()
|
||||
}
|
||||
|
||||
const userMessageContent = userMessages.reduce((prev, curr) => {
|
||||
const content = curr.role === 'user' ? `User: ${curr.content}` : `Assistant: ${curr.content}`
|
||||
return prev + (prev ? '\n' : '') + content
|
||||
}, '')
|
||||
|
||||
const systemMessage = {
|
||||
role: 'system',
|
||||
content: '你是一名擅长会话的助理,你需要将用户的会话总结为 10 个字以内的标题,不要使用标点符号和其他特殊符号。'
|
||||
content: SUMMARIZE_PROMPT
|
||||
}
|
||||
|
||||
const userMessage = {
|
||||
role: 'user',
|
||||
content: userMessageContent
|
||||
}
|
||||
|
||||
const message = await this.sdk.messages.create({
|
||||
messages: userMessages as Anthropic.Messages.MessageParam[],
|
||||
messages: [userMessage] as Anthropic.Messages.MessageParam[],
|
||||
model: model.id,
|
||||
system: systemMessage.content,
|
||||
stream: false,
|
||||
@@ -165,16 +178,16 @@ export default class AnthropicProvider extends BaseProvider {
|
||||
const model = getDefaultModel()
|
||||
|
||||
const message = await this.sdk.messages.create({
|
||||
model: model.id,
|
||||
system: prompt,
|
||||
stream: false,
|
||||
max_tokens: 4096,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content
|
||||
}
|
||||
],
|
||||
model: model.id,
|
||||
system: prompt,
|
||||
stream: false,
|
||||
max_tokens: 4096
|
||||
]
|
||||
})
|
||||
|
||||
return message.content[0].type === 'text' ? message.content[0].text : ''
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Part,
|
||||
TextPart
|
||||
} from '@google/generative-ai'
|
||||
import { SUMMARIZE_PROMPT } from '@renderer/config/prompts'
|
||||
import { getAssistantSettings, getDefaultModel, getTopNamingModel } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES } from '@renderer/services/event'
|
||||
import { filterContextMessages } from '@renderer/services/messages'
|
||||
@@ -40,7 +41,7 @@ export default class GeminiProvider extends BaseProvider {
|
||||
}
|
||||
} as InlineDataPart)
|
||||
}
|
||||
if (file.type === FileTypes.TEXT) {
|
||||
if ([FileTypes.TEXT, FileTypes.DOCUMENT].includes(file.type)) {
|
||||
const fileContent = await (await window.api.file.read(file.id + file.ext)).trim()
|
||||
parts.push({
|
||||
text: file.origin_name + '\n' + fileContent
|
||||
@@ -145,14 +146,26 @@ export default class GeminiProvider extends BaseProvider {
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string> {
|
||||
const model = getTopNamingModel() || assistant.model || getDefaultModel()
|
||||
|
||||
const userMessages = takeRight(messages, 5).map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}))
|
||||
const userMessages = takeRight(messages, 5)
|
||||
.filter((message) => !message.isPreset)
|
||||
.map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}))
|
||||
|
||||
const userMessageContent = userMessages.reduce((prev, curr) => {
|
||||
const content = curr.role === 'user' ? `User: ${curr.content}` : `Assistant: ${curr.content}`
|
||||
return prev + (prev ? '\n' : '') + content
|
||||
}, '')
|
||||
|
||||
const systemMessage = {
|
||||
role: 'system',
|
||||
content: '你是一名擅长会话的助理,你需要将用户的会话总结为 10 个字以内的标题,不要使用标点符号和其他特殊符号。'
|
||||
content: SUMMARIZE_PROMPT
|
||||
}
|
||||
|
||||
const userMessage = {
|
||||
role: 'user',
|
||||
content: userMessageContent
|
||||
}
|
||||
|
||||
const geminiModel = this.sdk.getGenerativeModel({
|
||||
@@ -163,16 +176,9 @@ export default class GeminiProvider extends BaseProvider {
|
||||
}
|
||||
})
|
||||
|
||||
const lastUserMessage = userMessages.pop()
|
||||
const chat = await geminiModel.startChat()
|
||||
|
||||
const chat = await geminiModel.startChat({
|
||||
history: userMessages.map((message) => ({
|
||||
role: message.role === 'user' ? 'user' : 'model',
|
||||
parts: [{ text: message.content }]
|
||||
}))
|
||||
})
|
||||
|
||||
const { response } = await chat.sendMessage(lastUserMessage?.content!)
|
||||
const { response } = await chat.sendMessage(userMessage.content)
|
||||
|
||||
return response.text()
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { isLocalAi } from '@renderer/config/env'
|
||||
import { isSupportedModel, isVisionModel } from '@renderer/config/models'
|
||||
import { SUMMARIZE_PROMPT } from '@renderer/config/prompts'
|
||||
import { getAssistantSettings, getDefaultModel, getTopNamingModel } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES } from '@renderer/services/event'
|
||||
import { filterContextMessages } from '@renderer/services/messages'
|
||||
import { Assistant, FileTypes, Message, Model, Provider, Suggestion } from '@renderer/types'
|
||||
import { removeQuotes } from '@renderer/utils'
|
||||
import { first, takeRight } from 'lodash'
|
||||
import { takeRight } from 'lodash'
|
||||
import OpenAI, { AzureOpenAI } from 'openai'
|
||||
import {
|
||||
ChatCompletionContentPart,
|
||||
@@ -45,7 +45,7 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
}
|
||||
|
||||
private get isNotSupportFiles() {
|
||||
const providers = ['deepseek', 'baichuan', 'minimax', 'yi', 'doubao']
|
||||
const providers = ['deepseek', 'baichuan', 'minimax', 'doubao']
|
||||
return providers.includes(this.provider.id)
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
|
||||
if (this.isNotSupportFiles) {
|
||||
if (message.files) {
|
||||
const textFiles = message.files.filter((file) => file.type === FileTypes.TEXT)
|
||||
const textFiles = message.files.filter((file) => [FileTypes.TEXT, FileTypes.DOCUMENT].includes(file.type))
|
||||
|
||||
if (textFiles.length > 0) {
|
||||
let text = ''
|
||||
@@ -104,7 +104,7 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
image_url: { url: image.data }
|
||||
})
|
||||
}
|
||||
if (file.type === FileTypes.TEXT) {
|
||||
if ([FileTypes.TEXT, FileTypes.DOCUMENT].includes(file.type)) {
|
||||
const fileContent = await (await window.api.file.read(file.id + file.ext)).trim()
|
||||
parts.push({
|
||||
type: 'text',
|
||||
@@ -134,13 +134,16 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
userMessages.push(await this.getMessageParam(message, model))
|
||||
}
|
||||
|
||||
const isOpenAIo1 = model.id.includes('o1-')
|
||||
const isSupportStreamOutput = streamOutput && this.isSupportStreamOutput(model.id)
|
||||
|
||||
// @ts-ignore key is not typed
|
||||
const stream = await this.sdk.chat.completions.create({
|
||||
model: model.id,
|
||||
messages: [systemMessage, ...userMessages].filter(Boolean) as ChatCompletionMessageParam[],
|
||||
temperature: assistant?.settings?.temperature,
|
||||
messages: [isOpenAIo1 ? undefined : systemMessage, ...userMessages].filter(
|
||||
Boolean
|
||||
) as ChatCompletionMessageParam[],
|
||||
temperature: isOpenAIo1 ? 1 : assistant?.settings?.temperature,
|
||||
max_tokens: maxTokens,
|
||||
keep_alive: this.keepAliveTime,
|
||||
stream: isSupportStreamOutput
|
||||
@@ -187,23 +190,35 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string> {
|
||||
const model = getTopNamingModel() || assistant.model || getDefaultModel()
|
||||
|
||||
const userMessages = takeRight(messages, 5).map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}))
|
||||
const userMessages = takeRight(messages, 5)
|
||||
.filter((message) => !message.isPreset)
|
||||
.map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}))
|
||||
|
||||
const userMessageContent = userMessages.reduce((prev, curr) => {
|
||||
const content = curr.role === 'user' ? `User: ${curr.content}` : `Assistant: ${curr.content}`
|
||||
return prev + (prev ? '\n' : '') + content
|
||||
}, '')
|
||||
|
||||
const systemMessage = {
|
||||
role: 'system',
|
||||
content: '你是一名擅长会话的助理,你需要将用户的会话总结为 10 个字以内的标题,不要使用标点符号和其他特殊符号。'
|
||||
content: SUMMARIZE_PROMPT
|
||||
}
|
||||
|
||||
const userMessage = {
|
||||
role: 'user',
|
||||
content: userMessageContent
|
||||
}
|
||||
|
||||
// @ts-ignore key is not typed
|
||||
const response = await this.sdk.chat.completions.create({
|
||||
model: model.id,
|
||||
messages: [systemMessage, ...(isLocalAi ? [first(userMessages)] : userMessages)] as ChatCompletionMessageParam[],
|
||||
messages: [systemMessage, userMessage] as ChatCompletionMessageParam[],
|
||||
stream: false,
|
||||
max_tokens: 50,
|
||||
keep_alive: this.keepAliveTime
|
||||
keep_alive: this.keepAliveTime,
|
||||
max_tokens: 1000
|
||||
})
|
||||
|
||||
return removeQuotes(response.choices[0].message?.content?.substring(0, 50) || '')
|
||||
@@ -216,8 +231,8 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
model: model.id,
|
||||
stream: false,
|
||||
messages: [
|
||||
{ role: 'user', content },
|
||||
{ role: 'system', content: prompt }
|
||||
{ role: 'system', content: prompt },
|
||||
{ role: 'user', content }
|
||||
]
|
||||
})
|
||||
|
||||
|
||||
@@ -17,3 +17,7 @@ export default class ProviderFactory {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function isOpenAIProvider(provider: Provider) {
|
||||
return !['anthropic', 'gemini'].includes(provider.id)
|
||||
}
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { DEFAULT_CONEXTCOUNT, DEFAULT_MAX_TOKENS, DEFAULT_TEMPERATURE } from '@renderer/config/constant'
|
||||
import db from '@renderer/databases'
|
||||
import i18n from '@renderer/i18n'
|
||||
import store from '@renderer/store'
|
||||
import { updateAgent } from '@renderer/store/agents'
|
||||
import { updateAssistant } from '@renderer/store/assistants'
|
||||
import { Agent, Assistant, AssistantSettings, Model, Provider, Topic } from '@renderer/types'
|
||||
import { getLeadingEmoji, removeLeadingEmoji, uuid } from '@renderer/utils'
|
||||
import { addAssistant } from '@renderer/store/assistants'
|
||||
import { Agent, Assistant, AssistantSettings, Message, Model, Provider, Topic } from '@renderer/types'
|
||||
import { uuid } from '@renderer/utils'
|
||||
|
||||
import { estimateMessageUsage } from './tokens'
|
||||
|
||||
export function getDefaultAssistant(): Assistant {
|
||||
return {
|
||||
id: 'default',
|
||||
name: i18n.t('chat.default.name'),
|
||||
prompt: '',
|
||||
topics: [getDefaultTopic('default')]
|
||||
topics: [getDefaultTopic('default')],
|
||||
messages: [],
|
||||
type: 'assistant'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,19 +86,9 @@ export const getAssistantSettings = (assistant: Assistant): AssistantSettings =>
|
||||
temperature: assistant?.settings?.temperature ?? DEFAULT_TEMPERATURE,
|
||||
enableMaxTokens: assistant?.settings?.enableMaxTokens ?? false,
|
||||
maxTokens: getAssistantMaxTokens(),
|
||||
streamOutput: assistant?.settings?.streamOutput ?? true
|
||||
}
|
||||
}
|
||||
|
||||
export function covertAgentToAssistant(agent: Agent): Assistant {
|
||||
const id = agent.group === 'system' ? uuid() : String(agent.id)
|
||||
return {
|
||||
...getDefaultAssistant(),
|
||||
...agent,
|
||||
id,
|
||||
topics: [getDefaultTopic(id)],
|
||||
name: getAssistantNameWithAgent(agent),
|
||||
settings: getDefaultAssistantSettings()
|
||||
streamOutput: assistant?.settings?.streamOutput ?? true,
|
||||
hideMessages: assistant?.settings?.hideMessages ?? false,
|
||||
autoResetModel: assistant?.settings?.autoResetModel ?? false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,38 +96,58 @@ export function getAssistantNameWithAgent(agent: Agent) {
|
||||
return agent.emoji ? agent.emoji + ' ' + agent.name : agent.name
|
||||
}
|
||||
|
||||
export function syncAsistantToAgent(assistant: Assistant) {
|
||||
const agents = store.getState().agents.agents
|
||||
const agent = agents.find((a) => a.id === assistant.id)
|
||||
|
||||
if (agent) {
|
||||
store.dispatch(
|
||||
updateAgent({
|
||||
...agent,
|
||||
emoji: getLeadingEmoji(assistant.name),
|
||||
name: removeLeadingEmoji(assistant.name),
|
||||
prompt: assistant.prompt
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function syncAgentToAssistant(agent: Agent) {
|
||||
const assistants = store.getState().assistants.assistants
|
||||
const assistant = assistants.find((a) => a.id === agent.id)
|
||||
|
||||
if (assistant) {
|
||||
store.dispatch(
|
||||
updateAssistant({
|
||||
...assistant,
|
||||
name: getAssistantNameWithAgent(agent),
|
||||
prompt: agent.prompt
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function getAssistantById(id: string) {
|
||||
const assistants = store.getState().assistants.assistants
|
||||
return assistants.find((a) => a.id === id)
|
||||
}
|
||||
|
||||
export async function addAssistantMessagesToTopic({ assistant, topic }: { assistant: Assistant; topic: Topic }) {
|
||||
const messages: Message[] = []
|
||||
const defaultModel = getDefaultModel()
|
||||
|
||||
for (const msg of assistant?.messages || []) {
|
||||
const message: Message = {
|
||||
id: uuid(),
|
||||
assistantId: assistant.id,
|
||||
role: msg.role,
|
||||
content: msg.content,
|
||||
topicId: topic.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
status: 'success',
|
||||
modelId: assistant.defaultModel?.id || defaultModel.id,
|
||||
type: 'text',
|
||||
isPreset: true
|
||||
}
|
||||
message.usage = await estimateMessageUsage(message)
|
||||
messages.push(message)
|
||||
}
|
||||
|
||||
db.topics.put({ id: topic.id, messages }, topic.id)
|
||||
|
||||
return messages
|
||||
}
|
||||
|
||||
export async function createAssistantFromAgent(agent: Agent) {
|
||||
const assistantId = uuid()
|
||||
const topic = getDefaultTopic(assistantId)
|
||||
|
||||
const assistant: Assistant = {
|
||||
...agent,
|
||||
id: assistantId,
|
||||
name: agent.emoji ? agent.emoji + ' ' + agent.name : agent.name,
|
||||
topics: [topic],
|
||||
model: agent.defaultModel,
|
||||
type: 'assistant'
|
||||
}
|
||||
|
||||
store.dispatch(addAssistant(assistant))
|
||||
|
||||
await addAssistantMessagesToTopic({ assistant, topic })
|
||||
|
||||
window.message.success({
|
||||
content: i18n.t('message.assistant.added.content'),
|
||||
key: 'assistant-added'
|
||||
})
|
||||
|
||||
return assistant
|
||||
}
|
||||
|
||||
@@ -29,9 +29,6 @@ export async function restore() {
|
||||
data = JSON.parse(await window.api.decompress(file.content))
|
||||
}
|
||||
|
||||
// 处理文件内容
|
||||
console.log('Parsed file content:', data)
|
||||
|
||||
await handleData(data)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
@@ -19,5 +19,6 @@ export const EVENT_NAMES = {
|
||||
NEW_CONTEXT: 'NEW_CONTEXT',
|
||||
NEW_BRANCH: 'NEW_BRANCH',
|
||||
EXPORT_TOPIC_IMAGE: 'EXPORT_TOPIC_IMAGE',
|
||||
LOCATE_MESSAGE: 'LOCATE_MESSAGE'
|
||||
LOCATE_MESSAGE: 'LOCATE_MESSAGE',
|
||||
ADD_NEW_TOPIC: 'ADD_NEW_TOPIC'
|
||||
}
|
||||
|
||||
@@ -17,10 +17,8 @@ async function getFileContent(file: FileType) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const fileId = file.id + file.ext
|
||||
|
||||
if (file.type === FileTypes.TEXT) {
|
||||
return await window.api.file.read(fileId)
|
||||
return await window.api.file.read(file.id + file.ext)
|
||||
}
|
||||
|
||||
return ''
|
||||
@@ -79,7 +77,7 @@ export async function estimateMessageUsage(message: Message): Promise<Completion
|
||||
return {
|
||||
prompt_tokens: promptUsedTokens,
|
||||
completion_tokens: completionUsedTokens,
|
||||
total_tokens: usedTokens + imageTokens - 7
|
||||
total_tokens: usedTokens + (imageTokens ? imageTokens - 7 : 0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { Agent } from '@renderer/types'
|
||||
import { DEFAULT_CONEXTCOUNT, DEFAULT_TEMPERATURE } from '@renderer/config/constant'
|
||||
import { Agent, AssistantSettings } from '@renderer/types'
|
||||
|
||||
export interface AgentsState {
|
||||
agents: Agent[]
|
||||
@@ -9,25 +10,49 @@ const initialState: AgentsState = {
|
||||
agents: []
|
||||
}
|
||||
|
||||
const runtimeSlice = createSlice({
|
||||
const assistantsSlice = createSlice({
|
||||
name: 'agents',
|
||||
initialState,
|
||||
reducers: {
|
||||
updateAgents: (state, action: PayloadAction<Agent[]>) => {
|
||||
state.agents = action.payload
|
||||
},
|
||||
addAgent: (state, action: PayloadAction<Agent>) => {
|
||||
state.agents.push(action.payload)
|
||||
},
|
||||
removeAgent: (state, action: PayloadAction<Agent>) => {
|
||||
state.agents = state.agents.filter((a) => a.id !== action.payload.id)
|
||||
removeAgent: (state, action: PayloadAction<{ id: string }>) => {
|
||||
state.agents = state.agents.filter((c) => c.id !== action.payload.id)
|
||||
},
|
||||
updateAgent: (state, action: PayloadAction<Agent>) => {
|
||||
state.agents = state.agents.map((a) => (a.id === action.payload.id ? action.payload : a))
|
||||
state.agents = state.agents.map((c) => (c.id === action.payload.id ? action.payload : c))
|
||||
},
|
||||
updateAgents: (state, action: PayloadAction<Agent[]>) => {
|
||||
state.agents = action.payload
|
||||
updateAgentSettings: (
|
||||
state,
|
||||
action: PayloadAction<{ assistantId: string; settings: Partial<AssistantSettings> }>
|
||||
) => {
|
||||
for (const agent of state.agents) {
|
||||
const settings = action.payload.settings
|
||||
if (agent.id === action.payload.assistantId) {
|
||||
for (const key in settings) {
|
||||
if (!agent.settings) {
|
||||
agent.settings = {
|
||||
temperature: DEFAULT_TEMPERATURE,
|
||||
contextCount: DEFAULT_CONEXTCOUNT,
|
||||
enableMaxTokens: false,
|
||||
maxTokens: 0,
|
||||
streamOutput: true,
|
||||
hideMessages: false,
|
||||
autoResetModel: false
|
||||
}
|
||||
}
|
||||
agent.settings[key] = settings[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const { addAgent, removeAgent, updateAgent, updateAgents } = runtimeSlice.actions
|
||||
export const { updateAgents, addAgent, removeAgent, updateAgent, updateAgentSettings } = assistantsSlice.actions
|
||||
|
||||
export default runtimeSlice.reducer
|
||||
export default assistantsSlice.reducer
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { DEFAULT_CONEXTCOUNT, DEFAULT_TEMPERATURE } from '@renderer/config/constant'
|
||||
import { TopicManager } from '@renderer/hooks/useTopic'
|
||||
import { getDefaultAssistant, getDefaultTopic } from '@renderer/services/assistant'
|
||||
import { Assistant, AssistantSettings, Model, Topic } from '@renderer/types'
|
||||
@@ -33,20 +34,34 @@ const assistantsSlice = createSlice({
|
||||
updateAssistant: (state, action: PayloadAction<Assistant>) => {
|
||||
state.assistants = state.assistants.map((c) => (c.id === action.payload.id ? action.payload : c))
|
||||
},
|
||||
updateAssistantSettings: (state, action: PayloadAction<{ assistantId: string; settings: AssistantSettings }>) => {
|
||||
state.assistants = state.assistants.map((assistant) =>
|
||||
assistant.id === action.payload.assistantId
|
||||
? {
|
||||
...assistant,
|
||||
settings: action.payload.settings
|
||||
updateAssistantSettings: (
|
||||
state,
|
||||
action: PayloadAction<{ assistantId: string; settings: Partial<AssistantSettings> }>
|
||||
) => {
|
||||
for (const assistant of state.assistants) {
|
||||
const settings = action.payload.settings
|
||||
if (assistant.id === action.payload.assistantId) {
|
||||
for (const key in settings) {
|
||||
if (!assistant.settings) {
|
||||
assistant.settings = {
|
||||
temperature: DEFAULT_TEMPERATURE,
|
||||
contextCount: DEFAULT_CONEXTCOUNT,
|
||||
enableMaxTokens: false,
|
||||
maxTokens: 0,
|
||||
streamOutput: true,
|
||||
hideMessages: false,
|
||||
autoResetModel: false
|
||||
}
|
||||
}
|
||||
: assistant
|
||||
)
|
||||
assistant.settings[key] = settings[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
addTopic: (state, action: PayloadAction<{ assistantId: string; topic: Topic }>) => {
|
||||
const topic = action.payload.topic
|
||||
topic.createdAt = new Date().toISOString()
|
||||
topic.updatedAt = new Date().toISOString()
|
||||
topic.createdAt = topic.createdAt || new Date().toISOString()
|
||||
topic.updatedAt = topic.updatedAt || new Date().toISOString()
|
||||
state.assistants = state.assistants.map((assistant) =>
|
||||
assistant.id === action.payload.assistantId
|
||||
? {
|
||||
|
||||
@@ -22,7 +22,7 @@ const persistedReducer = persistReducer(
|
||||
{
|
||||
key: 'cherry-studio',
|
||||
storage,
|
||||
version: 30,
|
||||
version: 33,
|
||||
blacklist: ['runtime'],
|
||||
migrate
|
||||
},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user