Compare commits

...

88 Commits

Author SHA1 Message Date
kangfenmao
27631d9cff chore(version): 0.8.3 2024-10-24 18:47:20 +08:00
kangfenmao
596cf8e3f2 docs: update translation and api url tip 2024-10-24 16:19:47 +08:00
kangfenmao
6e2ab66b81 fix: 添加默认助手会添加两个 #238 2024-10-24 15:46:08 +08:00
kangfenmao
2cbb4c8831 fix: 公式显示问题 #239 2024-10-24 15:33:04 +08:00
kangfenmao
5347f63aa8 fix: 添加默认助手会添加两个 #238 2024-10-24 15:05:13 +08:00
kangfenmao
077a66c675 feat: scrollbar 2024-10-24 14:58:13 +08:00
kangfenmao
6e7b6d8387 build: update yarn.lock 2024-10-24 11:45:41 +08:00
Ikko Eltociear Ashimine
bdf6df1936 docs: add Japanese README file
I created Japanese translated README.
2024-10-23 20:50:58 +08:00
kangfenmao
a2dd440f77 fix: 公式又不居中了 #231 2024-10-23 20:49:22 +08:00
kangfenmao
b47d6c95e7 fix: 修复数据库和 store 数据不一致问题 2024-10-23 14:08:48 +08:00
kangfenmao
6265d27ebc feat: add cherry-stuido-db project 2024-10-22 22:01:56 +08:00
kangfenmao
0dd60cb129 chore(version): 0.8.2 2024-10-22 20:06:11 +08:00
kangfenmao
04dae10d89 fix: 汉语新解卡片 css 2024-10-22 19:53:59 +08:00
kangfenmao
71ef0f319f feat: 话题分享功能 #103 2024-10-22 19:01:46 +08:00
kangfenmao
58817ae82f fix: 文件保存相关问题 #208 2024-10-22 17:37:22 +08:00
kangfenmao
7e477cb9c7 docs: CONTRIBUTING.md.md to CONTRIBUTING.md 2024-10-22 16:04:31 +08:00
kangfenmao
1063610c01 fix: scrollbar width 2024-10-22 16:03:13 +08:00
kangfenmao
927670d3a3 build: add pulish:artifacts command 2024-10-22 15:43:28 +08:00
XuQing Chai
2fea7659b1 Modify the path of README.zh.md in README.md correctly 2024-10-21 23:27:18 +08:00
kangfenmao
43b9298329 feat: 智能体改进:名称、上下文支持、模型参数支持 #59 2024-10-21 23:21:46 +08:00
kangfenmao
fe2e3bfc36 feat: add qwen2-vl modal vision support 2024-10-18 13:21:11 +08:00
牡丹凤凰
bae80fda8d Merge pull request #205 from cawabj/develop
misc
2024-10-18 03:31:22 +08:00
首都爱护动物协会
ab709b9c61 misc 2024-10-18 03:30:05 +08:00
kangfenmao
2c28e3bb76 style: improved layout and functionality for the prompt editing field. 2024-10-17 16:52:18 +08:00
kangfenmao
d98020e12c docs: update readme documentation with telegram link and welcome message 2024-10-17 16:29:47 +08:00
kangfenmao
25addc390f docs: update community information and telegram 2024-10-17 16:22:19 +08:00
kangfenmao
88d04a1a6e docs: add product hunt 2024-10-17 15:59:41 +08:00
kangfenmao
1f582c672d fix: remove some file extensions 2024-10-17 15:13:18 +08:00
kangfenmao
c913b2a6d0 fix: java 格式文件上传支持 #201
close #201
2024-10-17 14:26:08 +08:00
kangfenmao
267c60f24d docs: update LICENSE 2024-10-17 14:09:30 +08:00
kangfenmao
a8ccaf6847 feat: Agents 页面改版 #198 2024-10-17 13:44:52 +08:00
kangfenmao
a3a005b946 docs: update commercial use license terms 2024-10-17 13:36:20 +08:00
kangfenmao
2220a6016e feat: added human-readable file size formatting and unit support 2024-10-17 13:35:51 +08:00
kangfenmao
3197390f1a docs: update references to main branch 2024-10-17 10:06:21 +08:00
kangfenmao
5f04d1adb1 fix: local package.json 2024-10-16 17:43:19 +08:00
kangfenmao
76b6593545 fix: 检查更新按钮不生效 #184
close #184
2024-10-16 13:14:15 +08:00
kangfenmao
04ce641bf7 fix: removed unnecessary newline replacement
- Removed unnecessary newline replacement from input message content.
2024-10-16 11:23:58 +08:00
kangfenmao
31e912aac3 fix: 点击清除上下文直接跳转到最下面 #192
close #192
2024-10-16 09:53:56 +08:00
kangfenmao
832ec99d92 chore: removed resources from excluded files
- Removed resources from excluded files.
2024-10-16 09:44:29 +08:00
kangfenmao
ef9fda6d0c chore(version): 0.8.1 2024-10-15 21:19:54 +08:00
kangfenmao
624230411a feat: added new translations and api url handling features
- Added new translation strings for API URL actions and hints.
- Updated Chinese translations and added new provider API URL descriptions.
- Added new translations for API URL preview and reset tip.
- Added support for Open AI API settings preview and hint.
- Added a new isOpenAIProvider function to handle specific provider type checks.
- Added a new function to validate if a given URL has a valid non-root path.
2024-10-15 21:14:19 +08:00
kangfenmao
14808649f8 feat: added conditional rendering to messagetokens component
- Added conditional rendering to MessageTokens component.
- Added parameter 'isLastMessage' to MessageTokens component to determine conditional rendering based on message position.
2024-10-15 20:22:01 +08:00
kangfenmao
3cc8cfb43b fix: code font size 2024-10-15 19:21:18 +08:00
kangfenmao
4055111ade feat: add show line number in code 2024-10-15 19:18:12 +08:00
kangfenmao
dc98b27e3e feat: add license.html 2024-10-15 19:02:53 +08:00
kangfenmao
90fec317e5 feat: add data settings 2024-10-15 18:56:09 +08:00
kangfenmao
303a0e20a0 fix: webdav备份恢复的逻辑似乎有点问题 #178 2024-10-15 17:48:48 +08:00
kangfenmao
d69252a7da feat: add success message on new branch creation
- Added new functionality to emit success message upon creating a new branch.
2024-10-15 17:13:41 +08:00
kangfenmao
99f05383cb feat: update translations and add new topic functionality 2024-10-15 16:33:15 +08:00
kangfenmao
5ba6c9f882 feat: add default timestamps for topic updates
- Added default values for createdAt and updatedAt timestamps when updating topics.
2024-10-15 16:19:38 +08:00
kangfenmao
27f64409d6 feat: added drag and drop file upload feature #190
- Added drag and drop file uploading functionality to input bar.

