Compare commits

..

No commits in common. "486989817320adb6a3511548d2ebb86d065d578f" and "8f2299b875ba331128a130a3b5ecaf0a87a6d722" have entirely different histories.

103 changed files with 1178 additions and 2715 deletions

View File

@ -1,4 +1,4 @@
name: 🐛 错误报告 (中文)
name: 🐛 错误报告
description: 创建一个报告以帮助我们改进
title: '[错误]: '
labels: ['bug']
@ -7,20 +7,17 @@ body:
attributes:
value: |
感谢您花时间填写此错误报告!
在提交此问题之前,请确保您已经了解了[常见问题](https://docs.cherry-ai.com/question-contact/questions)和[知识科普](https://docs.cherry-ai.com/question-contact/knowledge)
- type: checkboxes
id: checklist
attributes:
label: 提交前检查
label: Issue 检查清单
description: |
在提交 Issue 前请确保您已经完成了以下所有步骤
options:
- label: 理解 Issue 是用于反馈和解决问题的,而非吐槽评论区,将尽可能提供更多信息帮助问题解决
- label: 已经查看了置顶 Issue 并搜索了现有的 Issue但没有找到类似的问题
required: true
- label: 我已经查看了置顶 Issue 并搜索了现有的 [开放Issue](https://github.com/CherryHQ/cherry-studio/issues)和[已关闭Issue](https://github.com/CherryHQ/cherry-studio/issues?q=is%3Aissue%20state%3Aclosed%20),没有找到类似的问题。
required: true
- label: 我填写了简短且清晰明确的标题,以便开发者在翻阅 Issue 列表时能快速确定大致问题。而不是“一个建议”、“卡住了”等。
- label: 正确填写了 Issue 标题。
required: true
- type: dropdown
@ -48,7 +45,7 @@ body:
id: description
attributes:
label: 错误描述
description: 描述问题时请尽可能详细
description: 清晰简洁地描述错误是什么
placeholder: 告诉我们发生了什么...
validations:
required: true
@ -57,7 +54,7 @@ body:
id: reproduction
attributes:
label: 重现步骤
description: 提供详细的重现步骤,以便于我们可以准确地重现问题
description: 重现行为的步骤
placeholder: |
1. 转到 '...'
2. 点击 '....'
@ -85,4 +82,4 @@ body:
id: additional
attributes:
label: 附加信息
description: 任何能让我们对你所遇到的问题有更多了解的东西
description: 在此添加有关问题的任何其他上下文

View File

@ -1,4 +1,4 @@
name: 💡 功能建议 (中文)
name: 💡 功能建议
description: 为项目提出新的想法
title: '[功能]: '
labels: ['enhancement']
@ -7,22 +7,17 @@ body:
attributes:
value: |
感谢您花时间提出新的功能建议!
在提交此问题之前,请确保您已经了解了[项目规划](https://docs.cherry-ai.com/cherrystudio/planning)和[功能介绍](https://docs.cherry-ai.com/cherrystudio/preview)
- type: checkboxes
id: checklist
attributes:
label: 提交前检查
label: Issue 检查清单
description: |
在提交 Issue 前请确保您已经完成了以下所有步骤
options:
- label: 理解 Issue 是用于反馈和解决问题的,而非吐槽评论区,将尽可能提供更多信息帮助问题解决
- label: 已经查看了置顶 Issue 并搜索了现有的 Issue但没有找到类似的问题
required: true
- label: 我已经查看了置顶 Issue 并搜索了现有的 [开放Issue](https://github.com/CherryHQ/cherry-studio/issues)和[已关闭Issue](https://github.com/CherryHQ/cherry-studio/issues?q=is%3Aissue%20state%3Aclosed%20),没有找到类似的建议。
required: true
- label: 我填写了简短且清晰明确的标题,以便开发者在翻阅 Issue 列表时能快速确定大致问题。而不是“一个建议”、“卡住了”等。
required: true
- label: 最新的 Cherry Studio 版本没有实现我所提出的功能。
- label: 正确填写了 Issue 标题。
required: true
- type: dropdown
@ -49,7 +44,7 @@ body:
- type: textarea
id: problem
attributes:
label: 您的功能建议是否与某个问题/issue相关?
label: 您的功能建议是否与某个问题相关?
description: 请简明扼要地描述您遇到的问题
placeholder: 我总是感到沮丧,因为...
validations:

View File

@ -1,6 +1,6 @@
name: 讨论 & 提问 (中文)
description: 寻求帮助、讨论问题、提出疑问等...
title: '[讨论]: '
name: 提问
description: 提出一个问题或寻求帮助
title: '[问题]: '
labels: ['question']
body:
- type: markdown
@ -15,9 +15,9 @@ body:
description: |
在提交 Issue 前请确保您已经完成了以下所有步骤
options:
- label: 理解 Issue 是用于反馈和解决问题的,而非吐槽评论区,将尽可能提供更多信息帮助问题解决
- label: 已经查看了置顶 Issue 并搜索了现有的 Issue但没有找到类似的问题
required: true
- label: 我确认自己需要的是提出问题并且讨论问题,而不是 Bug 反馈或需求建议
- label: 正确填写了 Issue 标题
required: true
- type: dropdown

View File

@ -6,8 +6,7 @@ body:
- type: markdown
attributes:
value: |
Thank you for taking the time to fill out this bug report!
Before submitting this issue, please make sure that you have understood the [FAQ](https://docs.cherry-ai.com/question-contact/questions) and [Knowledge Science](https://docs.cherry-ai.com/question-contact/knowledge)
Thanks for taking the time to fill out this bug report!
- type: checkboxes
id: checklist
@ -16,11 +15,9 @@ body:
description: |
Before submitting an issue, please make sure you have completed the following steps
options:
- label: I understand that issues are for feedback and problem solving, not for complaining in the comment section, and will provide as much information as possible to help solve the problem.
- label: I have viewed the pinned issues and searched existing issues but couldn't find anything similar.
required: true
- label: I've looked at pinned issues and searched for existing [Open Issues](https://github.com/CherryHQ/cherry-studio/issues), [Closed Issues](https://github.com/CherryHQ/cherry-studio/issues?q=is%3Aissue%20state%3Aclosed), and [Discussions](https://github.com/CherryHQ/cherry-studio/discussions), no similar issue or discussion was found.
required: true
- label: I've filled in short, clear headings so that developers can quickly identify a rough idea of what to expect when flipping through the list of issues. And not "a suggestion", "stuck", etc.
- label: I have filled out the issue title correctly.
required: true
- type: dropdown
@ -48,8 +45,8 @@ body:
id: description
attributes:
label: Bug Description
description: Please be as detailed as possible when describing the problem. Please provide screenshots or screen recordings whenever possible to help us better understand the issue.
placeholder: Tell us what happened... (Remember to attach screenshots/recordings if applicable)
description: A clear and concise description of what the bug is
placeholder: Tell us what happened...
validations:
required: true
@ -57,14 +54,12 @@ body:
id: reproduction
attributes:
label: Steps To Reproduce
description: Provide detailed steps to reproduce the issue so that our developers can reproduce the issue accurately. Please include screenshots or screen recordings for each step when possible.
description: Steps to reproduce the behavior
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
Remember to attach screenshots/recordings for each step when possible!
validations:
required: true
@ -87,4 +82,4 @@ body:
id: additional
attributes:
label: Additional Context
description: Anything that gives us a better understanding of the problem you're experiencing
description: Add any other context about the problem here

View File

@ -6,8 +6,7 @@ body:
- type: markdown
attributes:
value: |
Thank you for taking the time to submit a feature request!
Before submitting this issue, please make sure you have reviewed the [Project Roadmap](https://docs.cherry-ai.com/cherrystudio/planning) and the [Feature Overview](https://docs.cherry-ai.com/cherrystudio/preview).
Thanks for taking the time to suggest a new feature!
- type: checkboxes
id: checklist
@ -16,13 +15,9 @@ body:
description: |
Before submitting an issue, please make sure you have completed the following steps
options:
- label: I understand that issues are for reporting problems and requesting features, not for off-topic comments, and I will provide as much detail as possible to help resolve the issue.
- label: I have viewed the pinned issues and searched existing issues but couldn't find anything similar.
required: true
- label: I have checked the pinned issues and searched through the existing [open issues](https://github.com/CherryHQ/cherry-studio/issues), [closed issues](https://github.com/CherryHQ/cherry-studio/issues?q=is%3Aissue%20state%3Aclosed), and [discussions](https://github.com/CherryHQ/cherry-studio/discussions) and did not find a similar suggestion.
required: true
- label: I have provided a short and descriptive title so that developers can quickly understand the issue when browsing the issue list, rather than vague titles like "A suggestion" or "Stuck."
required: true
- label: The latest version of Cherry Studio does not include the feature I am suggesting.
- label: I have filled out the issue title correctly.
required: true
- type: dropdown
@ -49,28 +44,28 @@ body:
- type: textarea
id: problem
attributes:
label: Is your feature request related to an existing issue?
description: Please briefly describe the problem you are experiencing. If possible, include screenshots or recordings to help illustrate the current situation or pain points.
placeholder: I often feel frustrated because... (Remember to attach screenshots/recordings if applicable)
label: Is your feature request related to a problem?
description: A clear and concise description of what the problem is
placeholder: I'm always frustrated when...
validations:
required: true
- type: textarea
id: solution
attributes:
label: Desired Solution
description: Please briefly describe what you would like to happen. You can include mockups, screenshots, or screen recordings to better illustrate your proposed solution.
label: Describe the solution you'd like
description: A clear and concise description of what you want to happen
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternative Solutions
description: Please briefly describe any alternative solutions or features you have considered. Feel free to include screenshots or mockups of alternative approaches.
label: Describe alternatives you've considered
description: A clear and concise description of any alternative solutions or features you've considered
- type: textarea
id: additional
attributes:
label: Additional Information
description: Add any other context, screenshots, mockups or recordings that can help us better understand your feature request.
label: Additional Context
description: Add any other context or screenshots about the feature request here

View File

@ -1,12 +1,12 @@
name: Discussion & Questions
description: Seeking help, discussing issues, asking questions, etc...
title: '[Discussion]: '
name: Question
description: Ask a question or seek help
title: '[Question]: '
labels: ['question']
body:
- type: markdown
attributes:
value: |
Thank you for your question! Please describe your issue in as much detail as possible so that we can better assist you.
Thanks for asking a question! Please provide as much detail as possible so we can better assist you.
- type: checkboxes
id: checklist
@ -15,11 +15,9 @@ body:
description: |
Before submitting an issue, please make sure you have completed the following steps
options:
- label: I understand that issues are meant for feedback and problem-solving, not for venting, and I will provide as much detail as possible to help resolve the issue.
- label: I have viewed the pinned issues and searched existing issues but couldn't find anything similar.
required: true
- label: I have checked the pinned issues and searched through the existing [open issues](https://github.com/CherryHQ/cherry-studio/issues), [closed issues](https://github.com/CherryHQ/cherry-studio/issues?q=is%3Aissue%20state%3Aclosed), and [discussions](https://github.com/CherryHQ/cherry-studio/discussions) and did not find a similar suggestion.
required: true
- label: I confirm that I am here to ask questions and discuss issues, not to report bugs or request features.
- label: I have filled out the issue title correctly.
required: true
- type: dropdown
@ -47,8 +45,8 @@ body:
id: question
attributes:
label: Your Question
description: Please describe your issue in detail. Include screenshots or screen recordings whenever possible to help us better understand your question.
placeholder: Please explain your issue as clearly as possible...(Remember to attach screenshots/recordings if applicable)
description: Please describe your question in detail
placeholder: Please explain your question as clearly as possible...
validations:
required: true
@ -56,23 +54,23 @@ body:
id: context
attributes:
label: Context
description: Please provide some background information to help us better understand your question. Screenshots or recordings of your current setup or situation can be very helpful.
placeholder: "For example: use case, solutions you've tried, etc. Don't forget to include relevant screenshots/recordings!"
description: Please provide some background information to help us better understand your question
placeholder: "For example: use case, solutions you've tried, etc."
- type: textarea
id: additional
attributes:
label: Additional Information
description: Any other relevant information, screenshots, recordings, or code examples that can help us better assist you
description: Any other relevant information, screenshots, or code examples
render: shell
- type: dropdown
id: priority
attributes:
label: Priority
description: How urgent is this issue for you?
description: How urgent is this question for you?
options:
- Low (Review when available)
- Low (Can wait)
- Medium (Would like a response soon)
- High (Blocking progress)
validations:

View File

@ -60,20 +60,6 @@ Cherry Studio is a desktop client that supports for multiple LLM providers, avai
- 📝 Complete Markdown Rendering
- 🤲 Easy Content Sharing
# 📝 TODO
- [x] Quick popup (read clipboard, quick question, explain, translate, summarize)
- [x] Comparison of multi-model answers
- [x] Support login using SSO provided by service providers
- [ ] All models support networking (in development...)
- [ ] Launch of the first official version
- [ ] Plugin functionality (JavaScript)
- [ ] Browser extension (highlight text to translate, summarize, add to knowledge base)
- [ ] iOS & Android client
- [ ] AI notes
- [ ] Voice input and output (AI call)
- [ ] Data backup supports custom backup content
# 🖥️ Develop
## IDE Setup

View File

@ -61,20 +61,6 @@ Cherry Studioは、複数のLLMプロバイダーをサポートするデスク
- 📝 完全な Markdown レンダリング
- 🤲 簡単な共有機能
# 📝 TODO
- [x] クイックポップアップ(クリップボードの読み取り、簡単な質問、説明、翻訳、要約)
- [x] 複数モデルの回答の比較
- [x] サービスプロバイダーが提供するSSOを使用したログインをサポート
- [ ] すべてのモデルがネットワークをサポート(開発中...
- [ ] 最初の公式バージョンのリリース
- [ ] プラグイン機能JavaScript
- [ ] ブラウザ拡張機能(テキストをハイライトして翻訳、要約、ナレッジベースに追加)
- [ ] iOS & Android クライアント
- [ ] AIート
- [ ] 音声入出力AIコール
- [ ] データバックアップはカスタムバックアップコンテンツをサポート
# 🖥️ 開発
## IDEの設定

View File

@ -61,20 +61,6 @@ Cherry Studio 是一款支持多个大语言模型LLM服务商的桌面客
- 📝 完整的 Markdown 渲染
- 🤲 便捷的内容分享功能
# 📝 待辦事項
- [x] 快捷彈窗 (讀取剪貼簿、快速提問、解釋、翻譯、總結)
- [x] 多模型回答對比
- [x] 支援使用服務供應商提供的 SSO 進行登入
- [ ] 全部模型支援連網(開發中...
- [ ] 推出第一個正式版
- [ ] 插件功能JavaScript
- [ ] 瀏覽器插件(劃詞翻譯、總結、新增至知識庫)
- [ ] iOS & Android 客戶端
- [ ] AI 筆記
- [ ] 語音輸入輸出AI 通話)
- [ ] 資料備份支援自訂備份內容
# 🖥️ 开发
## IDE 设置

View File

@ -80,11 +80,11 @@ afterPack: scripts/after-pack.js
afterSign: scripts/notarize.js
releaseInfo:
releaseNotes: |
消息分组支持网格模式
知识库支持多选
知识库添加目录支持显示进度
知识库支持 DRAFTS, EPUB、代码等
知识库支持调节匹配度阈值
添加 NotebookLM, Coze 小程序
增加话题提示词
OpenRouter 支持 Web 搜索
增加服务商 LM Studio、魔搭、Perplexity、无问芯穹、DMXAPI
提及功能支持上下按键循环选择模型
小程序增加小艺
增加Notion连接检测功能
编辑模型弹窗搜索模型时同时搜索模型的名字和ID
编辑模型弹窗增加推理模型筛选按钮
修复思考模型思考时间显示错误
修复部分模型翻译出错

View File

@ -1,6 +1,6 @@
{
"name": "CherryStudio",
"version": "0.9.27",
"version": "0.9.24",
"private": true,
"description": "A powerful AI assistant for producer.",
"main": "./out/main/index.js",
@ -94,7 +94,6 @@
"@types/markdown-it": "^14",
"@types/md5": "^2.3.5",
"@types/node": "^18.19.9",
"@types/pako": "^1.0.2",
"@types/react": "^18.2.48",
"@types/react-dom": "^18.2.18",
"@types/react-infinite-scroll-component": "^5.0.0",
@ -138,7 +137,7 @@
"redux": "^5.0.1",
"redux-persist": "^6.0.0",
"rehype-katex": "^7.0.1",
"rehype-mathjax": "^7.0.0",
"rehype-mathjax": "^6.0.0",
"rehype-raw": "^7.0.0",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",

View File

@ -2,7 +2,6 @@ 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 thirdPartyApplicationExts = ['.draftsExport']
export const bookExts = ['.epub']
export const textExts = [
'.txt', // 普通文本文件
@ -90,10 +89,7 @@ export const textExts = [
'.groovy', // Gradle 构建文件
'.kts', // Kotlin Script 文件
'.java', // Java 代码文件
'.cs', // C# 代码文件
'.cpp', // C++ 代码文件
'.c', // C++ 代码文件
'.h' // C++ 头文件
'.cs' // C# 代码文件
]
export const ZOOM_SHORTCUTS = [

View File

@ -1,5 +1,5 @@
import { electronApp, optimizer } from '@electron-toolkit/utils'
import { app } from 'electron'
import { app, BrowserWindow } from 'electron'
import installExtension, { REDUX_DEVTOOLS } from 'electron-devtools-installer'
import { registerIpc } from './ipc'
@ -46,13 +46,15 @@ if (!app.requestSingleInstanceLock()) {
new TrayService()
app.on('activate', function () {
const mainWindow = windowService.getMainWindow()
if (!mainWindow || mainWindow.isDestroyed()) {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
windowService.createMainWindow()
} else {
windowService.showMainWindow()
}
})
registerShortcuts(mainWindow)
registerIpc(mainWindow, app)
@ -66,7 +68,12 @@ if (!app.requestSingleInstanceLock()) {
// Listen for second instance
app.on('second-instance', () => {
windowService.showMainWindow()
const mainWindow = BrowserWindow.getAllWindows()[0]
if (mainWindow) {
mainWindow.isMinimized() && mainWindow.restore()
mainWindow.show()
mainWindow.focus()
}
})
app.on('browser-window-created', (_, window) => {

View File

@ -1,22 +0,0 @@
import * as fs from 'node:fs'
import { JsonLoader } from '@llm-tools/embedjs'
/**
* Drafts
* JSON contenttagsmodified_at
*/
export class DraftsExportLoader extends JsonLoader {
constructor(filePath: string) {
const fileContent = fs.readFileSync(filePath, 'utf-8')
const rawJson = JSON.parse(fileContent) as any[]
const json = rawJson.map((item) => {
return {
content: item.content?.replace(/\n/g, '<br>'),
tags: item.tags,
modified_at: item.created_at
}
})
super({ object: json })
}
}

View File

@ -1,18 +1,17 @@
import * as fs from 'node:fs'
import { JsonLoader, LocalPathLoader, RAGApplication, TextLoader } from '@llm-tools/embedjs'
import { LocalPathLoader, RAGApplication, TextLoader } from '@llm-tools/embedjs'
import type { AddLoaderReturn } from '@llm-tools/embedjs-interfaces'
import { WebLoader } from '@llm-tools/embedjs-loader-web'
import { LoaderReturn } from '@shared/config/types'
import { FileType, KnowledgeBaseParams } from '@types'
import Logger from 'electron-log'
import { DraftsExportLoader } from './draftsExportLoader'
import { EpubLoader } from './epubLoader'
import { OdLoader, OdType } from './odLoader'
// embedjs内置loader类型
const commonExts = ['.pdf', '.csv', '.docx', '.pptx', '.xlsx', '.md']
const commonExts = ['.pdf', '.csv', '.json', '.docx', '.pptx', '.xlsx', '.md']
export async function addOdLoader(
ragApplication: RAGApplication,
@ -90,19 +89,7 @@ export async function addFileLoader(
} as LoaderReturn
}
// DraftsExport类型 (file.ext会自动转换成小写)
if (['.draftsexport'].includes(file.ext)) {
const loaderReturn = await ragApplication.addLoader(new DraftsExportLoader(file.path) as any, forceReload)
return {
entriesAdded: loaderReturn.entriesAdded,
uniqueId: loaderReturn.uniqueId,
uniqueIds: [loaderReturn.uniqueId],
loaderType: loaderReturn.loaderType
}
}
const fileContent = fs.readFileSync(file.path, 'utf-8')
// HTML类型
if (['.html', '.htm'].includes(file.ext)) {
const loaderReturn = await ragApplication.addLoader(
@ -121,27 +108,6 @@ export async function addFileLoader(
}
}
// JSON类型
if (['.json'].includes(file.ext)) {
let jsonObject = {}
let jsonParsed = true
try {
jsonObject = JSON.parse(fileContent)
} catch (error) {
jsonParsed = false
Logger.warn('[KnowledgeBase] failed parsing json file, failling back to text processing:', file.path, error)
}
if (jsonParsed) {
const loaderReturn = await ragApplication.addLoader(new JsonLoader({ object: jsonObject }))
return {
entriesAdded: loaderReturn.entriesAdded,
uniqueId: loaderReturn.uniqueId,
uniqueIds: [loaderReturn.uniqueId],
loaderType: loaderReturn.loaderType
}
}
}
// 文本类型
const loaderReturn = await ragApplication.addLoader(
new TextLoader({ text: fileContent, chunkSize: base.chunkSize, chunkOverlap: base.chunkOverlap }) as any,

View File

@ -15,8 +15,6 @@ import { FileType, KnowledgeBaseParams, KnowledgeItem } from '@types'
import { app } from 'electron'
import { v4 as uuidv4 } from 'uuid'
import { windowService } from './WindowService'
class KnowledgeService {
private storageDir = path.join(app.getPath('userData'), 'Data', 'KnowledgeBase')
@ -85,23 +83,10 @@ class KnowledgeService {
): Promise<LoaderReturn> => {
const ragApplication = await this.getRagApplication(base)
const sendDirectoryProcessingPercent = (totalFiles: number, processedFiles: number) => {
const mainWindow = windowService.getMainWindow()
mainWindow?.webContents.send(base.id, (processedFiles / totalFiles) * 100)
}
if (item.type === 'directory') {
const directory = item.content as string
const files = getAllFiles(directory)
const totalFiles = files.length
let processedFiles = 0
const loaderPromises = files.map(async (file) => {
const result = await addFileLoader(ragApplication, file, base, forceReload)
processedFiles++
sendDirectoryProcessingPercent(totalFiles, processedFiles)
return result
})
const loaderPromises = files.map((file) => addFileLoader(ragApplication, file, base, forceReload))
const loaderResults = await Promise.all(loaderPromises)
const uniqueIds = loaderResults.map((result) => result.uniqueId)
return {

View File

@ -47,8 +47,8 @@ function formatShortcutKey(shortcut: string[]): string {
function handleZoom(delta: number) {
return (window: BrowserWindow) => {
const currentZoom = configManager.getZoomFactor()
const newZoom = Number((currentZoom + delta).toFixed(1))
const currentZoom = window.webContents.getZoomFactor()
const newZoom = currentZoom + delta
if (newZoom >= 0.1 && newZoom <= 5.0) {
window.webContents.setZoomFactor(newZoom)
configManager.setZoomFactor(newZoom)
@ -70,12 +70,10 @@ const convertShortcutRecordedByKeyboardEventKeyValueToElectronGlobalShortcutForm
return accelerator
.map((key) => {
switch (key) {
case 'Command':
return 'CommandOrControl'
case 'Control':
return 'Control'
return 'CommandOrControl'
case 'Ctrl':
return 'Control'
return 'CommandOrControl'
case 'ArrowUp':
return 'Up'
case 'ArrowDown':
@ -112,9 +110,7 @@ const convertShortcutRecordedByKeyboardEventKeyValueToElectronGlobalShortcutForm
}
export function registerShortcuts(window: BrowserWindow) {
window.once('ready-to-show', () => {
window.webContents.setZoomFactor(configManager.getZoomFactor())
})
window.webContents.setZoomFactor(configManager.getZoomFactor())
const register = () => {
if (window.isDestroyed()) return

View File

@ -28,7 +28,6 @@ export class WindowService {
public createMainWindow(): BrowserWindow {
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.show()
return this.mainWindow
}
@ -249,32 +248,17 @@ export class WindowService {
event.preventDefault()
mainWindow.hide()
})
mainWindow.on('closed', () => {
this.mainWindow = null
})
mainWindow.on('show', () => {
if (this.miniWindow && !this.miniWindow.isDestroyed()) {
this.miniWindow.hide()
}
})
}
public showMainWindow() {
if (this.miniWindow && !this.miniWindow.isDestroyed()) {
this.miniWindow.hide()
}
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
if (this.mainWindow) {
if (this.mainWindow.isMinimized()) {
this.mainWindow.restore()
return this.mainWindow.restore()
}
this.mainWindow.show()
this.mainWindow.focus()
} else {
this.mainWindow = this.createMainWindow()
this.mainWindow.focus()
this.createMainWindow()
}
}
@ -285,10 +269,7 @@ export class WindowService {
return
}
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.hide()
}
if (this.selectionMenuWindow && !this.selectionMenuWindow.isDestroyed()) {
if (this.selectionMenuWindow) {
this.selectionMenuWindow.hide()
}

View File

@ -18,10 +18,6 @@ export function getAllFiles(dirPath: string, arrayOfFiles: FileType[] = []): Fil
const files = fs.readdirSync(dirPath)
files.forEach((file) => {
if (file.startsWith('.')) {
return
}
const fullPath = path.join(dirPath, file)
if (fs.statSync(fullPath).isDirectory()) {
arrayOfFiles = getAllFiles(fullPath, arrayOfFiles)

View File

@ -119,9 +119,6 @@ declare global {
encrypt: (text: string, secretKey: string, iv: string) => Promise<{ iv: string; encryptedData: string }>
decrypt: (encryptedData: string, iv: string, secretKey: string) => Promise<string>
}
shell: {
openExternal: (url: string, options?: OpenExternalOptions) => Promise<void>
}
}
}
}

View File

@ -1,6 +1,6 @@
import { electronAPI } from '@electron-toolkit/preload'
import { FileType, KnowledgeBaseParams, KnowledgeItem, Shortcut, WebDavConfig } from '@types'
import { contextBridge, ipcRenderer, OpenDialogOptions, shell } from 'electron'
import { contextBridge, ipcRenderer, OpenDialogOptions } from 'electron'
// Custom APIs for renderer
const api = {
@ -104,9 +104,6 @@ const api = {
encrypt: (text: string, secretKey: string, iv: string) => ipcRenderer.invoke('aes:encrypt', text, secretKey, iv),
decrypt: (encryptedData: string, iv: string, secretKey: string) =>
ipcRenderer.invoke('aes:decrypt', encryptedData, iv, secretKey)
},
shell: {
openExternal: shell.openExternal
}
}

View File

@ -6,7 +6,6 @@
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; connect-src blob: *; script-src 'self' 'unsafe-eval' *; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' *; font-src 'self' data: *; img-src 'self' data: file: * blob:; frame-src * file:" />
<title>Cherry Studio</title>
<style>
html,

View File

@ -10,7 +10,6 @@ import TopViewContainer from './components/TopView'
import AntdProvider from './context/AntdProvider'
import { SyntaxHighlighterProvider } from './context/SyntaxHighlighterProvider'
import { ThemeProvider } from './context/ThemeProvider'
import NavigationHandler from './handler/NavigationHandler'
import AgentsPage from './pages/agents/AgentsPage'
import AppsPage from './pages/apps/AppsPage'
import FilesPage from './pages/files/FilesPage'
@ -29,8 +28,6 @@ function App(): JSX.Element {
<PersistGate loading={null} persistor={persistor}>
<TopViewContainer>
<HashRouter>
<NavigationHandler />
{/* 添加导航处理组件 */}
<Sidebar />
<Routes>
<Route path="/" element={<HomePage />} />

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -64,10 +64,6 @@
&:first-child {
margin-top: 0;
}
&:has(+ ul) {
margin-bottom: 0;
}
}
ul {

View File

@ -46,28 +46,23 @@ const DragableList: FC<Props<any>> = ({
<DragDropContext onDragStart={onDragStart} onDragEnd={_onDragEnd}>
<Droppable droppableId="droppable" {...droppableProps}>
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef} style={style}>
<div {...provided.droppableProps} ref={provided.innerRef} style={{ ...style }}>
{list.map((item, index) => {
const id = item.id || item
return (
<Draggable key={`draggable_${id}_${index}`} draggableId={id} index={index}>
<Draggable key={`draggable_${id}_${index}`} draggableId={id} index={index} {...droppableProps}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{
...listStyle,
...provided.draggableProps.style,
marginBottom: 8
}}>
style={{ ...provided.draggableProps.style, marginBottom: 8, ...listStyle }}>
{children(item, index)}
</div>
)}
</Draggable>
)
})}
{provided.placeholder}
</div>
)}
</Droppable>

View File

@ -1,7 +1,6 @@
/* eslint-disable react/no-unknown-property */
import { CloseOutlined, CodeOutlined, ExportOutlined, PushpinOutlined, ReloadOutlined } from '@ant-design/icons'
import { CloseOutlined, ExportOutlined, PushpinOutlined, ReloadOutlined } from '@ant-design/icons'
import { isMac, isWindows } from '@renderer/config/constant'
import { AppLogo } from '@renderer/config/env'
import { DEFAULT_MIN_APPS } from '@renderer/config/minapps'
import { useBridge } from '@renderer/hooks/useBridge'
import { useMinapps } from '@renderer/hooks/useMinapps'
@ -42,11 +41,7 @@ const PopupContainer: React.FC<Props> = ({ app, resolve }) => {
}
MinApp.onClose = onClose
const openDevTools = () => {
if (webviewRef.current) {
webviewRef.current.openDevTools()
}
}
const onReload = () => {
if (webviewRef.current) {
webviewRef.current.src = app.url
@ -54,17 +49,14 @@ const PopupContainer: React.FC<Props> = ({ app, resolve }) => {
}
const onOpenLink = () => {
if (webviewRef.current) {
const currentUrl = webviewRef.current.getURL()
window.api.openWebsite(currentUrl)
}
window.api.openWebsite(app.url)
}
const onTogglePin = () => {
const newPinned = isPinned ? pinned.filter((item) => item.id !== app.id) : [...pinned, app]
updatePinnedMinapps(newPinned)
}
const isInDevelopment = process.env.NODE_ENV === 'development'
const Title = () => {
return (
<TitleContainer style={{ justifyContent: 'space-between' }}>
@ -83,11 +75,6 @@ const PopupContainer: React.FC<Props> = ({ app, resolve }) => {
<ExportOutlined />
</Button>
)}
{isInDevelopment && (
<Button onClick={openDevTools}>
<CodeOutlined />
</Button>
)}
<Button onClick={() => onClose()}>
<CloseOutlined />
</Button>
@ -249,10 +236,6 @@ export default class MinApp {
await delay(0)
}
if (!app.logo) {
app.logo = AppLogo
}
MinApp.app = app
store.dispatch(setMinappShow(true))

View File

@ -4,7 +4,7 @@ import App from '@renderer/pages/apps/App'
import { Popover } from 'antd'
import { Empty } from 'antd'
import { isEmpty } from 'lodash'
import { FC, useEffect, useState } from 'react'
import { FC, useState, useEffect } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import styled from 'styled-components'
@ -26,19 +26,19 @@ const MinAppsPopover: FC<Props> = ({ children }) => {
setOpen(false)
}
const [maxHeight, setMaxHeight] = useState(window.innerHeight - 100)
const [maxHeight, setMaxHeight] = useState(window.innerHeight - 100);
useEffect(() => {
const handleResize = () => {
setMaxHeight(window.innerHeight - 100)
}
setMaxHeight(window.innerHeight - 100);
};
window.addEventListener('resize', handleResize)
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize)
}
}, [])
window.removeEventListener('resize', handleResize);
};
}, []);
const content = (
<PopoverContent maxHeight={maxHeight}>
@ -74,9 +74,9 @@ const PopoverContent = styled(Scrollbar)<{ maxHeight: number }>`
`
const AppsContainer = styled.div`
display: grid;
display: grid;
grid-template-columns: repeat(6, minmax(90px, 1fr));
gap: 18px;
`
`;
export default MinAppsPopover

View File

@ -1,6 +1,6 @@
import { Input, Modal } from 'antd'
import { TextAreaProps } from 'antd/es/input'
import { useRef, useState } from 'react'
import { useState } from 'react'
import { Box } from '../Layout'
import { TopView } from '../TopView'
@ -27,7 +27,6 @@ const PromptPopupContainer: React.FC<Props> = ({
}) => {
const [value, setValue] = useState(defaultValue)
const [open, setOpen] = useState(true)
const textAreaRef = useRef<any>(null)
const onOk = () => {
setOpen(false)
@ -42,35 +41,17 @@ const PromptPopupContainer: React.FC<Props> = ({
resolve(null)
}
const handleAfterOpenChange = (visible: boolean) => {
if (visible) {
const textArea = textAreaRef.current?.resizableTextArea?.textArea
if (textArea) {
textArea.focus()
const length = textArea.value.length
textArea.setSelectionRange(length, length)
}
}
}
PromptPopup.hide = onCancel
return (
<Modal
title={title}
open={open}
onOk={onOk}
onCancel={onCancel}
afterClose={onClose}
afterOpenChange={handleAfterOpenChange}
centered>
<Modal title={title} open={open} onOk={onOk} onCancel={onCancel} afterClose={onClose} centered>
<Box mb={8}>{message}</Box>
<Input.TextArea
ref={textAreaRef}
placeholder={inputPlaceholder}
value={value}
onChange={(e) => setValue(e.target.value)}
allowClear
autoFocus
onPressEnter={onOk}
rows={1}
{...inputProps}

View File

@ -51,17 +51,6 @@ const PopupContainer: React.FC<Props> = ({ text, textareaProps, modalProps, reso
setTimeout(resizeTextArea, 0)
}, [])
const handleAfterOpenChange = (visible: boolean) => {
if (visible) {
const textArea = textareaRef.current?.resizableTextArea?.textArea
if (textArea) {
textArea.focus()
const length = textArea.value.length
textArea.setSelectionRange(length, length)
}
}
}
TextEditPopup.hide = onCancel
return (
@ -76,7 +65,6 @@ const PopupContainer: React.FC<Props> = ({ text, textareaProps, modalProps, reso
onOk={onOk}
onCancel={onCancel}
afterClose={onClose}
afterOpenChange={handleAfterOpenChange}
centered>
<TextArea
ref={textareaRef}

View File

@ -50,7 +50,6 @@ const Sidebar: FC = () => {
const onOpenDocs = () => {
MinApp.start({
id: 'docs',
name: t('docs.title'),
url: 'https://docs.cherry-ai.com/',
logo: AppLogo
@ -78,11 +77,9 @@ const Sidebar: FC = () => {
</AppsContainer>
)}
</MainMenusContainer>
<Menus>
<Menus onClick={MinApp.onClose}>
<Tooltip title={t('docs.title')} mouseEnterDelay={0.8} placement="right">
<Icon
onClick={onOpenDocs}
className={minappShow && MinApp.app?.url === 'https://docs.cherry-ai.com/' ? 'active' : ''}>
<Icon onClick={onOpenDocs}>
<QuestionCircleOutlined />
</Icon>
</Tooltip>
@ -96,14 +93,8 @@ const Sidebar: FC = () => {
</Icon>
</Tooltip>
<Tooltip title={t('settings.title')} mouseEnterDelay={0.8} placement="right">
<StyledLink
onClick={async () => {
if (minappShow) {
await MinApp.close()
}
await to(isLocalAi ? '/settings/assistant' : '/settings/provider')
}}>
<Icon className={pathname.startsWith('/settings') && !minappShow ? 'active' : ''}>
<StyledLink onClick={() => to(isLocalAi ? '/settings/assistant' : '/settings/provider')}>
<Icon className={pathname.startsWith('/settings') ? 'active' : ''}>
<i className="iconfont icon-setting" />
</Icon>
</StyledLink>
@ -117,11 +108,10 @@ const MainMenus: FC = () => {
const { t } = useTranslation()
const { pathname } = useLocation()
const { sidebarIcons } = useSettings()
const { minappShow } = useRuntime()
const navigate = useNavigate()
const isRoute = (path: string): string => (pathname === path && !minappShow ? 'active' : '')
const isRoutes = (path: string): string => (pathname.startsWith(path) && !minappShow ? 'active' : '')
const isRoute = (path: string): string => (pathname === path ? 'active' : '')
const isRoutes = (path: string): string => (pathname.startsWith(path) ? 'active' : '')
const iconMap = {
assistants: <i className="iconfont icon-chat" />,
@ -149,13 +139,7 @@ const MainMenus: FC = () => {
return (
<Tooltip key={icon} title={t(`${icon}.title`)} mouseEnterDelay={0.8} placement="right">
<StyledLink
onClick={async () => {
if (minappShow) {
await MinApp.close()
}
navigate(path)
}}>
<StyledLink onClick={() => navigate(path)}>
<Icon className={isActive}>{iconMap[icon]}</Icon>
</StyledLink>
</Tooltip>
@ -166,7 +150,6 @@ const MainMenus: FC = () => {
const PinnedApps: FC = () => {
const { pinned, updatePinnedMinapps } = useMinapps()
const { t } = useTranslation()
const { minappShow } = useRuntime()
return (
<DragableList list={pinned} onUpdate={updatePinnedMinapps} listStyle={{ marginBottom: 5 }}>
@ -181,12 +164,11 @@ const PinnedApps: FC = () => {
}
}
]
const isActive = minappShow && MinApp.app?.id === app.id
return (
<Tooltip key={app.id} title={app.name} mouseEnterDelay={0.8} placement="right">
<StyledLink>
<Dropdown menu={{ items: menuItems }} trigger={['contextMenu']}>
<Icon onClick={() => MinApp.start(app)} className={isActive ? 'active' : ''}>
<Icon onClick={() => MinApp.start(app)}>
<MinAppIcon size={20} app={app} style={{ borderRadius: 6 }} />
</Icon>
</Dropdown>

View File

@ -1,12 +1,9 @@
import ThreeMinTopAppLogo from '@renderer/assets/images/apps/3mintop.png?url'
import AbacusLogo from '@renderer/assets/images/apps/abacus.webp?url'
import AIStudioLogo from '@renderer/assets/images/apps/aistudio.svg?url'
import BaiduAiAppLogo from '@renderer/assets/images/apps/baidu-ai.png?url'
import BaicuanAppLogo from '@renderer/assets/images/apps/baixiaoying.webp?url'
import BoltAppLogo from '@renderer/assets/images/apps/bolt.svg?url'
import CozeAppLogo from '@renderer/assets/images/apps/coze.webp?url'
import DevvAppLogo from '@renderer/assets/images/apps/devv.png?url'
import DifyAppLogo from '@renderer/assets/images/apps/dify.webp?url'
import DoubaoAppLogo from '@renderer/assets/images/apps/doubao.png?url'
import DuckDuckGoAppLogo from '@renderer/assets/images/apps/duckduckgo.webp?url'
import FeloAppLogo from '@renderer/assets/images/apps/felo.png?url'
@ -18,12 +15,9 @@ import GrokAppLogo from '@renderer/assets/images/apps/grok.png?url'
import HikaLogo from '@renderer/assets/images/apps/hika.webp?url'
import HuggingChatLogo from '@renderer/assets/images/apps/huggingchat.svg?url'
import KimiAppLogo from '@renderer/assets/images/apps/kimi.jpg?url'
import LambdaChatLogo from '@renderer/assets/images/apps/lambdachat.webp?url'
import LeChatLogo from '@renderer/assets/images/apps/lechat.png?url'
import MetasoAppLogo from '@renderer/assets/images/apps/metaso.webp?url'
import NamiAiLogo from '@renderer/assets/images/apps/nm.png?url'
import NamiAiSearchLogo from '@renderer/assets/images/apps/nm-search.webp?url'
import NotebookLMAppLogo from '@renderer/assets/images/apps/notebooklm.svg?url'
import PerplexityAppLogo from '@renderer/assets/images/apps/perplexity.webp?url'
import PoeAppLogo from '@renderer/assets/images/apps/poe.webp?url'
import ZhipuProviderLogo from '@renderer/assets/images/apps/qingyan.png?url'
@ -33,11 +27,12 @@ import SparkDeskAppLogo from '@renderer/assets/images/apps/sparkdesk.png?url'
import ThinkAnyLogo from '@renderer/assets/images/apps/thinkany.webp?url'
import TiangongAiLogo from '@renderer/assets/images/apps/tiangong.png?url'
import WanZhiAppLogo from '@renderer/assets/images/apps/wanzhi.jpg?url'
import WPSLingXiLogo from '@renderer/assets/images/apps/wpslingxi.webp?url'
import XiaoYiAppLogo from '@renderer/assets/images/apps/xiaoyi.webp?url'
import TencentYuanbaoAppLogo from '@renderer/assets/images/apps/yuanbao.png?url'
import NotebookLMAppLogo from '@renderer/assets/images/apps/notebooklm.svg?url'
import YuewenAppLogo from '@renderer/assets/images/apps/yuewen.png?url'
import ZhihuAppLogo from '@renderer/assets/images/apps/zhihu.png?url'
import CozeAppLogo from '@renderer/assets/images/apps/coze.webp?url'
import ClaudeAppLogo from '@renderer/assets/images/models/claude.png?url'
import HailuoModelLogo from '@renderer/assets/images/models/hailuo.png?url'
import QwenModelLogo from '@renderer/assets/images/models/qwen.png?url'
@ -176,7 +171,7 @@ export const DEFAULT_MIN_APPS: MinAppType[] = [
},
{
id: 'perplexity',
name: 'Perplexity',
name: 'perplexity',
logo: PerplexityAppLogo,
url: 'https://www.perplexity.ai/'
},
@ -311,7 +306,7 @@ export const DEFAULT_MIN_APPS: MinAppType[] = [
id: 'notebooklm',
name: 'NotebookLM',
logo: NotebookLMAppLogo,
url: 'https://notebooklm.google.com/'
url: 'https://notebooklm.google.com/',
},
{
id: 'coze',
@ -319,41 +314,6 @@ export const DEFAULT_MIN_APPS: MinAppType[] = [
logo: CozeAppLogo,
url: 'https://www.coze.com/space',
bodered: true
},
{
id: 'dify',
name: 'Dify',
logo: DifyAppLogo,
url: 'https://cloud.dify.ai/apps',
bodered: true
},
{
id: 'wpslingxi',
name: 'WPS灵犀',
logo: WPSLingXiLogo,
url: 'https://copilot.wps.cn/',
bodered: true
},
{
id: 'lechat',
name: 'LeChat',
logo: LeChatLogo,
url: 'https://chat.mistral.ai/chat',
bodered: true
},
{
id: 'abacus',
name: 'Abacus',
logo: AbacusLogo,
url: 'https://apps.abacus.ai/chatllm',
bodered: true
},
{
id: 'lambdachat',
name: 'Lambda Chat',
logo: LambdaChatLogo,
url: 'https://lambda.chat/',
bodered: true
}
]

View File

@ -150,8 +150,7 @@ const visionAllowedModels = [
'gpt-4o(?:-[\\w-]+)?',
'chatgpt-4o(?:-[\\w-]+)?',
'o1(?:-[\\w-]+)?',
'deepseek-vl(?:[\\w-]+)?',
'kimi-latest'
'deepseek-vl(?:[\\w-]+)?'
]
const visionExcludedModels = ['gpt-4-\\d+-preview', 'gpt-4-turbo-preview', 'gpt-4-32k', 'gpt-4-\\d+']
@ -162,9 +161,10 @@ export const VISION_REGEX = new RegExp(
)
export const TEXT_TO_IMAGE_REGEX = /flux|diffusion|stabilityai|sd-|dall|cogview|janus/i
export const REASONING_REGEX = /^(o\d+(?:-[\w-]+)?|.*\b(?:reasoner|thinking)\b.*|.*-[rR]\d+.*)$/i
export const REASONING_REGEX = /^(o\d+(?:-[\w-]+)?|.*\breasoner\b.*|.*-[rR]\d+.*)$/i
export const EMBEDDING_REGEX = /(?:^text-|embed|bge-|e5-|LLM2Vec|retrieval|uae-|gte-|jina-clip|jina-embeddings)/i
export const EMBEDDING_REGEX =
/(?:^text-|embed|rerank|davinci|babbage|bge-|e5-|LLM2Vec|retrieval|uae-|gte-|jina-clip|jina-embeddings)/i
export const NOT_SUPPORTED_REGEX = /(?:^tts|rerank|whisper|speech)/i
export function getModelLogo(modelId: string) {
@ -178,7 +178,6 @@ export function getModelLogo(modelId: string) {
pixtral: isLight ? PixtralModelLogo : PixtralModelLogoDark,
jina: isLight ? JinaModelLogo : JinaModelLogoDark,
abab: isLight ? MinimaxModelLogo : MinimaxModelLogoDark,
minimax: isLight ? MinimaxModelLogo : MinimaxModelLogoDark,
o3: isLight ? ChatGPTo1ModelLogo : ChatGPTo1ModelLogoDark,
o1: isLight ? ChatGPTo1ModelLogo : ChatGPTo1ModelLogoDark,
'gpt-3': isLight ? ChatGPT35ModelLogo : ChatGPT35ModelLogoDark,
@ -195,16 +194,13 @@ export function getModelLogo(modelId: string) {
glm: isLight ? ChatGLMModelLogo : ChatGLMModelLogoDark,
deepseek: isLight ? DeepSeekModelLogo : DeepSeekModelLogoDark,
qwen: isLight ? QwenModelLogo : QwenModelLogoDark,
'qwq-': isLight ? QwenModelLogo : QwenModelLogoDark,
'qvq-': isLight ? QwenModelLogo : QwenModelLogoDark,
Omni: isLight ? QwenModelLogo : QwenModelLogoDark,
qwq: isLight ? QwenModelLogo : QwenModelLogoDark,
gemma: isLight ? GemmaModelLogo : GemmaModelLogoDark,
'yi-': isLight ? YiModelLogo : YiModelLogoDark,
llama: isLight ? LlamaModelLogo : LlamaModelLogoDark,
mixtral: isLight ? MistralModelLogo : MistralModelLogo,
mistral: isLight ? MistralModelLogo : MistralModelLogoDark,
moonshot: isLight ? MoonshotModelLogo : MoonshotModelLogoDark,
kimi: isLight ? MoonshotModelLogo : MoonshotModelLogoDark,
phi: isLight ? MicrosoftModelLogo : MicrosoftModelLogoDark,
baichuan: isLight ? BaichuanModelLogo : BaichuanModelLogoDark,
claude: isLight ? ClaudeModelLogo : ClaudeModelLogoDark,
@ -1330,70 +1326,34 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
],
dmxapi: [
{
id: 'Qwen/Qwen2.5-7B-Instruct',
id: 'gpt-3.5-turbo',
provider: 'dmxapi',
name: 'Qwen/Qwen2.5-7B-Instruct',
group: '免费模型'
},
{
id: 'ERNIE-Speed-128K',
provider: 'dmxapi',
name: 'ERNIE-Speed-128K',
group: '免费模型'
},
{
id: 'THUDM/glm-4-9b-chat',
provider: 'dmxapi',
name: 'THUDM/glm-4-9b-chat',
group: '免费模型'
},
{
id: 'glm-4-flash',
provider: 'dmxapi',
name: 'glm-4-flash',
group: '免费模型'
},
{
id: 'hunyuan-lite',
provider: 'dmxapi',
name: 'hunyuan-lite',
group: '免费模型'
name: 'GPT-3.5-Turbo',
group: 'OpenAI'
},
{
id: 'gpt-4o',
provider: 'dmxapi',
name: 'gpt-4o',
name: 'GPT-4o',
group: 'OpenAI'
},
{
id: 'gpt-4o-mini',
provider: 'dmxapi',
name: 'gpt-4o-mini',
name: 'GPT-4o-Mini',
group: 'OpenAI'
},
{
id: 'DMXAPI-DeepSeek-R1',
id: 'deepseek-reasoner',
provider: 'dmxapi',
name: 'DMXAPI-DeepSeek-R1',
name: 'DeepSeek Reasoner',
group: 'DeepSeek'
},
{
id: 'DMXAPI-DeepSeek-V3',
id: 'deepseek-chat',
provider: 'dmxapi',
name: 'DMXAPI-DeepSeek-V3',
name: 'DeepSeek Chat',
group: 'DeepSeek'
},
{
id: 'claude-3-5-sonnet-20241022',
provider: 'dmxapi',
name: 'claude-3-5-sonnet-20241022',
group: 'Claude'
},
{
id: 'gemini-2.0-flash',
provider: 'dmxapi',
name: 'gemini-2.0-flash',
group: 'Gemini'
}
],
perplexity: [
@ -1603,10 +1563,6 @@ export function isEmbeddingModel(model: Model): boolean {
return false
}
if (model.provider === 'doubao') {
return EMBEDDING_REGEX.test(model.name)
}
return EMBEDDING_REGEX.test(model.id) || model.type?.includes('embedding') || false
}
@ -1615,10 +1571,6 @@ export function isVisionModel(model: Model): boolean {
return false
}
if (model.provider === 'doubao') {
return VISION_REGEX.test(model.name) || model.type?.includes('vision') || false
}
return VISION_REGEX.test(model.id) || model.type?.includes('vision') || false
}
@ -1627,10 +1579,6 @@ export function isReasoningModel(model: Model): boolean {
return false
}
if (model.provider === 'doubao') {
return REASONING_REGEX.test(model.name) || model.type?.includes('reasoning') || false
}
return REASONING_REGEX.test(model.id) || model.type?.includes('reasoning') || false
}
@ -1683,16 +1631,6 @@ export function isWebSearchModel(model: Model): boolean {
return model?.id?.startsWith('glm-4-')
}
if (provider.id === 'dashscope') {
const models = ['qwen-turbo', 'qwen-max', 'qwen-plus']
// matches id like qwen-max-0919, qwen-max-latest
return models.some((i) => model.id.startsWith(i))
}
if (provider.id === 'openrouter') {
return true
}
return false
}
@ -1705,21 +1643,6 @@ export function getOpenAIWebSearchParams(assistant: Assistant, model: Model): Re
return { enable_enhancement: true }
}
if (model.provider === 'dashscope') {
return {
enable_search: true,
search_options: {
forced_search: true
}
}
}
if (model.provider === 'openrouter') {
return {
plugins: [{ id: 'web' }]
}
}
return {
tools: webSearchTools
}

View File

@ -212,13 +212,13 @@ export const PROVIDER_CONFIG = {
},
dmxapi: {
api: {
url: 'https://www.dmxapi.cn'
url: 'https://api.dmxapi.com'
},
websites: {
official: 'https://www.dmxapi.cn/register?aff=bwwY',
apiKey: 'https://www.dmxapi.cn/register?aff=bwwY',
docs: 'https://dmxapi.cn/models.html#code-block',
models: 'https://www.dmxapi.cn/pricing'
official: 'https://dmxapi.com/',
apiKey: 'https://www.dmxapi.com/token',
docs: 'https://dmxapi.com/models.html#code-block',
models: 'https://www.dmxapi.com/pricing'
}
},
perplexity: {
@ -526,7 +526,7 @@ export const PROVIDER_CONFIG = {
},
websites: {
official: 'https://cloud.baidu.com/',
apiKey: 'https://console.bce.baidu.com/iam/#/iam/apikey/list',
apiKey: 'https://cloud.baidu.com/console/qianfan/apikey',
docs: 'https://cloud.baidu.com/doc/index.html',
models: 'https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Fm2vrveyu'
}

View File

@ -55,20 +55,5 @@ export const TranslateLanguageOptions = [
value: 'arabic',
label: i18n.t('languages.arabic'),
emoji: '🇸🇦'
},
{
value: 'german',
label: i18n.t('languages.german'),
emoji: '🇩🇪'
}
]
export const translateLanguageOptions = (): typeof TranslateLanguageOptions => {
return TranslateLanguageOptions.map((option) => {
return {
value: option.value,
label: i18n.t(`languages.${option.value}`),
emoji: option.emoji
}
})
}

View File

@ -60,7 +60,7 @@ export const SyntaxHighlighterProvider: React.FC<PropsWithChildren> = ({ childre
const mappedLanguage = languageMap[language] || language
code = code?.trimEnd() ?? ''
code = code.trimEnd()
const escapedCode = code?.replace(/[<>]/g, (char) => ({ '<': '&lt;', '>': '&gt;' })[char]!)
try {

View File

@ -1,4 +1,4 @@
import { FileType, KnowledgeItem, Topic, TranslateHistory } from '@renderer/types'
import { FileType, KnowledgeItem, Topic } from '@renderer/types'
import { Dexie, type EntityTable } from 'dexie'
// Database declaration (move this to its own module also)
@ -7,7 +7,6 @@ export const db = new Dexie('CherryStudio') as Dexie & {
topics: EntityTable<Pick<Topic, 'id' | 'messages'>, 'id'>
settings: EntityTable<{ id: string; value: any }, 'id'>
knowledge_notes: EntityTable<KnowledgeItem, 'id'>
translate_history: EntityTable<TranslateHistory, 'id'>
}
db.version(1).stores({
@ -27,12 +26,4 @@ db.version(3).stores({
knowledge_notes: '&id, baseId, type, content, created_at, updated_at'
})
db.version(4).stores({
files: 'id, name, origin_name, path, size, ext, type, created_at, count',
topics: '&id, messages',
settings: '&id, value',
knowledge_notes: '&id, baseId, type, content, created_at, updated_at',
translate_history: '&id, sourceText, targetText, sourceLanguage, targetLanguage, createdAt'
})
export default db

View File

@ -1,17 +0,0 @@
import { useHotkeys } from 'react-hotkeys-hook'
import { useNavigate } from 'react-router-dom'
const NavigationHandler: React.FC = () => {
const navigate = useNavigate()
useHotkeys(
'meta+, ! ctrl+,',
function () {
navigate('/settings/provider')
},
{ splitKey: '!' }
)
return null
}
export default NavigationHandler

View File

@ -44,7 +44,7 @@ export function useAssistant(id: string) {
return {
assistant,
model: assistant?.model ?? assistant?.defaultModel ?? defaultModel,
model: assistant?.model ?? defaultModel,
addTopic: (topic: Topic) => dispatch(addTopic({ assistantId: assistant.id, topic })),
removeTopic: (topic: Topic) => {
TopicManager.removeTopic(topic.id)

View File

@ -198,27 +198,6 @@ export const useKnowledge = (baseId: string) => {
return base?.items.filter((item) => item.type === type && item.processingStatus !== undefined) || []
}
// 获取目录处理进度
const getDirectoryProcessingPercent = (itemId?: string) => {
const [percent, setPercent] = useState<number>(0)
useEffect(() => {
if (!itemId) {
return
}
const cleanup = window.electron.ipcRenderer.on(itemId, (_, progressingPercent: number) => {
setPercent(progressingPercent)
})
return () => {
cleanup()
}
}, [itemId])
return percent
}
// 清除已完成的项目
const clearCompleted = () => {
dispatch(clearCompletedProcessing({ baseId }))
@ -301,7 +280,6 @@ export const useKnowledge = (baseId: string) => {
refreshItem,
getProcessingStatus,
getProcessingItemsByType,
getDirectoryProcessingPercent,
clearCompleted,
clearAll,
removeItem,
@ -329,22 +307,16 @@ export const useKnowledgeBases = () => {
// remove assistant knowledge_base
const _assistants = assistants.map((assistant) => {
if (assistant.knowledge_bases?.find((kb) => kb.id === baseId)) {
return {
...assistant,
knowledge_bases: assistant.knowledge_bases.filter((kb) => kb.id !== baseId)
}
if (assistant.knowledge_base?.id === baseId) {
return { ...assistant, knowledge_base: undefined }
}
return assistant
})
// remove agent knowledge_base
const _agents = agents.map((agent) => {
if (agent.knowledge_bases?.find((kb) => kb.id === baseId)) {
return {
...agent,
knowledge_bases: agent.knowledge_bases.filter((kb) => kb.id !== baseId)
}
if (agent.knowledge_base?.id === baseId) {
return { ...agent, knowledge_base: undefined }
}
return agent
})

View File

@ -1,13 +1,7 @@
import { useProviders } from './useProvider'
export function useModel(id?: string, providerId?: string) {
export function useModel(id?: string) {
const { providers } = useProviders()
const allModels = providers.map((p) => p.models).flat()
return allModels.find((m) => {
if (providerId) {
return m.id === id && m.provider === providerId
} else {
return m.id === id
}
})
return allModels.find((m) => m.id === id)
}

View File

@ -51,7 +51,6 @@
"settings.reasoning_effort.high": "high",
"settings.reasoning_effort.low": "low",
"settings.reasoning_effort.medium": "medium",
"settings.reasoning_effort.off": "off",
"settings.reasoning_effort.tip": "Only supports reasoning models",
"title": "Assistants"
},
@ -121,8 +120,6 @@
"settings.top_p.tip": "Default value is 1, the smaller the value, the less variety in the answers, the easier to understand, the larger the value, the larger the range of the AI's vocabulary, the more diverse",
"settings.max_tokens.confirm": "Enable max tokens limit",
"settings.max_tokens.confirm_content": "Enable max tokens limit, affects the length of the result. Need to consider the context limit of the model, otherwise an error will be reported",
"settings.thought_auto_collapse": "Automatically Collapse Thought Content",
"settings.thought_auto_collapse.tip": "Automatically collapse thought content after thinking ends",
"suggestions.title": "Suggested Questions",
"thinking": "Thinking",
"topics.auto_rename": "Auto Rename",
@ -139,13 +136,10 @@
"topics.pinned": "Pinned Topics",
"topics.title": "Topics",
"topics.unpinned": "Unpinned Topics",
"topics.delete.shortcut": "Hold {{key}} to delete directly",
"translate": "Translate",
"topics.prompt": "Topic Prompts",
"topics.prompt.tips": "Topic Prompts: Additional supplementary prompts provided for the current topic",
"topics.prompt.edit.title": "Edit Topic Prompts",
"artifacts.button.openExternal": "Open in external browser",
"artifacts.preview.openExternal.error.content": "Error opening the external browser."
"topics.prompt.edit.title": "Edit Topic Prompts"
},
"common": {
"add": "Add",
@ -320,8 +314,7 @@
"korean": "Korean",
"portuguese": "Portuguese",
"russian": "Russian",
"spanish": "Spanish",
"german": "German"
"spanish": "Spanish"
},
"mermaid": {
"download": {
@ -338,18 +331,6 @@
},
"title": "Mermaid Diagram"
},
"plantuml": {
"download": {
"png": "Download PNG",
"svg": "Download SVG",
"failed": "Download failed, please check the network"
},
"tabs": {
"preview": "Preview",
"source": "Source"
},
"title": "PlantUML Diagram"
},
"message": {
"api.check.model.title": "Select the model to use for detection",
"api.connection.failed": "Connection failed",
@ -371,7 +352,7 @@
"error.invalid.enter.model": "Please select a model",
"error.invalid.proxy.url": "Invalid proxy URL",
"error.invalid.webdav": "Invalid WebDAV settings",
"error.notion.export": "Failed to export to Notion. Please check connection status and configuration according to documentation",
"error.notion.export": "Notion import failed",
"error.notion.no_api_key": "Notion ApiKey or Notion DatabaseID is not configured",
"group.delete.content": "Deleting a group message will delete the user's question and all assistant's answers",
"group.delete.title": "Delete Group Message",
@ -383,7 +364,6 @@
"message.multi_model_style.fold": "Fold",
"message.multi_model_style.horizontal": "Horizontal",
"message.multi_model_style.vertical": "Vertical",
"message.multi_model_style.grid": "Grid",
"message.style": "Message style",
"message.style.bubble": "Bubble",
"message.style.plain": "Plain",
@ -393,13 +373,13 @@
"reset.double.confirm.title": "DATA LOST !!!",
"restore.success": "Restored successfully",
"save.success.title": "Saved successfully",
"success.notion.export": "Successfully exported to Notion",
"success.notion.export": "Notion import successful",
"switch.disabled": "Please wait for the current reply to complete",
"topic.added": "New topic added",
"upgrade.success.button": "Restart",
"upgrade.success.content": "Please restart the application to complete the upgrade",
"upgrade.success.title": "Upgrade successfully",
"warn.notion.exporting": "Exporting to Notion, please do not request export repeatedly!",
"warn.notion.exporting": "Notion is importing, please do not import repeatedly",
"error.invalid.api.host": "Invalid API Host",
"error.invalid.api.key": "Invalid API Key"
},
@ -579,45 +559,36 @@
},
"data.title": "Data Directory",
"notion.api_key": "Notion API Key",
"notion.api_key_placeholder": "Enter Notion API Key",
"notion.database_id": "Notion Database ID",
"notion.database_id_placeholder": "Enter Notion Database ID",
"notion.page_name_key": "Page Title Field Name",
"notion.page_name_key_placeholder": "Enter page title field name, default is Name",
"notion.title": "Notion Configuration",
"notion.help": "Notion Configuration Documentation",
"notion.check": {
"button": "Check",
"fail": "Connection failed, please check network and Api_key and Database_id",
"fail": "Connection failed, please check the configuration",
"success": "Connection successful",
"error": "Connection error, please check network configuration and Api_key and Database_id",
"error": "Connection error, please check the network",
"empty_api_key": "Api_key is not configured",
"empty_database_id": "Database_id is not configured"
},
"title": "Data Settings",
"webdav": {
"autoSync": "Auto Backup",
"autoSync.off": "Off",
"backup.button": "Backup to WebDAV",
"host": "WebDAV Host",
"host.placeholder": "http://localhost:8080",
"minute_interval_one": "{{count}} minute",
"minute_interval_other": "{{count}} minutes",
"hour_interval_one": "{{count}} hour",
"hour_interval_other": "{{count}} hours",
"lastSync": "Last Backup",
"noSync": "Waiting for next backup",
"password": "WebDAV Password",
"path": "WebDAV Path",
"path.placeholder": "/backup",
"restore.button": "Restore from WebDAV",
"restore.content": "Restore from WebDAV will overwrite the current data, continue?",
"restore.title": "Restore from WebDAV",
"syncError": "Backup Error",
"syncStatus": "Backup Status",
"title": "WebDAV",
"user": "WebDAV User"
}
"webdav.autoSync": "Auto Backup",
"webdav.autoSync.off": "Off",
"webdav.backup.button": "Backup to WebDAV",
"webdav.host": "WebDAV Host",
"webdav.host.placeholder": "http://localhost:8080",
"webdav.hours": "Hours",
"webdav.lastSync": "Last Backup",
"webdav.minutes": "Minutes",
"webdav.noSync": "Waiting for next backup",
"webdav.password": "WebDAV Password",
"webdav.path": "WebDAV Path",
"webdav.path.placeholder": "/backup",
"webdav.restore.button": "Restore from WebDAV",
"webdav.restore.content": "Restore from WebDAV will overwrite the current data, continue?",
"webdav.restore.title": "Restore from WebDAV",
"webdav.syncError": "Backup Error",
"webdav.syncStatus": "Backup Status",
"webdav.title": "WebDAV",
"webdav.user": "WebDAV User"
},
"display.custom.css": "Custom CSS",
"display.custom.css.placeholder": "/* Put custom CSS here */",
@ -665,10 +636,6 @@
"messages.input.title": "Input Settings",
"messages.markdown_rendering_input_message": "Markdown render input message",
"messages.math_engine": "Math engine",
"messages.grid_columns": "Message grid display columns",
"messages.grid_popover_trigger": "Grid detail trigger",
"messages.grid_popover_trigger.hover": "Hover to display",
"messages.grid_popover_trigger.click": "Click to display",
"messages.metrics": "{{time_first_token_millsec}}ms to first token | {{token_speed}} tok/sec",
"messages.model.title": "Model Settings",
"messages.title": "Message Settings",
@ -741,7 +708,7 @@
},
"shortcuts": {
"action": "Action",
"alt_warning": "On Mac, Option key combinations only work with the Space key",
"alt_warning": "Mac does not support Option + letters as shortcuts",
"clear_shortcut": "Clear Shortcut",
"clear_topic": "Clear Messages",
"copy_last_message": "Copy Last Message",
@ -760,8 +727,7 @@
"toggle_show_topics": "Toggle Topics",
"zoom_in": "Zoom In",
"zoom_out": "Zoom Out",
"zoom_reset": "Reset Zoom",
"show_settings": "Open Settings"
"zoom_reset": "Reset Zoom"
},
"theme.auto": "Auto",
"theme.dark": "Dark",
@ -780,7 +746,6 @@
"translate": {
"any.language": "Any language",
"button.translate": "Translate",
"tooltip.newline": "Newline",
"close": "Close",
"confirm": {
"content": "Translation will replace the original text, continue?",
@ -791,14 +756,7 @@
"input.placeholder": "Enter text to translate",
"output.placeholder": "Translation",
"processing": "Translation in progress...",
"title": "Translation",
"history": {
"title": "Translation History",
"empty": "No translation history",
"clear": "Clear History",
"delete": "Delete",
"clear_description": "Clear history will delete all translation history, continue?"
}
"title": "Translation"
},
"tray": {
"quit": "Quit",

View File

@ -52,7 +52,6 @@
"settings.reasoning_effort.high": "長い",
"settings.reasoning_effort.low": "短い",
"settings.reasoning_effort.medium": "中程度",
"settings.reasoning_effort.off": "オフ",
"settings.reasoning_effort.tip": "この設定は推論モデルのみサポートしています"
},
"auth": {
@ -121,8 +120,6 @@
"settings.top_p.tip": "デフォルト値は1で、値が小さいほど回答の多様性が減り、理解しやすくなります。値が大きいほど、AIの語彙範囲が広がり、多様性が増します",
"settings.max_tokens.confirm": "最大トークン制限を有効にする",
"settings.max_tokens.confirm_content": "最大トークン制限を有効にすると、モデルが生成できる最大トークン数が制限されます。これにより、返される結果の長さに影響が出る可能性があります。モデルのコンテキスト制限に基づいて設定する必要があります。そうしないとエラーが発生します",
"settings.thought_auto_collapse": "思考内容を自動的に折りたたむ",
"settings.thought_auto_collapse.tip": "思考が終了したら思考内容を自動的に折りたたみます",
"suggestions.title": "提案された質問",
"thinking": "思考中...",
"topics.auto_rename": "自動リネーム",
@ -139,13 +136,10 @@
"topics.pinned": "トピックを固定",
"topics.title": "トピック",
"topics.unpinned": "固定解除",
"topics.delete.shortcut": "{{key}}キーを押しながらで直接削除",
"translate": "翻訳",
"topics.prompt": "トピック提示語",
"topics.prompt.tips": "トピック提示語:現在のトピックに対して追加の補足提示語を提供",
"topics.prompt.edit.title": "トピック提示語を編集する",
"artifacts.button.openExternal": "外部ブラウザで開く",
"artifacts.preview.openExternal.error.content": "外部ブラウザの起動に失敗しました。"
"topics.prompt.edit.title": "トピック提示語を編集する"
},
"common": {
"add": "追加",
@ -315,7 +309,6 @@
"chinese-traditional": "繁体字中国語",
"english": "英語",
"french": "フランス語",
"german": "ドイツ語",
"italian": "イタリア語",
"japanese": "日本語",
"korean": "韓国語",
@ -358,7 +351,7 @@
"error.invalid.enter.model": "モデルを選択してください",
"error.invalid.proxy.url": "無効なプロキシURL",
"error.invalid.webdav": "無効なWebDAV設定",
"error.notion.export": "Notionへのエクスポートに失敗しました。接続状態と設定を確認してください",
"error.notion.export": "Notion インポートに失敗",
"error.notion.no_api_key": "Notion ApiKey または Notion DatabaseID が設定されていません",
"group.delete.content": "分組メッセージを削除するとユーザーの質問と助け手の回答がすべて削除されます",
"group.delete.title": "分組メッセージを削除",
@ -370,7 +363,6 @@
"message.multi_model_style.fold": "折りたたむ",
"message.multi_model_style.horizontal": "水平",
"message.multi_model_style.vertical": "垂直",
"message.multi_model_style.grid": "グリッド",
"message.style": "メッセージスタイル",
"message.style.bubble": "バブル",
"message.style.plain": "プレーン",
@ -380,13 +372,13 @@
"reset.double.confirm.title": "データが失われます!!!",
"restore.success": "復元に成功しました",
"save.success.title": "保存に成功しました",
"success.notion.export": "Notionへのエクスポートに成功しました",
"success.notion.export": "Notion へのインポートに成功",
"switch.disabled": "現在の応答が完了するまで切り替えを無効にします",
"topic.added": "新しいトピックが追加されました",
"upgrade.success.button": "再起動",
"upgrade.success.content": "アップグレードを完了するためにアプリケーションを再起動してください",
"upgrade.success.title": "アップグレードに成功しました",
"warn.notion.exporting": "Notionにエクスポート中です。重複してエクスポートしないでください! ",
"warn.notion.exporting": "Notion 正在インポート中です。重複インポートしないでください。",
"error.enter.name": "ナレッジベース名を入力してください",
"error.invalid.api.host": "無効なAPIアドレスです",
"error.invalid.api.key": "無効なAPIキーです"
@ -567,45 +559,17 @@
},
"data.title": "データディレクトリ",
"notion.api_key": "Notion APIキー",
"notion.api_key_placeholder": "Notion APIキーを入力してください",
"notion.database_id": "Notion データベースID",
"notion.database_id_placeholder": "Notion データベースIDを入力してください",
"notion.page_name_key": "ページタイトルフィールド名",
"notion.page_name_key_placeholder": "ページタイトルフィールド名を入力してください。デフォルトは Name です",
"notion.title": "Notion 設定",
"notion.help": "Notion 設定ドキュメント",
"notion.check": {
"button": "確認",
"fail": "接続エラー、ネットワーク設定とApi_keyとDatabase_idを確認してください",
"fail": "接続に失敗しました。設定を確認してください。",
"success": "接続に成功しました。",
"error": "接続エラー、ネットワーク設定とApi_keyとDatabase_idを確認してください",
"error": "接続エラーが発生しました。ネットワークを確認してください。",
"empty_api_key": "Api_keyが設定されていません",
"empty_database_id": "Database_idが設定されていません"
},
"title": "データ設定",
"webdav": {
"autoSync": "自動バックアップ",
"autoSync.off": "オフ",
"backup.button": "WebDAVにバックアップ",
"host": "WebDAVホスト",
"host.placeholder": "http://localhost:8080",
"minute_interval_one": "{{count}} 分",
"minute_interval_other": "{{count}} 分",
"hour_interval_one": "{{count}} 時間",
"hour_interval_other": "{{count}} 時間",
"lastSync": "最終バックアップ",
"noSync": "次回のバックアップを待機中",
"password": "WebDAVパスワード",
"path": "WebDAVパス",
"path.placeholder": "/backup",
"restore.button": "WebDAVから復元",
"restore.content": "WebDAVから復元すると現在のデータが上書きされます。続行しますか",
"restore.title": "WebDAVから復元",
"syncError": "バックアップエラー",
"syncStatus": "バックアップ状態",
"title": "WebDAV",
"user": "WebDAVユーザー"
},
"webdav.autoSync": "自動バックアップ",
"webdav.autoSync.off": "オフ",
"webdav.backup.button": "WebDAVにバックアップ",
@ -624,11 +588,7 @@
"webdav.syncError": "バックアップエラー",
"webdav.syncStatus": "バックアップ状態",
"webdav.title": "WebDAV",
"webdav.user": "WebDAVユーザー",
"minute_interval_one": "{{count}} 分",
"minute_interval_other": "{{count}} 分",
"hour_interval_one": "{{count}} 時間",
"hour_interval_other": "{{count}} 時間"
"webdav.user": "WebDAVユーザー"
},
"display.custom.css": "カスタムCSS",
"display.custom.css.placeholder": "/* ここにカスタムCSSを入力 */",
@ -676,10 +636,6 @@
"messages.input.title": "入力設定",
"messages.markdown_rendering_input_message": "Markdownで入力メッセージをレンダリング",
"messages.math_engine": "数式エンジン",
"messages.grid_columns": "メッセージグリッドの表示列数",
"messages.grid_popover_trigger": "グリッド詳細トリガー",
"messages.grid_popover_trigger.hover": "ホバーで表示",
"messages.grid_popover_trigger.click": "クリックで表示",
"messages.metrics": "最初のトークンまでの時間 {{time_first_token_millsec}}ms | トークン速度 {{token_speed}} tok/sec",
"messages.model.title": "モデル設定",
"messages.title": "メッセージ設定",
@ -752,7 +708,7 @@
},
"shortcuts": {
"action": "操作",
"alt_warning": "MacではOptionキーとの組み合わせは、スペースキーのみ使用可能です",
"alt_warning": "MacではOption + 文字をショートカットとして使用できません",
"clear_shortcut": "ショートカットをクリア",
"clear_topic": "メッセージを消去",
"copy_last_message": "最後のメッセージをコピー",
@ -771,8 +727,7 @@
"toggle_show_topics": "トピックの表示を切り替え",
"zoom_in": "ズームイン",
"zoom_out": "ズームアウト",
"zoom_reset": "ズームをリセット",
"show_settings": "設定を開く"
"zoom_reset": "ズームをリセット"
},
"theme.auto": "自動",
"theme.dark": "ダークテーマ",
@ -791,7 +746,6 @@
"translate": {
"any.language": "任意の言語",
"button.translate": "翻訳",
"tooltip.newline": "改行",
"close": "閉じる",
"confirm": {
"content": "翻訳すると元のテキストが上書きされます。続行しますか?",

View File

@ -52,7 +52,6 @@
"settings.reasoning_effort.high": "Длинная",
"settings.reasoning_effort.low": "Короткая",
"settings.reasoning_effort.medium": "Средняя",
"settings.reasoning_effort.off": "Выключено",
"settings.reasoning_effort.tip": "Эта настройка поддерживается только моделями с рассуждением"
},
"auth": {
@ -121,8 +120,6 @@
"settings.top_p.tip": "Значение по умолчанию 1, чем меньше значение, тем меньше вариативности в ответах, тем проще понять, чем больше значение, тем больше вариативности в ответах, тем больше разнообразие",
"settings.max_tokens.confirm": "Включить лимит максимальных токенов",
"settings.max_tokens.confirm_content": "Включить лимит максимальных токенов, влияет на длину результата. Нужно учитывать контекст модели, иначе будет ошибка",
"settings.thought_auto_collapse": "Автоматически сворачивать содержание мыслей",
"settings.thought_auto_collapse.tip": "Автоматически сворачивать содержание мыслей после завершения размышления",
"suggestions.title": "Предложенные вопросы",
"thinking": "Мыслим",
"topics.auto_rename": "Автопереименование",
@ -139,13 +136,10 @@
"topics.pinned": "Закрепленные темы",
"topics.title": "Топики",
"topics.unpinned": "Открепленные темы",
"topics.delete.shortcut": "Удерживайте {{key}} для мгновенного удаления",
"translate": "Перевести",
"topics.prompt": "Тематические подсказки",
"topics.prompt.tips": "Тематические подсказки: Дополнительные подсказки, предоставленные для текущей темы",
"topics.prompt.edit.title": "Редактировать подсказки темы",
"artifacts.button.openExternal": "Открыть во внешнем браузере",
"artifacts.preview.openExternal.error.content": "Внешний браузер открылся с ошибкой"
"topics.prompt.edit.title": "Редактировать подсказки темы"
},
"common": {
"add": "Добавить",
@ -315,7 +309,6 @@
"chinese-traditional": "Китайский традиционный",
"english": "Английский",
"french": "Французский",
"german": "Немецкий",
"italian": "Итальянский",
"japanese": "Японский",
"korean": "Корейский",
@ -359,7 +352,7 @@
"error.invalid.enter.model": "Пожалуйста, выберите модель",
"error.invalid.proxy.url": "Неверный URL прокси",
"error.invalid.webdav": "Неверные настройки WebDAV",
"error.notion.export": "Ошибка экспорта в Notion, пожалуйста, проверьте состояние подключения и настройки в документации",
"error.notion.export": "Импорт в Notion не удался",
"error.notion.no_api_key": "Notion ApiKey или Notion DatabaseID не настроен",
"group.delete.content": "Удаление группы сообщений удалит пользовательский вопрос и все ответы помощника",
"group.delete.title": "Удалить группу сообщений",
@ -371,7 +364,6 @@
"message.multi_model_style.fold": "Свернуть",
"message.multi_model_style.horizontal": "Горизонтальный",
"message.multi_model_style.vertical": "Вертикальный",
"message.multi_model_style.grid": "клетчатый вид",
"message.style": "Стиль сообщения",
"message.style.bubble": "Пузырь",
"message.style.plain": "Простой",
@ -381,13 +373,13 @@
"reset.double.confirm.title": "ДАННЫЕ БУДУТ УТЕРЯНЫ !!!",
"restore.success": "Успешно восстановлено",
"save.success.title": "Успешно сохранено",
"success.notion.export": "Успешный экспорт в Notion",
"success.notion.export": "Импорт в Notion выполнен успешно",
"switch.disabled": "Пожалуйста, дождитесь завершения текущего ответа",
"topic.added": "Новый топик добавлен",
"upgrade.success.button": "Перезапустить",
"upgrade.success.content": "Пожалуйста, перезапустите приложение для завершения обновления",
"upgrade.success.title": "Обновление успешно",
"warn.notion.exporting": "Экспортируется в Notion, пожалуйста, не отправляйте повторные запросы!",
"warn.notion.exporting": "Идет импорт в Notion, пожалуйста, не повторяйте импорт",
"error.invalid.api.host": "Неверный API адрес",
"error.invalid.api.key": "Неверный API ключ"
},
@ -567,47 +559,36 @@
},
"data.title": "Каталог данных",
"notion.api_key": "Ключ API Notion",
"notion.api_key_placeholder": "Введите ключ API Notion",
"notion.database_id": "ID базы данных Notion",
"notion.database_id_placeholder": "Введите ID базы данных Notion",
"notion.page_name_key": "Название поля заголовка страницы",
"notion.page_name_key_placeholder": "Введите название поля заголовка страницы, по умолчанию Name",
"notion.title": "Настройки Notion",
"notion.help": "Документация по настройке Notion",
"notion.check": {
"button": "Проверить",
"fail": "Не удалось подключиться, пожалуйста, проверьте сеть и правильность Api_key и Database_id",
"fail": "Ошибка подключения, проверьте настройки",
"success": "Подключение успешно",
"error": "Аномалия в подключении, пожалуйста, проверьте настройки сети, а также правильность Api_key и Database_id",
"error": "Ошибка подключения, проверьте сеть",
"empty_api_key": "Не настроен Api_key",
"empty_database_id": "Не настроен Database_id"
},
"title": "Настройки данных",
"webdav": {
"autoSync": "Автоматическое резервное копирование",
"autoSync.off": "Выключено",
"backup.button": "Резервное копирование на WebDAV",
"host": "Хост WebDAV",
"host.placeholder": "http://localhost:8080",
"minute_interval_one": "{{count}} минута",
"minute_interval_few": "{{count}} минуты",
"minute_interval_many": "{{count}} минут",
"hour_interval_one": "{{count}} час",
"hour_interval_few": "{{count}} часа",
"hour_interval_many": "{{count}} часов",
"lastSync": "Последняя синхронизация",
"noSync": "Ожидание следующего резервного копирования",
"password": "Пароль WebDAV",
"path": "Путь WebDAV",
"path.placeholder": "/backup",
"restore.button": "Восстановление с WebDAV",
"restore.content": "Восстановление с WebDAV перезапишет текущие данные, продолжить?",
"restore.title": "Восстановление с WebDAV",
"syncError": "Ошибка резервного копирования",
"syncStatus": "Статус резервного копирования",
"title": "WebDAV",
"user": "Пользователь WebDAV"
}
"webdav.autoSync": "Автоматическое резервное копирование",
"webdav.autoSync.off": "Выключено",
"webdav.backup.button": "Резервное копирование на WebDAV",
"webdav.host": "Хост WebDAV",
"webdav.host.placeholder": "http://localhost:8080",
"webdav.hours": "часов",
"webdav.lastSync": "Последняя синхронизация",
"webdav.minutes": "минут",
"webdav.noSync": "Ожидание следующего резервного копирования",
"webdav.password": "Пароль WebDAV",
"webdav.path": "Путь WebDAV",
"webdav.path.placeholder": "/backup",
"webdav.restore.button": "Восстановление с WebDAV",
"webdav.restore.content": "Восстановление с WebDAV перезапишет текущие данные, продолжить?",
"webdav.restore.title": "Восстановление с WebDAV",
"webdav.syncError": "Ошибка резервного копирования",
"webdav.syncStatus": "Статус резервного копирования",
"webdav.title": "WebDAV",
"webdav.user": "Пользователь WebDAV"
},
"display.custom.css": "Пользовательский CSS",
"display.custom.css.placeholder": "/* Здесь введите пользовательский CSS */",
@ -656,10 +637,6 @@
"messages.math_engine": "Математический движок",
"messages.metrics": "{{time_first_token_millsec}}ms до первого токена | {{token_speed}} tok/sec",
"messages.model.title": "Настройки модели",
"messages.grid_columns": "Количество столбцов сетки сообщений",
"messages.grid_popover_trigger": "Триггер для отображения подробной информации в сетке",
"messages.grid_popover_trigger.hover": "Наведение для отображения",
"messages.grid_popover_trigger.click": "Нажатие для отображения",
"messages.title": "Настройки сообщений",
"messages.use_serif_font": "Использовать serif шрифт",
"model": "Модель по умолчанию",
@ -730,7 +707,7 @@
},
"shortcuts": {
"action": "Действие",
"alt_warning": "В Mac сочетания с клавишей Option работают только с пробелом",
"alt_warning": "Mac не поддерживает Option + буквы как горячие клавиши",
"clear_shortcut": "Очистить сочетание клавиш",
"clear_topic": "Очистить все сообщения",
"copy_last_message": "Копировать последнее сообщение",
@ -749,8 +726,7 @@
"toggle_show_topics": "Переключить отображение топиков",
"zoom_in": "Увеличить",
"zoom_out": "Уменьшить",
"zoom_reset": "Сбросить масштаб",
"show_settings": "Открыть настройки"
"zoom_reset": "Сбросить масштаб"
},
"theme.auto": "Автоматически",
"theme.dark": "Темная",
@ -770,7 +746,6 @@
"translate": {
"any.language": "Любой язык",
"button.translate": "Перевести",
"tooltip.newline": "Перевести",
"close": "Закрыть",
"confirm": {
"content": "Перевод заменит исходный текст, продолжить?",

View File

@ -51,7 +51,6 @@
"settings.reasoning_effort.high": "长",
"settings.reasoning_effort.low": "短",
"settings.reasoning_effort.medium": "中",
"settings.reasoning_effort.off": "关",
"settings.reasoning_effort.tip": "该设置仅支持推理模型",
"title": "助手"
},
@ -74,8 +73,6 @@
"add.assistant.title": "添加助手",
"artifacts.button.download": "下载",
"artifacts.button.preview": "预览",
"artifacts.button.openExternal": "外部浏览器打开",
"artifacts.preview.openExternal.error.content": "外部浏览器打开出错",
"assistant.search.placeholder": "搜索",
"deeply_thought": "已深度思考(用时 {{secounds}} 秒)",
"default.description": "你好,我是默认助手。你可以立刻开始跟我聊天。",
@ -123,8 +120,6 @@
"settings.top_p.tip": "默认值为 1值越小AI 生成的内容越单调也越容易理解值越大AI 回复的词汇围越大,越多样化",
"settings.max_tokens.confirm": "开启消息长度限制",
"settings.max_tokens.confirm_content": "开启消息长度限制后,单次交互所用的最大 Token 数, 会影响返回结果的长度。要根据模型上下文限制来设置,否则会报错",
"settings.thought_auto_collapse": "思考内容自动折叠",
"settings.thought_auto_collapse.tip": "思考结束后思考内容自动折叠",
"suggestions.title": "建议的问题",
"thinking": "思考中",
"topics.auto_rename": "生成话题名",
@ -141,10 +136,10 @@
"topics.pinned": "固定话题",
"topics.title": "话题",
"topics.unpinned": "取消固定",
"topics.delete.shortcut": "按住 {{key}} 可直接删除",
"translate": "翻译",
"topics.prompt": "话题提示词",
"topics.prompt.tips": "话题提示词: 针对当前话题提供额外的补充提示词"
"topics.prompt.tips": "话题提示词: 针对当前话题提供额外的补充提示词",
"topics.prompt.edit.title": "编辑话题提示词"
},
"common": {
"add": "添加",
@ -319,8 +314,7 @@
"korean": "韩文",
"portuguese": "葡萄牙文",
"russian": "俄文",
"spanish": "西班牙文",
"german": "德文"
"spanish": "西班牙文"
},
"mermaid": {
"download": {
@ -337,18 +331,6 @@
},
"title": "Mermaid 图表"
},
"plantuml": {
"title": "PlantUML 图表",
"download": {
"png": "下载 PNG",
"svg": "下载 SVG",
"failed": "下载失败,请检查网络"
},
"tabs": {
"preview": "预览",
"source": "源码"
}
},
"message": {
"api.check.model.title": "请选择要检测的模型",
"api.connection.failed": "连接失败",
@ -372,7 +354,7 @@
"error.invalid.enter.model": "请选择一个模型",
"error.invalid.proxy.url": "无效的代理地址",
"error.invalid.webdav": "无效的 WebDAV 设置",
"error.notion.export": "导出Notion错误请检查连接状态并对照文档检查配置",
"error.notion.export": "Notion 导入失败",
"error.notion.no_api_key": "未配置Notion ApiKey或Notion DatabaseID",
"group.delete.content": "删除分组消息会删除用户提问和所有助手的回答",
"group.delete.title": "删除分组消息",
@ -384,7 +366,6 @@
"message.multi_model_style.fold": "折叠",
"message.multi_model_style.horizontal": "水平",
"message.multi_model_style.vertical": "垂直",
"message.multi_model_style.grid": "网格",
"message.style": "消息样式",
"message.style.bubble": "气泡",
"message.style.plain": "简洁",
@ -394,13 +375,13 @@
"reset.double.confirm.title": "数据丢失!!!",
"restore.success": "恢复成功",
"save.success.title": "保存成功",
"success.notion.export": "成功导出到Notion",
"success.notion.export": "导入Notion成功",
"switch.disabled": "请等待当前回复完成后操作",
"topic.added": "话题添加成功",
"upgrade.success.button": "重启",
"upgrade.success.content": "重启用以完成升级",
"upgrade.success.title": "升级成功",
"warn.notion.exporting": "正在导出到Notion, 请勿重复请求导出!"
"warn.notion.exporting": "Notion正在导入请勿重复导入"
},
"minapp": {
"sidebar.add.title": "添加到侧边栏",
@ -578,49 +559,36 @@
},
"data.title": "数据目录",
"notion.api_key": "Notion 密钥",
"notion.api_key_placeholder": "请输入Notion 密钥",
"notion.database_id": "Notion 数据库 ID",
"notion.database_id_placeholder": "请输入Notion 数据库 ID",
"notion.page_name_key": "页面标题字段名",
"notion.page_name_key_placeholder": "请输入页面标题字段名,默认为 Name",
"notion.database_id": "Notion 数据库ID",
"notion.title": "Notion 配置",
"notion.help": "Notion 配置文档",
"notion.check": {
"button": "检查",
"fail": "连接失败,请检查网络及Api_key和Database_id是否正确",
"fail": "连接失败,请检查配置",
"success": "连接成功",
"error": "连接异常,请检查网络及Api_key和Database_id是否正确",
"error": "连接异常,请检查网络",
"empty_api_key": "未配置Api_key",
"empty_database_id": "未配置Database_id"
},
"title": "数据设置",
"webdav": {
"autoSync": "自动备份",
"autoSync.off": "关闭",
"backup.button": "备份到 WebDAV",
"host": "WebDAV 地址",
"host.placeholder": "http://localhost:8080",
"minute_interval_one": "{{count}} 分钟",
"minute_interval_other": "{{count}} 分钟",
"hour_interval_one": "{{count}} 小时",
"hour_interval_other": "{{count}} 小时",
"lastSync": "上次备份时间",
"noSync": "等待下次备份",
"password": "WebDAV 密码",
"path": "WebDAV 路径",
"path.placeholder": "/backup",
"restore.button": "从 WebDAV 恢复",
"restore.content": "从 WebDAV 恢复将覆盖当前数据,是否继续?",
"restore.title": "从 WebDAV 恢复",
"syncError": "备份错误",
"syncStatus": "备份状态",
"title": "WebDAV",
"user": "WebDAV 用户名"
},
"minute_interval_one": "{{count}} 分钟",
"minute_interval_other": "{{count}} 分钟",
"hour_interval_one": "{{count}} 小时",
"hour_interval_other": "{{count}} 小时"
"webdav.autoSync": "自动备份",
"webdav.autoSync.off": "关闭",
"webdav.backup.button": "备份到 WebDAV",
"webdav.host": "WebDAV 地址",
"webdav.host.placeholder": "http://localhost:8080",
"webdav.hours": "小时",
"webdav.lastSync": "上次备份时间",
"webdav.minutes": "分钟",
"webdav.noSync": "等待下次备份",
"webdav.password": "WebDAV 密码",
"webdav.path": "WebDAV 路径",
"webdav.path.placeholder": "/backup",
"webdav.restore.button": "从 WebDAV 恢复",
"webdav.restore.content": "从 WebDAV 恢复将覆盖当前数据,是否继续?",
"webdav.restore.title": "从 WebDAV 恢复",
"webdav.syncError": "备份错误",
"webdav.syncStatus": "备份状态",
"webdav.title": "WebDAV",
"webdav.user": "WebDAV 用户名"
},
"display.custom.css": "自定义 CSS",
"display.custom.css.placeholder": "/* 这里写自定义CSS */",
@ -668,10 +636,6 @@
"messages.input.title": "输入设置",
"messages.markdown_rendering_input_message": "Markdown 渲染输入消息",
"messages.math_engine": "数学公式引擎",
"messages.grid_columns": "消息网格展示列数",
"messages.grid_popover_trigger": "网格详情触发",
"messages.grid_popover_trigger.hover": "悬停显示",
"messages.grid_popover_trigger.click": "点击显示",
"messages.metrics": "首字时延 {{time_first_token_millsec}}ms | 每秒 {{token_speed}} tokens",
"messages.model.title": "模型设置",
"messages.title": "消息设置",
@ -744,7 +708,7 @@
},
"shortcuts": {
"action": "操作",
"alt_warning": "Mac 系统中 Option 键只能与空格键组合使用",
"alt_warning": "Mac 系统不能使用 Option + 字母作为快捷键",
"clear_shortcut": "清除快捷键",
"clear_topic": "清空消息",
"copy_last_message": "复制上一条消息",
@ -757,7 +721,6 @@
"reset_to_default": "重置为默认",
"search_message": "搜索消息",
"show_app": "显示应用",
"show_settings": "打开设置",
"title": "快捷方式",
"toggle_new_context": "清除上下文",
"toggle_show_assistants": "切换助手显示",
@ -783,7 +746,6 @@
"translate": {
"any.language": "任意语言",
"button.translate": "翻译",
"tooltip.newline": "换行",
"close": "关闭",
"confirm": {
"content": "翻译后将覆盖原文,是否继续?",
@ -794,14 +756,7 @@
"input.placeholder": "输入文本进行翻译",
"output.placeholder": "翻译",
"processing": "翻译中...",
"title": "翻译",
"history": {
"title": "翻译历史",
"empty": "暂无翻译历史",
"clear": "清空历史",
"delete": "删除",
"clear_description": "清空历史将删除所有翻译历史记录,是否继续?"
}
"title": "翻译"
},
"tray": {
"quit": "退出",

View File

@ -51,7 +51,6 @@
"settings.reasoning_effort.high": "長",
"settings.reasoning_effort.low": "短",
"settings.reasoning_effort.medium": "中",
"settings.reasoning_effort.off": "關",
"settings.reasoning_effort.tip": "該設置僅支持推理模型",
"title": "助手"
},
@ -121,8 +120,6 @@
"settings.top_p.tip": "模型生成文本的隨機程度。值越小AI 生成的內容越單調也越容易理解值越大AI 回覆的詞彙範圍越大,越多樣化",
"settings.max_tokens.confirm": "啟用消息長度限制",
"settings.max_tokens.confirm_content": "啟用消息長度限制後,單次交互所用的最大 Token 數, 會影響返回結果的長度。要根據模型上下文限制來設置,否則會報錯",
"settings.thought_auto_collapse": "思考內容自動折疊",
"settings.thought_auto_collapse.tip": "思考結束後思考內容自動折疊",
"suggestions.title": "建議的問題",
"thinking": "思考中",
"topics.auto_rename": "自動重新命名",
@ -139,13 +136,10 @@
"topics.pinned": "固定話題",
"topics.title": "話題",
"topics.unpinned": "取消固定",
"topics.delete.shortcut": "按住 {{key}} 可直接刪除",
"translate": "翻譯",
"topics.prompt": "話題提示詞",
"topics.prompt.tips": "話題提示詞:針對目前話題提供額外的補充提示詞",
"topics.prompt.edit.title": "編輯話題提示詞",
"artifacts.button.openExternal": "外部瀏覽器打開",
"artifacts.preview.openExternal.error.content": "外部瀏覽器打開出錯"
"topics.prompt.edit.title": "編輯話題提示詞"
},
"common": {
"add": "添加",
@ -320,8 +314,7 @@
"korean": "韓文",
"portuguese": "葡萄牙文",
"russian": "俄文",
"spanish": "西班牙文",
"german": "德文"
"spanish": "西班牙文"
},
"mermaid": {
"download": {
@ -359,7 +352,7 @@
"error.invalid.enter.model": "請選擇一個模型",
"error.invalid.proxy.url": "無效的代理 URL",
"error.invalid.webdav": "無效的 WebDAV 設定",
"error.notion.export": "導出Notion錯誤請檢查連接狀態並對照文檔檢查配置",
"error.notion.export": "Notion 匯入失敗",
"error.notion.no_api_key": "未配置 Notion ApiKey 或 Notion DatabaseID",
"group.delete.content": "刪除分組消息會刪除用戶提問和所有助手的回答",
"group.delete.title": "刪除分組消息",
@ -371,7 +364,6 @@
"message.multi_model_style.fold": "折疊",
"message.multi_model_style.horizontal": "水平",
"message.multi_model_style.vertical": "垂直",
"message.multi_model_style.grid": "网格",
"message.style": "消息樣式",
"message.style.bubble": "氣泡",
"message.style.plain": "簡潔",
@ -381,13 +373,13 @@
"reset.double.confirm.title": "資料將會丟失!!!",
"restore.success": "恢復成功",
"save.success.title": "保存成功",
"success.notion.export": "成功導出到Notion",
"success.notion.export": "匯入 Notion 成功",
"switch.disabled": "請等待當前回覆完成",
"topic.added": "新話題已添加",
"upgrade.success.button": "重新啟動",
"upgrade.success.content": "請重新啟動應用以完成升級",
"upgrade.success.title": "升級成功",
"warn.notion.exporting": "正在導出到Notion請勿重複請求導出",
"warn.notion.exporting": "Notion 正在匯入,請勿重複匯入",
"error.invalid.api.host": "無效的 API 位址",
"error.invalid.api.key": "無效的 API 密鑰"
},
@ -564,52 +556,39 @@
"title": "清除緩存"
},
"data.title": "數據目錄",
"notion.api_key": "Notion 密鑰",
"notion.api_key_placeholder": "請輸入Notion 密鑰",
"notion.api_key": "Notion 金鑰",
"notion.database_id": "Notion 資料庫 ID",
"notion.database_id_placeholder": "請輸入Notion 資料庫 ID",
"notion.page_name_key": "頁面標題欄位名稱",
"notion.page_name_key_placeholder": "請輸入頁面標題欄位名稱,預設為 Name",
"notion.title": "Notion 配置",
"notion.help": "Notion 配置文檔",
"notion.check": {
"button": "檢查",
"fail": "連接失敗請檢查網絡及Api_key和Database_id是否正確",
"fail": "連線失敗,請檢查配置",
"success": "連線成功",
"error": "連接異常請檢查網絡及Api_key和Database_id是否正確",
"error": "連線異常,請檢查網路",
"empty_api_key": "未配置Api_key",
"empty_database_id": "未配置Database_id"
},
"title": "數據設定",
"webdav": {
"autoSync": "自動備份",
"autoSync.off": "關閉",
"backup.button": "備份到 WebDAV",
"host": "WebDAV 主機位址",
"host.placeholder": "http://localhost:8080",
"minute_interval_one": "{{count}} 分鐘",
"minute_interval_other": "{{count}} 分鐘",
"hour_interval_one": "{{count}} 小時",
"hour_interval_other": "{{count}} 小時",
"lastSync": "上次備份時間",
"noSync": "等待下次備份",
"password": "WebDAV 密碼",
"path": "WebDAV 路徑",
"path.placeholder": "/backup",
"restore.button": "從 WebDAV 恢復",
"restore.content": "從 WebDAV 恢復將覆蓋當前資料,是否繼續?",
"restore.title": "從 WebDAV 恢復",
"syncError": "備份錯誤",
"syncStatus": "備份狀態",
"title": "WebDAV",
"user": "WebDAV 使用者名稱"
},
"webdav.autoSync": "自動備份",
"webdav.autoSync.off": "關閉",
"webdav.backup.button": "從 WebDAV 備份",
"webdav.host": "WebDAV 主機位址",
"webdav.host.placeholder": "http://localhost:8080",
"webdav.hours": "小時",
"webdav.lastSync": "上次同步時間",
"webdav.minutes": "分鐘",
"webdav.noSync": "等待下次備份",
"webdav.password": "WebDAV 密碼",
"webdav.path": "WebDAV Path",
"webdav.path.placeholder": "/backup",
"webdav.restore.button": "從 WebDAV 恢復",
"webdav.restore.content": "從 WebDAV 恢復將覆蓋當前資料,是否繼續?",
"webdav.restore.title": "從 WebDAV 恢復",
"webdav.syncError": "備份錯誤",
"webdav.syncStatus": "備份狀態",
"webdav.title": "WebDAV",
"webdav.user": "WebDAV 使用者名稱",
"app_data": "應用數據",
"app_logs": "應用日誌",
"minute_interval_one": "{{count}} 分鐘",
"minute_interval_other": "{{count}} 分鐘",
"hour_interval_one": "{{count}} 小時",
"hour_interval_other": "{{count}} 小時"
"app_logs": "應用日誌"
},
"display.custom.css": "自定義 CSS",
"display.custom.css.placeholder": "/* 這裡寫自定義 CSS */",
@ -656,10 +635,6 @@
"messages.input.show_estimated_tokens": "顯示預估 Token 數",
"messages.input.title": "輸入設定",
"messages.math_engine": "Markdown 渲染輸入訊息",
"messages.grid_columns": "消息網格展示列數",
"messages.grid_popover_trigger": "網格詳情觸發",
"messages.grid_popover_trigger.hover": "懸停顯示",
"messages.grid_popover_trigger.click": "點擊顯示",
"messages.metrics": "首字時延 {{time_first_token_millsec}}ms | 每秒 {{token_speed}} tokens",
"messages.model.title": "模型設定",
"messages.title": "訊息設定",
@ -732,7 +707,7 @@
},
"shortcuts": {
"action": "操作",
"alt_warning": "Mac 系統中 Option 鍵只能與空白鍵組合使用",
"alt_warning": "Mac 不能使用 Option + 字母作為快捷鍵",
"clear_shortcut": "清除快捷鍵",
"clear_topic": "清除所有訊息",
"copy_last_message": "複製上一条消息",
@ -751,8 +726,7 @@
"toggle_show_topics": "切換話題顯示",
"zoom_in": "放大界面",
"zoom_out": "縮小界面",
"zoom_reset": "重置縮放",
"show_settings": "打開設定"
"zoom_reset": "重置縮放"
},
"theme.auto": "自動",
"theme.dark": "深色主題",
@ -772,7 +746,6 @@
"translate": {
"any.language": "任意語言",
"button.translate": "翻譯",
"tooltip.newline": "換行",
"close": "關閉",
"confirm": {
"content": "翻譯後將覆蓋原文,是否繼續?",

View File

@ -9,7 +9,7 @@ import { useSidebarIconShow } from '@renderer/hooks/useSidebarIcon'
import { fetchGenerate } from '@renderer/services/ApiService'
import { getDefaultModel } from '@renderer/services/AssistantService'
import { useAppSelector } from '@renderer/store'
import { Agent, KnowledgeBase } from '@renderer/types'
import { Agent } from '@renderer/types'
import { getLeadingEmoji, uuid } from '@renderer/utils'
import { Button, Form, FormInstance, Input, Modal, Popover, Select, SelectProps } from 'antd'
import TextArea from 'antd/es/input/TextArea'
@ -25,7 +25,7 @@ type FieldType = {
id: string
name: string
prompt: string
knowledge_base_ids: string[]
knowledge_base_id: string
}
const PopupContainer: React.FC<Props> = ({ resolve }) => {
@ -37,8 +37,8 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
const [emoji, setEmoji] = useState('')
const [loading, setLoading] = useState(false)
const knowledgeState = useAppSelector((state) => state.knowledge)
const showKnowledgeIcon = useSidebarIconShow('knowledge')
const knowledgeOptions: SelectProps['options'] = []
const showKnowledgeIcon = useSidebarIconShow('knowledge')
knowledgeState.bases.forEach((base) => {
knowledgeOptions.push({
@ -57,9 +57,7 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
const _agent: Agent = {
id: uuid(),
name: values.name,
knowledge_bases: values.knowledge_base_ids
?.map((id) => knowledgeState.bases.find((t) => t.id === id))
?.filter((base): base is KnowledgeBase => base !== undefined),
knowledge_base: knowledgeState.bases.find((t) => t.id === values.knowledge_base_id),
emoji: _emoji,
prompt: values.prompt,
defaultModel: getDefaultModel(),
@ -156,18 +154,12 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
/>
</div>
{showKnowledgeIcon && (
<Form.Item name="knowledge_base_ids" label={t('agents.add.knowledge_base')} rules={[{ required: false }]}>
<Form.Item name="knowledge_base_id" label={t('agents.add.knowledge_base')} rules={[{ required: false }]}>
<Select
mode="multiple"
allowClear
placeholder={t('agents.add.knowledge_base.placeholder')}
menuItemSelectedIcon={<CheckOutlined />}
options={knowledgeOptions}
filterOption={(input, option) =>
String(option?.label ?? '')
.toLowerCase()
.includes(input.toLowerCase())
}
/>
</Form.Item>
)}

View File

@ -27,7 +27,6 @@ import store, { useAppDispatch, useAppSelector } from '@renderer/store'
import { setGenerating, setSearching } from '@renderer/store/runtime'
import { Assistant, FileType, KnowledgeBase, Message, Model, Topic } from '@renderer/types'
import { classNames, delay, getFileExtension, uuid } from '@renderer/utils'
import { abortCompletion } from '@renderer/utils/abortController'
import { documentExts, imageExts, textExts } from '@shared/config/constant'
import { Button, Popconfirm, Tooltip } from 'antd'
import TextArea, { TextAreaRef } from 'antd/es/input/TextArea'
@ -53,6 +52,7 @@ interface Props {
let _text = ''
let _files: FileType[] = []
let _base: KnowledgeBase | undefined
const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
const [text, setText] = useState(_text)
@ -83,10 +83,10 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
const [spaceClickCount, setSpaceClickCount] = useState(0)
const spaceClickTimer = useRef<NodeJS.Timeout>()
const [isTranslating, setIsTranslating] = useState(false)
const [selectedKnowledgeBases, setSelectedKnowledgeBases] = useState<KnowledgeBase[]>([])
const [selectedKnowledgeBase, setSelectedKnowledgeBase] = useState<KnowledgeBase | undefined>(_base)
const [mentionModels, setMentionModels] = useState<Model[]>([])
const [isMentionPopupOpen, setIsMentionPopupOpen] = useState(false)
const currentMessageId = useRef<string>()
const isVision = useMemo(() => isVisionModel(model), [model])
const supportExts = useMemo(() => [...textExts, ...documentExts, ...(isVision ? imageExts : [])], [isVision])
@ -104,6 +104,7 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
_text = text
_files = files
_base = selectedKnowledgeBase
const sendMessage = useCallback(async () => {
await modelGenerating()
@ -123,8 +124,8 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
status: 'success'
}
if (selectedKnowledgeBases) {
message.knowledgeBaseIds = selectedKnowledgeBases.map((base) => base.id)
if (selectedKnowledgeBase) {
message.knowledgeBaseIds = [selectedKnowledgeBase.id]
}
if (files.length > 0) {
@ -134,7 +135,7 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
if (mentionModels.length > 0) {
message.mentions = mentionModels
}
currentMessageId.current = message.id
EventEmitter.emit(EVENT_NAMES.SEND_MESSAGE, message)
setText('')
@ -143,7 +144,7 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
setTimeout(() => resizeTextArea(), 0)
setExpend(false)
}, [inputEmpty, text, assistant.id, assistant.topics, selectedKnowledgeBases, files, mentionModels])
}, [inputEmpty, text, assistant.id, assistant.topics, selectedKnowledgeBase, files, mentionModels])
const translate = async () => {
if (isTranslating) {
@ -242,11 +243,6 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
sendMessage()
return event.preventDefault()
}
if (event.key === 'Backspace' && text.trim() === '' && mentionModels.length > 0) {
setMentionModels((prev) => prev.slice(0, -1))
return event.preventDefault()
}
}
const addNewTopic = useCallback(async () => {
@ -275,9 +271,6 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
}
const onPause = () => {
if (currentMessageId.current) {
abortCompletion(currentMessageId.current)
}
window.keyv.set(EVENT_NAMES.CHAT_COMPLETION_PAUSED, true)
store.dispatch(setGenerating(false))
}
@ -465,15 +458,14 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
}, [])
useEffect(() => {
// if assistant knowledge bases are undefined return []
setSelectedKnowledgeBases(showKnowledgeIcon ? (assistant.knowledge_bases ?? []) : [])
}, [assistant.id, assistant.knowledge_bases, showKnowledgeIcon])
setSelectedKnowledgeBase(showKnowledgeIcon ? assistant.knowledge_base : undefined)
}, [assistant.id, assistant.knowledge_base, showKnowledgeIcon])
const textareaRows = window.innerHeight >= 1000 || isBubbleStyle ? 2 : 1
const handleKnowledgeBaseSelect = (bases?: KnowledgeBase[]) => {
updateAssistant({ ...assistant, knowledge_bases: bases })
setSelectedKnowledgeBases(bases ?? [])
const handleKnowledgeBaseSelect = (base?: KnowledgeBase) => {
updateAssistant({ ...assistant, knowledge_base: base })
setSelectedKnowledgeBase(base)
}
const onMentionModel = (model: Model) => {
@ -581,7 +573,7 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
</Tooltip>
{showKnowledgeIcon && (
<KnowledgeBaseButton
selectedBases={selectedKnowledgeBases}
selectedBase={selectedKnowledgeBase}
onSelect={handleKnowledgeBaseSelect}
ToolbarButton={ToolbarButton}
disabled={files.length > 0}

View File

@ -1,68 +1,71 @@
import { CheckOutlined, FileSearchOutlined } from '@ant-design/icons'
import { FileSearchOutlined } from '@ant-design/icons'
import { useAppSelector } from '@renderer/store'
import { KnowledgeBase } from '@renderer/types'
import { Popover, Select, SelectProps, Tooltip } from 'antd'
import { Button, Popover, Tooltip } from 'antd'
import { FC } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
interface Props {
selectedBases?: KnowledgeBase[]
onSelect: (bases: KnowledgeBase[]) => void
selectedBase?: KnowledgeBase
onSelect: (base?: KnowledgeBase) => void
disabled?: boolean
ToolbarButton?: any
}
const KnowledgeBaseSelector: FC<Props> = ({ selectedBases, onSelect }) => {
const KnowledgeBaseSelector: FC<Props> = ({ selectedBase, onSelect }) => {
const { t } = useTranslation()
const knowledgeState = useAppSelector((state) => state.knowledge)
const knowledgeOptions: SelectProps['options'] = knowledgeState.bases.map((base) => ({
label: base.name,
value: base.id
}))
return (
<SelectorContainer>
{knowledgeState.bases.length === 0 ? (
<EmptyMessage>{t('knowledge.no_bases')}</EmptyMessage>
) : (
<Select
mode="multiple"
value={selectedBases?.map((base) => base.id)}
allowClear
placeholder={t('agents.add.knowledge_base.placeholder')}
menuItemSelectedIcon={<CheckOutlined />}
options={knowledgeOptions}
filterOption={(input, option) =>
String(option?.label ?? '')
.toLowerCase()
.includes(input.toLowerCase())
}
onChange={(ids) => {
const newSelected = knowledgeState.bases.filter((base) => ids.includes(base.id))
onSelect(newSelected)
}}
style={{ width: '200px' }}
/>
<>
{selectedBase && (
<Button type="link" block onClick={() => onSelect(undefined)} style={{ textAlign: 'left' }}>
{t('knowledge.clear_selection')}
</Button>
)}
{knowledgeState.bases.map((base) => (
<Button
key={base.id}
type={selectedBase?.id === base.id ? 'primary' : 'text'}
block
onClick={() => onSelect(base)}
style={{ textAlign: 'left' }}>
{base.name}
</Button>
))}
</>
)}
</SelectorContainer>
)
}
const KnowledgeBaseButton: FC<Props> = ({ selectedBases, onSelect, disabled, ToolbarButton }) => {
const KnowledgeBaseButton: FC<Props> = ({ selectedBase, onSelect, disabled, ToolbarButton }) => {
const { t } = useTranslation()
if (selectedBase) {
return (
<Tooltip placement="top" title={selectedBase.name} arrow>
<ToolbarButton type="text" onClick={() => onSelect(undefined)}>
<FileSearchOutlined style={{ color: selectedBase ? 'var(--color-link)' : 'var(--color-icon)' }} />
</ToolbarButton>
</Tooltip>
)
}
return (
<Tooltip placement="top" title={t('chat.input.knowledge_base')} arrow>
<Popover
placement="top"
content={<KnowledgeBaseSelector selectedBases={selectedBases} onSelect={onSelect} />}
content={<KnowledgeBaseSelector selectedBase={selectedBase} onSelect={onSelect} />}
overlayStyle={{ maxWidth: 400 }}
trigger="click">
<ToolbarButton type="text" disabled={disabled}>
<FileSearchOutlined
style={{ color: selectedBases && selectedBases?.length > 0 ? 'var(--color-link)' : 'var(--color-icon)' }}
/>
<ToolbarButton type="text" onClick={() => selectedBase && onSelect(undefined)} disabled={disabled}>
<FileSearchOutlined style={{ color: selectedBase ? 'var(--color-link)' : 'var(--color-icon)' }} />
</ToolbarButton>
</Popover>
</Tooltip>

View File

@ -28,8 +28,6 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
const menuRef = useRef<HTMLDivElement>(null)
const [searchText, setSearchText] = useState('')
const itemRefs = useRef<Array<HTMLDivElement | null>>([])
// Add a new state to track if menu was dismissed
const [menuDismissed, setMenuDismissed] = useState(false)
const setItemRef = (index: number, el: HTMLDivElement | null) => {
itemRefs.current[index] = el
@ -46,7 +44,7 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
const handleModelSelect = (model: Model) => {
// Check if model is already selected
if (mentionModels.some((selected) => getModelUniqId(selected) === getModelUniqId(model))) {
if (mentionModels.some((selected) => selected.id === model.id)) {
return
}
onSelect(model)
@ -174,13 +172,12 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
loadPinnedModels()
}, [])
// Scroll to the first menu item when the mode selection menu opens
useLayoutEffect(() => {
if (isOpen && selectedIndex > -1 && itemRefs.current[selectedIndex]) {
requestAnimationFrame(() => {
itemRefs.current[selectedIndex]?.scrollIntoView({ block: 'nearest' })
})
if (isOpen && flatModelItems.length > 0 && itemRefs.current[0]) {
itemRefs.current[0].scrollIntoView({ block: 'nearest' })
}
}, [isOpen, selectedIndex])
}, [isOpen, flatModelItems])
useEffect(() => {
const showModelSelector = () => {
@ -189,7 +186,6 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
setIsOpen(true)
setSelectedIndex(0)
setSearchText('')
setMenuDismissed(false) // Reset dismissed flag when manually showing selector
}
const handleKeyDown = (e: KeyboardEvent) => {
@ -213,7 +209,7 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
e.preventDefault()
if (selectedIndex >= 0 && selectedIndex < flatModelItems.length) {
const selectedModel = flatModelItems[selectedIndex].model
if (!mentionModels.some((selected) => getModelUniqId(selected) === getModelUniqId(selectedModel))) {
if (!mentionModels.some((selected) => selected.id === selectedModel.id)) {
flatModelItems[selectedIndex].onClick()
}
setIsOpen(false)
@ -222,7 +218,6 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
} else if (e.key === 'Escape') {
setIsOpen(false)
setSearchText('')
setMenuDismissed(true) // Set dismissed flag when Escape is pressed
}
}
@ -235,14 +230,10 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
if (lastAtIndex === -1 || textBeforeCursor.slice(lastAtIndex + 1).includes(' ')) {
setIsOpen(false)
setSearchText('')
setMenuDismissed(false) // Reset dismissed flag when @ is removed
} else {
// Only open menu if it wasn't explicitly dismissed
if (!menuDismissed) {
setIsOpen(true)
const searchStr = textBeforeCursor.slice(lastAtIndex + 1)
setSearchText(searchStr)
}
} else if (lastAtIndex !== -1) {
// Get the text after @ for search
const searchStr = textBeforeCursor.slice(lastAtIndex + 1)
setSearchText(searchStr)
}
}
@ -261,42 +252,39 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
textArea.removeEventListener('input', handleTextChange)
}
}
}, [isOpen, selectedIndex, flatModelItems, mentionModels, menuDismissed])
}, [isOpen, selectedIndex, flatModelItems, mentionModels])
// Hide dropdown if no models available
if (flatModelItems.length === 0) {
return null
}
const menu = (
<div ref={menuRef} className="ant-dropdown-menu">
{flatModelItems.length > 0 ? (
modelMenuItems.map((group, groupIndex) => {
if (!group) return null
{modelMenuItems.map((group, groupIndex) => {
if (!group) return null
// Calculate starting index for items in this group
const startIndex = modelMenuItems.slice(0, groupIndex).reduce((acc, g) => acc + (g?.children?.length || 0), 0)
// Calculate the starting index for this group's items
const startIndex = modelMenuItems.slice(0, groupIndex).reduce((acc, g) => acc + (g?.children?.length || 0), 0)
return (
<div key={group.key} className="ant-dropdown-menu-item-group">
<div className="ant-dropdown-menu-item-group-title">{group.label}</div>
<div>
{group.children.map((item, idx) => (
<div
key={item.key}
ref={(el) => setItemRef(startIndex + idx, el)}
className={`ant-dropdown-menu-item ${
selectedIndex === startIndex + idx ? 'ant-dropdown-menu-item-selected' : ''
}`}
onClick={item.onClick}>
<span className="ant-dropdown-menu-item-icon">{item.icon}</span>
{item.label}
</div>
))}
</div>
return (
<div key={group.key} className="ant-dropdown-menu-item-group">
<div className="ant-dropdown-menu-item-group-title">{group.label}</div>
<div>
{group.children.map((item, idx) => (
<div
key={item.key}
ref={(el) => setItemRef(startIndex + idx, el)}
className={`ant-dropdown-menu-item ${selectedIndex === startIndex + idx ? 'ant-dropdown-menu-item-selected' : ''}`}
onClick={item.onClick}>
<span className="ant-dropdown-menu-item-icon">{item.icon}</span>
{item.label}
</div>
))}
</div>
)
})
) : (
<div className="ant-dropdown-menu-item-group">
<div className="ant-dropdown-menu-item no-results">{t('models.no_matches')}</div>
</div>
)}
</div>
)
})}
</div>
)
@ -346,17 +334,6 @@ const DropdownMenuStyle = createGlobalStyle`
&::-webkit-scrollbar-track {
background: transparent;
}
.no-results {
padding: 8px 12px;
color: var(--color-text-3);
cursor: default;
font-size: 14px;
&:hover {
background: none;
}
}
}
.ant-dropdown-menu-item-group {

View File

@ -1,5 +1,4 @@
import { useProviders } from '@renderer/hooks/useProvider'
import { getModelUniqId } from '@renderer/services/ModelService'
import { Model } from '@renderer/types'
import { Flex, Tag } from 'antd'
import { FC } from 'react'
@ -14,19 +13,14 @@ const MentionModelsInput: FC<{
const { t } = useTranslation()
const getProviderName = (model: Model) => {
const provider = providers.find((p) => p.id === model?.provider)
const provider = providers.find((p) => p.models?.some((m) => m.id === model.id))
return provider ? (provider.isSystem ? t(`provider.${provider.id}`) : provider.name) : ''
}
return (
<Container gap="4px 0" wrap>
{selectedModels.map((model) => (
<Tag
bordered={false}
color="processing"
key={getModelUniqId(model)}
closable
onClose={() => onRemoveModel(model)}>
<Tag bordered={false} color="processing" key={model.id} closable onClose={() => onRemoveModel(model)}>
@{model.name} ({getProviderName(model)})
</Tag>
))}

View File

@ -1,4 +1,4 @@
import { DownloadOutlined, ExpandOutlined, LinkOutlined } from '@ant-design/icons'
import { DownloadOutlined, ExpandOutlined } from '@ant-design/icons'
import MinApp from '@renderer/components/MinApp'
import { AppLogo } from '@renderer/config/env'
import { extractTitle } from '@renderer/utils/formats'
@ -13,55 +13,29 @@ interface Props {
const Artifacts: FC<Props> = ({ html }) => {
const { t } = useTranslation()
const title = extractTitle(html) || 'Artifacts ' + t('chat.artifacts.button.preview')
const title = extractTitle(html) || 'Artifacts' + ' ' + t('chat.artifacts.button.preview')
/**
*
*/
const handleOpenInApp = async () => {
const onPreview = async () => {
const path = await window.api.file.create('artifacts-preview.html')
await window.api.file.write(path, html)
const filePath = `file://${path}`
MinApp.start({
name: title,
logo: AppLogo,
url: filePath
url: `file://${path}`
})
}
/**
*
*/
const handleOpenExternal = async () => {
const path = await window.api.file.create('artifacts-preview.html')
await window.api.file.write(path, html)
const filePath = `file://${path}`
if (window.api.shell && window.api.shell.openExternal) {
window.api.shell.openExternal(filePath)
} else {
console.error(t('artifacts.preview.openExternal.error.content'))
}
}
/**
*
*/
const onDownload = () => {
window.api.file.save(`${title}.html`, html)
}
return (
<Container>
<Button icon={<ExpandOutlined />} onClick={handleOpenInApp}>
<Button type="primary" icon={<ExpandOutlined />} onClick={onPreview} size="small">
{t('chat.artifacts.button.preview')}
</Button>
<Button icon={<LinkOutlined />} onClick={handleOpenExternal}>
{t('chat.artifacts.button.openExternal')}
</Button>
<Button icon={<DownloadOutlined />} onClick={onDownload}>
<Button icon={<DownloadOutlined />} onClick={onDownload} size="small">
{t('chat.artifacts.button.download')}
</Button>
</Container>

View File

@ -10,7 +10,6 @@ import styled from 'styled-components'
import Artifacts from './Artifacts'
import Mermaid from './Mermaid'
import { isValidPlantUML, PlantUML } from './PlantUML'
import SvgPreview from './SvgPreview'
interface CodeBlockProps {
@ -63,10 +62,6 @@ const CodeBlock: React.FC<CodeBlockProps> = ({ children, className }) => {
return <Mermaid chart={children} />
}
if (language === 'plantuml' && isValidPlantUML(children)) {
return <PlantUML diagram={children} />
}
if (language === 'svg') {
return (
<CodeBlockWrapper className="code-block">
@ -154,7 +149,6 @@ const CopyButton: React.FC<{ text: string; style?: React.CSSProperties }> = ({ t
const { t } = useTranslation()
const onCopy = () => {
if (!text) return
navigator.clipboard.writeText(text)
window.message.success({ content: t('message.copied'), key: 'copy-code' })
setCopied(true)

View File

@ -1,286 +0,0 @@
import { CopyOutlined, LoadingOutlined } from '@ant-design/icons'
import { TopView } from '@renderer/components/TopView'
import { useTheme } from '@renderer/context/ThemeProvider'
import { Button, Modal, Space, Spin, Tabs } from 'antd'
import pako from 'pako'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
interface PlantUMLPopupProps {
resolve: (data: any) => void
diagram: string
}
export function isValidPlantUML(diagram: string | null): boolean {
if (!diagram || !diagram.trim().startsWith('@start')) {
return false
}
const diagramType = diagram.match(/@start(\w+)/)?.[1]
return diagramType !== undefined && diagram.search(`@end${diagramType}`) !== -1
}
const PlantUMLServer = 'https://www.plantuml.com/plantuml'
function encode64(data: Uint8Array) {
let r = ''
for (let i = 0; i < data.length; i += 3) {
if (i + 2 === data.length) {
r += append3bytes(data[i], data[i + 1], 0)
} else if (i + 1 === data.length) {
r += append3bytes(data[i], 0, 0)
} else {
r += append3bytes(data[i], data[i + 1], data[i + 2])
}
}
return r
}
function encode6bit(b: number) {
if (b < 10) {
return String.fromCharCode(48 + b)
}
b -= 10
if (b < 26) {
return String.fromCharCode(65 + b)
}
b -= 26
if (b < 26) {
return String.fromCharCode(97 + b)
}
b -= 26
if (b === 0) {
return '-'
}
if (b === 1) {
return '_'
}
return '?'
}
function append3bytes(b1: number, b2: number, b3: number) {
const c1 = b1 >> 2
const c2 = ((b1 & 0x3) << 4) | (b2 >> 4)
const c3 = ((b2 & 0xf) << 2) | (b3 >> 6)
const c4 = b3 & 0x3f
let r = ''
r += encode6bit(c1 & 0x3f)
r += encode6bit(c2 & 0x3f)
r += encode6bit(c3 & 0x3f)
r += encode6bit(c4 & 0x3f)
return r
}
/**
* https://plantuml.com/zh/code-javascript-synchronous
* To use PlantUML image generation, a text diagram description have to be :
1. Encoded in UTF-8
2. Compressed using Deflate algorithm
3. Reencoded in ASCII using a transformation _close_ to base64
*/
function encodeDiagram(diagram: string): string {
const utf8text = new TextEncoder().encode(diagram)
const compressed = pako.deflateRaw(utf8text)
return encode64(compressed)
}
type PlantUMLServerImageProps = {
format: 'png' | 'svg'
diagram: string
onClick?: React.MouseEventHandler<HTMLDivElement>
}
function getPlantUMLImageUrl(format: 'png' | 'svg', diagram: string, isDark?: boolean) {
const encodedDiagram = encodeDiagram(diagram)
if (isDark) {
return `${PlantUMLServer}/d${format}/${encodedDiagram}`
}
return `${PlantUMLServer}/${format}/${encodedDiagram}`
}
const PlantUMLServerImage: React.FC<PlantUMLServerImageProps> = ({ format, diagram, onClick }) => {
const [loading, setLoading] = useState(true)
const { theme } = useTheme()
const isDark = theme === 'dark'
const url = getPlantUMLImageUrl(format, diagram, isDark)
return (
<StyledPlantUML onClick={onClick}>
<Spin
spinning={loading}
indicator={
<LoadingOutlined
spin
style={{
fontSize: 32
}}
/>
}>
<img
src={url}
onLoad={() => {
setLoading(false)
}}
onError={(e) => {
setLoading(false)
const target = e.target as HTMLImageElement
target.style.opacity = '0.5'
target.style.filter = 'blur(2px)'
}}
/>
</Spin>
</StyledPlantUML>
)
}
const PlantUMLPopupCantaier: React.FC<PlantUMLPopupProps> = ({ resolve, diagram }) => {
const [open, setOpen] = useState(true)
const [downloading, setDownloading] = useState({
png: false,
svg: false
})
const [activeTab, setActiveTab] = useState('preview')
const { t } = useTranslation()
console.log(`plantuml diagram: ${diagram}`)
const encodedDiagram = encodeDiagram(diagram)
const onOk = () => {
setOpen(false)
}
const onCancel = () => {
setOpen(false)
}
const onClose = () => {
resolve({})
}
const handleDownload = (format: 'svg' | 'png') => {
const timestamp = Date.now()
const url = `${PlantUMLServer}/${format}/${encodedDiagram}`
setDownloading((prev) => ({ ...prev, [format]: true }))
const filename = `plantuml-diagram-${timestamp}.${format}`
downloadUrl(url, filename)
.catch(() => {
window.message.error(t('plantuml.download.failed'))
})
.finally(() => {
setDownloading((prev) => ({ ...prev, [format]: false }))
})
}
function handleCopy() {
navigator.clipboard.writeText(diagram)
window.message.success(t('message.copy.success'))
}
return (
<Modal
title={t('plantuml.title')}
open={open}
onOk={onOk}
onCancel={onCancel}
afterClose={onClose}
width={1000}
centered
footer={[
<Space key="download-buttons">
{activeTab === 'source' && (
<Button onClick={handleCopy} icon={<CopyOutlined />}>
{t('common.copy')}
</Button>
)}
{activeTab === 'preview' && (
<>
<Button onClick={() => handleDownload('svg')} loading={downloading.svg}>
{t('plantuml.download.svg')}
</Button>
<Button onClick={() => handleDownload('png')} loading={downloading.png}>
{t('plantuml.download.png')}
</Button>
</>
)}
</Space>
]}>
<Tabs
activeKey={activeTab}
onChange={(key) => setActiveTab(key)}
items={[
{
key: 'preview',
label: t('plantuml.tabs.preview'),
children: <PlantUMLServerImage format="svg" diagram={diagram} />
},
{
key: 'source',
label: t('plantuml.tabs.source'),
children: (
<pre
style={{
maxHeight: 'calc(80vh - 200px)',
overflowY: 'auto',
padding: '16px'
}}>
{diagram}
</pre>
)
}
]}
/>
</Modal>
)
}
class PlantUMLPopupTopView {
static topviewId = 0
static hide() {
TopView.hide('PlantUMLPopup')
}
static show(diagram: string) {
return new Promise<any>((resolve) => {
TopView.show(
<PlantUMLPopupCantaier
resolve={(v) => {
resolve(v)
this.hide()
}}
diagram={diagram}
/>,
'PlantUMLPopup'
)
})
}
}
interface PlantUMLProps {
diagram: string
}
export const PlantUML: React.FC<PlantUMLProps> = ({ diagram }) => {
// const { t } = useTranslation()
const onPreview = () => {
PlantUMLPopupTopView.show(diagram)
}
return <PlantUMLServerImage onClick={onPreview} format="svg" diagram={diagram} />
}
const StyledPlantUML = styled.div`
max-height: calc(80vh - 100px);
text-align: center;
overflow-y: auto;
img {
max-width: 100%;
height: auto;
min-height: 100px;
background: var(--color-code-background);
cursor: pointer;
}
`
async function downloadUrl(url: string, filename: string) {
const response = await fetch(url)
if (!response.ok) {
window.message.warning({ content: response.statusText, duration: 1.5 })
return
}
const blob = await response.blob()
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = filename
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(link.href)
}

View File

@ -6,9 +6,8 @@ import { useMessageStyle, useSettings } from '@renderer/hooks/useSettings'
import { useTopic } from '@renderer/hooks/useTopic'
import { fetchChatCompletion } from '@renderer/services/ApiService'
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
import { getContextCount, getMessageModelId } from '@renderer/services/MessagesService'
import { getModelUniqId } from '@renderer/services/ModelService'
import { estimateHistoryTokens, estimateMessageUsage } from '@renderer/services/TokenService'
import { getMessageModelId } from '@renderer/services/MessagesService'
import { estimateMessageUsage } from '@renderer/services/TokenService'
import { Message, Topic } from '@renderer/types'
import { classNames, runAsyncFunction } from '@renderer/utils'
import { Divider } from 'antd'
@ -57,7 +56,7 @@ const MessageItem: FC<Props> = ({
const [message, setMessage] = useState(_message)
const { t } = useTranslation()
const { assistant, setModel } = useAssistant(message.assistantId)
const model = useModel(getMessageModelId(message), message.model?.provider) || message.model
const model = useModel(getMessageModelId(message)) || message.model
const { isBubbleStyle } = useMessageStyle()
const { showMessageDivider, messageFont, fontSize } = useSettings()
const messageContainerRef = useRef<HTMLDivElement>(null)
@ -76,22 +75,13 @@ const MessageItem: FC<Props> = ({
const messageBackground = getMessageBackground(isBubbleStyle, isAssistantMessage)
const onEditMessage = useCallback(
async (msg: Message) => {
const usage = await estimateMessageUsage(msg)
msg.usage = usage
(msg: Message) => {
setMessage(msg)
const messages = onGetMessages?.()?.map((m) => (m.id === message.id ? msg : m))
messages && onSetMessages?.(messages)
topic && db.topics.update(topic.id, { messages })
if (messages) {
const tokensCount = await estimateHistoryTokens(assistant, messages)
const contextCount = getContextCount(assistant, messages)
EventEmitter.emit(EVENT_NAMES.ESTIMATED_TOKEN_COUNT, { tokensCount, contextCount })
}
},
[message.id, onGetMessages, onSetMessages, topic, assistant]
[message.id, onGetMessages, onSetMessages, topic]
)
const messageHighlightHandler = (highlight: boolean = true) => {
@ -186,7 +176,7 @@ const MessageItem: FC<Props> = ({
})}
ref={messageContainerRef}
style={{ ...style, alignItems: isBubbleStyle ? (isAssistantMessage ? 'start' : 'end') : undefined }}>
<MessageHeader message={message} assistant={assistant} model={model} key={getModelUniqId(model)} />
<MessageHeader message={message} assistant={assistant} model={model} key={getMessageModelId(message)} />
<MessageContentContainer
className="message-content-container"
style={{ fontFamily, fontSize, background: messageBackground }}>
@ -250,7 +240,6 @@ const MessageContentContainer = styled.div`
justify-content: space-between;
margin-left: 46px;
margin-top: 5px;
overflow-y: auto;
`
const MessageFooter = styled.div`

View File

@ -1,5 +1,4 @@
import { InfoCircleOutlined, SyncOutlined, TranslationOutlined } from '@ant-design/icons'
import { getModelUniqId } from '@renderer/services/ModelService'
import { Message, Model } from '@renderer/types'
import { getBriefInfo } from '@renderer/utils'
import { withMessageThought } from '@renderer/utils/formats'
@ -78,7 +77,7 @@ const MessageContent: React.FC<Props> = ({ message: _message, model }) => {
return (
<Fragment>
<Flex gap="8px" wrap style={{ marginBottom: 10 }}>
{message.mentions?.map((model) => <MentionTag key={getModelUniqId(model)}>{'@' + model.name}</MentionTag>)}
{message.mentions?.map((model) => <MentionTag key={model.id}>{'@' + model.name}</MentionTag>)}
</Flex>
<MessageThought message={message} />
<Markdown message={{ ...message, content: processedContent }} />

View File

@ -1,5 +1,4 @@
import { Message } from '@renderer/types'
import { formatErrorMessage } from '@renderer/utils/error'
import { Alert as AntdAlert } from 'antd'
import { FC } from 'react'
import { useTranslation } from 'react-i18next'
@ -9,16 +8,8 @@ import Markdown from '../Markdown/Markdown'
const MessageError: FC<{ message: Message }> = ({ message }) => {
return (
<>
<Markdown message={message} />
{message.error && (
<Markdown
message={{
...message,
content: formatErrorMessage(message.error)
}}
/>
)}
<MessageErrorInfo message={message} />
<Markdown message={message} />
</>
)
}
@ -36,7 +27,7 @@ const MessageErrorInfo: FC<{ message: Message }> = ({ message }) => {
}
const Alert = styled(AntdAlert)`
margin: 15px 0 8px;
margin-bottom: 15px;
padding: 10px;
font-size: 12px;
`

View File

@ -1,14 +1,17 @@
import { ColumnHeightOutlined, ColumnWidthOutlined, DeleteOutlined, FolderOutlined } from '@ant-design/icons'
import ModelAvatar from '@renderer/components/Avatar/ModelAvatar'
import { HStack } from '@renderer/components/Layout'
import Scrollbar from '@renderer/components/Scrollbar'
import { useSettings } from '@renderer/hooks/useSettings'
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
import { MultiModelMessageStyle } from '@renderer/store/settings'
import { Message, Topic } from '@renderer/types'
import { Popover } from 'antd'
import { Dispatch, FC, memo, SetStateAction, useCallback, useEffect, useState } from 'react'
import { Message, Model, Topic } from '@renderer/types'
import { Button, Segmented as AntdSegmented } from 'antd'
import { Dispatch, FC, SetStateAction, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled, { css } from 'styled-components'
import MessageItem from './Message'
import MessageGroupMenuBar from './MessageGroupMenuBar'
interface Props {
messages: (Message & { index: number })[]
@ -29,7 +32,7 @@ const MessageGroup: FC<Props> = ({
onGetMessages,
onDeleteGroupMessages
}) => {
const { multiModelMessageStyle: multiModelMessageStyleSetting, gridColumns, gridPopoverTrigger } = useSettings()
const { multiModelMessageStyle: multiModelMessageStyleSetting } = useSettings()
const { t } = useTranslation()
const [multiModelMessageStyle, setMultiModelMessageStyle] =
@ -39,9 +42,8 @@ const MessageGroup: FC<Props> = ({
const [selectedIndex, setSelectedIndex] = useState(messageLength - 1)
const isGrouped = messageLength > 1
const isHorizontal = multiModelMessageStyle === 'horizontal'
const onDelete = useCallback(async () => {
const onDelete = async () => {
window.modal.confirm({
title: t('message.group.delete.title'),
content: t('message.group.delete.content'),
@ -55,144 +57,116 @@ const MessageGroup: FC<Props> = ({
askId && onDeleteGroupMessages?.(askId)
}
})
}, [messages, onDeleteGroupMessages, t])
}
useEffect(() => {
setSelectedIndex(messageLength - 1)
}, [messageLength])
const isHorizontal = multiModelMessageStyle === 'horizontal'
return (
<GroupContainer $isGrouped={isGrouped} $layout={multiModelMessageStyle}>
<GridContainer $count={messageLength} $layout={multiModelMessageStyle} $gridColumns={gridColumns}>
{messages.map((message, index) => {
const isGridGroupMessage = multiModelMessageStyle === 'grid' && message.role === 'assistant' && isGrouped
if (isGridGroupMessage) {
return (
<Popover
content={
<MessageWrapper
$layout={multiModelMessageStyle}
$selected={index === selectedIndex}
$isGrouped={isGrouped}
$isInPopover={true}
key={message.id}>
<MessageItem
isGrouped={isGrouped}
message={message}
topic={topic}
index={message.index}
hidePresetMessages={hidePresetMessages}
style={{
paddingTop: isGrouped && ['horizontal', 'grid'].includes(multiModelMessageStyle) ? 0 : 15
}}
onSetMessages={onSetMessages}
onDeleteMessage={onDeleteMessage}
onGetMessages={onGetMessages}
/>
</MessageWrapper>
}
trigger={gridPopoverTrigger}
styles={{ root: { maxWidth: '60vw', minWidth: '550px', overflowY: 'auto', zIndex: 1000 } }}
getPopupContainer={(triggerNode) => triggerNode.parentNode as HTMLElement}
key={message.id}>
<MessageWrapper
$layout={multiModelMessageStyle}
$selected={index === selectedIndex}
$isGrouped={isGrouped}
key={message.id}>
<MessageItem
isGrouped={isGrouped}
message={message}
topic={topic}
index={message.index}
hidePresetMessages={hidePresetMessages}
style={
gridPopoverTrigger === 'hover' && isGrouped
? {
paddingTop: isGrouped && ['horizontal', 'grid'].includes(multiModelMessageStyle) ? 0 : 15,
overflow: isGrouped ? 'hidden' : 'auto',
maxHeight: isGrouped ? '280px' : 'unset'
}
: undefined
}
onSetMessages={onSetMessages}
onDeleteMessage={onDeleteMessage}
onGetMessages={onGetMessages}
/>
</MessageWrapper>
</Popover>
)
}
return (
<MessageWrapper
$layout={multiModelMessageStyle}
$selected={index === selectedIndex}
$isGrouped={isGrouped}
key={message.id}
className={message.role === 'assistant' && isHorizontal && isGrouped ? 'group-message-wrapper' : ''}>
<MessageItem
isGrouped={isGrouped}
message={message}
topic={topic}
index={message.index}
hidePresetMessages={hidePresetMessages}
style={{ paddingTop: isGrouped && ['horizontal', 'grid'].includes(multiModelMessageStyle) ? 0 : 15 }}
onSetMessages={onSetMessages}
onDeleteMessage={onDeleteMessage}
onGetMessages={onGetMessages}
/>
</MessageWrapper>
)
})}
<GridContainer $count={messageLength} $layout={multiModelMessageStyle}>
{messages.map((message, index) => (
<MessageWrapper
$layout={multiModelMessageStyle}
$selected={index === selectedIndex}
$isGrouped={isGrouped}
key={message.id}
className={message.role === 'assistant' && isHorizontal && isGrouped ? 'group-message-wrapper' : ''}>
<MessageItem
isGrouped={isGrouped}
message={message}
topic={topic}
index={message.index}
hidePresetMessages={hidePresetMessages}
style={{ paddingTop: isGrouped && multiModelMessageStyle === 'horizontal' ? 0 : 15 }}
onSetMessages={onSetMessages}
onDeleteMessage={onDeleteMessage}
onGetMessages={onGetMessages}
/>
</MessageWrapper>
))}
</GridContainer>
{isGrouped && (
<MessageGroupMenuBar
multiModelMessageStyle={multiModelMessageStyle}
setMultiModelMessageStyle={setMultiModelMessageStyle}
messages={messages}
selectedIndex={selectedIndex}
setSelectedIndex={setSelectedIndex}
onDelete={onDelete}
/>
<GroupMenuBar className="group-menu-bar" $layout={multiModelMessageStyle}>
<HStack style={{ alignItems: 'center', flex: 1, overflow: 'hidden' }}>
<LayoutContainer>
{['fold', 'vertical', 'horizontal'].map((layout) => (
<LayoutOption
key={layout}
active={multiModelMessageStyle === layout}
onClick={() => setMultiModelMessageStyle(layout as MultiModelMessageStyle)}>
{layout === 'fold' ? (
<FolderOutlined />
) : layout === 'horizontal' ? (
<ColumnWidthOutlined />
) : (
<ColumnHeightOutlined />
)}
</LayoutOption>
))}
</LayoutContainer>
{multiModelMessageStyle === 'fold' && (
<ModelsContainer>
<Segmented
value={selectedIndex.toString()}
onChange={(value) => {
setSelectedIndex(Number(value))
EventEmitter.emit(EVENT_NAMES.LOCATE_MESSAGE + ':' + messages[Number(value)].id, false)
}}
options={messages.map((message, index) => ({
label: (
<SegmentedLabel>
<ModelAvatar model={message.model as Model} size={20} />
<ModelName>{message.model?.name}</ModelName>
</SegmentedLabel>
),
value: index.toString()
}))}
size="small"
/>
</ModelsContainer>
)}
</HStack>
<Button
type="text"
size="small"
icon={<DeleteOutlined style={{ color: 'var(--color-error)' }} />}
onClick={onDelete}
/>
</GroupMenuBar>
)}
</GroupContainer>
)
}
const GroupContainer = styled.div<{ $isGrouped: boolean; $layout: MultiModelMessageStyle }>`
padding-top: ${({ $isGrouped, $layout }) => ($isGrouped && 'horizontal' === $layout ? '15px' : '0')};
padding-top: ${({ $isGrouped, $layout }) => ($isGrouped && $layout === 'horizontal' ? '15px' : '0')};
`
const GridContainer = styled.div<{ $count: number; $layout: MultiModelMessageStyle; $gridColumns: number }>`
const GridContainer = styled.div<{ $count: number; $layout: MultiModelMessageStyle }>`
width: 100%;
display: grid;
grid-template-columns: repeat(
${({ $layout, $count }) => (['fold', 'vertical'].includes($layout) ? 1 : $count)},
${(props) => (['fold', 'vertical'].includes(props.$layout) ? 1 : props.$count)},
minmax(550px, 1fr)
);
gap: ${({ $layout }) => ($layout === 'horizontal' ? '16px' : '0')};
@media (max-width: 800px) {
grid-template-columns: repeat(
${({ $layout, $count }) => (['fold', 'vertical'].includes($layout) ? 1 : $count)},
${(props) => (['fold', 'vertical'].includes(props.$layout) ? 1 : props.$count)},
minmax(400px, 1fr)
);
}
overflow-y: auto;
${({ $gridColumns, $layout, $count }) =>
$layout === 'grid' &&
css`
grid-template-columns: repeat(${$count > 1 ? $gridColumns || 2 : 1}, minmax(0, 1fr));
grid-template-rows: auto;
gap: 16px;
margin-top: 20px;
`}
`
interface MessageWrapperProps {
$layout: 'fold' | 'horizontal' | 'vertical' | 'grid'
$layout: 'fold' | 'horizontal' | 'vertical'
$selected: boolean
$isGrouped: boolean
$isInPopover?: boolean
}
const MessageWrapper = styled(Scrollbar)<MessageWrapperProps>`
@ -206,7 +180,6 @@ const MessageWrapper = styled(Scrollbar)<MessageWrapperProps>`
}
return 'block'
}};
${({ $layout, $isGrouped }) => {
if ($layout === 'horizontal' && $isGrouped) {
return css`
@ -214,26 +187,82 @@ const MessageWrapper = styled(Scrollbar)<MessageWrapperProps>`
padding: 10px;
border-radius: 6px;
max-height: 600px;
overflow-y: auto;
margin-bottom: 10px;
`
}
return ''
}}
${({ $layout, $isInPopover, $isGrouped }) =>
$layout === 'grid' && $isGrouped
? css`
max-height: ${$isInPopover ? '50vh' : '300px'};
overflow-y: auto;
border: 0.5px solid ${$isInPopover ? 'transparent' : 'var(--color-border)'};
padding: 10px;
border-radius: 6px;
background-color: var(--color-background);
`
: css`
overflow-y: auto;
border-radius: 6px;
`}
`
export default memo(MessageGroup)
const GroupMenuBar = styled.div<{ $layout: MultiModelMessageStyle }>`
display: flex;
flex-direction: row;
align-items: center;
gap: 10px;
padding: 6px 10px;
border-radius: 6px;
margin-top: 10px;
justify-content: space-between;
overflow: hidden;
border: 0.5px solid var(--color-border);
height: 40px;
margin-left: ${({ $layout }) => ($layout === 'horizontal' ? '0' : '40px')};
transition: all 0.3s ease;
`
const LayoutContainer = styled.div`
display: flex;
gap: 10px;
flex-direction: row;
`
const LayoutOption = styled.div<{ active: boolean }>`
cursor: pointer;
padding: 2px 10px;
border-radius: 4px;
background-color: ${({ active }) => (active ? 'var(--color-background-soft)' : 'transparent')};
&:hover {
background-color: ${({ active }) => (active ? 'var(--color-background-soft)' : 'var(--color-hover)')};
}
`
const ModelsContainer = styled(Scrollbar)`
display: flex;
flex-direction: column;
justify-content: space-between;
&::-webkit-scrollbar {
display: none;
}
`
const Segmented = styled(AntdSegmented)`
.ant-segmented-item {
background-color: transparent !important;
transition: none !important;
&:hover {
background: transparent !important;
}
}
.ant-segmented-thumb,
.ant-segmented-item-selected {
background-color: transparent !important;
border: 0.5px solid var(--color-border);
transition: none !important;
}
`
const SegmentedLabel = styled.div`
display: flex;
align-items: center;
gap: 5px;
padding: 3px 0;
`
const ModelName = styled.span`
font-weight: 500;
font-size: 12px;
`
export default MessageGroup

View File

@ -1,161 +0,0 @@
import {
ColumnHeightOutlined,
ColumnWidthOutlined,
DeleteOutlined,
FolderOutlined,
NumberOutlined
} from '@ant-design/icons'
import ModelAvatar from '@renderer/components/Avatar/ModelAvatar'
import { HStack } from '@renderer/components/Layout'
import Scrollbar from '@renderer/components/Scrollbar'
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
import { MultiModelMessageStyle } from '@renderer/store/settings'
import { Message, Model } from '@renderer/types'
import { Button, Segmented as AntdSegmented } from 'antd'
import { FC, memo } from 'react'
import styled from 'styled-components'
import MessageGroupSettings from './MessageGroupSettings'
interface Props {
multiModelMessageStyle: MultiModelMessageStyle
setMultiModelMessageStyle: (style: MultiModelMessageStyle) => void
messages: Message[]
selectedIndex: number
setSelectedIndex: (index: number) => void
onDelete: () => void
}
const MessageGroupMenuBar: FC<Props> = ({
multiModelMessageStyle,
setMultiModelMessageStyle,
messages,
selectedIndex,
setSelectedIndex,
onDelete
}) => {
return (
<GroupMenuBar $layout={multiModelMessageStyle}>
<HStack style={{ alignItems: 'center', flex: 1, overflow: 'hidden' }}>
<LayoutContainer>
{['fold', 'vertical', 'horizontal', 'grid'].map((layout) => (
<LayoutOption
key={layout}
$active={multiModelMessageStyle === layout}
onClick={() => setMultiModelMessageStyle(layout as MultiModelMessageStyle)}>
{layout === 'fold' ? (
<FolderOutlined />
) : layout === 'horizontal' ? (
<ColumnWidthOutlined />
) : layout === 'vertical' ? (
<ColumnHeightOutlined />
) : (
<NumberOutlined />
)}
</LayoutOption>
))}
</LayoutContainer>
{multiModelMessageStyle === 'fold' && (
<ModelsContainer>
<Segmented
value={selectedIndex.toString()}
onChange={(value) => {
setSelectedIndex(Number(value))
EventEmitter.emit(EVENT_NAMES.LOCATE_MESSAGE + ':' + messages[Number(value)].id, false)
}}
options={messages.map((message, index) => ({
label: (
<SegmentedLabel>
<ModelAvatar model={message.model as Model} size={20} />
<ModelName>{message.model?.name}</ModelName>
</SegmentedLabel>
),
value: index.toString()
}))}
size="small"
/>
</ModelsContainer>
)}
{multiModelMessageStyle === 'grid' && <MessageGroupSettings />}
</HStack>
<Button
type="text"
size="small"
icon={<DeleteOutlined style={{ color: 'var(--color-error)' }} />}
onClick={onDelete}
/>
</GroupMenuBar>
)
}
const GroupMenuBar = styled.div<{ $layout: MultiModelMessageStyle }>`
display: flex;
flex-direction: row;
align-items: center;
gap: 10px;
padding: 6px 10px;
border-radius: 6px;
margin-top: 10px;
justify-content: space-between;
overflow: hidden;
border: 0.5px solid var(--color-border);
height: 40px;
transition: all 0.3s ease;
background-color: var(--color-background);
`
const LayoutContainer = styled.div`
display: flex;
gap: 10px;
flex-direction: row;
`
const LayoutOption = styled.div<{ $active: boolean }>`
cursor: pointer;
padding: 2px 10px;
border-radius: 4px;
background-color: ${({ $active }) => ($active ? 'var(--color-background-soft)' : 'transparent')};
&:hover {
background-color: ${({ $active }) => ($active ? 'var(--color-background-soft)' : 'var(--color-hover)')};
}
`
const ModelsContainer = styled(Scrollbar)`
display: flex;
flex-direction: column;
justify-content: space-between;
&::-webkit-scrollbar {
display: none;
}
`
const Segmented = styled(AntdSegmented)`
.ant-segmented-item {
background-color: transparent !important;
transition: none !important;
&:hover {
background: transparent !important;
}
}
.ant-segmented-thumb,
.ant-segmented-item-selected {
background-color: transparent !important;
border: 0.5px solid var(--color-border);
transition: none !important;
}
`
const SegmentedLabel = styled.div`
display: flex;
align-items: center;
gap: 5px;
padding: 3px 0;
`
const ModelName = styled.span`
font-weight: 500;
font-size: 12px;
`
export default memo(MessageGroupMenuBar)

View File

@ -1,59 +0,0 @@
import { SettingOutlined } from '@ant-design/icons'
import { useSettings } from '@renderer/hooks/useSettings'
import { SettingDivider } from '@renderer/pages/settings'
import { SettingRow } from '@renderer/pages/settings'
import { useAppDispatch } from '@renderer/store'
import { setGridColumns, setGridPopoverTrigger } from '@renderer/store/settings'
import { Col, Row, Select, Slider } from 'antd'
import { Popover } from 'antd'
import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
const MessageGroupSettings: FC = () => {
const dispatch = useAppDispatch()
const { t } = useTranslation()
const { gridColumns, gridPopoverTrigger } = useSettings()
const [gridColumnsValue, setGridColumnsValue] = useState(gridColumns)
return (
<Popover
trigger={undefined}
showArrow
content={
<div style={{ padding: 10 }}>
<SettingRow>
<div style={{ marginRight: 10 }}>{t('settings.messages.grid_popover_trigger')}</div>
<Select
value={gridPopoverTrigger || 'hover'}
onChange={(value) => dispatch(setGridPopoverTrigger(value as 'hover' | 'click'))}
size="small">
<Select.Option value="hover">{t('settings.messages.grid_popover_trigger.hover')}</Select.Option>
<Select.Option value="click">{t('settings.messages.grid_popover_trigger.click')}</Select.Option>
</Select>
</SettingRow>
<SettingDivider />
<SettingRow>
<div>{t('settings.messages.grid_columns')}</div>
</SettingRow>
<Row align="middle" gutter={10}>
<Col span={24}>
<Slider
value={gridColumnsValue}
style={{ width: '100%' }}
onChange={(value) => setGridColumnsValue(value)}
onChangeComplete={(value) => dispatch(setGridColumns(value))}
min={2}
max={6}
step={1}
/>
</Col>
</Row>
</div>
}>
<SettingOutlined style={{ marginLeft: 15, cursor: 'pointer' }} />
</Popover>
)
}
export default MessageGroupSettings

View File

@ -60,16 +60,12 @@ const MessageMenubar: FC<Props> = (props) => {
const isUserMessage = message.role === 'user'
const onCopy = useCallback(
(e: React.MouseEvent) => {
e.stopPropagation()
navigator.clipboard.writeText(removeTrailingDoubleSpaces(message.content))
window.message.success({ content: t('message.copied'), key: 'copy-message' })
setCopied(true)
setTimeout(() => setCopied(false), 2000)
},
[message.content, t]
)
const onCopy = useCallback(() => {
navigator.clipboard.writeText(removeTrailingDoubleSpaces(message.content))
window.message.success({ content: t('message.copied'), key: 'copy-message' })
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}, [message.content, t])
const onNewBranch = useCallback(async () => {
await modelGenerating()
@ -199,16 +195,14 @@ const MessageMenubar: FC<Props> = (props) => {
[message, onEdit, onNewBranch, t]
)
const onRegenerate = async (e: React.MouseEvent | undefined) => {
e?.stopPropagation?.()
const onRegenerate = async () => {
await modelGenerating()
const selectedModel = isGrouped ? model : assistantModel
const _message = resetAssistantMessage(message, selectedModel)
onEditMessage?.(_message)
}
const onMentionModel = async (e: React.MouseEvent) => {
e.stopPropagation()
const onMentionModel = async () => {
await modelGenerating()
const selectedModel = await SelectModelPopup.show({ model })
if (!selectedModel) return
@ -222,13 +216,9 @@ const MessageMenubar: FC<Props> = (props) => {
onEditMessage?.(_message)
}
const onUseful = useCallback(
(e: React.MouseEvent) => {
e.stopPropagation()
onEditMessage?.({ ...message, useful: !message.useful })
},
[message, onEditMessage]
)
const onUseful = useCallback(() => {
onEditMessage?.({ ...message, useful: !message.useful })
}, [message, onEditMessage])
return (
<MenusBar className={`menubar ${isLastMessage && 'show'}`}>
@ -280,14 +270,13 @@ const MessageMenubar: FC<Props> = (props) => {
key: 'translate-close',
onClick: () => onEditMessage?.({ ...message, translatedContent: undefined })
}
],
onClick: (e) => e.domEvent.stopPropagation()
]
}}
trigger={['click']}
placement="topRight"
arrow>
<Tooltip title={t('chat.translate')} mouseEnterDelay={1.2}>
<ActionButton className="message-action-button" onClick={(e) => e.stopPropagation()}>
<ActionButton className="message-action-button">
<TranslationOutlined />
</ActionButton>
</Tooltip>
@ -309,25 +298,14 @@ const MessageMenubar: FC<Props> = (props) => {
<Tooltip title={t('common.delete')} mouseEnterDelay={1}>
<ActionButton
className="message-action-button"
onClick={
isGrouped
? (e) => {
e.stopPropagation()
onDeleteMessage?.(message)
}
: (e) => e.stopPropagation()
}>
onClick={isGrouped ? () => onDeleteMessage?.(message) : undefined}>
<DeleteOutlined />
</ActionButton>
</Tooltip>
</Popconfirm>
{!isUserMessage && (
<Dropdown
menu={{ items: dropdownItems, onClick: (e) => e.domEvent.stopPropagation() }}
trigger={['click']}
placement="topRight"
arrow>
<ActionButton className="message-action-button" onClick={(e) => e.stopPropagation()}>
<Dropdown menu={{ items: dropdownItems }} trigger={['click']} placement="topRight" arrow>
<ActionButton className="message-action-button">
<MenuOutlined />
</ActionButton>
</Dropdown>

View File

@ -1,13 +1,11 @@
import { CheckOutlined } from '@ant-design/icons'
import { useSettings } from '@renderer/hooks/useSettings'
import { Message } from '@renderer/types'
import { Collapse, message as antdMessage, Tooltip } from 'antd'
import { FC, useEffect, useMemo, useState } from 'react'
import { Collapse } from 'antd'
import { FC, useEffect, useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import BarLoader from 'react-spinners/BarLoader'
import styled from 'styled-components'
import Markdown from '../Markdown/Markdown'
import { useSettings } from '@renderer/hooks/useSettings'
interface Props {
message: Message
@ -15,10 +13,9 @@ interface Props {
const MessageThought: FC<Props> = ({ message }) => {
const [activeKey, setActiveKey] = useState<'thought' | ''>('thought')
const [copied, setCopied] = useState(false)
const isThinking = !message.content
const { t } = useTranslation()
const { messageFont, fontSize, thoughtAutoCollapse } = useSettings()
const { messageFont, fontSize } = useSettings()
const fontFamily = useMemo(() => {
return messageFont === 'serif'
? 'serif'
@ -26,30 +23,19 @@ const MessageThought: FC<Props> = ({ message }) => {
}, [messageFont])
useEffect(() => {
if (!isThinking && thoughtAutoCollapse) setActiveKey('')
}, [isThinking, thoughtAutoCollapse])
if (!isThinking) setActiveKey('')
}, [isThinking])
if (!message.reasoning_content) {
return null
}
const copyThought = () => {
if (message.reasoning_content) {
navigator.clipboard.writeText(message.reasoning_content)
antdMessage.success({ content: t('message.copied'), key: 'copy-message' })
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
}
const thinkingTime = message.metrics?.time_thinking_millsec || 0
const thinkingTimeSeconds = (thinkingTime / 1000).toFixed(1)
const isPaused = message.status === 'paused'
return (
<CollapseContainer
activeKey={activeKey}
size="small"
onChange={() => setActiveKey((key) => (key ? '' : 'thought'))}
className="message-thought-container"
items={[
@ -60,21 +46,7 @@ const MessageThought: FC<Props> = ({ message }) => {
<TinkingText>
{isThinking ? t('chat.thinking') : t('chat.deeply_thought', { secounds: thinkingTimeSeconds })}
</TinkingText>
{isThinking && !isPaused && <BarLoader color="#9254de" />}
{(!isThinking || isPaused) && (
<Tooltip title={t('common.copy')} mouseEnterDelay={0.8}>
<ActionButton
className="message-action-button"
onClick={(e) => {
e.stopPropagation()
copyThought()
}}
aria-label={t('common.copy')}>
{!copied && <i className="iconfont icon-copy"></i>}
{copied && <CheckOutlined style={{ color: 'var(--color-primary)' }} />}
</ActionButton>
</Tooltip>
)}
{isThinking && <BarLoader color="#9254de" />}
</MessageTitleLabel>
),
children: (
@ -104,32 +76,4 @@ const TinkingText = styled.span`
color: var(--color-text-2);
`
const ActionButton = styled.button`
background: none;
border: none;
color: var(--color-text-2);
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
margin-left: auto;
opacity: 0.6;
transition: all 0.3s;
&:hover {
opacity: 1;
color: var(--color-text);
}
&:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
.iconfont {
font-size: 14px;
}
`
export default MessageThought

View File

@ -166,8 +166,7 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
setMessages([])
setDisplayMessages([])
const defaultTopic = getDefaultTopic(assistant.id)
const _topic = getTopic(assistant, topic.id)
_topic && updateTopic({ ..._topic, name: defaultTopic.name, messages: [] })
updateTopic({ ...topic, name: defaultTopic.name, messages: [] })
TopicManager.clearTopicMessages(topic.id)
}),
EventEmitter.on(EVENT_NAMES.EXPORT_TOPIC_IMAGE, async () => {

View File

@ -1,4 +1,3 @@
import { useTheme } from '@renderer/context/ThemeProvider'
import AssistantSettingsPopup from '@renderer/pages/settings/AssistantSettings'
import { Assistant, Topic } from '@renderer/types'
import { FC } from 'react'
@ -12,30 +11,26 @@ interface Props {
const Prompt: FC<Props> = ({ assistant, topic }) => {
const { t } = useTranslation()
const { theme } = useTheme()
const prompt = assistant.prompt || t('chat.default.description')
const topicPrompt = topic?.prompt || ''
const isDark = theme === 'dark'
if (!prompt && !topicPrompt) {
return null
}
return (
<Container className="system-prompt" onClick={() => AssistantSettingsPopup.show({ assistant })} $isDark={isDark}>
<Container className="system-prompt" onClick={() => AssistantSettingsPopup.show({ assistant })}>
<Text>{prompt}</Text>
</Container>
)
}
const Container = styled.div<{ $isDark: boolean }>`
const Container = styled.div`
padding: 10px 20px;
background-color: var(--color-background-soft);
margin: 4px 20px 0 20px;
border-radius: 6px;
cursor: pointer;
border: 0.5px solid var(--color-border);
background-color: ${({ $isDark }) => ($isDark ? 'var(--color-background-soft)' : 'transparent')};
`
const Text = styled.div`

View File

@ -5,7 +5,6 @@ import MinAppsPopover from '@renderer/components/Popups/MinAppsPopover'
import SearchPopup from '@renderer/components/Popups/SearchPopup'
import { isMac, isWindows } from '@renderer/config/constant'
import { useAssistant } from '@renderer/hooks/useAssistant'
import { modelGenerating } from '@renderer/hooks/useRuntime'
import { useSettings } from '@renderer/hooks/useSettings'
import { useShortcut } from '@renderer/hooks/useShortcuts'
import { useShowAssistants, useShowTopics } from '@renderer/hooks/useStore'
@ -48,11 +47,6 @@ const HeaderNavbar: FC<Props> = ({ activeAssistant }) => {
SearchPopup.show()
})
const handleNarrowModeToggle = async () => {
await modelGenerating()
dispatch(setNarrowMode(!narrowMode))
}
return (
<Navbar className="home-navbar">
{showAssistants && (
@ -86,7 +80,7 @@ const HeaderNavbar: FC<Props> = ({ activeAssistant }) => {
<NarrowIcon onClick={() => SearchPopup.show()}>
<SearchOutlined />
</NarrowIcon>
<NarrowIcon onClick={handleNarrowModeToggle}>
<NarrowIcon onClick={() => dispatch(setNarrowMode(!narrowMode))}>
<i className="iconfont icon-icon-adaptive-width"></i>
</NarrowIcon>
{sidebarIcons.visible.includes('minapp') && (

View File

@ -27,8 +27,7 @@ import {
setPasteLongTextThreshold,
setRenderInputMessageAsMarkdown,
setShowInputEstimatedTokens,
setShowMessageDivider,
setThoughtAutoCollapse
setShowMessageDivider
} from '@renderer/store/settings'
import { Assistant, AssistantSettings, ThemeMode, TranslateLanguageVarious } from '@renderer/types'
import { modalConfirm } from '@renderer/utils'
@ -70,8 +69,7 @@ const SettingsTab: FC<Props> = (props) => {
mathEngine,
autoTranslateWithSpace,
pasteLongTextThreshold,
multiModelMessageStyle,
thoughtAutoCollapse
multiModelMessageStyle
} = useSettings()
const onUpdateAssistantSettings = (settings: Partial<AssistantSettings>) => {
@ -263,20 +261,6 @@ const SettingsTab: FC<Props> = (props) => {
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>
{t('chat.settings.thought_auto_collapse')}
<Tooltip title={t('chat.settings.thought_auto_collapse.tip')}>
<QuestionIcon style={{ marginLeft: 4 }} />
</Tooltip>
</SettingRowTitleSmall>
<Switch
size="small"
checked={thoughtAutoCollapse}
onChange={(checked) => dispatch(setThoughtAutoCollapse(checked))}
/>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>{t('message.message.style')}</SettingRowTitleSmall>
<Select
@ -299,7 +283,6 @@ const SettingsTab: FC<Props> = (props) => {
<Select.Option value="fold">{t('message.message.multi_model_style.fold')}</Select.Option>
<Select.Option value="vertical">{t('message.message.multi_model_style.vertical')}</Select.Option>
<Select.Option value="horizontal">{t('message.message.multi_model_style.horizontal')}</Select.Option>
<Select.Option value="grid">{t('message.message.multi_model_style.grid')}</Select.Option>
</Select>
</SettingRow>
<SettingDivider />

View File

@ -11,7 +11,6 @@ import {
import DragableList from '@renderer/components/DragableList'
import PromptPopup from '@renderer/components/Popups/PromptPopup'
import Scrollbar from '@renderer/components/Scrollbar'
import { isMac } from '@renderer/config/constant'
import { useAssistant, useAssistants } from '@renderer/hooks/useAssistant'
import { modelGenerating } from '@renderer/hooks/useRuntime'
import { useSettings } from '@renderer/hooks/useSettings'
@ -25,7 +24,7 @@ import { exportTopicAsMarkdown, exportTopicToNotion, topicToMarkdown } from '@re
import { Dropdown, MenuProps, Tooltip } from 'antd'
import dayjs from 'dayjs'
import { findIndex } from 'lodash'
import { FC, useCallback, useRef, useState } from 'react'
import { FC, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
@ -43,42 +42,6 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
const borderRadius = showTopicTime ? 12 : 'var(--list-item-border-radius)'
const [deletingTopicId, setDeletingTopicId] = useState<string | null>(null)
const deleteTimerRef = useRef<NodeJS.Timeout>()
const handleDeleteClick = useCallback((topicId: string, e: React.MouseEvent) => {
e.stopPropagation()
if (deleteTimerRef.current) {
clearTimeout(deleteTimerRef.current)
}
setDeletingTopicId(topicId)
deleteTimerRef.current = setTimeout(() => setDeletingTopicId(null), 2000)
}, [])
const onClearMessages = useCallback(() => {
window.keyv.set(EVENT_NAMES.CHAT_COMPLETION_PAUSED, true)
store.dispatch(setGenerating(false))
EventEmitter.emit(EVENT_NAMES.CLEAR_MESSAGES)
}, [])
const handleConfirmDelete = useCallback(
async (topic: Topic, e: React.MouseEvent) => {
e.stopPropagation()
if (assistant.topics.length === 1) {
return onClearMessages()
}
await modelGenerating()
const index = findIndex(assistant.topics, (t) => t.id === topic.id)
setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? index - 1 : index + 1])
removeTopic(topic)
setDeletingTopicId(null)
},
[assistant.topics, onClearMessages, removeTopic, setActiveTopic]
)
const onPinTopic = useCallback(
(topic: Topic) => {
const updatedTopic = { ...topic, pinned: !topic.pinned }
@ -91,7 +54,7 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
async (topic: Topic) => {
await modelGenerating()
const index = findIndex(assistant.topics, (t) => t.id === topic.id)
setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? index - 1 : index + 1])
setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? 0 : index + 1])
removeTopic(topic)
},
[assistant.topics, removeTopic, setActiveTopic]
@ -115,6 +78,12 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
[setActiveTopic]
)
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'] = [
@ -250,7 +219,7 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
return menus
},
[assistant, assistants, onClearMessages, onDeleteTopic, onPinTopic, onMoveTopic, t, updateTopic]
[assistant, assistants, onClearMessages, onPinTopic, onDeleteTopic, onMoveTopic, t, updateTopic]
)
return (
@ -275,34 +244,17 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
)}
<MenuButton className="pin">{topic.pinned && <PushpinOutlined />}</MenuButton>
{isActive && !topic.pinned && (
<Tooltip
placement="bottom"
mouseEnterDelay={0.7}
title={
<div>
<div style={{ fontSize: '12px', opacity: 0.8, fontStyle: 'italic' }}>
{t('chat.topics.delete.shortcut', { key: isMac ? '⌘' : 'Ctrl' })}
</div>
</div>
}>
<MenuButton
className="menu"
onClick={(e) => {
if (e.ctrlKey || e.metaKey) {
handleConfirmDelete(topic, e)
} else if (deletingTopicId === topic.id) {
handleConfirmDelete(topic, e)
} else {
handleDeleteClick(topic.id, e)
}
}}>
{deletingTopicId === topic.id ? (
<DeleteOutlined style={{ color: 'var(--color-error)' }} />
) : (
<CloseOutlined />
)}
</MenuButton>
</Tooltip>
<MenuButton
className="menu"
onClick={(e) => {
e.stopPropagation()
if (assistant.topics.length === 1) {
return onClearMessages()
}
onDeleteTopic(topic)
}}>
<CloseOutlined />
</MenuButton>
)}
</TopicListItem>
</Dropdown>

View File

@ -18,7 +18,7 @@ import { useKnowledge } from '@renderer/hooks/useKnowledge'
import FileManager from '@renderer/services/FileManager'
import { getProviderName } from '@renderer/services/ProviderService'
import { FileType, FileTypes, KnowledgeBase } from '@renderer/types'
import { bookExts, documentExts, textExts, thirdPartyApplicationExts } from '@shared/config/constant'
import { bookExts, documentExts, textExts } from '@shared/config/constant'
import { Alert, Button, Card, Divider, message, Tag, Tooltip, Typography, Upload } from 'antd'
import { FC } from 'react'
import { useTranslation } from 'react-i18next'
@ -35,7 +35,7 @@ interface KnowledgeContentProps {
selectedBase: KnowledgeBase
}
const fileTypes = [...bookExts, ...thirdPartyApplicationExts, ...documentExts, ...textExts]
const fileTypes = [...bookExts, ...documentExts, ...textExts]
const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
const { t } = useTranslation()
@ -53,7 +53,6 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
addSitemap,
removeItem,
getProcessingStatus,
getDirectoryProcessingPercent,
addNote,
addDirectory
} = useKnowledge(selectedBase.id || '')
@ -65,8 +64,6 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
return null
}
const progressingPercent = getDirectoryProcessingPercent(base?.id)
const handleAddFile = () => {
if (disabled) {
return
@ -220,7 +217,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
style={{ marginTop: 10, background: 'transparent' }}>
<p className="ant-upload-text">{t('knowledge.drag_file')}</p>
<p className="ant-upload-hint">
{t('knowledge.file_hint', { file_types: 'TXT, MD, HTML, PDF, DOCX, PPTX, XLSX, EPUB...' })}
{t('knowledge.file_hint', { file_types: fileTypes.slice(0, 6).join(', ').replaceAll('.', '') })}
</p>
</Dragger>
</FileSection>
@ -242,7 +239,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} type="file" />
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} />
</StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter>
@ -274,13 +271,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper>
<StatusIcon
sourceId={item.id}
base={base}
getProcessingStatus={getProcessingStatus}
progressingPercent={progressingPercent}
type="directory"
/>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} />
</StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter>
@ -312,7 +303,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} type="url" />
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} />
</StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter>
@ -344,12 +335,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper>
<StatusIcon
sourceId={item.id}
base={base}
getProcessingStatus={getProcessingStatus}
type="sitemap"
/>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} />
</StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter>
@ -376,7 +362,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter>
<Button type="text" onClick={() => handleEditNote(note)} icon={<EditOutlined />} />
<StatusIconWrapper>
<StatusIcon sourceId={note.id} base={base} getProcessingStatus={getProcessingStatus} type="note" />
<StatusIcon sourceId={note.id} base={base} getProcessingStatus={getProcessingStatus} />
</StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(note)} icon={<DeleteOutlined />} />
</FlexAlignCenter>

View File

@ -65,7 +65,6 @@ const KnowledgePage: FC = () => {
title: t('knowledge.delete_confirm'),
centered: true,
onOk: () => {
setSelectedBase(undefined)
deleteKnowledgeBase(base.id)
}
})

View File

@ -1,6 +1,6 @@
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'
import { KnowledgeBase, ProcessingStatus } from '@renderer/types'
import { Progress, Tooltip } from 'antd'
import { Tooltip } from 'antd'
import { FC } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
@ -9,11 +9,9 @@ interface StatusIconProps {
sourceId: string
base: KnowledgeBase
getProcessingStatus: (sourceId: string) => ProcessingStatus | undefined
progressingPercent?: number
type: string
}
const StatusIcon: FC<StatusIconProps> = ({ sourceId, base, getProcessingStatus, progressingPercent, type }) => {
const StatusIcon: FC<StatusIconProps> = ({ sourceId, base, getProcessingStatus }) => {
const { t } = useTranslation()
const status = getProcessingStatus(sourceId)
const item = base.items.find((item) => item.id === sourceId)
@ -41,16 +39,12 @@ const StatusIcon: FC<StatusIconProps> = ({ sourceId, base, getProcessingStatus,
<StatusDot $status="pending" />
</Tooltip>
)
case 'processing': {
return type === 'directory' ? (
<Progress type="circle" size={14} percent={Number(progressingPercent?.toFixed(0))} />
) : (
case 'processing':
return (
<Tooltip title={t('knowledge.status_processing')} placement="left">
<StatusDot $status="processing" />
</Tooltip>
)
}
case 'completed':
return (
<Tooltip title={t('knowledge.status_completed')} placement="left">

View File

@ -16,14 +16,18 @@ const AssistantKnowledgeBaseSettings: React.FC<Props> = ({ assistant, updateAssi
const { t } = useTranslation()
const knowledgeState = useAppSelector((state) => state.knowledge)
const knowledgeOptions: SelectProps['options'] = knowledgeState.bases.map((base) => ({
label: base.name,
value: base.id
}))
const knowledgeOptions: SelectProps['options'] = []
knowledgeState.bases.forEach((base) => {
knowledgeOptions.push({
label: base.name,
value: base.id
})
})
const onUpdate = (value) => {
const knowledge_bases = value.map((id) => knowledgeState.bases.find((b) => b.id === id))
const _assistant = { ...assistant, knowledge_bases }
const knowledge_base = knowledgeState.bases.find((t) => t.id === value)
const _assistant = { ...assistant, knowledge_base }
updateAssistant(_assistant)
}
@ -33,18 +37,12 @@ const AssistantKnowledgeBaseSettings: React.FC<Props> = ({ assistant, updateAssi
{t('common.knowledge_base')}
</Box>
<Select
mode="multiple"
allowClear
value={assistant.knowledge_bases?.map((b) => b.id)}
defaultValue={assistant.knowledge_base?.id}
placeholder={t('agents.add.knowledge_base.placeholder')}
menuItemSelectedIcon={<CheckOutlined />}
options={knowledgeOptions}
onChange={(value) => onUpdate(value)}
filterOption={(input, option) =>
String(option?.label ?? '')
.toLowerCase()
.includes(input.toLowerCase())
}
/>
</Container>
)

View File

@ -23,7 +23,7 @@ const AssistantModelSettings: FC<Props> = ({ assistant, updateAssistant, updateA
const [contextCount, setContextCount] = useState(assistant?.settings?.contextCount ?? DEFAULT_CONTEXTCOUNT)
const [enableMaxTokens, setEnableMaxTokens] = useState(assistant?.settings?.enableMaxTokens ?? false)
const [maxTokens, setMaxTokens] = useState(assistant?.settings?.maxTokens ?? 0)
const [reasoningEffort, setReasoningEffort] = useState(assistant?.settings?.reasoning_effort)
const [reasoningEffort, setReasoningEffort] = useState(assistant?.settings?.reasoning_effort ?? 'medium')
const [streamOutput, setStreamOutput] = useState(assistant?.settings?.streamOutput ?? true)
const [defaultModel, setDefaultModel] = useState(assistant?.defaultModel)
const [topP, setTopP] = useState(assistant?.settings?.topP ?? 1)
@ -172,7 +172,6 @@ const AssistantModelSettings: FC<Props> = ({ assistant, updateAssistant, updateA
setDefaultModel(selectedModel)
updateAssistant({
...assistant,
model: selectedModel,
defaultModel: selectedModel
})
}
@ -392,7 +391,6 @@ const AssistantModelSettings: FC<Props> = ({ assistant, updateAssistant, updateA
<Radio.Button value="low">{t('assistants.settings.reasoning_effort.low')}</Radio.Button>
<Radio.Button value="medium">{t('assistants.settings.reasoning_effort.medium')}</Radio.Button>
<Radio.Button value="high">{t('assistants.settings.reasoning_effort.high')}</Radio.Button>
<Radio.Button value={undefined}>{t('assistants.settings.reasoning_effort.off')}</Radio.Button>
</Radio.Group>
</SettingRow>
<Divider style={{ margin: '10px 0' }} />

View File

@ -1,10 +1,6 @@
import 'emoji-picker-element'
import EmojiPicker from '@renderer/components/EmojiPicker'
import { Box, HStack } from '@renderer/components/Layout'
import { Assistant, AssistantSettings } from '@renderer/types'
import { getLeadingEmoji } from '@renderer/utils'
import { Button, Input, Popover } from 'antd'
import { Button, Input } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
@ -18,19 +14,12 @@ interface Props {
}
const AssistantPromptSettings: React.FC<Props> = ({ assistant, updateAssistant, onOk }) => {
const [emoji, setEmoji] = useState(getLeadingEmoji(assistant.name) || '⭐️')
const [name, setName] = useState(assistant.name.replace(getLeadingEmoji(assistant.name) || '', '').trim())
const [name, setName] = useState(assistant.name)
const [prompt, setPrompt] = useState(assistant.prompt)
const { t } = useTranslation()
const onUpdate = () => {
const _assistant = { ...assistant, name: `${emoji} ${name}`.trim(), prompt }
updateAssistant(_assistant)
}
const handleEmojiSelect = (selectedEmoji: string) => {
setEmoji(selectedEmoji)
const _assistant = { ...assistant, name: `${selectedEmoji} ${name}`.trim(), prompt }
const _assistant = { ...assistant, name, prompt }
updateAssistant(_assistant)
}
@ -39,18 +28,12 @@ const AssistantPromptSettings: React.FC<Props> = ({ assistant, updateAssistant,
<Box mb={8} style={{ fontWeight: 'bold' }}>
{t('common.name')}
</Box>
<HStack gap={8} alignItems="center">
<Popover content={<EmojiPicker onEmojiClick={handleEmojiSelect} />} arrow>
<Button style={{ fontSize: 20, padding: '4px 8px', minWidth: '42px', height: '32px' }}>{emoji}</Button>
</Popover>
<Input
placeholder={t('common.assistant') + t('common.name')}
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={onUpdate}
style={{ flex: 1 }}
/>
</HStack>
<Input
placeholder={t('common.assistant') + t('common.name')}
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={onUpdate}
/>
<Box mt={8} mb={8} style={{ fontWeight: 'bold' }}>
{t('common.prompt')}
</Box>

View File

@ -1,13 +1,12 @@
import { FileSearchOutlined, FolderOpenOutlined, InfoCircleOutlined, SaveOutlined } from '@ant-design/icons'
import { FileSearchOutlined, FolderOpenOutlined, SaveOutlined } from '@ant-design/icons'
import { Client } from '@notionhq/client'
import { HStack } from '@renderer/components/Layout'
import MinApp from '@renderer/components/MinApp'
import { useTheme } from '@renderer/context/ThemeProvider'
import { backup, reset, restore } from '@renderer/services/BackupService'
import { RootState, useAppDispatch } from '@renderer/store'
import { setNotionApiKey, setNotionDatabaseID, setNotionPageNameKey } from '@renderer/store/settings'
import { setNotionApiKey, setNotionDatabaseID } from '@renderer/store/settings'
import { AppInfo } from '@renderer/types'
import { Button, Modal, Tooltip, Typography } from 'antd'
import { Button, Modal, Typography } from 'antd'
import Input from 'antd/es/input/Input'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
@ -23,9 +22,10 @@ const NotionSettings: FC = () => {
const { theme } = useTheme()
const dispatch = useAppDispatch()
// 这里可以添加 Notion 相关的状态和逻辑
// 例如:
const notionApiKey = useSelector((state: RootState) => state.settings.notionApiKey)
const notionDatabaseID = useSelector((state: RootState) => state.settings.notionDatabaseID)
const notionPageNameKey = useSelector((state: RootState) => state.settings.notionPageNameKey)
const handleNotionTokenChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(setNotionApiKey(e.target.value))
@ -34,11 +34,6 @@ const NotionSettings: FC = () => {
const handleNotionDatabaseIdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(setNotionDatabaseID(e.target.value))
}
const handleNotionPageNameKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(setNotionPageNameKey(e.target.value))
}
const handleNotionConnectionCheck = () => {
if (notionApiKey === null) {
window.message.error(t('settings.data.notion.check.empty_api_key'))
@ -65,66 +60,36 @@ const NotionSettings: FC = () => {
})
}
const handleNotionTitleClick = () => {
MinApp.start({
id: 'notion-help',
name: 'Notion Help',
url: 'https://docs.cherry-ai.com/advanced-basic/notion'
})
}
return (
<SettingGroup theme={theme}>
<SettingTitle style={{ justifyContent: 'flex-start', gap: 10 }}>
{t('settings.data.notion.title')}
<Tooltip title={t('settings.data.notion.help')} placement="right">
<InfoCircleOutlined
style={{ color: 'var(--color-text-2)', cursor: 'pointer' }}
onClick={handleNotionTitleClick}
/>
</Tooltip>
</SettingTitle>
<SettingTitle>{t('settings.data.notion.title')}</SettingTitle>
<SettingDivider />
<SettingRow>
<SettingRowTitle>{t('settings.data.notion.database_id')}</SettingRowTitle>
<HStack alignItems="center" gap="5px" style={{ width: 315 }}>
<HStack alignItems="center" gap="5px">
<Input
type="text"
value={notionDatabaseID || ''}
onChange={handleNotionDatabaseIdChange}
onBlur={handleNotionDatabaseIdChange}
style={{ width: 315 }}
placeholder={t('settings.data.notion.database_id_placeholder')}
/>
</HStack>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitle>{t('settings.data.notion.page_name_key')}</SettingRowTitle>
<HStack alignItems="center" gap="5px" style={{ width: 315 }}>
<Input
type="text"
value={notionPageNameKey || ''}
onChange={handleNotionPageNameKeyChange}
onBlur={handleNotionPageNameKeyChange}
style={{ width: 315 }}
placeholder={t('settings.data.notion.page_name_key_placeholder')}
/>
</HStack>
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitle>{t('settings.data.notion.api_key')}</SettingRowTitle>
<HStack alignItems="center" gap="5px" style={{ width: 315 }}>
<HStack alignItems="center" gap="5px">
<Input
type="password"
value={notionApiKey || ''}
onChange={handleNotionTokenChange}
onBlur={handleNotionTokenChange}
style={{ width: 250 }}
placeholder={t('settings.data.notion.api_key_placeholder')}
/>
<Button onClick={handleNotionConnectionCheck}>{t('settings.data.notion.check.button')}</Button>
<Button onClick={handleNotionConnectionCheck} style={{ width: 60 }}>
{t('settings.data.notion.check.button')}
</Button>
</HStack>
</SettingRow>
<SettingDivider /> {/* 添加分割线 */}

View File

@ -40,7 +40,7 @@ const WebDavSettings: FC = () => {
const dispatch = useAppDispatch()
const { t } = useTranslation()
const { t, i18n } = useTranslation()
const { webdavSync } = useRuntime()
@ -163,6 +163,7 @@ const WebDavSettings: FC = () => {
<SettingRow>
<SettingRowTitle>{t('settings.general.backup.title')}</SettingRowTitle>
<HStack gap="5px" justifyContent="space-between">
{/* 添加 在线备份 在线还原 按钮 */}
<Button onClick={onBackup} icon={<SaveOutlined />} loading={backuping}>
{t('settings.data.webdav.backup.button')}
</Button>
@ -176,15 +177,19 @@ const WebDavSettings: FC = () => {
<SettingRowTitle>{t('settings.data.webdav.autoSync')}</SettingRowTitle>
<Select value={syncInterval} onChange={onSyncIntervalChange} disabled={!webdavHost} style={{ width: 120 }}>
<Select.Option value={0}>{t('settings.data.webdav.autoSync.off')}</Select.Option>
<Select.Option value={1}>{t('settings.data.webdav.minute_interval', { count: 1 })}</Select.Option>
<Select.Option value={5}>{t('settings.data.webdav.minute_interval', { count: 5 })}</Select.Option>
<Select.Option value={15}>{t('settings.data.webdav.minute_interval', { count: 15 })}</Select.Option>
<Select.Option value={30}>{t('settings.data.webdav.minute_interval', { count: 30 })}</Select.Option>
<Select.Option value={60}>{t('settings.data.webdav.hour_interval', { count: 1 })}</Select.Option>
<Select.Option value={120}>{t('settings.data.webdav.hour_interval', { count: 2 })}</Select.Option>
<Select.Option value={360}>{t('settings.data.webdav.hour_interval', { count: 6 })}</Select.Option>
<Select.Option value={720}>{t('settings.data.webdav.hour_interval', { count: 12 })}</Select.Option>
<Select.Option value={1440}>{t('settings.data.webdav.hour_interval', { count: 24 })}</Select.Option>
<Select.Option value={1}>
1 {i18n.language === 'en-US' ? t('settings.data.webdav.minute') : t('settings.data.webdav.minutes')}
</Select.Option>
<Select.Option value={5}>5 {t('settings.data.webdav.minutes')}</Select.Option>
<Select.Option value={15}>15 {t('settings.data.webdav.minutes')}</Select.Option>
<Select.Option value={30}>30 {t('settings.data.webdav.minutes')}</Select.Option>
<Select.Option value={60}>
1 {i18n.language === 'en-US' ? t('settings.data.webdav.hour') : t('settings.data.webdav.hours')}
</Select.Option>
<Select.Option value={120}>2 {t('settings.data.webdav.hours')}</Select.Option>
<Select.Option value={360}>6 {t('settings.data.webdav.hours')}</Select.Option>
<Select.Option value={720}>12 {t('settings.data.webdav.hours')}</Select.Option>
<Select.Option value={1440}>24 {t('settings.data.webdav.hours')}</Select.Option>
</Select>
</SettingRow>
{webdavSync && syncInterval > 0 && (

View File

@ -23,6 +23,50 @@ interface MiniAppManagerProps {
type ListType = 'visible' | 'disabled'
// 添加 reorderLists 函数的接口定义
interface ReorderListsParams {
sourceList: MinAppType[]
destList: MinAppType[]
sourceIndex: number
destIndex: number
isSameList: boolean
}
interface ReorderListsResult {
sourceList: MinAppType[]
destList: MinAppType[]
}
// 添加 reorderLists 函数
const reorderLists = ({
sourceList,
destList,
sourceIndex,
destIndex,
isSameList
}: ReorderListsParams): ReorderListsResult => {
if (isSameList) {
// 在同一列表内重新排序
const newList = [...sourceList]
const [removed] = newList.splice(sourceIndex, 1)
newList.splice(destIndex, 0, removed)
return {
sourceList: newList,
destList: destList
}
} else {
// 在不同列表间移动
const newSourceList = [...sourceList]
const [removed] = newSourceList.splice(sourceIndex, 1)
const newDestList = [...destList]
newDestList.splice(destIndex, 0, removed)
return {
sourceList: newSourceList,
destList: newDestList
}
}
}
const MiniAppIconsManager: FC<MiniAppManagerProps> = ({
visibleMiniApps,
disabledMiniApps,
@ -48,35 +92,25 @@ const MiniAppIconsManager: FC<MiniAppManagerProps> = ({
if (!result.destination) return
const { source, destination } = result
const sourceList = source.droppableId as ListType
const destList = destination.droppableId as ListType
if (source.droppableId === destination.droppableId) {
// 在同一列表内重新排序
const list = source.droppableId === 'visible' ? [...visibleMiniApps] : [...disabledMiniApps]
const [removed] = list.splice(source.index, 1)
list.splice(destination.index, 0, removed)
if (source.droppableId === destination.droppableId) return
if (source.droppableId === 'visible') {
handleListUpdate(list, disabledMiniApps)
} else {
handleListUpdate(visibleMiniApps, list)
}
return
}
const newLists = reorderLists({
sourceList: sourceList === 'visible' ? visibleMiniApps : disabledMiniApps,
destList: destList === 'visible' ? visibleMiniApps : disabledMiniApps,
sourceIndex: source.index,
destIndex: destination.index,
isSameList: sourceList === destList
})
// 在不同列表间移动
const sourceList = source.droppableId === 'visible' ? [...visibleMiniApps] : [...disabledMiniApps]
const destList = destination.droppableId === 'visible' ? [...visibleMiniApps] : [...disabledMiniApps]
const [removed] = sourceList.splice(source.index, 1)
const targetList = destList.filter((app) => app.id !== removed.id)
targetList.splice(destination.index, 0, removed)
const newVisibleMiniApps = destination.droppableId === 'visible' ? targetList : sourceList
const newDisabledMiniApps = destination.droppableId === 'disabled' ? targetList : sourceList
handleListUpdate(newVisibleMiniApps, newDisabledMiniApps)
handleListUpdate(
sourceList === 'visible' ? newLists.sourceList : newLists.destList,
sourceList === 'visible' ? newLists.destList : newLists.sourceList
)
},
[visibleMiniApps, disabledMiniApps, handleListUpdate]
[disabledMiniApps, handleListUpdate, visibleMiniApps]
)
const onMoveMiniApp = useCallback(
@ -119,15 +153,17 @@ const MiniAppIconsManager: FC<MiniAppManagerProps> = ({
<Droppable droppableId={listType}>
{(provided: DroppableProvided) => (
<ProgramList ref={provided.innerRef} {...provided.droppableProps}>
{(listType === 'visible' ? visibleMiniApps : disabledMiniApps).map((program, index) => (
<Draggable key={program.id} draggableId={String(program.id)} index={index}>
{(provided: DraggableProvided) => renderProgramItem(program, provided, listType)}
</Draggable>
))}
{disabledMiniApps.length === 0 && listType === 'disabled' && (
<EmptyPlaceholder>{t('settings.display.minApp.empty')}</EmptyPlaceholder>
)}
{provided.placeholder}
<ScrollContainer>
{(listType === 'visible' ? visibleMiniApps : disabledMiniApps).map((program, index) => (
<Draggable key={program.id} draggableId={String(program.id)} index={index}>
{(provided: DraggableProvided) => renderProgramItem(program, provided, listType)}
</Draggable>
))}
{disabledMiniApps.length === 0 && listType === 'disabled' && (
<EmptyPlaceholder>{t('settings.display.minApp.empty')}</EmptyPlaceholder>
)}
{provided.placeholder}
</ScrollContainer>
</ProgramList>
)}
</Droppable>
@ -145,6 +181,12 @@ const AppLogo = styled.img`
object-fit: contain;
`
const ScrollContainer = styled.div`
overflow-y: auto;
height: 100%;
padding-right: 5px;
`
const ProgramSection = styled.div`
display: flex;
gap: 20px;
@ -166,29 +208,13 @@ const ProgramList = styled.div`
height: 365px;
min-height: 365px;
padding: 10px;
padding-right: 5px;
background: var(--color-background-soft);
border-radius: 8px;
border: 1px solid var(--color-border);
overflow-y: auto;
scroll-behavior: smooth;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: var(--color-border);
border-radius: 3px;
}
&::-webkit-scrollbar-thumb:hover {
background: var(--color-border-hover);
}
display: flex;
flex-direction: column;
overflow-y: hidden;
`
const ProgramItem = styled.div`

View File

@ -10,7 +10,7 @@ import {
import { HStack } from '@renderer/components/Layout'
import ModelTags from '@renderer/components/ModelTags'
import OAuthButton from '@renderer/components/OAuth/OAuthButton'
import { getModelLogo, isEmbeddingModel, isReasoningModel, isVisionModel } from '@renderer/config/models'
import { EMBEDDING_REGEX, getModelLogo, REASONING_REGEX, VISION_REGEX } from '@renderer/config/models'
import { PROVIDER_CONFIG } from '@renderer/config/providers'
import { useTheme } from '@renderer/context/ThemeProvider'
import { useAssistants, useDefaultModel } from '@renderer/hooks/useAssistant'
@ -192,9 +192,9 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
const modelTypeContent = (model: Model) => {
// 获取默认选中的类型
const defaultTypes = [
...(isVisionModel(model) ? ['vision'] : []),
...(isEmbeddingModel(model) ? ['embedding'] : []),
...(isReasoningModel(model) ? ['reasoning'] : [])
...(VISION_REGEX.test(model.id) ? ['vision'] : []),
...(EMBEDDING_REGEX.test(model.id) ? ['embedding'] : []),
...(REASONING_REGEX.test(model.id) ? ['reasoning'] : [])
] as ModelType[]
// 合并现有选择和默认类型
@ -206,21 +206,9 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
value={selectedTypes}
onChange={(types) => onUpdateModelTypes(model, types as ModelType[])}
options={[
{
label: t('models.type.vision'),
value: 'vision',
disabled: isVisionModel(model)
},
{
label: t('models.type.embedding'),
value: 'embedding',
disabled: isEmbeddingModel(model)
},
{
label: t('models.type.reasoning'),
value: 'reasoning',
disabled: isReasoningModel(model)
}
{ label: t('models.type.vision'), value: 'vision', disabled: VISION_REGEX.test(model.id) },
{ label: t('models.type.embedding'), value: 'embedding', disabled: EMBEDDING_REGEX.test(model.id) },
{ label: t('models.type.reasoning'), value: 'reasoning', disabled: REASONING_REGEX.test(model.id) }
]}
/>
</div>

View File

@ -59,8 +59,7 @@ const ShortcutSettings: FC = () => {
const hasModifier = keys.some((key) => ['Control', 'Ctrl', 'Command', 'Alt', 'Shift'].includes(key))
const hasNonModifier = keys.some((key) => !['Control', 'Ctrl', 'Command', 'Alt', 'Shift'].includes(key))
// only allows option + space
if (isMac && keys[0] === 'Alt' && !['Space', undefined].includes(keys[1])) {
if (isMac && keys.includes('Alt')) {
window.message.warning({
content: t('settings.shortcuts.alt_warning'),
key: 'shortcut-alt-warning'

View File

@ -1,27 +1,18 @@
import {
CheckOutlined,
DeleteOutlined,
HistoryOutlined,
SendOutlined,
SettingOutlined,
WarningOutlined
} from '@ant-design/icons'
import { CheckOutlined, SendOutlined, SettingOutlined, SwapOutlined, WarningOutlined } from '@ant-design/icons'
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
import CopyIcon from '@renderer/components/Icons/CopyIcon'
import { isLocalAi } from '@renderer/config/env'
import { translateLanguageOptions } from '@renderer/config/translate'
import { TranslateLanguageOptions } from '@renderer/config/translate'
import db from '@renderer/databases'
import { useDefaultModel } from '@renderer/hooks/useAssistant'
import { fetchTranslate } from '@renderer/services/ApiService'
import { getDefaultTranslateAssistant } from '@renderer/services/AssistantService'
import { Assistant, Message, TranslateHistory } from '@renderer/types'
import { Assistant, Message } from '@renderer/types'
import { runAsyncFunction, uuid } from '@renderer/utils'
import { Button, Dropdown, Empty, Flex, Popconfirm, Select, Space, Tooltip } from 'antd'
import TextArea, { TextAreaRef } from 'antd/es/input/TextArea'
import dayjs from 'dayjs'
import { useLiveQuery } from 'dexie-react-hooks'
import { Button, Select, Space } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { isEmpty } from 'lodash'
import { FC, useEffect, useRef, useState } from 'react'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
@ -38,42 +29,11 @@ const TranslatePage: FC = () => {
const { translateModel } = useDefaultModel()
const [loading, setLoading] = useState(false)
const [copied, setCopied] = useState(false)
const [historyDrawerVisible, setHistoryDrawerVisible] = useState(false)
const contentContainerRef = useRef<HTMLDivElement>(null)
const textAreaRef = useRef<TextAreaRef>(null)
const translateHistory = useLiveQuery(() => db.translate_history.orderBy('createdAt').reverse().toArray(), [])
_text = text
_result = result
_targetLanguage = targetLanguage
const saveTranslateHistory = async (
sourceText: string,
targetText: string,
sourceLanguage: string,
targetLanguage: string
) => {
const history: TranslateHistory = {
id: uuid(),
sourceText,
targetText,
sourceLanguage,
targetLanguage,
createdAt: new Date().toISOString()
}
console.log('🌟TEO🌟 ~ saveTranslateHistory ~ history:', history)
await db.translate_history.add(history)
}
const deleteHistory = async (id: string) => {
db.translate_history.delete(id)
}
const clearHistory = async () => {
db.translate_history.clear()
}
const onTranslate = async () => {
if (!text.trim()) {
return
@ -102,17 +62,7 @@ const TranslatePage: FC = () => {
}
setLoading(true)
let translatedText = ''
await fetchTranslate({
message,
assistant,
onResponse: (text) => {
translatedText = text
setResult(text)
}
})
await saveTranslateHistory(text, translatedText, 'any', targetLanguage)
await fetchTranslate({ message, assistant, onResponse: (text) => setResult(text) })
setLoading(false)
}
@ -122,12 +72,6 @@ const TranslatePage: FC = () => {
setTimeout(() => setCopied(false), 2000)
}
const onHistoryItemClick = (history: TranslateHistory) => {
setText(history.sourceText)
setResult(history.targetText)
setTargetLanguage(history.targetLanguage)
}
useEffect(() => {
isEmpty(text) && setResult('')
}, [text])
@ -139,13 +83,6 @@ const TranslatePage: FC = () => {
})
}, [])
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
e.preventDefault()
onTranslate()
}
}
const SettingButton = () => {
if (isLocalAi) {
return null
@ -172,163 +109,104 @@ const TranslatePage: FC = () => {
}
return (
<Container id="translate-page">
<Container>
<Navbar>
<NavbarCenter style={{ borderRight: 'none', gap: 10 }}>
{t('translate.title')}
<Button
className="nodrag"
color="default"
variant={historyDrawerVisible ? 'filled' : 'text'}
type="text"
icon={<HistoryOutlined />}
onClick={() => setHistoryDrawerVisible(!historyDrawerVisible)}
/>
</NavbarCenter>
<NavbarCenter style={{ borderRight: 'none' }}>{t('translate.title')}</NavbarCenter>
</Navbar>
<ContentContainer id="content-container" ref={contentContainerRef} $historyDrawerVisible={historyDrawerVisible}>
<HistoryContainner $historyDrawerVisible={historyDrawerVisible}>
<OperationBar>
<span style={{ fontSize: 16 }}>{t('translate.history.title')}</span>
{!isEmpty(translateHistory) && (
<Popconfirm
title={t('translate.history.clear')}
description={t('translate.history.clear_description')}
onConfirm={clearHistory}>
<Button type="text" size="small" danger icon={<DeleteOutlined />}>
{t('translate.history.clear')}
</Button>
</Popconfirm>
)}
</OperationBar>
{translateHistory && translateHistory.length ? (
<HistoryList>
{translateHistory.map((item) => (
<Dropdown
key={item.id}
trigger={['contextMenu']}
menu={{
items: [
{
key: 'delete',
label: t('translate.history.delete'),
icon: <DeleteOutlined />,
danger: true,
onClick: () => deleteHistory(item.id)
}
]
}}>
<HistoryListItem onClick={() => onHistoryItemClick(item)}>
<Flex justify="space-between" vertical gap={4} style={{ width: '100%' }}>
<HistoryListItemTitle>{item.sourceText}</HistoryListItemTitle>
<HistoryListItemTitle>{item.targetText}</HistoryListItemTitle>
<HistoryListItemDate>{dayjs(item.createdAt).format('MM/DD HH:mm')}</HistoryListItemDate>
</Flex>
</HistoryListItem>
</Dropdown>
))}
</HistoryList>
) : (
<Flex justify="center" align="center" style={{ flex: 1 }}>
<Empty description={t('translate.history.empty')} />
</Flex>
)}
</HistoryContainner>
<InputContainer>
<OperationBar>
<Flex align="center" gap={20}>
<Select
showSearch
value="any"
style={{ width: 180 }}
optionFilterProp="label"
disabled
options={[{ label: t('translate.any.language'), value: 'any' }]}
/>
<SettingButton />
</Flex>
<Tooltip
mouseEnterDelay={0.5}
styles={{ body: { fontSize: '12px' } }}
title={
<div style={{ textAlign: 'center' }}>
Enter: {t('translate.button.translate')}
<br />
Shift + Enter: {t('translate.tooltip.newline')}
</div>
}>
<TranslateButton
type="primary"
loading={loading}
onClick={onTranslate}
disabled={!text.trim()}
icon={<SendOutlined />}>
{t('translate.button.translate')}
</TranslateButton>
</Tooltip>
</OperationBar>
<Textarea
ref={textAreaRef}
variant="borderless"
placeholder={t('translate.input.placeholder')}
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={onKeyDown}
disabled={loading}
spellCheck={false}
allowClear
<ContentContainer id="content-container">
<MenuContainer>
<Select
showSearch
value="any"
style={{ width: 180 }}
optionFilterProp="label"
disabled
options={[{ label: t('translate.any.language'), value: 'any' }]}
/>
</InputContainer>
<OutputContainer>
<OperationBar>
<Select
showSearch
value={targetLanguage}
style={{ width: 180 }}
optionFilterProp="label"
options={translateLanguageOptions()}
onChange={(value) => {
setTargetLanguage(value)
db.settings.put({ id: 'translate:target:language', value })
}}
optionRender={(option) => (
<Space>
<span role="img" aria-label={option.data.label}>
{option.data.emoji}
</span>
{option.label}
</Space>
)}
<SwapOutlined />
<Select
showSearch
value={targetLanguage}
style={{ width: 180 }}
optionFilterProp="label"
options={TranslateLanguageOptions}
onChange={(value) => {
setTargetLanguage(value)
db.settings.put({ id: 'translate:target:language', value })
}}
optionRender={(option) => (
<Space>
<span role="img" aria-label={option.data.label}>
{option.data.emoji}
</span>
{option.label}
</Space>
)}
/>
<SettingButton />
</MenuContainer>
<TranslateInputWrapper>
<InputContainer>
<Textarea
variant="borderless"
placeholder={t('translate.input.placeholder')}
value={text}
onChange={(e) => setText(e.target.value)}
disabled={loading}
spellCheck={false}
allowClear
/>
<TranslateButton
type="primary"
loading={loading}
onClick={onTranslate}
disabled={!text.trim()}
icon={<SendOutlined />}>
{t('translate.button.translate')}
</TranslateButton>
</InputContainer>
<OutputContainer>
<OutputText>{result || t('translate.output.placeholder')}</OutputText>
<CopyButton
onClick={onCopy}
disabled={!result}
icon={copied ? <CheckOutlined style={{ color: 'var(--color-primary)' }} /> : <CopyIcon />}
/>
</OperationBar>
<OutputText>{result || t('translate.output.placeholder')}</OutputText>
</OutputContainer>
</OutputContainer>
</TranslateInputWrapper>
</ContentContainer>
</Container>
)
}
const Container = styled.div`
display: flex;
flex: 1;
flex-direction: column;
height: 100%;
`
const ContentContainer = styled.div<{ $historyDrawerVisible: boolean }>`
height: calc(100vh - var(--navbar-height));
display: grid;
grid-template-columns: auto 1fr 1fr;
const ContentContainer = styled.div`
display: flex;
flex: 1;
padding: 20px 15px;
position: relative;
flex-direction: column;
height: 100%;
padding: 20px;
`
const MenuContainer = styled.div`
display: flex;
flex-direction: row;
align-items: center;
margin-bottom: 15px;
gap: 20px;
`
const TranslateInputWrapper = styled.div`
display: flex;
flex-direction: row;
min-height: 350px;
gap: 20px;
`
const InputContainer = styled.div`
@ -336,136 +214,52 @@ const InputContainer = styled.div`
display: flex;
flex: 1;
flex-direction: column;
height: 100%;
border: 1px solid var(--color-border-soft);
border-radius: 10px;
padding-bottom: 5px;
padding-right: 2px;
margin-right: 15px;
`
const OperationBar = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 10px 8px 10px 10px;
`
const Textarea = styled(TextArea)`
display: flex;
flex: 1;
padding: 20px;
font-size: 16px;
border-radius: 0;
overflow: auto;
.ant-input {
resize: none;
padding: 5px 16px;
}
.ant-input-clear-icon {
font-size: 16px;
padding: 15px 20px;
}
`
const OutputContainer = styled.div`
min-height: 0;
position: relative;
display: flex;
flex: 1;
flex-direction: column;
height: 100%;
padding: 10px;
background-color: var(--color-background-soft);
border-radius: 10px;
padding-bottom: 5px;
padding-right: 2px;
`
const OutputText = styled.div`
min-height: 0;
flex: 1;
padding: 5px 16px;
overflow-y: auto;
padding: 5px 10px;
max-height: calc(100vh - var(--navbar-height) - 120px);
overflow: auto;
white-space: pre-wrap;
`
const TranslateButton = styled(Button)``
const CopyButton = styled(Button)``
const HistoryContainner = styled.div<{ $historyDrawerVisible: boolean }>`
width: ${({ $historyDrawerVisible }) => ($historyDrawerVisible ? '300px' : '0')};
height: calc(100vh - var(--navbar-height) - 40px);
transition:
width 0.2s,
opacity 0.2s;
border: 1px solid var(--color-border-soft);
border-radius: 10px;
margin-right: 15px;
display: flex;
flex-direction: column;
overflow: hidden;
padding-right: 2px;
padding-bottom: 5px;
${({ $historyDrawerVisible }) =>
!$historyDrawerVisible &&
`
border: none;
margin-right: 0;
opacity: 0;
`}
const TranslateButton = styled(Button)`
position: absolute;
right: 15px;
bottom: 15px;
z-index: 10;
`
const HistoryList = styled.div`
flex: 1;
display: flex;
flex-direction: column;
gap: 16px;
overflow-y: auto;
padding: 0 5px;
`
const HistoryListItem = styled.div`
width: 100%;
padding: 5px 10px;
border-radius: var(--list-item-border-radius);
cursor: pointer;
transition: background-color 0.2s;
position: relative;
button {
opacity: 0;
transition: opacity 0.2s;
}
&:hover {
background-color: var(--color-background-mute);
button {
opacity: 1;
}
}
&:not(:last-child)::after {
content: '';
display: block;
width: 100%;
height: 1px;
border-bottom: 1px dashed var(--color-border-soft);
position: absolute;
bottom: -8px;
left: 0;
}
`
const HistoryListItemTitle = styled.div`
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
font-size: 13px;
`
const HistoryListItemDate = styled.div`
font-size: 12px;
color: var(--color-text-3);
const CopyButton = styled(Button)`
position: absolute;
right: 15px;
bottom: 15px;
`
export default TranslatePage

View File

@ -13,6 +13,7 @@ import OpenAI from 'openai'
import { CompletionsParams } from '.'
import BaseProvider from './BaseProvider'
export default class AnthropicProvider extends BaseProvider {
private sdk: Anthropic
@ -107,14 +108,9 @@ export default class AnthropicProvider extends BaseProvider {
})
}
const lastUserMessage = _messages.findLast((m) => m.role === 'user')
const { abortController, cleanup } = this.createAbortController(lastUserMessage?.id)
const { signal } = abortController
return new Promise<void>((resolve, reject) => {
const stream = this.sdk.messages
.stream({ ...body, stream: true }, { signal })
.stream({ ...body, stream: true })
.on('text', (text) => {
if (window.keyv.get(EVENT_NAMES.CHAT_COMPLETION_PAUSED)) {
stream.controller.abort()
@ -150,7 +146,7 @@ export default class AnthropicProvider extends BaseProvider {
resolve()
})
.on('error', (error) => reject(error))
}).finally(cleanup)
})
}
public async translate(message: Message, assistant: Assistant, onResponse?: (text: string) => void) {

View File

@ -3,13 +3,11 @@ import { getLMStudioKeepAliveTime } from '@renderer/hooks/useLMStudio'
import { getOllamaKeepAliveTime } from '@renderer/hooks/useOllama'
import { getKnowledgeReferences } from '@renderer/services/KnowledgeService'
import store from '@renderer/store'
import type { Assistant, GenerateImageParams, Message, Model, Provider, Suggestion } from '@renderer/types'
import { Assistant, GenerateImageParams, Message, Model, Provider, Suggestion } from '@renderer/types'
import { delay, isJSON, parseJSON } from '@renderer/utils'
import { addAbortController, removeAbortController } from '@renderer/utils/abortController'
import { t } from 'i18next'
import type OpenAI from 'openai'
import OpenAI from 'openai'
import type { CompletionsParams } from '.'
import { CompletionsParams } from '.'
export default abstract class BaseProvider {
protected provider: Provider
@ -85,35 +83,21 @@ export default abstract class BaseProvider {
return message.content
}
const bases = store.getState().knowledge.bases.filter((kb) => message.knowledgeBaseIds?.includes(kb.id))
const knowledgeId = message.knowledgeBaseIds[0]
const base = store.getState().knowledge.bases.find((kb) => kb.id === knowledgeId)
if (!bases || bases.length === 0) {
if (!base) {
return message.content
}
const allReferencesPromises = bases.map(async (base) => {
const references = await getKnowledgeReferences(base, message)
const { referencesContent, referencesCount } = await getKnowledgeReferences(base, message)
return {
knowledgeBaseId: base.id,
references
}
})
const allReferences = (await Promise.all(allReferencesPromises))
.filter((result) => result.references && result.references.length > 0)
.flat()
if (allReferences.length === 0) {
window.message.info({
content: t('knowledge.no_match'),
duration: 4,
key: 'knowledge-base-no-match-info'
})
// 如果知识库中未检索到内容则使用通用逻辑
if (referencesCount === 0) {
return message.content
}
const allReferencesContent = `\`\`\`json\n${JSON.stringify(allReferences, null, 2)}\n\`\`\``
return REFERENCE_PROMPT.replace('{question}', message.content).replace('{references}', allReferencesContent)
return REFERENCE_PROMPT.replace('{question}', message.content).replace('{references}', referencesContent)
}
protected getCustomParameters(assistant: Assistant) {
@ -136,21 +120,4 @@ export default abstract class BaseProvider {
}, {}) || {}
)
}
protected createAbortController(messageId?: string) {
const abortController = new AbortController()
if (messageId) {
addAbortController(messageId, () => abortController.abort())
}
return {
abortController,
cleanup: () => {
if (messageId) {
removeAbortController(messageId)
}
}
}
}
}

View File

@ -24,6 +24,7 @@ import OpenAI from 'openai'
import { CompletionsParams } from '.'
import BaseProvider from './BaseProvider'
export default class GeminiProvider extends BaseProvider {
private sdk: GoogleGenerativeAI
private requestOptions: RequestOptions
@ -203,11 +204,7 @@ export default class GeminiProvider extends BaseProvider {
return
}
const lastUserMessage = userMessages.findLast((m) => m.role === 'user')
const { abortController, cleanup } = this.createAbortController(lastUserMessage?.id)
const { signal } = abortController
const userMessagesStream = await chat.sendMessageStream(messageContents.parts, { signal }).finally(cleanup)
const userMessagesStream = await chat.sendMessageStream(messageContents.parts)
let time_first_token_millsec = 0
for await (const chunk of userMessagesStream.stream) {

View File

@ -213,31 +213,21 @@ export default class OpenAIProvider extends BaseProvider {
let time_first_token_millsec = 0
let time_first_content_millsec = 0
const start_time_millsec = new Date().getTime()
const lastUserMessage = _messages.findLast((m) => m.role === 'user')
const { abortController, cleanup } = this.createAbortController(lastUserMessage?.id)
const { signal } = abortController
const stream = await this.sdk.chat.completions
// @ts-ignore key is not typed
.create(
{
model: model.id,
messages: [systemMessage, ...userMessages].filter(Boolean) as ChatCompletionMessageParam[],
temperature: this.getTemperature(assistant, model),
top_p: this.getTopP(assistant, model),
max_tokens: maxTokens,
keep_alive: this.keepAliveTime,
stream: isSupportStreamOutput(),
...this.getReasoningEffort(assistant, model),
...getOpenAIWebSearchParams(assistant, model),
...this.getProviderSpecificParameters(assistant, model),
...this.getCustomParameters(assistant)
},
{
signal
}
)
.finally(cleanup)
// @ts-ignore key is not typed
const stream = await this.sdk.chat.completions.create({
model: model.id,
messages: [systemMessage, ...userMessages].filter(Boolean) as ChatCompletionMessageParam[],
temperature: this.getTemperature(assistant, model),
top_p: this.getTopP(assistant, model),
max_tokens: maxTokens,
keep_alive: this.keepAliveTime,
stream: isSupportStreamOutput(),
...this.getReasoningEffort(assistant, model),
...getOpenAIWebSearchParams(assistant, model),
...this.getProviderSpecificParameters(assistant, model),
...this.getCustomParameters(assistant)
})
if (!isSupportStreamOutput()) {
const time_completion_millsec = new Date().getTime() - start_time_millsec

View File

@ -2,8 +2,7 @@ import i18n from '@renderer/i18n'
import store from '@renderer/store'
import { setGenerating } from '@renderer/store/runtime'
import { Assistant, Message, Model, Provider, Suggestion } from '@renderer/types'
import { addAbortController } from '@renderer/utils/abortController'
import { formatMessageError } from '@renderer/utils/error'
import { formatErrorMessage, formatMessageError } from '@renderer/utils/error'
import { isEmpty } from 'lodash'
import AiProvider from '../providers/AiProvider'
@ -17,6 +16,7 @@ import {
import { EVENT_NAMES, EventEmitter } from './EventService'
import { filterMessages, filterUsefulMessages } from './MessagesService'
import { estimateMessagesUsage } from './TokenService'
export async function fetchChatCompletion({
message,
messages,
@ -37,14 +37,18 @@ export async function fetchChatCompletion({
onResponse({ ...message })
const pauseFn = (message: Message) => {
message.status = 'paused'
EventEmitter.emit(EVENT_NAMES.RECEIVE_MESSAGE, message)
store.dispatch(setGenerating(false))
onResponse({ ...message, status: 'paused' })
}
addAbortController(message.askId ?? message.id, pauseFn.bind(null, message))
// Handle paused state
let paused = false
const timer = setInterval(() => {
if (window.keyv.get(EVENT_NAMES.CHAT_COMPLETION_PAUSED)) {
paused = true
message.status = 'paused'
EventEmitter.emit(EVENT_NAMES.RECEIVE_MESSAGE, message)
store.dispatch(setGenerating(false))
onResponse({ ...message, status: 'paused' })
clearInterval(timer)
}
}, 1000)
try {
let _messages: Message[] = []
@ -90,9 +94,16 @@ export async function fetchChatCompletion({
}
} catch (error: any) {
message.status = 'error'
message.content = formatErrorMessage(error)
message.error = formatMessageError(error)
}
timer && clearInterval(timer)
if (paused) {
return message
}
// Update message status
message.status = window.keyv.get(EVENT_NAMES.CHAT_COMPLETION_PAUSED) ? 'paused' : message.status

View File

@ -30,8 +30,8 @@ export function getDefaultTranslateAssistant(targetLanguage: string, text: strin
assistant.prompt = store
.getState()
.settings.translateModelPrompt.replaceAll('{{target_language}}', targetLanguage)
.replaceAll('{{text}}', text)
.settings.translateModelPrompt.replace('{{target_language}}', targetLanguage)
.replace('{{text}}', text)
return assistant
}

View File

@ -3,6 +3,7 @@ import { DEFAULT_KNOWLEDGE_DOCUMENT_COUNT, DEFAULT_KNOWLEDGE_THRESHOLD } from '@
import { getEmbeddingMaxContext } from '@renderer/config/embedings'
import AiProvider from '@renderer/providers/AiProvider'
import { FileType, KnowledgeBase, KnowledgeBaseParams, Message } from '@renderer/types'
import { t } from 'i18next'
import { take } from 'lodash'
import { getProviderByModel } from './AssistantService'
@ -90,6 +91,14 @@ export const getKnowledgeReferences = async (base: KnowledgeBase, message: Messa
return item.score >= threshold
})
)
if (searchResults.length === 0) {
window.message.info({
content: t('knowledge.no_match'),
duration: 4,
key: 'knowledge-base-no-match-info'
})
return { referencesContent: '', referencesCount: 0 }
}
const _searchResults = await Promise.all(
searchResults.map(async (item) => {
@ -112,5 +121,7 @@ export const getKnowledgeReferences = async (base: KnowledgeBase, message: Messa
})
)
return references
const referencesContent = `\`\`\`json\n${JSON.stringify(references, null, 2)}\n\`\`\``
return { referencesContent, referencesCount: references.length }
}

View File

@ -1,6 +1,5 @@
import store from '@renderer/store'
import { Model } from '@renderer/types'
import { t } from 'i18next'
import { pick } from 'lodash'
export const getModelUniqId = (m?: Model) => {
@ -18,13 +17,5 @@ export const hasModel = (m?: Model) => {
}
export function getModelName(model?: Model) {
const provider = store.getState().llm.providers.find((p) => p.id === model?.provider)
const modelName = model?.name || model?.id || ''
if (provider) {
const providerName = provider?.isSystem ? t(`provider.${provider.id}`) : provider?.name
return `${modelName} | ${providerName}`
}
return modelName
return model?.name || model?.id || ''
}

View File

@ -30,7 +30,7 @@ const persistedReducer = persistReducer(
{
key: 'cherry-studio',
storage,
version: 70,
version: 69,
blacklist: ['runtime'],
migrate
},

View File

@ -152,7 +152,7 @@ const initialState: LlmState = {
name: 'DMXAPI',
type: 'openai',
apiKey: '',
apiHost: 'https://www.dmxapi.cn',
apiHost: 'https://api.dmxapi.com',
models: SYSTEM_MODELS.dmxapi,
isSystem: true,
enabled: false

View File

@ -1071,32 +1071,6 @@ const migrateConfig = {
state.minapps.enabled.push(coze)
}
}
state.settings.gridColumns = 2
state.settings.gridPopoverTrigger = 'hover'
return state
},
'70': (state: RootState) => {
state.llm.providers.forEach((provider) => {
if (provider.id === 'dmxapi') {
provider.apiHost = 'https://www.dmxapi.cn'
}
})
return state
},
'71': (state: RootState) => {
const appIds = ['dify', 'wpslingxi', 'lechat', 'abacus', 'lambdachat']
if (state.minapps) {
appIds.forEach((id) => {
const app = DEFAULT_MIN_APPS.find((app) => app.id === id)
if (app) {
state.minapps.enabled.push(app)
}
})
}
state.settings.thoughtAutoCollapse = true
return state
}
}

View File

@ -44,8 +44,6 @@ export interface SettingsState {
mathEngine: 'MathJax' | 'KaTeX'
messageStyle: 'plain' | 'bubble'
codeStyle: CodeStyleVarious
gridColumns: number
gridPopoverTrigger: 'hover' | 'click'
// webdav 配置 host, user, pass, path
webdavHost: string
webdavUser: string
@ -69,11 +67,9 @@ export interface SettingsState {
multiModelMessageStyle: MultiModelMessageStyle
notionDatabaseID: string | null
notionApiKey: string | null
notionPageNameKey: string | null
thoughtAutoCollapse: boolean
}
export type MultiModelMessageStyle = 'horizontal' | 'vertical' | 'fold' | 'grid'
export type MultiModelMessageStyle = 'horizontal' | 'vertical' | 'fold'
const initialState: SettingsState = {
showAssistants: true,
@ -103,8 +99,6 @@ const initialState: SettingsState = {
mathEngine: 'KaTeX',
messageStyle: 'plain',
codeStyle: 'auto',
gridColumns: 2,
gridPopoverTrigger: 'hover',
webdavHost: '',
webdavUser: '',
webdavPass: '',
@ -125,9 +119,7 @@ const initialState: SettingsState = {
clickTrayToShowQuickAssistant: false,
multiModelMessageStyle: 'fold',
notionDatabaseID: '',
notionApiKey: '',
notionPageNameKey: 'Name',
thoughtAutoCollapse: true
notionApiKey: ''
}
const settingsSlice = createSlice({
@ -232,12 +224,6 @@ const settingsSlice = createSlice({
setMathEngine: (state, action: PayloadAction<'MathJax' | 'KaTeX'>) => {
state.mathEngine = action.payload
},
setGridColumns: (state, action: PayloadAction<number>) => {
state.gridColumns = action.payload
},
setGridPopoverTrigger: (state, action: PayloadAction<'hover' | 'click'>) => {
state.gridPopoverTrigger = action.payload
},
setMessageStyle: (state, action: PayloadAction<'plain' | 'bubble'>) => {
state.messageStyle = action.payload
},
@ -279,7 +265,7 @@ const settingsSlice = createSlice({
setEnableQuickAssistant: (state, action: PayloadAction<boolean>) => {
state.enableQuickAssistant = action.payload
},
setMultiModelMessageStyle: (state, action: PayloadAction<'horizontal' | 'vertical' | 'fold' | 'grid'>) => {
setMultiModelMessageStyle: (state, action: PayloadAction<'horizontal' | 'vertical' | 'fold'>) => {
state.multiModelMessageStyle = action.payload
},
setNotionDatabaseID: (state, action: PayloadAction<string>) => {
@ -287,12 +273,6 @@ const settingsSlice = createSlice({
},
setNotionApiKey: (state, action: PayloadAction<string>) => {
state.notionApiKey = action.payload
},
setNotionPageNameKey: (state, action: PayloadAction<string>) => {
state.notionPageNameKey = action.payload
},
setThoughtAutoCollapse: (state, action: PayloadAction<boolean>) => {
state.thoughtAutoCollapse = action.payload
}
}
})
@ -330,8 +310,6 @@ export const {
setCodeShowLineNumbers,
setCodeCollapsible,
setMathEngine,
setGridColumns,
setGridPopoverTrigger,
setMessageStyle,
setCodeStyle,
setTranslateModelPrompt,
@ -346,9 +324,7 @@ export const {
setEnableQuickAssistant,
setMultiModelMessageStyle,
setNotionDatabaseID,
setNotionApiKey,
setNotionPageNameKey,
setThoughtAutoCollapse
setNotionApiKey
} = settingsSlice.actions
export default settingsSlice.reducer

View File

@ -10,13 +10,6 @@ export interface ShortcutsState {
const initialState: ShortcutsState = {
shortcuts: [
...ZOOM_SHORTCUTS,
{
key: 'show_settings',
shortcut: [isMac ? 'Command' : 'Ctrl', ','],
editable: false,
enabled: true,
system: true
},
{
key: 'show_app',
shortcut: [],

View File

@ -5,7 +5,7 @@ export type Assistant = {
id: string
name: string
prompt: string
knowledge_bases?: KnowledgeBase[]
knowledge_base?: KnowledgeBase
topics: Topic[]
type: string
emoji?: string
@ -271,13 +271,4 @@ export type GenerateImageParams = {
promptEnhancement?: boolean
}
export interface TranslateHistory {
id: string
sourceText: string
targetText: string
sourceLanguage: string
targetLanguage: string
createdAt: string
}
export type SidebarIcon = 'assistants' | 'agents' | 'paintings' | 'translate' | 'minapp' | 'knowledge' | 'files'

View File

@ -1,25 +0,0 @@
export const abortMap = new Map<string, () => void>()
export const addAbortController = (id: string, abortFn: () => void) => {
let callback = abortFn
const existingCallback = abortMap.get(id)
if (existingCallback) {
callback = () => {
existingCallback?.()
abortFn()
}
}
abortMap.set(id, callback)
}
export const removeAbortController = (id: string) => {
abortMap.delete(id)
}
export const abortCompletion = (id: string) => {
const abortFn = abortMap.get(id)
if (abortFn) {
abortFn()
removeAbortController(id)
}
}

View File

@ -67,7 +67,7 @@ export const exportTopicToNotion = async (topic: Topic) => {
const response = await notion.pages.create({
parent: { database_id: notionDatabaseID },
properties: {
[store.getState().settings.notionPageNameKey || 'Name']: {
Name: {
title: [{ text: { content: topic.name } }]
}
},

View File

@ -50,7 +50,7 @@ const Inputbar: FC = () => {
const [spaceClickCount, setSpaceClickCount] = useState(0)
const spaceClickTimer = useRef<NodeJS.Timeout>()
const [isTranslating, setIsTranslating] = useState(false)
const [selectedKnowledgeBase, setSelectedKnowledgeBase] = useState<KnowledgeBase | undefined>()
const [selectedKnowledgeBase, setSelectedKnowledgeBase] = useState<KnowledgeBase>()
const isVision = useMemo(() => isVisionModel(model), [model])
const supportExts = useMemo(() => [...textExts, ...documentExts, ...(isVision ? imageExts : [])], [isVision])
@ -274,8 +274,8 @@ const Inputbar: FC = () => {
}
}, [])
const handleKnowledgeBaseSelect = (bases: KnowledgeBase[]) => {
setSelectedKnowledgeBase(bases?.[0])
const handleKnowledgeBaseSelect = (base?: KnowledgeBase) => {
setSelectedKnowledgeBase(base)
}
return (
@ -317,7 +317,7 @@ const Inputbar: FC = () => {
</Popconfirm>
</Tooltip>
<KnowledgeBaseButton
selectedBases={selectedKnowledgeBase ? [selectedKnowledgeBase] : []}
selectedBase={selectedKnowledgeBase}
onSelect={handleKnowledgeBaseSelect}
ToolbarButton={ToolbarButton}
disabled={files.length > 0}

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