close #190
2024-10-15 16:15:59 +08:00
kangfenmao
7237729ff6 feat: enhanced model search in popup
- Improved search functionality for selecting models in the popup by modifying the filter criteria to include both model and provider names.
2024-10-15 15:55:15 +08:00
kangfenmao
d29cd3c657 feat: improved data display and scrolling experience
- Increased file list pagination size to improve data display.
- Disable inline styles for Markdown content.
- Removed overflow functionality for a smoother scrolling experience.
2024-10-15 15:15:58 +08:00
kangfenmao
8c87f59822 docs: update readme 2024-10-15 15:15:45 +08:00
1355873789
5780141df4 新增:腾讯混元服务商 2024-10-15 01:58:17 +08:00
kangfenmao
f5799ef47b fix: 一次上传多个文件 #183
close #183
2024-10-14 22:52:35 +08:00
kangfenmao
6f502049f4 chore(version): 0.8.0 2024-10-14 14:57:19 +08:00
kangfenmao
c68ad4febb feat: add artifacts preview 2024-10-14 14:37:04 +08:00
kangfenmao
2ebcec9f59 feat: add event listeners and topic handling improvements #181
- Added event listeners for estimated token count and add new topic events.
- Updated default topic handling when clearing messages.
- Removed feature to add new topics directly in Navbar and replaced it with emitting an event to create a new topic.
- Added the functionality to add new topics, clear messages, and handle topic switching with improved conditional logic.
- The event constants configuration has been updated to include two new event names.
2024-10-14 10:39:14 +08:00
kangfenmao
7bc74a5b86 feat: add clear message menu to topic context menu 2024-10-14 10:19:48 +08:00
kangfenmao
75152421d9 fix: DashScope upgrade 2024-10-14 09:57:56 +08:00
1355873789
3326074076 chore: 更新 provider 名称, Dashscope 更新为 Bailian 2024-10-14 09:17:01 +08:00
kangfenmao
362d82bdcc fix: text input token caused stuttering 2024-10-13 00:50:28 +08:00
kangfenmao
fcce241c82 style: improved visual separation and aesthetic
- Added a border radius to scrollbar thumb styles for improved aesthetic.
- Updated the Divider component to include a border for better visual separation.
- Added border to the divider in SelectModelPopup for improved visibility.
2024-10-13 00:38:13 +08:00
kangfenmao
693b06c126 docs: remove uppercase filename docs 2024-10-12 23:24:00 +08:00
kangfenmao
c310c71576 fix: 长文本输入时生成文件后文本依旧保留 #179 2024-10-12 23:22:32 +08:00
kangfenmao
bea95fc52f fix: 使用滚动条显示不全 #176 2024-10-12 17:42:16 +08:00
kangfenmao
969cf8ea21 fix: 移除 input 等输入标签的渲染 2024-10-12 17:37:56 +08:00
kangfenmao
5b357f14e5 chore(version): 0.7.16 2024-10-12 15:31:21 +08:00
kangfenmao
de5db4f805 fix: 修复无法正常选择文本文档的问题 2024-10-12 14:56:17 +08:00
kangfenmao
1ccb5edda7 chore(version): 0.7.15 2024-10-12 14:14:46 +08:00
kangfenmao
97b8749dd1 fix: 一键返回到消息顶部 #166
close #166
2024-10-12 14:03:06 +08:00
kangfenmao
a6d7ecae81 fix: 自定义界面字体 #158 2024-10-12 13:57:45 +08:00
kangfenmao
938efb5aef refactor: renamed model display names and fixed logic
- Renamed the display of model names to show the exact model name instead of capitalized first letter.
- Fixed logic to handle model name retrieval for assistant messages.
- Renaming of model display name to use the model's original name instead of a capitalized version.
- Removed unnecessary import and corrected label formatting in the options array.
2024-10-12 13:52:17 +08:00
kangfenmao
9baf0f772e fix: 黑暗模式的启动页是白色的 #118
close #118
2024-10-12 13:40:34 +08:00
kangfenmao
ff5de3625e fix: o1模型设置使用优化 #172 2024-10-12 13:28:42 +08:00
kangfenmao
f1cfdb29f8 feat: add document files support 2024-10-12 13:18:53 +08:00
kangfenmao
26e48f07fd fix: old version of the backup file cannot be restored. 2024-10-12 10:09:52 +08:00
kangfenmao
8bb5fb9811 feat: add event handling to blur current target element after showing popup
- Added event handling to the onSelectModel function to blur the current target element after showing the SelectModelPopup.
2024-10-12 10:00:03 +08:00
kangfenmao
d41667b599 feat: update release notes and add image preview component
- Updated release notes to reflect changes including image preview and download.
- Added interactive image preview component with toolbar for rotation, zooming, and downloading.
- Added support for image previews in Markdown rendering.
- Added functionality to download files from a URL with automatic filename detection and handling.
2024-10-12 09:53:20 +08:00
kangfenmao
85152cbcd7 chore(version): 0.7.14 2024-10-11 23:22:51 +08:00
kangfenmao
b80863111f feat: update release notes and fix issues
- This commit updates release notes to include new features and fix existing issues.
- Removed non-essential keyboard shortcuts from context menu items.
2024-10-11 18:04:08 +08:00
kangfenmao
6cd88fa51d feat: add bolt minapp 2024-10-11 14:15:37 +08:00
kangfenmao
3619e8f47b style: updated ui styles and translations
- Adjusted padding styles in AssistantModelSettings component.
- The addition of a close button to the Assistant Prompt Settings component to enhance its functionality.
- Added OK callback event to AssistantPromptSettings component.
- Added translations for new UI elements.
- Updated translation data for Chinese language.
- Added new translations and updated existing values in the language file to incorporate additional features.
2024-10-11 14:05:50 +08:00
kangfenmao
5b41dd24d4 refactor: regenerate model on selection
- Updated the logic in the `onSelectModel` function to regenerate the model when a selection is made.
2024-10-11 13:49:06 +08:00
kangfenmao
91dd2f233a fix: azure openai model provider wrong 2024-10-11 13:42:36 +08:00
kangfenmao
7e651f9abc feat: quickly select model 2024-10-11 13:31:14 +08:00
kangfenmao
e44f666c5c refactor: latex解析不支持矩阵环境 #169 2024-10-11 10:15:46 +08:00
121 changed files with 6662 additions and 1931 deletions

View File

@@ -71,5 +71,6 @@ jobs:
dist/*.rpm
dist/*.tar.gz
dist/latest*.yml
dist/*.blockmap
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}

6
.gitignore vendored
View File

@@ -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
View 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
View 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
View File

@@ -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.

91
README.ja.md Normal file
View File

@@ -0,0 +1,91 @@
<div align="center">
<a href="https://github.com/kangfenmao/cherry-studio/releases">
<img src="https://github.com/kangfenmao/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" />
</a>
</div>
<div align="center">
<a href="./README.md">English</a> | <a href="./README.zh.md">中文</a> | 日本語
</div>
# 🍒 Cherry Studio
![](https://github.com/user-attachments/assets/7b4f2f78-5cbe-4be8-9aec-f98d8405a505)
Cherry Studioは、複数のLLMプロバイダーをサポートするデスクトップクライアントで、Windows、Mac、Linuxで利用可能です。
👏 [Telegramグループ](https://t.me/CherryStudioAI)に参加しましょう
# 🌠 スクリーンショット
![](https://github.com/user-attachments/assets/28585d83-4bf0-4714-b561-8c7bf57cc600)
![](https://github.com/user-attachments/assets/8576863a-f632-4776-bc12-657eeced9da3)
![](https://github.com/user-attachments/assets/790790d7-b462-48dd-bde1-91c1697a4648)
# 🌟 特徴
<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&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
</div>
1. 複数のLLMプロバイダーをサポート。
2. 複数のアシスタントを作成可能。
3. 複数のトピックを作成可能。
4. 同じ会話で複数のモデルを使用して質問に回答可能。
5. ドラッグアンドドロップでの並べ替えをサポート。
6. コードハイライト。
7. Mermaidチャート
# 🖥️ 開発
## IDEの設定
[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)
## プロジェクトの設定
### インストール
```bash
$ yarn
```
### 開発
```bash
$ yarn dev
```
### ビルド
```bash
# Windowsの場合
$ yarn build:win
# macOSの場合
$ yarn build:mac
# Linuxの場合
$ yarn build:linux
```
# ⭐️ スター履歴
[![Star History Chart](https://api.star-history.com/svg?repos=kangfenmao/cherry-studio&type=Timeline)](https://star-history.com/#kangfenmao/cherry-studio&Timeline)
# 🚀 コントリビューター
<a href="https://github.com/kangfenmao/cherry-studio/graphs/contributors">
<img src="https://contrib.rocks/image?repo=kangfenmao/cherry-studio" />
</a>
# コミュニティ
[Telegram](https://t.me/CherryStudioAI)
# スポンサー
[Buy Me a Coffee](docs/sponsor.md)
# 📃 ライセンス
[LICENSE](./LICENSE)

View File

@@ -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> | <a href="./README.ja.md">日本語</a>
</div>
# 🍒 Cherry Studio
![](https://github.com/user-attachments/assets/7b4f2f78-5cbe-4be8-9aec-f98d8405a505)
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
![](https://github.com/user-attachments/assets/28585d83-4bf0-4714-b561-8c7bf57cc600)
@@ -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&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;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)

View File

@@ -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> / <a href="./README.ja.md">日本語</a>
</div>
# 🍒 Cherry Studio
![](https://github.com/user-attachments/assets/995910f3-177a-4d1e-97ea-04e3b009ba36)
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&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
</div>
## 😌 轻松上手
🍏WindowsMacLinux跨平台支持
@@ -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
[![Star History Chart](https://api.star-history.com/svg?repos=kangfenmao/cherry-studio&type=Timeline)](https://star-history.com/#kangfenmao/cherry-studio&Timeline)
# 社区
[Telegram](https://t.me/CherryStudioAI)
# 赞助
[微信赞赏码](docs/sponsor.md)

View File

@@ -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>

View File

@@ -1,95 +0,0 @@
# FAQ 文档
本文档适用于:产品手册、官网页面、课程测验、现场 Q&A。
## 问题1Cherry Studio 支持哪些操作系统?
- **答案**Cherry Studio 支持 Windows、Mac 和 Linux 操作系统。
## 问题2Cherry Studio 的主要功能有哪些?
- **答案**Cherry Studio 的主要功能包括:
1. 支持多个 LLM 提供商
2. 允许创建多个助手
3. 支持创建多个主题
4. 允许在同一对话中使用多个模型来回答问题
5. 支持拖放排序
6. 代码高亮
7. Mermaid 图表支持
## 问题3Cherry 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`
## 问题5Cherry 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
## 问题7Cherry Studio 的 `/src` 目录主要包含哪些内容?
- **答案**Cherry Studio 的 `/src` 目录主要包含以下内容:
- 主进程代码Electron 主进程)
- 渲染进程代码(用户界面)
- 组件
- 工具函数
- 状态管理
- 样式文件
## 问题8如何在 Cherry Studio 中添加新的 LLM 提供商?
- **答案**:要在 Cherry Studio 中添加新的 LLM 提供商,你需要:
1.`/src/services` 或类似目录下创建新的服务文件
2. 实现与新 LLM 提供商 API 的集成
3. 在用户界面中添加新提供商的选项
4. 更新配置和状态管理以支持新提供商
## 问题9Cherry 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. 在用户界面中添加新主题的选项
## 问题11Cherry 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. 确保测试覆盖主要功能和组件

View File

@@ -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:
@@ -64,10 +63,6 @@ electronDownload:
afterSign: scripts/notarize.js
releaseInfo:
releaseNotes: |
本次更新:
增加 Azure OpenAI 服务商
修复表格换行问题
近期更新:
增加 WebDAV 备份功能 by @DrayChou
增加话题历史记录
增加消息搜索功能
增加数学公式渲染引擎切换
多个系统滚动条样式统一
修复添加默认助手会添加两个

View File

@@ -1,6 +1,6 @@
{
"name": "CherryStudio",
"version": "0.7.13",
"version": "0.8.3",
"private": true,
"description": "A powerful AI assistant for producer.",
"main": "./out/main/index.js",
@@ -8,7 +8,11 @@
"homepage": "https://github.com/kangfenmao/cherry-studio",
"workspaces": {
"packages": [
"local"
"local",
"packages/*"
],
"nohoist": [
"packages/database"
]
},
"scripts": {
@@ -27,6 +31,8 @@
"build:linux": "dotenv electron-vite build && electron-builder --linux --publish never",
"release": "node scripts/version.js",
"publish": "yarn release patch push",
"pulish:artifacts": "cd packages/artifacts && npm publish && cd -",
"generate:agents": "yarn workspace @cherry-studio/database agents",
"generate:icons": "electron-icon-builder --input=./build/logo.png --output=build"
},
"dependencies": {
@@ -35,10 +41,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"
},
@@ -86,6 +93,7 @@
"openai": "^4.52.1",
"prettier": "^3.2.4",
"react": "^18.2.0",
"react-custom-scrollbars-2": "^4.5.0",
"react-dom": "^18.2.0",
"react-i18next": "^14.1.2",
"react-markdown": "^9.0.1",
@@ -96,7 +104,8 @@
"react-syntax-highlighter": "^15.5.0",
"redux": "^5.0.1",
"redux-persist": "^6.0.0",
"rehype-katex": "^7.0.0",
"rehype-katex": "^7.0.1",
"rehype-mathjax": "^6.0.0",
"rehype-raw": "^7.0.0",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",

View File

@@ -0,0 +1 @@
# Cherry Studio Artifacts

View 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"
}

View 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;
}

3
packages/database/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
data/*
!data/.gitkeep

Binary file not shown.

View File

@@ -0,0 +1,3 @@
# Cherry Studio Database
Cherry Studio 依赖的数据文件由这个数据库来生成,数据库文件请联系开发者获取

View File

View File

@@ -0,0 +1,13 @@
{
"name": "@cherry-studio/database",
"packageManager": "yarn@4.3.1",
"dependencies": {
"csv-parser": "^3.0.0",
"sqlite3": "^5.1.7"
},
"scripts": {
"agents": "node src/agents.js",
"email": "yarn csv && node src/email.js",
"csv": "node src/csv.js"
}
}

View File

@@ -0,0 +1,45 @@
const sqlite3 = require('sqlite3').verbose()
const fs = require('fs')
// 连接到数据库
const db = new sqlite3.Database('./data/CherryStudio.sqlite3', (err) => {
if (err) {
console.error('Error connecting to the database:', err.message)
return
}
console.log('Connected to the database.')
})
// 查询数据并转换为JSON
db.all('SELECT * FROM agents', [], (err, rows) => {
if (err) {
console.error('Error querying the database:', err.message)
return
}
// 将 ID 类型转换为字符串
for (const row of rows) {
row.id = row.id.toString()
}
// 将查询结果转换为JSON字符串
const jsonData = JSON.stringify(rows, null, 2)
// 将JSON数据写入文件
fs.writeFile('../../src/renderer/src/config/agents.json', jsonData, (err) => {
if (err) {
console.error('Error writing to file:', err.message)
return
}
console.log('Data has been written to agents.json')
})
// 关闭数据库连接
db.close((err) => {
if (err) {
console.error('Error closing the database:', err.message)
return
}
console.log('Database connection closed.')
})
})

View File

@@ -0,0 +1,77 @@
const fs = require('fs')
const csv = require('csv-parser')
const sqlite3 = require('sqlite3').verbose()
// 连接到 SQLite 数据库
const db = new sqlite3.Database('./data/CherryStudio.sqlite3', (err) => {
if (err) {
console.error('Error opening database', err)
return
}
console.log('Connected to the SQLite database.')
})
// 创建一个数组来存储 CSV 数据
const results = []
// 读取 CSV 文件
fs.createReadStream('./data/data.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
// 准备 SQL 插入语句,使用 INSERT OR IGNORE
const stmt = db.prepare('INSERT OR IGNORE INTO emails (email, github, sent) VALUES (?, ?, ?)')
// 插入每一行数据
let inserted = 0
let skipped = 0
let emptyEmail = 0
db.serialize(() => {
// 开始一个事务以提高性能
db.run('BEGIN TRANSACTION')
results.forEach((row) => {
// 检查 email 是否为空
if (!row.email || row.email.trim() === '') {
emptyEmail++
return // 跳过这一行
}
stmt.run(row.email, row['user-href'], 0, function (err) {
if (err) {
console.error('Error inserting row', err)
} else {
if (this.changes === 1) {
inserted++
} else {
skipped++
}
}
})
})
// 提交事务
db.run('COMMIT', (err) => {
if (err) {
console.error('Error committing transaction', err)
} else {
console.log(
`Insertion complete. Inserted: ${inserted}, Skipped (duplicate): ${skipped}, Skipped (empty email): ${emptyEmail}`
)
}
// 完成插入
stmt.finalize()
// 关闭数据库连接
db.close((err) => {
if (err) {
console.error('Error closing database', err)
} else {
console.log('Database connection closed.')
}
})
})
})
})

View File

@@ -0,0 +1,36 @@
const sqlite3 = require('sqlite3').verbose()
// 连接到数据库
const db = new sqlite3.Database('./data/CherryStudio.sqlite3', (err) => {
if (err) {
console.error('Error connecting to the database:', err.message)
return
}
})
// 查询数据并转换为JSON
db.all('SELECT * FROM emails WHERE sent = 0', [], (err, rows) => {
if (err) {
console.error('Error querying the database:', err.message)
return
}
for (const row of rows) {
console.log(row.email)
// Update row set sent = 1
db.run('UPDATE emails SET sent = 1 WHERE id = ?', [row.id], (err) => {
if (err) {
console.error('Error updating the database:', err.message)
return
}
})
}
// 关闭数据库连接
db.close((err) => {
if (err) {
console.error('Error closing the database:', err.message)
return
}
})
})

1643
packages/database/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

View 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
View 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 代码文件
]

View File

@@ -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)

View File

@@ -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

View File

@@ -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)
}
}

View File

@@ -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
}

View File

@@ -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
View 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
}
}

View File

@@ -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()
})

View File

@@ -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),

View File

@@ -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>

View 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

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -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 {

View File

@@ -1,6 +1,6 @@
@import './markdown.scss';
@import './scrollbar.scss';
@import './ant.scss';
@import './scrollbar.scss';
@import '../fonts/icon-fonts/iconfont.css';
@import '../fonts/ubuntu/ubuntu.css';
@@ -37,8 +37,6 @@
--color-error: #f44336;
--color-link: #1677ff;
--color-code-background: #323232;
--color-scrollbar-thumb: rgba(255, 255, 255, 0.08);
--color-scrollbar-thumb-hover: rgba(255, 255, 255, 0.15);
--color-hover: rgba(40, 40, 40, 1);
--color-active: rgba(55, 55, 55, 1);
@@ -48,7 +46,7 @@
--navbar-height: 40px;
--sidebar-width: 50px;
--status-bar-height: 40px;
--input-bar-height: 85px;
--input-bar-height: 100px;
--assistants-width: 275px;
--topic-list-width: 275px;
@@ -88,8 +86,6 @@ body[theme-mode='light'] {
--color-error: #f44336;
--color-link: #1677ff;
--color-code-background: #e3e3e3;
--color-scrollbar-thumb: rgba(0, 0, 0, 0.08);
--color-scrollbar-thumb-hover: rgba(0, 0, 0, 0.15);
--color-hover: var(--color-white-mute);
--color-active: var(--color-white-soft);

View File

@@ -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;

View File

@@ -1,7 +1,17 @@
:root {
--color-scrollbar-thumb: #6b6b6b;
--color-scrollbar-thumb-hover: #939393;
}
body[theme-mode='light'] {
--color-scrollbar-thumb: #b1b1b1;
--color-scrollbar-thumb-hover: #7d7d7d;
}
/* 全局初始化滚动条样式 */
::-webkit-scrollbar {
width: 2px;
height: 2px;
width: 5px;
height: 5px;
}
::-webkit-scrollbar-track {
@@ -9,8 +19,17 @@
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background: var(--color-scrollbar-thumb);
&:hover {
background: var(--color-scrollbar-thumb-hover);
}
}
pre::-webkit-scrollbar-thumb {
border-radius: 0;
background: rgba(0, 0, 0, 0.08);
&:hover {
background: rgba(0, 0, 0, 0.15);
}
}

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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'
)
})
}

View File

@@ -3,9 +3,10 @@ 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 { uuid } from '@renderer/utils'
import { Divider, Input, InputRef, Modal, Tag } from 'antd'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -26,35 +27,24 @@ 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) => {
let assistant: Assistant
if (agent.id === 'default') {
assistant = { ...agent, id: uuid() }
addAssistant(assistant)
} else {
assistant = await createAssistantFromAgent(agent)
}
const assistant = covertAgentToAssistant(agent)
addAssistant(assistant)
setTimeout(() => EventEmitter.emit(EVENT_NAMES.SHOW_ASSISTANTS), 0)
resolve(assistant)
setOpen(false)
@@ -79,8 +69,7 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
open={open}
onCancel={onCancel}
afterClose={onClose}
transitionName="ant-move-down"
maskTransitionName="ant-fade"
transitionName="ant-move-up"
styles={{ content: { borderRadius: 20, padding: 0, overflow: 'hidden', paddingBottom: 20 } }}
closeIcon={null}
footer={null}>
@@ -102,7 +91,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 +101,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>

View File

@@ -0,0 +1,182 @@
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'
import { Scrollbar } from '../Scrollbar'
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 }} />
<Scrollbar style={{ height: '50vh' }}>
<Container>
{filteredItems.length > 0 ? (
<StyledMenu
items={filteredItems}
selectedKeys={model ? [getModelUniqId(model)] : []}
mode="inline"
inlineIndent={6}
/>
) : (
<EmptyState>
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
</EmptyState>
)}
</Container>
</Scrollbar>
</Modal>
)
}
const Container = styled.div`
margin-top: 10px;
`
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')
})
}
}

View File

@@ -55,7 +55,6 @@ const PopupContainer: React.FC<Props> = ({ text, textareaProps, modalProps, reso
width="60vw"
style={{ maxHeight: '70vh' }}
transitionName="ant-move-down"
maskTransitionName="ant-fade"
okText={t('common.save')}
{...modalProps}
open={open}

View File

@@ -0,0 +1,22 @@
import { ScrollbarProps, Scrollbars } from 'react-custom-scrollbars-2'
import styled from 'styled-components'
export const Scrollbar: React.FC<ScrollbarProps> = ({ children, ...props }) => {
return (
<Scrollbars
autoHide
{...props}
renderThumbVertical={(props) => <Thumb {...props} />}
renderTrackHorizontal={(props) => <Thumb {...props} />}>
{children}
</Scrollbars>
)
}
const Thumb = styled.div`
border-radius: 10px;
background-color: var(--color-scrollbar-thumb);
&:hover {
background-color: var(--color-scrollbar-thumb-hover);
}
`

View File

@@ -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

View File

@@ -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 代码文件
]

View File

@@ -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
}
]

View File

@@ -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',

View 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 个字以内的标题,不要使用标点符号和其他特殊符号。'

View File

@@ -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'

View File

@@ -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 }))
}
}
}

View File

@@ -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 }))
}
}

View File

@@ -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)),

View File

@@ -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",
@@ -194,6 +226,7 @@
"messages.input.send_shortcuts": "Send shortcuts",
"messages.input.paste_long_text_as_file": "Paste long text as file",
"messages.markdown_rendering_input_message": "Markdown render input msg",
"messages.math_engine": "Math render engine",
"general.title": "General Settings",
"general.user_name": "User Name",
"general.user_name.placeholder": "Enter your name",
@@ -201,20 +234,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 +257,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": "Ending with / ignores v1, ending with # forces use of input address",
"models.default_assistant_model": "Default Assistant Model",
"models.topic_naming_model": "Topic Naming Model",
"models.translate_model": "Translate Model",
@@ -273,7 +306,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",

View File

@@ -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": "默认助手",
@@ -194,6 +226,7 @@
"messages.input.send_shortcuts": "发送快捷键",
"messages.input.paste_long_text_as_file": "长文本粘贴为文件",
"messages.markdown_rendering_input_message": "Markdown 渲染输入消息",
"messages.math_engine": "数学公式引擎",
"general.title": "常规设置",
"general.user_name": "用户名",
"general.user_name.placeholder": "请输入用户名",
@@ -203,18 +236,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 +257,8 @@
"provider.docs_more_details": "获取更多详情",
"provider.search_placeholder": "搜索模型 ID 或名称",
"provider.api.url.reset": "重置",
"provider.api.url.preview": "预览: {{url}}",
"provider.api.url.tip": "/结尾忽略v1版本#结尾强制使用输入地址",
"models.default_assistant_model": "默认助手模型",
"models.topic_naming_model": "话题命名模型",
"models.translate_model": "翻译模型",
@@ -273,7 +306,8 @@
"font_size.title": "消息字体大小",
"topic.position": "话题位置",
"topic.position.left": "左侧",
"topic.position.right": "右侧"
"topic.position.right": "右侧",
"topic.show.time": "显示话题时间"
},
"translate": {
"title": "翻译",

View File

@@ -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": "預設助手",
@@ -193,7 +225,8 @@
"messages.input.show_estimated_tokens": "顯示預估輸入 Token 數",
"messages.input.send_shortcuts": "發送快捷鍵",
"messages.input.paste_long_text_as_file": "將長文本貼上為檔案",
"messages.markdown_rendering_input_message": "Markdown 渲染輸入訊息",
"messages.math_engine": "Markdown 渲染輸入訊息",
"messages.math_render_engine": "數學公式引擎",
"general.title": "一般設定",
"general.user_name": "使用者名稱",
"general.user_name.placeholder": "輸入您的名稱",
@@ -201,20 +234,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 +257,8 @@
"provider.docs_more_details": "查看更多細節",
"provider.search_placeholder": "搜尋模型 ID 或名稱",
"provider.api.url.reset": "重置",
"provider.api.url.preview": "預覽: {{url}}",
"provider.api.url.tip": "/結尾忽略v1版本#結尾強制使用輸入位址",
"models.default_assistant_model": "預設助手模型",
"models.topic_naming_model": "話題命名模型",
"models.translate_model": "翻譯模型",
@@ -273,7 +306,8 @@
"font_size.title": "訊息字體大小",
"topic.position": "話題位置",
"topic.position.left": "左側",
"topic.position.right": "右側"
"topic.position.right": "右側",
"topic.show.time": "顯示話題時間"
},
"translate": {
"title": "翻譯",

View File

@@ -0,0 +1,162 @@
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 { Scrollbar } from '@renderer/components/Scrollbar'
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 (
<Scrollbar style={{ maxWidth: 'var(--assistants-width)' }}>
<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>
)}
<div style={{ height: 10 }} />
</Container>
</Scrollbar>
)
}
const Container = styled.div`
padding: 15px;
display: flex;
flex-direction: column;
border-right: 0.5px solid var(--color-border);
min-height: calc(100vh - var(--navbar-height));
width: var(--assistants-width);
`
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

View File

@@ -1,52 +1,57 @@
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 { Scrollbar } from '@renderer/components/Scrollbar'
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,30 +60,35 @@ const AppsPage: FC = () => {
<NavbarCenter style={{ borderRight: 'none' }}>{t('agents.title')}</NavbarCenter>
</Navbar>
<ContentContainer id="content-container">
<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 }} />
</AssistantsContainer>
<Agents onClick={onAddAgentConfirm} />
<Scrollbar>
<AssistantsContainer>
<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>
</Scrollbar>
</ContentContainer>
</Container>
)
@@ -97,24 +107,20 @@ 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;
`
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

View File

@@ -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()

View File

@@ -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;
`

View File

@@ -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')
}
}

View File

@@ -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

View File

@@ -1,8 +1,10 @@
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
import { VStack } from '@renderer/components/Layout'
import { Scrollbar } from '@renderer/components/Scrollbar'
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 +14,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 +23,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')
}
@@ -65,15 +67,17 @@ const FilesPage: FC = () => {
<NavbarCenter style={{ borderRight: 'none' }}>{t('files.title')}</NavbarCenter>
</Navbar>
<ContentContainer id="content-container">
<VStack style={{ width: '100%' }}>
<Table
dataSource={dataSource}
columns={columns}
style={{ width: '100%', marginBottom: 20 }}
size="small"
pagination={{ pageSize: 15 }}
/>
</VStack>
<Scrollbar>
<VStack style={{ width: '100%', padding: 15 }}>
<Table
dataSource={dataSource}
columns={columns}
style={{ width: '100%', marginBottom: 20 }}
size="small"
pagination={{ pageSize: 100 }}
/>
</VStack>
</Scrollbar>
</ContentContainer>
</Container>
)
@@ -92,8 +96,6 @@ const ContentContainer = styled.div`
flex-direction: row;
justify-content: center;
height: 100%;
overflow-y: scroll;
padding: 15px;
`
const FileNameText = styled.div`

View File

@@ -118,6 +118,7 @@ const Header = styled.div`
align-items: center;
justify-content: center;
padding: 8px 20px;
padding-top: 10px;
width: 100%;
position: relative;
`

View File

@@ -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}

View File

@@ -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}

View File

@@ -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',

View File

@@ -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

View 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

View File

@@ -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;

View 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

View File

@@ -8,28 +8,25 @@ 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()
const { renderInputMessageAsMarkdown, mathEngine } = useSettings()
const rehypeMath = mathEngine === 'KaTeX' ? rehypeKatex : rehypeMathjax
const messageContent = useMemo(() => {
const empty = isEmpty(message.content)
@@ -38,6 +35,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 ? [rehypeMath] : [rehypeRaw, rehypeMath]
}, [messageContent, rehypeMath])
if (message.role === 'user' && !renderInputMessageAsMarkdown) {
return <p style={{ marginBottom: 5, whiteSpace: 'pre-wrap' }}>{messageContent}</p>
}
@@ -46,8 +48,14 @@ const Markdown: FC<Props> = ({ message }) => {
<ReactMarkdown
className="markdown"
rehypePlugins={rehypePlugins}
remarkPlugins={remarkPlugins}
components={components as Partial<Components>}
remarkPlugins={[remarkMath, remarkGfm]}
components={
{
a: Link,
code: CodeBlock,
img: ImagePreview
} as Partial<Components>
}
remarkRehypeOptions={{
footnoteLabel: t('common.footnotes'),
footnoteLabelTagName: 'h4',

View File

@@ -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}

View File

@@ -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])

View File

@@ -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}>

View File

@@ -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

View File

@@ -1,3 +1,4 @@
import { Scrollbar } from '@renderer/components/Scrollbar'
import db from '@renderer/databases'
import { useAssistant } from '@renderer/hooks/useAssistant'
import { useSettings } from '@renderer/hooks/useSettings'
@@ -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,30 +220,29 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
}, [assistant, messages])
return (
<Container id="messages" 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) => (
<MessageItem
key={message.id}
message={message}
index={index}
onEditMessage={onEditMessage}
onDeleteMessage={onDeleteMessage}
/>
))}
<Prompt assistant={assistant} key={assistant.prompt} />
</Container>
<Scrollbar>
<Container id="messages" 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) => (
<MessageItem
key={message.id}
message={message}
index={index}
hidePresetMessages={assistant.settings?.hideMessages}
onEditMessage={onEditMessage}
onDeleteMessage={onDeleteMessage}
/>
))}
<Prompt assistant={assistant} key={assistant.prompt} />
</Container>
</Scrollbar>
)
}
const Container = styled.div`
position: relative;
display: flex;
flex-direction: column;
overflow-y: auto;
flex-direction: column-reverse;
max-height: calc(100vh - var(--input-bar-height) - var(--navbar-height));
padding: 10px 0;
background-color: var(--color-background);
padding-bottom: 20px;

View File

@@ -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>
)

View File

@@ -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} />

View File

@@ -1,298 +0,0 @@
import { CheckOutlined, QuestionCircleOutlined, ReloadOutlined } 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 { useSettings } from '@renderer/hooks/useSettings'
import { SettingDivider, SettingRow, SettingRowTitle, SettingSubtitle } from '@renderer/pages/settings'
import { useAppDispatch } from '@renderer/store'
import {
setFontSize,
setMessageFont,
setPasteLongTextAsFile,
setRenderInputMessageAsMarkdown,
setShowInputEstimatedTokens,
setShowMessageDivider
} from '@renderer/store/settings'
import { Assistant, AssistantSettings } from '@renderer/types'
import { Col, Row, Select, Slider, Switch, Tooltip } from 'antd'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
interface Props {
assistant: Assistant
}
const SettingsTab: FC<Props> = (props) => {
const { assistant, updateAssistantSettings, updateAssistant } = useAssistant(props.assistant.id)
const { fontSize } = useSettings()
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 [streamOutput, setStreamOutput] = useState(assistant?.settings?.streamOutput ?? true)
const [fontSizeValue, setFontSizeValue] = useState(fontSize)
const { t } = useTranslation()
const dispatch = useAppDispatch()
const {
showMessageDivider,
messageFont,
showInputEstimatedTokens,
sendMessageShortcut,
setSendMessageShortcut,
pasteLongTextAsFile,
renderInputMessageAsMarkdown
} = 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
})
}
const onTemperatureChange = (value) => {
if (!isNaN(value as number)) {
onUpdateAssistantSettings({ temperature: value })
}
}
const onConextCountChange = (value) => {
if (!isNaN(value as number)) {
onUpdateAssistantSettings({ contextCount: value })
}
}
const onMaxTokensChange = (value) => {
if (!isNaN(value as number)) {
onUpdateAssistantSettings({ 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
}
})
}
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])
return (
<Container>
<SettingSubtitle style={{ marginTop: 5 }}>
{t('settings.messages.model.title')}{' '}
<Tooltip title={t('chat.settings.reset')}>
<ReloadOutlined onClick={onReset} style={{ cursor: 'pointer', fontSize: 12, padding: '0 3px' }} />
</Tooltip>
</SettingSubtitle>
<SettingDivider />
<Row align="middle">
<Label>{t('chat.settings.temperature')}</Label>
<Tooltip title={t('chat.settings.temperature.tip')}>
<QuestionIcon />
</Tooltip>
</Row>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
min={0}
max={2}
onChange={setTemperature}
onChangeComplete={onTemperatureChange}
value={typeof temperature === 'number' ? temperature : 0}
step={0.1}
/>
</Col>
</Row>
<Row align="middle">
<Label>{t('chat.settings.conext_count')}</Label>
<Tooltip title={t('chat.settings.conext_count.tip')}>
<QuestionIcon />
</Tooltip>
</Row>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
min={0}
max={20}
onChange={setConextCount}
onChangeComplete={onConextCountChange}
value={typeof contextCount === 'number' ? contextCount : 0}
step={1}
/>
</Col>
</Row>
<SettingRow>
<SettingRowTitleSmall>{t('model.stream_output')}</SettingRowTitleSmall>
<Switch
size="small"
checked={streamOutput}
onChange={(checked) => {
setStreamOutput(checked)
onUpdateAssistantSettings({ streamOutput: checked })
}}
/>
</SettingRow>
<SettingDivider />
<Row align="middle" justify="space-between">
<HStack alignItems="center">
<Label>{t('chat.settings.max_tokens')}</Label>
<Tooltip title={t('chat.settings.max_tokens.tip')}>
<QuestionIcon />
</Tooltip>
</HStack>
<Switch
size="small"
checked={enableMaxTokens}
onChange={(enabled) => {
setEnableMaxTokens(enabled)
onUpdateAssistantSettings({ enableMaxTokens: enabled })
}}
/>
</Row>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
disabled={!enableMaxTokens}
min={0}
max={32000}
onChange={setMaxTokens}
onChangeComplete={onMaxTokensChange}
value={typeof maxTokens === 'number' ? maxTokens : 0}
step={100}
/>
</Col>
</Row>
<SettingSubtitle>{t('settings.messages.title')}</SettingSubtitle>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.divider')}</SettingRowTitleSmall>
<Switch
size="small"
checked={showMessageDivider}
onChange={(checked) => dispatch(setShowMessageDivider(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.use_serif_font')}</SettingRowTitleSmall>
<Switch
size="small"
checked={messageFont === 'serif'}
onChange={(checked) => dispatch(setMessageFont(checked ? 'serif' : 'system'))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.font_size.title')}</SettingRowTitleSmall>
</SettingRow>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
value={fontSizeValue}
onChange={(value) => setFontSizeValue(value)}
onChangeComplete={(value) => dispatch(setFontSize(value))}
min={12}
max={18}
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>
}}
/>
</Col>
</Row>
<SettingSubtitle>{t('settings.messages.input.title')}</SettingSubtitle>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.input.show_estimated_tokens')}</SettingRowTitleSmall>
<Switch
size="small"
checked={showInputEstimatedTokens}
onChange={(checked) => dispatch(setShowInputEstimatedTokens(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.input.paste_long_text_as_file')}</SettingRowTitleSmall>
<Switch
size="small"
checked={pasteLongTextAsFile}
onChange={(checked) => dispatch(setPasteLongTextAsFile(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.markdown_rendering_input_message')}</SettingRowTitleSmall>
<Switch
size="small"
checked={renderInputMessageAsMarkdown}
onChange={(checked) => dispatch(setRenderInputMessageAsMarkdown(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.input.send_shortcuts')}</SettingRowTitleSmall>
</SettingRow>
<Select
value={sendMessageShortcut}
menuItemSelectedIcon={<CheckOutlined />}
options={[
{ value: 'Enter', label: `Enter ${t('chat.input.send')}` },
{ value: 'Shift+Enter', label: `Shift + Enter ${t('chat.input.send')}` }
]}
onChange={(value) => setSendMessageShortcut(value)}
style={{ width: '100%', marginTop: 10 }}
/>
</Container>
)
}
const Container = styled.div`
display: flex;
flex: 1;
flex-direction: column;
overflow: hidden;
padding-bottom: 10px;
padding: 10px 15px;
`
const Label = styled.p`
margin: 0;
font-size: 12px;
margin-right: 5px;
`
const QuestionIcon = styled(QuestionCircleOutlined)`
font-size: 12px;
cursor: pointer;
color: var(--color-text-3);
`
const SettingRowTitleSmall = styled(SettingRowTitle)`
font-size: 13px;
`
export default SettingsTab

View File

@@ -1,7 +1,9 @@
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 { Scrollbar } from '@renderer/components/Scrollbar'
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 +14,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 +41,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 +56,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 +72,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(
@@ -153,69 +179,69 @@ const Assistants: FC<Props> = ({
}, [activeAssistant?.id, list, onSwitchAssistant])
return (
<Container>
{assistants.length >= 10 && (
<SearchContainer>
<Input
placeholder={t('chat.assistant.search.placeholder')}
suffix={<CommandKey>+K</CommandKey>}
value={search}
onChange={(e) => setSearch(e.target.value)}
style={{ borderRadius: 4, borderWidth: 0.5 }}
onKeyDown={onSearch}
ref={searchRef}
onFocus={() => dispatch(setSearching(true))}
onBlur={() => {
dispatch(setSearching(false))
setSearch('')
}}
allowClear
/>
</SearchContainer>
)}
<DragableList
list={list}
onUpdate={updateAssistants}
droppableProps={{ isDropDisabled: !isEmpty(search) }}
style={{ paddingBottom: dragging ? '34px' : 0 }}
onDragStart={() => setDragging(true)}
onDragEnd={() => setDragging(false)}>
{(assistant) => {
const isCurrent = assistant.id === activeAssistant?.id
return (
<Dropdown key={assistant.id} menu={{ items: getMenuItems(assistant) }} trigger={['contextMenu']}>
<AssistantItem onClick={() => onSwitchAssistant(assistant)} className={isCurrent ? 'active' : ''}>
<AssistantName className="name">{assistant.name || t('chat.default.name')}</AssistantName>
{isCurrent && (
<ArrowRightButton onClick={() => EventEmitter.emit(EVENT_NAMES.SWITCH_TOPIC_SIDEBAR)}>
<i className="iconfont icon-gridlines" />
</ArrowRightButton>
)}
{false && <TopicCount className="topics-count">{assistant.topics.length}</TopicCount>}
</AssistantItem>
</Dropdown>
)
}}
</DragableList>
{!dragging && (
<AssistantItem onClick={onCreateAssistant}>
<AssistantName>
<PlusOutlined style={{ color: 'var(--color-text-2)', marginRight: 4 }} />
{t('chat.add.assistant.title')}
</AssistantName>
</AssistantItem>
)}
</Container>
<Scrollbar>
<Container>
{assistants.length >= 10 && (
<SearchContainer>
<Input
placeholder={t('chat.assistant.search.placeholder')}
suffix={<CommandKey>+K</CommandKey>}
value={search}
onChange={(e) => setSearch(e.target.value)}
style={{ borderRadius: 16, borderWidth: 0.5 }}
onKeyDown={onSearch}
ref={searchRef}
onFocus={() => dispatch(setSearching(true))}
onBlur={() => {
dispatch(setSearching(false))
setSearch('')
}}
allowClear
/>
</SearchContainer>
)}
<DragableList
list={list}
onUpdate={updateAssistants}
droppableProps={{ isDropDisabled: !isEmpty(search) }}
style={{ paddingBottom: dragging ? '34px' : 0 }}
onDragStart={() => setDragging(true)}
onDragEnd={() => setDragging(false)}>
{(assistant) => {
const isCurrent = assistant.id === activeAssistant?.id
return (
<Dropdown key={assistant.id} menu={{ items: getMenuItems(assistant) }} trigger={['contextMenu']}>
<AssistantItem onClick={() => onSwitchAssistant(assistant)} className={isCurrent ? 'active' : ''}>
<AssistantName className="name">{assistant.name || t('chat.default.name')}</AssistantName>
{isCurrent && (
<ArrowRightButton onClick={() => EventEmitter.emit(EVENT_NAMES.SWITCH_TOPIC_SIDEBAR)}>
<i className="iconfont icon-gridlines" />
</ArrowRightButton>
)}
{false && <TopicCount className="topics-count">{assistant.topics.length}</TopicCount>}
</AssistantItem>
</Dropdown>
)
}}
</DragableList>
{!dragging && (
<AssistantItem onClick={onCreateAssistant}>
<AssistantName>
<PlusOutlined style={{ color: 'var(--color-text-2)', marginRight: 4 }} />
{t('chat.add.assistant.title')}
</AssistantName>
</AssistantItem>
)}
<div style={{ minHeight: 10 }}></div>
</Container>
</Scrollbar>
)
}
const Container = styled.div`
display: flex;
flex-direction: column;
height: calc(100vh - var(--navbar-height));
overflow-y: auto;
padding-top: 10px;
padding-bottom: 10px;
`
const AssistantItem = styled.div`

View File

@@ -0,0 +1,323 @@
import { CheckOutlined, QuestionCircleOutlined, ReloadOutlined } from '@ant-design/icons'
import { HStack } from '@renderer/components/Layout'
import { Scrollbar } from '@renderer/components/Scrollbar'
import { DEFAULT_CONEXTCOUNT, DEFAULT_MAX_TOKENS, DEFAULT_TEMPERATURE } from '@renderer/config/constant'
import { useAssistant } from '@renderer/hooks/useAssistant'
import { useSettings } from '@renderer/hooks/useSettings'
import { SettingDivider, SettingRow, SettingRowTitle, SettingSubtitle } from '@renderer/pages/settings'
import { useAppDispatch } from '@renderer/store'
import {
setCodeShowLineNumbers,
setFontSize,
setMathEngine,
setMessageFont,
setPasteLongTextAsFile,
setRenderInputMessageAsMarkdown,
setShowInputEstimatedTokens,
setShowMessageDivider
} from '@renderer/store/settings'
import { Assistant, AssistantSettings } from '@renderer/types'
import { Col, Row, Select, Slider, Switch, Tooltip } from 'antd'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
interface Props {
assistant: Assistant
}
const SettingsTab: FC<Props> = (props) => {
const { assistant, updateAssistantSettings, updateAssistant } = useAssistant(props.assistant.id)
const { fontSize } = useSettings()
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 [streamOutput, setStreamOutput] = useState(assistant?.settings?.streamOutput ?? true)
const [fontSizeValue, setFontSizeValue] = useState(fontSize)
const { t } = useTranslation()
const dispatch = useAppDispatch()
const {
showMessageDivider,
messageFont,
showInputEstimatedTokens,
sendMessageShortcut,
setSendMessageShortcut,
pasteLongTextAsFile,
renderInputMessageAsMarkdown,
codeShowLineNumbers,
mathEngine
} = useSettings()
const onUpdateAssistantSettings = (settings: Partial<AssistantSettings>) => {
updateAssistantSettings(settings)
}
const onTemperatureChange = (value) => {
if (!isNaN(value as number)) {
onUpdateAssistantSettings({ temperature: value })
}
}
const onConextCountChange = (value) => {
if (!isNaN(value as number)) {
onUpdateAssistantSettings({ contextCount: value })
}
}
const onMaxTokensChange = (value) => {
if (!isNaN(value as number)) {
onUpdateAssistantSettings({ 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,
hideMessages: false,
autoResetModel: false
}
})
}
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])
return (
<Scrollbar>
<Container>
<SettingSubtitle style={{ marginTop: 5 }}>
{t('settings.messages.model.title')}{' '}
<Tooltip title={t('chat.settings.reset')}>
<ReloadOutlined onClick={onReset} style={{ cursor: 'pointer', fontSize: 12, padding: '0 3px' }} />
</Tooltip>
</SettingSubtitle>
<SettingDivider />
<Row align="middle">
<Label>{t('chat.settings.temperature')}</Label>
<Tooltip title={t('chat.settings.temperature.tip')}>
<QuestionIcon />
</Tooltip>
</Row>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
min={0}
max={2}
onChange={setTemperature}
onChangeComplete={onTemperatureChange}
value={typeof temperature === 'number' ? temperature : 0}
step={0.1}
/>
</Col>
</Row>
<Row align="middle">
<Label>{t('chat.settings.conext_count')}</Label>
<Tooltip title={t('chat.settings.conext_count.tip')}>
<QuestionIcon />
</Tooltip>
</Row>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
min={0}
max={20}
onChange={setConextCount}
onChangeComplete={onConextCountChange}
value={typeof contextCount === 'number' ? contextCount : 0}
step={1}
/>
</Col>
</Row>
<SettingRow>
<SettingRowTitleSmall>{t('model.stream_output')}</SettingRowTitleSmall>
<Switch
size="small"
checked={streamOutput}
onChange={(checked) => {
setStreamOutput(checked)
onUpdateAssistantSettings({ streamOutput: checked })
}}
/>
</SettingRow>
<SettingDivider />
<Row align="middle" justify="space-between">
<HStack alignItems="center">
<Label>{t('chat.settings.max_tokens')}</Label>
<Tooltip title={t('chat.settings.max_tokens.tip')}>
<QuestionIcon />
</Tooltip>
</HStack>
<Switch
size="small"
checked={enableMaxTokens}
onChange={(enabled) => {
setEnableMaxTokens(enabled)
onUpdateAssistantSettings({ enableMaxTokens: enabled })
}}
/>
</Row>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
disabled={!enableMaxTokens}
min={0}
max={32000}
onChange={setMaxTokens}
onChangeComplete={onMaxTokensChange}
value={typeof maxTokens === 'number' ? maxTokens : 0}
step={100}
/>
</Col>
</Row>
<SettingSubtitle>{t('settings.messages.title')}</SettingSubtitle>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.divider')}</SettingRowTitleSmall>
<Switch
size="small"
checked={showMessageDivider}
onChange={(checked) => dispatch(setShowMessageDivider(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.use_serif_font')}</SettingRowTitleSmall>
<Switch
size="small"
checked={messageFont === 'serif'}
onChange={(checked) => dispatch(setMessageFont(checked ? 'serif' : 'system'))}
/>
</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.messages.math_engine')}</SettingRowTitleSmall>
<Select
value={mathEngine}
onChange={(value) => dispatch(setMathEngine(value))}
style={{ width: 100 }}
size="small">
<Select.Option value="KaTeX">KaTeX</Select.Option>
<Select.Option value="MathJax">MathJax</Select.Option>
</Select>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.font_size.title')}</SettingRowTitleSmall>
</SettingRow>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
value={fontSizeValue}
onChange={(value) => setFontSizeValue(value)}
onChangeComplete={(value) => dispatch(setFontSize(value))}
min={12}
max={22}
step={1}
marks={{
12: <span style={{ fontSize: '12px' }}>A</span>,
14: <span style={{ fontSize: '14px' }}>{t('common.default')}</span>,
22: <span style={{ fontSize: '18px' }}>A</span>
}}
/>
</Col>
</Row>
<SettingSubtitle>{t('settings.messages.input.title')}</SettingSubtitle>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.input.show_estimated_tokens')}</SettingRowTitleSmall>
<Switch
size="small"
checked={showInputEstimatedTokens}
onChange={(checked) => dispatch(setShowInputEstimatedTokens(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.input.paste_long_text_as_file')}</SettingRowTitleSmall>
<Switch
size="small"
checked={pasteLongTextAsFile}
onChange={(checked) => dispatch(setPasteLongTextAsFile(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.markdown_rendering_input_message')}</SettingRowTitleSmall>
<Switch
size="small"
checked={renderInputMessageAsMarkdown}
onChange={(checked) => dispatch(setRenderInputMessageAsMarkdown(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('settings.messages.input.send_shortcuts')}</SettingRowTitleSmall>
<Select
size="small"
value={sendMessageShortcut}
menuItemSelectedIcon={<CheckOutlined />}
options={[
{ value: 'Enter', label: 'Enter' },
{ value: 'Shift+Enter', label: `Shift + Enter` }
]}
onChange={(value) => setSendMessageShortcut(value)}
style={{ width: 100 }}
/>
</SettingRow>
</Container>
</Scrollbar>
)
}
const Container = styled.div`
display: flex;
flex: 1;
flex-direction: column;
padding-bottom: 10px;
padding: 10px 15px;
margin-bottom: 10px;
`
const Label = styled.p`
margin: 0;
font-size: 12px;
margin-right: 5px;
`
const QuestionIcon = styled(QuestionCircleOutlined)`
font-size: 12px;
cursor: pointer;
color: var(--color-text-3);
`
const SettingRowTitleSmall = styled(SettingRowTitle)`
font-size: 13px;
`
export default SettingsTab

View File

@@ -1,13 +1,25 @@
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 { Scrollbar } from '@renderer/components/Scrollbar'
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 +36,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 +46,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 +77,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 +115,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 +136,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,47 +174,51 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
return menus
},
[assistant, assistants, onDeleteTopic, onMoveTopic, t, updateTopic]
[assistant, assistants, onClearMessages, onDeleteTopic, onMoveTopic, t, updateTopic]
)
return (
<Container>
<DragableList list={assistant.topics} onUpdate={updateTopics}>
{(topic) => {
const isActive = topic.id === activeTopic?.id
return (
<Dropdown menu={{ items: getTopicMenuItems(topic) }} trigger={['contextMenu']} key={topic.id}>
<TopicListItem className={isActive ? 'active' : ''} onClick={() => onSwitchTopic(topic)}>
<TopicName className="name">{topic.name.replace('`', '')}</TopicName>
{assistant.topics.length > 1 && isActive && (
<MenuButton
className="menu"
onClick={(e) => {
e.stopPropagation()
onDeleteTopic(topic)
}}>
<CloseOutlined />
</MenuButton>
)}
</TopicListItem>
</Dropdown>
)
}}
</DragableList>
</Container>
<Scrollbar>
<Container>
<DragableList list={assistant.topics} onUpdate={updateTopics}>
{(topic) => {
const isActive = topic.id === activeTopic?.id
return (
<Dropdown menu={{ items: getTopicMenuItems(topic) }} trigger={['contextMenu']} key={topic.id}>
<TopicListItem
className={isActive ? 'active' : ''}
style={{ borderRadius }}
onClick={() => onSwitchTopic(topic)}>
<TopicName className="name">{topic.name.replace('`', '')}</TopicName>
{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 />
</MenuButton>
)}
</TopicListItem>
</Dropdown>
)
}}
</DragableList>
<div style={{ minHeight: '10px' }}></div>
</Container>
</Scrollbar>
)
}
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 +228,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 +264,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`

View File

@@ -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

View File

@@ -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`

View File

@@ -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

View File

@@ -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 />

View File

@@ -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

View File

@@ -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>

View 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

View File

@@ -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

View File

@@ -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)
}))
}))

View File

@@ -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,14 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
updateProvider({ ...provider, apiHost: configedApiHost })
}
const hostPreview = () => {
if (apiHost.endsWith('#')) {
return apiHost.replace('#', '')
}
return (apiHost.endsWith('/') ? apiHost : `${apiHost}/v1/`) + 'chat/completions'
}
return (
<SettingContainer
style={
@@ -138,6 +147,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>

View File

@@ -1,5 +1,6 @@
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons'
import { DragDropContext, Draggable, Droppable, DropResult } from '@hello-pangea/dnd'
import { Scrollbar } from '@renderer/components/Scrollbar'
import { getProviderLogo } from '@renderer/config/providers'
import { useAllProviders, useProviders } from '@renderer/hooks/useProvider'
import { Provider } from '@renderer/types'
@@ -85,56 +86,58 @@ const ProvidersList: FC = () => {
return (
<Container>
<ProviderListContainer>
<ProviderList>
<DragDropContext onDragStart={() => setDragging(true)} onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{providers.map((provider, index) => (
<Draggable key={`draggable_${provider.id}_${index}`} draggableId={provider.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{ ...provided.draggableProps.style, marginBottom: 5 }}>
<Dropdown
menu={{ items: provider.isSystem ? [] : getDropdownMenus(provider) }}
trigger={['contextMenu']}>
<ProviderListItem
key={JSON.stringify(provider)}
className={provider.id === selectedProvider?.id ? 'active' : ''}
onClick={() => setSelectedProvider(provider)}>
{provider.isSystem && (
<ProviderLogo shape="square" src={getProviderLogo(provider.id)} size={25} />
)}
{!provider.isSystem && (
<ProviderLogo
size={25}
shape="square"
style={{ backgroundColor: generateColorFromChar(provider.name), minWidth: 25 }}>
{getFirstCharacter(provider.name)}
</ProviderLogo>
)}
<ProviderItemName>
{provider.isSystem ? t(`provider.${provider.id}`) : provider.name}
</ProviderItemName>
{provider.enabled && (
<Tag color="green" style={{ marginLeft: 'auto' }}>
ON
</Tag>
)}
</ProviderListItem>
</Dropdown>
</div>
)}
</Draggable>
))}
</div>
)}
</Droppable>
</DragDropContext>
</ProviderList>
<Scrollbar>
<ProviderList>
<DragDropContext onDragStart={() => setDragging(true)} onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{providers.map((provider, index) => (
<Draggable key={`draggable_${provider.id}_${index}`} draggableId={provider.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{ ...provided.draggableProps.style, marginBottom: 5 }}>
<Dropdown
menu={{ items: provider.isSystem ? [] : getDropdownMenus(provider) }}
trigger={['contextMenu']}>
<ProviderListItem
key={JSON.stringify(provider)}
className={provider.id === selectedProvider?.id ? 'active' : ''}
onClick={() => setSelectedProvider(provider)}>
{provider.isSystem && (
<ProviderLogo shape="square" src={getProviderLogo(provider.id)} size={25} />
)}
{!provider.isSystem && (
<ProviderLogo
size={25}
shape="square"
style={{ backgroundColor: generateColorFromChar(provider.name), minWidth: 25 }}>
{getFirstCharacter(provider.name)}
</ProviderLogo>
)}
<ProviderItemName className="text-nowrap">
{provider.isSystem ? t(`provider.${provider.id}`) : provider.name}
</ProviderItemName>
{provider.enabled && (
<Tag color="green" style={{ marginLeft: 'auto' }}>
ON
</Tag>
)}
</ProviderListItem>
</Dropdown>
</div>
)}
</Draggable>
))}
</div>
)}
</Droppable>
</DragDropContext>
</ProviderList>
</Scrollbar>
{!dragging && (
<AddButtonWrapper>
<Button type="dashed" style={{ width: '100%' }} icon={<PlusOutlined />} onClick={onAddProvider} />
@@ -159,15 +162,12 @@ const ProviderListContainer = styled.div`
width: var(--assistants-width);
height: calc(100vh - var(--navbar-height));
border-right: 0.5px solid var(--color-border);
overflow-y: auto;
`
const ProviderList = styled.div`
display: flex;
flex: 1;
flex-direction: column;
height: calc(100vh - var(--navbar-height));
overflow: auto;
padding: 8px;
`
@@ -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;
`

Some files were not shown because too many files have changed in this diff Show More