Merge remote-tracking branch 'origin/main'

合并上游
This commit is contained in:
denislov 2025-02-21 13:24:13 +08:00
commit 4869898173
79 changed files with 1726 additions and 457 deletions

View File

@ -18,7 +18,7 @@ body:
options: 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 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.
required: true required: true
- label: I've looked at pinned issues and searched for existing [Open Issues](https://github.com/CherryHQ/cherry-studio/issues) and [Closed Issues]( https://github.com/CherryHQ/cherry-studio/issues?q=is%3Aissue%20state%3Aclosed%20), no similar issue was found. - 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 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'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.
required: true required: true
@ -48,8 +48,8 @@ body:
id: description id: description
attributes: attributes:
label: Bug Description label: Bug Description
description: Please be as detailed as possible when describing the problem 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... placeholder: Tell us what happened... (Remember to attach screenshots/recordings if applicable)
validations: validations:
required: true required: true
@ -57,12 +57,14 @@ body:
id: reproduction id: reproduction
attributes: attributes:
label: Steps To Reproduce label: Steps To Reproduce
description: Provide detailed steps to reproduce the issue so that our developers can reproduce the issue accurately 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.
placeholder: | placeholder: |
1. Go to '...' 1. Go to '...'
2. Click on '....' 2. Click on '....'
3. Scroll down to '....' 3. Scroll down to '....'
4. See error 4. See error
Remember to attach screenshots/recordings for each step when possible!
validations: validations:
required: true required: true

View File

@ -18,7 +18,7 @@ body:
options: 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 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.
required: true required: true
- label: I have checked the pinned issues and searched through the existing [open issues](https://github.com/CherryHQ/cherry-studio/issues) and [closed issues](https://github.com/CherryHQ/cherry-studio/issues?q=is%3Aissue%20state%3Aclosed) and did not find a similar suggestion. - 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 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." - 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 required: true
@ -50,8 +50,8 @@ body:
id: problem id: problem
attributes: attributes:
label: Is your feature request related to an existing issue? label: Is your feature request related to an existing issue?
description: Please briefly describe the problem you are experiencing. 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... placeholder: I often feel frustrated because... (Remember to attach screenshots/recordings if applicable)
validations: validations:
required: true required: true
@ -59,7 +59,7 @@ body:
id: solution id: solution
attributes: attributes:
label: Desired Solution label: Desired Solution
description: Please briefly describe what you would like to happen. description: Please briefly describe what you would like to happen. You can include mockups, screenshots, or screen recordings to better illustrate your proposed solution.
validations: validations:
required: true required: true
@ -67,10 +67,10 @@ body:
id: alternatives id: alternatives
attributes: attributes:
label: Alternative Solutions label: Alternative Solutions
description: Please briefly describe any alternative solutions or features you have considered. description: Please briefly describe any alternative solutions or features you have considered. Feel free to include screenshots or mockups of alternative approaches.
- type: textarea - type: textarea
id: additional id: additional
attributes: attributes:
label: Additional Information label: Additional Information
description: Add any other context or screenshots related to your feature request. description: Add any other context, screenshots, mockups or recordings that can help us better understand your feature request.

View File

@ -17,6 +17,8 @@ body:
options: 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 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.
required: true 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 confirm that I am here to ask questions and discuss issues, not to report bugs or request features.
required: true required: true
@ -45,8 +47,8 @@ body:
id: question id: question
attributes: attributes:
label: Your Question label: Your Question
description: Please describe your issue in detail. 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... placeholder: Please explain your issue as clearly as possible...(Remember to attach screenshots/recordings if applicable)
validations: validations:
required: true required: true
@ -54,14 +56,14 @@ body:
id: context id: context
attributes: attributes:
label: Context label: Context
description: Please provide some background information to help us better understand your question 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." placeholder: "For example: use case, solutions you've tried, etc. Don't forget to include relevant screenshots/recordings!"
- type: textarea - type: textarea
id: additional id: additional
attributes: attributes:
label: Additional Information label: Additional Information
description: Any other relevant information, screenshots, or code examples description: Any other relevant information, screenshots, recordings, or code examples that can help us better assist you
render: shell render: shell
- type: dropdown - type: dropdown

View File

@ -60,6 +60,20 @@ Cherry Studio is a desktop client that supports for multiple LLM providers, avai
- 📝 Complete Markdown Rendering - 📝 Complete Markdown Rendering
- 🤲 Easy Content Sharing - 🤲 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 # 🖥️ Develop
## IDE Setup ## IDE Setup

View File

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

View File

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

View File

@ -82,7 +82,9 @@ releaseInfo:
releaseNotes: | releaseNotes: |
消息分组支持网格模式 消息分组支持网格模式
知识库支持多选 知识库支持多选
支持库增加 DRAFTS, EPUB 知识库添加目录支持显示进度
知识库支持 DRAFTS, EPUB、代码等
知识库支持调节匹配度阈值 知识库支持调节匹配度阈值
添加 NotebookLM, Coze 小程序 添加 NotebookLM, Coze 小程序
增加话题提示词 增加话题提示词
OpenRouter 支持 Web 搜索

View File

@ -1,6 +1,6 @@
{ {
"name": "CherryStudio", "name": "CherryStudio",
"version": "0.9.25", "version": "0.9.27",
"private": true, "private": true,
"description": "A powerful AI assistant for producer.", "description": "A powerful AI assistant for producer.",
"main": "./out/main/index.js", "main": "./out/main/index.js",
@ -94,6 +94,7 @@
"@types/markdown-it": "^14", "@types/markdown-it": "^14",
"@types/md5": "^2.3.5", "@types/md5": "^2.3.5",
"@types/node": "^18.19.9", "@types/node": "^18.19.9",
"@types/pako": "^1.0.2",
"@types/react": "^18.2.48", "@types/react": "^18.2.48",
"@types/react-dom": "^18.2.18", "@types/react-dom": "^18.2.18",
"@types/react-infinite-scroll-component": "^5.0.0", "@types/react-infinite-scroll-component": "^5.0.0",

View File

@ -90,7 +90,10 @@ export const textExts = [
'.groovy', // Gradle 构建文件 '.groovy', // Gradle 构建文件
'.kts', // Kotlin Script 文件 '.kts', // Kotlin Script 文件
'.java', // Java 代码文件 '.java', // Java 代码文件
'.cs' // C# 代码文件 '.cs', // C# 代码文件
'.cpp', // C++ 代码文件
'.c', // C++ 代码文件
'.h' // C++ 头文件
] ]
export const ZOOM_SHORTCUTS = [ export const ZOOM_SHORTCUTS = [

View File

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

View File

@ -123,7 +123,15 @@ export async function addFileLoader(
// JSON类型 // JSON类型
if (['.json'].includes(file.ext)) { if (['.json'].includes(file.ext)) {
const jsonObject = JSON.parse(fileContent) 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 })) const loaderReturn = await ragApplication.addLoader(new JsonLoader({ object: jsonObject }))
return { return {
entriesAdded: loaderReturn.entriesAdded, entriesAdded: loaderReturn.entriesAdded,
@ -132,6 +140,7 @@ export async function addFileLoader(
loaderType: loaderReturn.loaderType loaderType: loaderReturn.loaderType
} }
} }
}
// 文本类型 // 文本类型
const loaderReturn = await ragApplication.addLoader( const loaderReturn = await ragApplication.addLoader(

View File

@ -15,6 +15,8 @@ import { FileType, KnowledgeBaseParams, KnowledgeItem } from '@types'
import { app } from 'electron' import { app } from 'electron'
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import { windowService } from './WindowService'
class KnowledgeService { class KnowledgeService {
private storageDir = path.join(app.getPath('userData'), 'Data', 'KnowledgeBase') private storageDir = path.join(app.getPath('userData'), 'Data', 'KnowledgeBase')
@ -83,10 +85,23 @@ class KnowledgeService {
): Promise<LoaderReturn> => { ): Promise<LoaderReturn> => {
const ragApplication = await this.getRagApplication(base) 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') { if (item.type === 'directory') {
const directory = item.content as string const directory = item.content as string
const files = getAllFiles(directory) const files = getAllFiles(directory)
const loaderPromises = files.map((file) => addFileLoader(ragApplication, file, base, forceReload)) 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 loaderResults = await Promise.all(loaderPromises) const loaderResults = await Promise.all(loaderPromises)
const uniqueIds = loaderResults.map((result) => result.uniqueId) const uniqueIds = loaderResults.map((result) => result.uniqueId)
return { return {

View File

@ -70,10 +70,12 @@ const convertShortcutRecordedByKeyboardEventKeyValueToElectronGlobalShortcutForm
return accelerator return accelerator
.map((key) => { .map((key) => {
switch (key) { switch (key) {
case 'Command':
return 'CommandOrControl'
case 'Control': case 'Control':
return 'CommandOrControl' return 'Control'
case 'Ctrl': case 'Ctrl':
return 'CommandOrControl' return 'Control'
case 'ArrowUp': case 'ArrowUp':
return 'Up' return 'Up'
case 'ArrowDown': case 'ArrowDown':

View File

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

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

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

View File

@ -1,5 +1,5 @@
/* eslint-disable react/no-unknown-property */ /* eslint-disable react/no-unknown-property */
import { CloseOutlined, ExportOutlined, PushpinOutlined, ReloadOutlined } from '@ant-design/icons' import { CloseOutlined, CodeOutlined, ExportOutlined, PushpinOutlined, ReloadOutlined } from '@ant-design/icons'
import { isMac, isWindows } from '@renderer/config/constant' import { isMac, isWindows } from '@renderer/config/constant'
import { AppLogo } from '@renderer/config/env' import { AppLogo } from '@renderer/config/env'
import { DEFAULT_MIN_APPS } from '@renderer/config/minapps' import { DEFAULT_MIN_APPS } from '@renderer/config/minapps'
@ -42,7 +42,11 @@ const PopupContainer: React.FC<Props> = ({ app, resolve }) => {
} }
MinApp.onClose = onClose MinApp.onClose = onClose
const openDevTools = () => {
if (webviewRef.current) {
webviewRef.current.openDevTools()
}
}
const onReload = () => { const onReload = () => {
if (webviewRef.current) { if (webviewRef.current) {
webviewRef.current.src = app.url webviewRef.current.src = app.url
@ -60,7 +64,7 @@ const PopupContainer: React.FC<Props> = ({ app, resolve }) => {
const newPinned = isPinned ? pinned.filter((item) => item.id !== app.id) : [...pinned, app] const newPinned = isPinned ? pinned.filter((item) => item.id !== app.id) : [...pinned, app]
updatePinnedMinapps(newPinned) updatePinnedMinapps(newPinned)
} }
const isInDevelopment = process.env.NODE_ENV === 'development'
const Title = () => { const Title = () => {
return ( return (
<TitleContainer style={{ justifyContent: 'space-between' }}> <TitleContainer style={{ justifyContent: 'space-between' }}>
@ -79,6 +83,11 @@ const PopupContainer: React.FC<Props> = ({ app, resolve }) => {
<ExportOutlined /> <ExportOutlined />
</Button> </Button>
)} )}
{isInDevelopment && (
<Button onClick={openDevTools}>
<CodeOutlined />
</Button>
)}
<Button onClick={() => onClose()}> <Button onClick={() => onClose()}>
<CloseOutlined /> <CloseOutlined />
</Button> </Button>

View File

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

View File

@ -1,10 +1,12 @@
import ThreeMinTopAppLogo from '@renderer/assets/images/apps/3mintop.png?url' 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 AIStudioLogo from '@renderer/assets/images/apps/aistudio.svg?url'
import BaiduAiAppLogo from '@renderer/assets/images/apps/baidu-ai.png?url' import BaiduAiAppLogo from '@renderer/assets/images/apps/baidu-ai.png?url'
import BaicuanAppLogo from '@renderer/assets/images/apps/baixiaoying.webp?url' import BaicuanAppLogo from '@renderer/assets/images/apps/baixiaoying.webp?url'
import BoltAppLogo from '@renderer/assets/images/apps/bolt.svg?url' import BoltAppLogo from '@renderer/assets/images/apps/bolt.svg?url'
import CozeAppLogo from '@renderer/assets/images/apps/coze.webp?url' import CozeAppLogo from '@renderer/assets/images/apps/coze.webp?url'
import DevvAppLogo from '@renderer/assets/images/apps/devv.png?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 DoubaoAppLogo from '@renderer/assets/images/apps/doubao.png?url'
import DuckDuckGoAppLogo from '@renderer/assets/images/apps/duckduckgo.webp?url' import DuckDuckGoAppLogo from '@renderer/assets/images/apps/duckduckgo.webp?url'
import FeloAppLogo from '@renderer/assets/images/apps/felo.png?url' import FeloAppLogo from '@renderer/assets/images/apps/felo.png?url'
@ -16,6 +18,8 @@ import GrokAppLogo from '@renderer/assets/images/apps/grok.png?url'
import HikaLogo from '@renderer/assets/images/apps/hika.webp?url' import HikaLogo from '@renderer/assets/images/apps/hika.webp?url'
import HuggingChatLogo from '@renderer/assets/images/apps/huggingchat.svg?url' import HuggingChatLogo from '@renderer/assets/images/apps/huggingchat.svg?url'
import KimiAppLogo from '@renderer/assets/images/apps/kimi.jpg?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 MetasoAppLogo from '@renderer/assets/images/apps/metaso.webp?url'
import NamiAiLogo from '@renderer/assets/images/apps/nm.png?url' import NamiAiLogo from '@renderer/assets/images/apps/nm.png?url'
import NamiAiSearchLogo from '@renderer/assets/images/apps/nm-search.webp?url' import NamiAiSearchLogo from '@renderer/assets/images/apps/nm-search.webp?url'
@ -29,6 +33,7 @@ import SparkDeskAppLogo from '@renderer/assets/images/apps/sparkdesk.png?url'
import ThinkAnyLogo from '@renderer/assets/images/apps/thinkany.webp?url' import ThinkAnyLogo from '@renderer/assets/images/apps/thinkany.webp?url'
import TiangongAiLogo from '@renderer/assets/images/apps/tiangong.png?url' import TiangongAiLogo from '@renderer/assets/images/apps/tiangong.png?url'
import WanZhiAppLogo from '@renderer/assets/images/apps/wanzhi.jpg?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 XiaoYiAppLogo from '@renderer/assets/images/apps/xiaoyi.webp?url'
import TencentYuanbaoAppLogo from '@renderer/assets/images/apps/yuanbao.png?url' import TencentYuanbaoAppLogo from '@renderer/assets/images/apps/yuanbao.png?url'
import YuewenAppLogo from '@renderer/assets/images/apps/yuewen.png?url' import YuewenAppLogo from '@renderer/assets/images/apps/yuewen.png?url'
@ -314,6 +319,41 @@ export const DEFAULT_MIN_APPS: MinAppType[] = [
logo: CozeAppLogo, logo: CozeAppLogo,
url: 'https://www.coze.com/space', url: 'https://www.coze.com/space',
bodered: true 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,7 +150,8 @@ const visionAllowedModels = [
'gpt-4o(?:-[\\w-]+)?', 'gpt-4o(?:-[\\w-]+)?',
'chatgpt-4o(?:-[\\w-]+)?', 'chatgpt-4o(?:-[\\w-]+)?',
'o1(?:-[\\w-]+)?', 'o1(?:-[\\w-]+)?',
'deepseek-vl(?:[\\w-]+)?' 'deepseek-vl(?:[\\w-]+)?',
'kimi-latest'
] ]
const visionExcludedModels = ['gpt-4-\\d+-preview', 'gpt-4-turbo-preview', 'gpt-4-32k', 'gpt-4-\\d+'] const visionExcludedModels = ['gpt-4-\\d+-preview', 'gpt-4-turbo-preview', 'gpt-4-32k', 'gpt-4-\\d+']
@ -163,8 +164,7 @@ export const VISION_REGEX = new RegExp(
export const TEXT_TO_IMAGE_REGEX = /flux|diffusion|stabilityai|sd-|dall|cogview|janus/i 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-]+)?|.*\b(?:reasoner|thinking)\b.*|.*-[rR]\d+.*)$/i
export const EMBEDDING_REGEX = export const EMBEDDING_REGEX = /(?:^text-|embed|bge-|e5-|LLM2Vec|retrieval|uae-|gte-|jina-clip|jina-embeddings)/i
/(?:^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 const NOT_SUPPORTED_REGEX = /(?:^tts|rerank|whisper|speech)/i
export function getModelLogo(modelId: string) { export function getModelLogo(modelId: string) {
@ -178,6 +178,7 @@ export function getModelLogo(modelId: string) {
pixtral: isLight ? PixtralModelLogo : PixtralModelLogoDark, pixtral: isLight ? PixtralModelLogo : PixtralModelLogoDark,
jina: isLight ? JinaModelLogo : JinaModelLogoDark, jina: isLight ? JinaModelLogo : JinaModelLogoDark,
abab: isLight ? MinimaxModelLogo : MinimaxModelLogoDark, abab: isLight ? MinimaxModelLogo : MinimaxModelLogoDark,
minimax: isLight ? MinimaxModelLogo : MinimaxModelLogoDark,
o3: isLight ? ChatGPTo1ModelLogo : ChatGPTo1ModelLogoDark, o3: isLight ? ChatGPTo1ModelLogo : ChatGPTo1ModelLogoDark,
o1: isLight ? ChatGPTo1ModelLogo : ChatGPTo1ModelLogoDark, o1: isLight ? ChatGPTo1ModelLogo : ChatGPTo1ModelLogoDark,
'gpt-3': isLight ? ChatGPT35ModelLogo : ChatGPT35ModelLogoDark, 'gpt-3': isLight ? ChatGPT35ModelLogo : ChatGPT35ModelLogoDark,
@ -194,13 +195,16 @@ export function getModelLogo(modelId: string) {
glm: isLight ? ChatGLMModelLogo : ChatGLMModelLogoDark, glm: isLight ? ChatGLMModelLogo : ChatGLMModelLogoDark,
deepseek: isLight ? DeepSeekModelLogo : DeepSeekModelLogoDark, deepseek: isLight ? DeepSeekModelLogo : DeepSeekModelLogoDark,
qwen: isLight ? QwenModelLogo : QwenModelLogoDark, qwen: isLight ? QwenModelLogo : QwenModelLogoDark,
qwq: isLight ? QwenModelLogo : QwenModelLogoDark, 'qwq-': isLight ? QwenModelLogo : QwenModelLogoDark,
'qvq-': isLight ? QwenModelLogo : QwenModelLogoDark,
Omni: isLight ? QwenModelLogo : QwenModelLogoDark,
gemma: isLight ? GemmaModelLogo : GemmaModelLogoDark, gemma: isLight ? GemmaModelLogo : GemmaModelLogoDark,
'yi-': isLight ? YiModelLogo : YiModelLogoDark, 'yi-': isLight ? YiModelLogo : YiModelLogoDark,
llama: isLight ? LlamaModelLogo : LlamaModelLogoDark, llama: isLight ? LlamaModelLogo : LlamaModelLogoDark,
mixtral: isLight ? MistralModelLogo : MistralModelLogo, mixtral: isLight ? MistralModelLogo : MistralModelLogo,
mistral: isLight ? MistralModelLogo : MistralModelLogoDark, mistral: isLight ? MistralModelLogo : MistralModelLogoDark,
moonshot: isLight ? MoonshotModelLogo : MoonshotModelLogoDark, moonshot: isLight ? MoonshotModelLogo : MoonshotModelLogoDark,
kimi: isLight ? MoonshotModelLogo : MoonshotModelLogoDark,
phi: isLight ? MicrosoftModelLogo : MicrosoftModelLogoDark, phi: isLight ? MicrosoftModelLogo : MicrosoftModelLogoDark,
baichuan: isLight ? BaichuanModelLogo : BaichuanModelLogoDark, baichuan: isLight ? BaichuanModelLogo : BaichuanModelLogoDark,
claude: isLight ? ClaudeModelLogo : ClaudeModelLogoDark, claude: isLight ? ClaudeModelLogo : ClaudeModelLogoDark,
@ -1599,6 +1603,10 @@ export function isEmbeddingModel(model: Model): boolean {
return false return false
} }
if (model.provider === 'doubao') {
return EMBEDDING_REGEX.test(model.name)
}
return EMBEDDING_REGEX.test(model.id) || model.type?.includes('embedding') || false return EMBEDDING_REGEX.test(model.id) || model.type?.includes('embedding') || false
} }
@ -1607,6 +1615,10 @@ export function isVisionModel(model: Model): boolean {
return false 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 return VISION_REGEX.test(model.id) || model.type?.includes('vision') || false
} }
@ -1615,6 +1627,10 @@ export function isReasoningModel(model: Model): boolean {
return false 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 return REASONING_REGEX.test(model.id) || model.type?.includes('reasoning') || false
} }
@ -1667,6 +1683,16 @@ export function isWebSearchModel(model: Model): boolean {
return model?.id?.startsWith('glm-4-') 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 return false
} }
@ -1679,6 +1705,21 @@ export function getOpenAIWebSearchParams(assistant: Assistant, model: Model): Re
return { enable_enhancement: true } 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 { return {
tools: webSearchTools tools: webSearchTools
} }

View File

@ -212,13 +212,13 @@ export const PROVIDER_CONFIG = {
}, },
dmxapi: { dmxapi: {
api: { api: {
url: 'https://www.dmxapi.com' url: 'https://www.dmxapi.cn'
}, },
websites: { websites: {
official: 'https://www.dmxapi.com/register?aff=81aj/', official: 'https://www.dmxapi.cn/register?aff=bwwY',
apiKey: 'https://www.dmxapi.com/register?aff=81aj', apiKey: 'https://www.dmxapi.cn/register?aff=bwwY',
docs: 'https://dmxapi.com/models.html#code-block', docs: 'https://dmxapi.cn/models.html#code-block',
models: 'https://www.dmxapi.com/pricing' models: 'https://www.dmxapi.cn/pricing'
} }
}, },
perplexity: { perplexity: {

View File

@ -55,5 +55,20 @@ export const TranslateLanguageOptions = [
value: 'arabic', value: 'arabic',
label: i18n.t('languages.arabic'), label: i18n.t('languages.arabic'),
emoji: '🇸🇦' 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 const mappedLanguage = languageMap[language] || language
code = code.trimEnd() code = code?.trimEnd() ?? ''
const escapedCode = code?.replace(/[<>]/g, (char) => ({ '<': '&lt;', '>': '&gt;' })[char]!) const escapedCode = code?.replace(/[<>]/g, (char) => ({ '<': '&lt;', '>': '&gt;' })[char]!)
try { try {

View File

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

View File

@ -0,0 +1,17 @@
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

@ -198,6 +198,27 @@ export const useKnowledge = (baseId: string) => {
return base?.items.filter((item) => item.type === type && item.processingStatus !== undefined) || [] 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 = () => { const clearCompleted = () => {
dispatch(clearCompletedProcessing({ baseId })) dispatch(clearCompletedProcessing({ baseId }))
@ -280,6 +301,7 @@ export const useKnowledge = (baseId: string) => {
refreshItem, refreshItem,
getProcessingStatus, getProcessingStatus,
getProcessingItemsByType, getProcessingItemsByType,
getDirectoryProcessingPercent,
clearCompleted, clearCompleted,
clearAll, clearAll,
removeItem, removeItem,

View File

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

View File

@ -51,6 +51,7 @@
"settings.reasoning_effort.high": "high", "settings.reasoning_effort.high": "high",
"settings.reasoning_effort.low": "low", "settings.reasoning_effort.low": "low",
"settings.reasoning_effort.medium": "medium", "settings.reasoning_effort.medium": "medium",
"settings.reasoning_effort.off": "off",
"settings.reasoning_effort.tip": "Only supports reasoning models", "settings.reasoning_effort.tip": "Only supports reasoning models",
"title": "Assistants" "title": "Assistants"
}, },
@ -120,6 +121,8 @@
"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.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": "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.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", "suggestions.title": "Suggested Questions",
"thinking": "Thinking", "thinking": "Thinking",
"topics.auto_rename": "Auto Rename", "topics.auto_rename": "Auto Rename",
@ -136,10 +139,13 @@
"topics.pinned": "Pinned Topics", "topics.pinned": "Pinned Topics",
"topics.title": "Topics", "topics.title": "Topics",
"topics.unpinned": "Unpinned Topics", "topics.unpinned": "Unpinned Topics",
"topics.delete.shortcut": "Hold {{key}} to delete directly",
"translate": "Translate", "translate": "Translate",
"topics.prompt": "Topic Prompts", "topics.prompt": "Topic Prompts",
"topics.prompt.tips": "Topic Prompts: Additional supplementary prompts provided for the current topic", "topics.prompt.tips": "Topic Prompts: Additional supplementary prompts provided for the current topic",
"topics.prompt.edit.title": "Edit Topic Prompts" "topics.prompt.edit.title": "Edit Topic Prompts",
"artifacts.button.openExternal": "Open in external browser",
"artifacts.preview.openExternal.error.content": "Error opening the external browser."
}, },
"common": { "common": {
"add": "Add", "add": "Add",
@ -314,7 +320,8 @@
"korean": "Korean", "korean": "Korean",
"portuguese": "Portuguese", "portuguese": "Portuguese",
"russian": "Russian", "russian": "Russian",
"spanish": "Spanish" "spanish": "Spanish",
"german": "German"
}, },
"mermaid": { "mermaid": {
"download": { "download": {
@ -331,6 +338,18 @@
}, },
"title": "Mermaid Diagram" "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": { "message": {
"api.check.model.title": "Select the model to use for detection", "api.check.model.title": "Select the model to use for detection",
"api.connection.failed": "Connection failed", "api.connection.failed": "Connection failed",
@ -352,7 +371,7 @@
"error.invalid.enter.model": "Please select a model", "error.invalid.enter.model": "Please select a model",
"error.invalid.proxy.url": "Invalid proxy URL", "error.invalid.proxy.url": "Invalid proxy URL",
"error.invalid.webdav": "Invalid WebDAV settings", "error.invalid.webdav": "Invalid WebDAV settings",
"error.notion.export": "Notion import failed", "error.notion.export": "Failed to export to Notion. Please check connection status and configuration according to documentation",
"error.notion.no_api_key": "Notion ApiKey or Notion DatabaseID is not configured", "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.content": "Deleting a group message will delete the user's question and all assistant's answers",
"group.delete.title": "Delete Group Message", "group.delete.title": "Delete Group Message",
@ -374,13 +393,13 @@
"reset.double.confirm.title": "DATA LOST !!!", "reset.double.confirm.title": "DATA LOST !!!",
"restore.success": "Restored successfully", "restore.success": "Restored successfully",
"save.success.title": "Saved successfully", "save.success.title": "Saved successfully",
"success.notion.export": "Notion import successful", "success.notion.export": "Successfully exported to Notion",
"switch.disabled": "Please wait for the current reply to complete", "switch.disabled": "Please wait for the current reply to complete",
"topic.added": "New topic added", "topic.added": "New topic added",
"upgrade.success.button": "Restart", "upgrade.success.button": "Restart",
"upgrade.success.content": "Please restart the application to complete the upgrade", "upgrade.success.content": "Please restart the application to complete the upgrade",
"upgrade.success.title": "Upgrade successfully", "upgrade.success.title": "Upgrade successfully",
"warn.notion.exporting": "Notion is importing, please do not import repeatedly", "warn.notion.exporting": "Exporting to Notion, please do not request export repeatedly!",
"error.invalid.api.host": "Invalid API Host", "error.invalid.api.host": "Invalid API Host",
"error.invalid.api.key": "Invalid API Key" "error.invalid.api.key": "Invalid API Key"
}, },
@ -563,35 +582,42 @@
"notion.api_key_placeholder": "Enter Notion API Key", "notion.api_key_placeholder": "Enter Notion API Key",
"notion.database_id": "Notion Database ID", "notion.database_id": "Notion Database ID",
"notion.database_id_placeholder": "Enter 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.title": "Notion Configuration",
"notion.help": "Notion Configuration Documentation",
"notion.check": { "notion.check": {
"button": "Check", "button": "Check",
"fail": "Connection failed, please check the configuration", "fail": "Connection failed, please check network and Api_key and Database_id",
"success": "Connection successful", "success": "Connection successful",
"error": "Connection error, please check the network", "error": "Connection error, please check network configuration and Api_key and Database_id",
"empty_api_key": "Api_key is not configured", "empty_api_key": "Api_key is not configured",
"empty_database_id": "Database_id is not configured" "empty_database_id": "Database_id is not configured"
}, },
"title": "Data Settings", "title": "Data Settings",
"webdav.autoSync": "Auto Backup", "webdav": {
"webdav.autoSync.off": "Off", "autoSync": "Auto Backup",
"webdav.backup.button": "Backup to WebDAV", "autoSync.off": "Off",
"webdav.host": "WebDAV Host", "backup.button": "Backup to WebDAV",
"webdav.host.placeholder": "http://localhost:8080", "host": "WebDAV Host",
"webdav.hours": "Hours", "host.placeholder": "http://localhost:8080",
"webdav.lastSync": "Last Backup", "minute_interval_one": "{{count}} minute",
"webdav.minutes": "Minutes", "minute_interval_other": "{{count}} minutes",
"webdav.noSync": "Waiting for next backup", "hour_interval_one": "{{count}} hour",
"webdav.password": "WebDAV Password", "hour_interval_other": "{{count}} hours",
"webdav.path": "WebDAV Path", "lastSync": "Last Backup",
"webdav.path.placeholder": "/backup", "noSync": "Waiting for next backup",
"webdav.restore.button": "Restore from WebDAV", "password": "WebDAV Password",
"webdav.restore.content": "Restore from WebDAV will overwrite the current data, continue?", "path": "WebDAV Path",
"webdav.restore.title": "Restore from WebDAV", "path.placeholder": "/backup",
"webdav.syncError": "Backup Error", "restore.button": "Restore from WebDAV",
"webdav.syncStatus": "Backup Status", "restore.content": "Restore from WebDAV will overwrite the current data, continue?",
"webdav.title": "WebDAV", "restore.title": "Restore from WebDAV",
"webdav.user": "WebDAV User" "syncError": "Backup Error",
"syncStatus": "Backup Status",
"title": "WebDAV",
"user": "WebDAV User"
}
}, },
"display.custom.css": "Custom CSS", "display.custom.css": "Custom CSS",
"display.custom.css.placeholder": "/* Put custom CSS here */", "display.custom.css.placeholder": "/* Put custom CSS here */",
@ -734,7 +760,8 @@
"toggle_show_topics": "Toggle Topics", "toggle_show_topics": "Toggle Topics",
"zoom_in": "Zoom In", "zoom_in": "Zoom In",
"zoom_out": "Zoom Out", "zoom_out": "Zoom Out",
"zoom_reset": "Reset Zoom" "zoom_reset": "Reset Zoom",
"show_settings": "Open Settings"
}, },
"theme.auto": "Auto", "theme.auto": "Auto",
"theme.dark": "Dark", "theme.dark": "Dark",
@ -753,6 +780,7 @@
"translate": { "translate": {
"any.language": "Any language", "any.language": "Any language",
"button.translate": "Translate", "button.translate": "Translate",
"tooltip.newline": "Newline",
"close": "Close", "close": "Close",
"confirm": { "confirm": {
"content": "Translation will replace the original text, continue?", "content": "Translation will replace the original text, continue?",
@ -763,7 +791,14 @@
"input.placeholder": "Enter text to translate", "input.placeholder": "Enter text to translate",
"output.placeholder": "Translation", "output.placeholder": "Translation",
"processing": "Translation in progress...", "processing": "Translation in progress...",
"title": "Translation" "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?"
}
}, },
"tray": { "tray": {
"quit": "Quit", "quit": "Quit",

View File

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

View File

@ -52,6 +52,7 @@
"settings.reasoning_effort.high": "Длинная", "settings.reasoning_effort.high": "Длинная",
"settings.reasoning_effort.low": "Короткая", "settings.reasoning_effort.low": "Короткая",
"settings.reasoning_effort.medium": "Средняя", "settings.reasoning_effort.medium": "Средняя",
"settings.reasoning_effort.off": "Выключено",
"settings.reasoning_effort.tip": "Эта настройка поддерживается только моделями с рассуждением" "settings.reasoning_effort.tip": "Эта настройка поддерживается только моделями с рассуждением"
}, },
"auth": { "auth": {
@ -120,6 +121,8 @@
"settings.top_p.tip": "Значение по умолчанию 1, чем меньше значение, тем меньше вариативности в ответах, тем проще понять, чем больше значение, тем больше вариативности в ответах, тем больше разнообразие", "settings.top_p.tip": "Значение по умолчанию 1, чем меньше значение, тем меньше вариативности в ответах, тем проще понять, чем больше значение, тем больше вариативности в ответах, тем больше разнообразие",
"settings.max_tokens.confirm": "Включить лимит максимальных токенов", "settings.max_tokens.confirm": "Включить лимит максимальных токенов",
"settings.max_tokens.confirm_content": "Включить лимит максимальных токенов, влияет на длину результата. Нужно учитывать контекст модели, иначе будет ошибка", "settings.max_tokens.confirm_content": "Включить лимит максимальных токенов, влияет на длину результата. Нужно учитывать контекст модели, иначе будет ошибка",
"settings.thought_auto_collapse": "Автоматически сворачивать содержание мыслей",
"settings.thought_auto_collapse.tip": "Автоматически сворачивать содержание мыслей после завершения размышления",
"suggestions.title": "Предложенные вопросы", "suggestions.title": "Предложенные вопросы",
"thinking": "Мыслим", "thinking": "Мыслим",
"topics.auto_rename": "Автопереименование", "topics.auto_rename": "Автопереименование",
@ -136,10 +139,13 @@
"topics.pinned": "Закрепленные темы", "topics.pinned": "Закрепленные темы",
"topics.title": "Топики", "topics.title": "Топики",
"topics.unpinned": "Открепленные темы", "topics.unpinned": "Открепленные темы",
"topics.delete.shortcut": "Удерживайте {{key}} для мгновенного удаления",
"translate": "Перевести", "translate": "Перевести",
"topics.prompt": "Тематические подсказки", "topics.prompt": "Тематические подсказки",
"topics.prompt.tips": "Тематические подсказки: Дополнительные подсказки, предоставленные для текущей темы", "topics.prompt.tips": "Тематические подсказки: Дополнительные подсказки, предоставленные для текущей темы",
"topics.prompt.edit.title": "Редактировать подсказки темы" "topics.prompt.edit.title": "Редактировать подсказки темы",
"artifacts.button.openExternal": "Открыть во внешнем браузере",
"artifacts.preview.openExternal.error.content": "Внешний браузер открылся с ошибкой"
}, },
"common": { "common": {
"add": "Добавить", "add": "Добавить",
@ -309,6 +315,7 @@
"chinese-traditional": "Китайский традиционный", "chinese-traditional": "Китайский традиционный",
"english": "Английский", "english": "Английский",
"french": "Французский", "french": "Французский",
"german": "Немецкий",
"italian": "Итальянский", "italian": "Итальянский",
"japanese": "Японский", "japanese": "Японский",
"korean": "Корейский", "korean": "Корейский",
@ -352,7 +359,7 @@
"error.invalid.enter.model": "Пожалуйста, выберите модель", "error.invalid.enter.model": "Пожалуйста, выберите модель",
"error.invalid.proxy.url": "Неверный URL прокси", "error.invalid.proxy.url": "Неверный URL прокси",
"error.invalid.webdav": "Неверные настройки WebDAV", "error.invalid.webdav": "Неверные настройки WebDAV",
"error.notion.export": "Импорт в Notion не удался", "error.notion.export": "Ошибка экспорта в Notion, пожалуйста, проверьте состояние подключения и настройки в документации",
"error.notion.no_api_key": "Notion ApiKey или Notion DatabaseID не настроен", "error.notion.no_api_key": "Notion ApiKey или Notion DatabaseID не настроен",
"group.delete.content": "Удаление группы сообщений удалит пользовательский вопрос и все ответы помощника", "group.delete.content": "Удаление группы сообщений удалит пользовательский вопрос и все ответы помощника",
"group.delete.title": "Удалить группу сообщений", "group.delete.title": "Удалить группу сообщений",
@ -374,13 +381,13 @@
"reset.double.confirm.title": "ДАННЫЕ БУДУТ УТЕРЯНЫ !!!", "reset.double.confirm.title": "ДАННЫЕ БУДУТ УТЕРЯНЫ !!!",
"restore.success": "Успешно восстановлено", "restore.success": "Успешно восстановлено",
"save.success.title": "Успешно сохранено", "save.success.title": "Успешно сохранено",
"success.notion.export": "Импорт в Notion выполнен успешно", "success.notion.export": "Успешный экспорт в Notion",
"switch.disabled": "Пожалуйста, дождитесь завершения текущего ответа", "switch.disabled": "Пожалуйста, дождитесь завершения текущего ответа",
"topic.added": "Новый топик добавлен", "topic.added": "Новый топик добавлен",
"upgrade.success.button": "Перезапустить", "upgrade.success.button": "Перезапустить",
"upgrade.success.content": "Пожалуйста, перезапустите приложение для завершения обновления", "upgrade.success.content": "Пожалуйста, перезапустите приложение для завершения обновления",
"upgrade.success.title": "Обновление успешно", "upgrade.success.title": "Обновление успешно",
"warn.notion.exporting": "Идет импорт в Notion, пожалуйста, не повторяйте импорт", "warn.notion.exporting": "Экспортируется в Notion, пожалуйста, не отправляйте повторные запросы!",
"error.invalid.api.host": "Неверный API адрес", "error.invalid.api.host": "Неверный API адрес",
"error.invalid.api.key": "Неверный API ключ" "error.invalid.api.key": "Неверный API ключ"
}, },
@ -563,35 +570,44 @@
"notion.api_key_placeholder": "Введите ключ API Notion", "notion.api_key_placeholder": "Введите ключ API Notion",
"notion.database_id": "ID базы данных Notion", "notion.database_id": "ID базы данных Notion",
"notion.database_id_placeholder": "Введите ID базы данных Notion", "notion.database_id_placeholder": "Введите ID базы данных Notion",
"notion.page_name_key": "Название поля заголовка страницы",
"notion.page_name_key_placeholder": "Введите название поля заголовка страницы, по умолчанию Name",
"notion.title": "Настройки Notion", "notion.title": "Настройки Notion",
"notion.help": "Документация по настройке Notion",
"notion.check": { "notion.check": {
"button": "Проверить", "button": "Проверить",
"fail": "Ошибка подключения, проверьте настройки", "fail": "Не удалось подключиться, пожалуйста, проверьте сеть и правильность Api_key и Database_id",
"success": "Подключение успешно", "success": "Подключение успешно",
"error": "Ошибка подключения, проверьте сеть", "error": "Аномалия в подключении, пожалуйста, проверьте настройки сети, а также правильность Api_key и Database_id",
"empty_api_key": "Не настроен Api_key", "empty_api_key": "Не настроен Api_key",
"empty_database_id": "Не настроен Database_id" "empty_database_id": "Не настроен Database_id"
}, },
"title": "Настройки данных", "title": "Настройки данных",
"webdav.autoSync": "Автоматическое резервное копирование", "webdav": {
"webdav.autoSync.off": "Выключено", "autoSync": "Автоматическое резервное копирование",
"webdav.backup.button": "Резервное копирование на WebDAV", "autoSync.off": "Выключено",
"webdav.host": "Хост WebDAV", "backup.button": "Резервное копирование на WebDAV",
"webdav.host.placeholder": "http://localhost:8080", "host": "Хост WebDAV",
"webdav.hours": "часов", "host.placeholder": "http://localhost:8080",
"webdav.lastSync": "Последняя синхронизация", "minute_interval_one": "{{count}} минута",
"webdav.minutes": "минут", "minute_interval_few": "{{count}} минуты",
"webdav.noSync": "Ожидание следующего резервного копирования", "minute_interval_many": "{{count}} минут",
"webdav.password": "Пароль WebDAV", "hour_interval_one": "{{count}} час",
"webdav.path": "Путь WebDAV", "hour_interval_few": "{{count}} часа",
"webdav.path.placeholder": "/backup", "hour_interval_many": "{{count}} часов",
"webdav.restore.button": "Восстановление с WebDAV", "lastSync": "Последняя синхронизация",
"webdav.restore.content": "Восстановление с WebDAV перезапишет текущие данные, продолжить?", "noSync": "Ожидание следующего резервного копирования",
"webdav.restore.title": "Восстановление с WebDAV", "password": "Пароль WebDAV",
"webdav.syncError": "Ошибка резервного копирования", "path": "Путь WebDAV",
"webdav.syncStatus": "Статус резервного копирования", "path.placeholder": "/backup",
"webdav.title": "WebDAV", "restore.button": "Восстановление с WebDAV",
"webdav.user": "Пользователь WebDAV" "restore.content": "Восстановление с WebDAV перезапишет текущие данные, продолжить?",
"restore.title": "Восстановление с WebDAV",
"syncError": "Ошибка резервного копирования",
"syncStatus": "Статус резервного копирования",
"title": "WebDAV",
"user": "Пользователь WebDAV"
}
}, },
"display.custom.css": "Пользовательский CSS", "display.custom.css": "Пользовательский CSS",
"display.custom.css.placeholder": "/* Здесь введите пользовательский CSS */", "display.custom.css.placeholder": "/* Здесь введите пользовательский CSS */",
@ -733,7 +749,8 @@
"toggle_show_topics": "Переключить отображение топиков", "toggle_show_topics": "Переключить отображение топиков",
"zoom_in": "Увеличить", "zoom_in": "Увеличить",
"zoom_out": "Уменьшить", "zoom_out": "Уменьшить",
"zoom_reset": "Сбросить масштаб" "zoom_reset": "Сбросить масштаб",
"show_settings": "Открыть настройки"
}, },
"theme.auto": "Автоматически", "theme.auto": "Автоматически",
"theme.dark": "Темная", "theme.dark": "Темная",
@ -753,6 +770,7 @@
"translate": { "translate": {
"any.language": "Любой язык", "any.language": "Любой язык",
"button.translate": "Перевести", "button.translate": "Перевести",
"tooltip.newline": "Перевести",
"close": "Закрыть", "close": "Закрыть",
"confirm": { "confirm": {
"content": "Перевод заменит исходный текст, продолжить?", "content": "Перевод заменит исходный текст, продолжить?",

View File

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

View File

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

View File

@ -25,7 +25,7 @@ type FieldType = {
id: string id: string
name: string name: string
prompt: string prompt: string
knowledge_base_id: string[] knowledge_base_ids: string[]
} }
const PopupContainer: React.FC<Props> = ({ resolve }) => { const PopupContainer: React.FC<Props> = ({ resolve }) => {
@ -57,9 +57,9 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
const _agent: Agent = { const _agent: Agent = {
id: uuid(), id: uuid(),
name: values.name, name: values.name,
knowledge_bases: values.knowledge_base_id knowledge_bases: values.knowledge_base_ids
.map((id) => knowledgeState.bases.find((t) => t.id === id)) ?.map((id) => knowledgeState.bases.find((t) => t.id === id))
.filter((base): base is KnowledgeBase => base !== undefined), ?.filter((base): base is KnowledgeBase => base !== undefined),
emoji: _emoji, emoji: _emoji,
prompt: values.prompt, prompt: values.prompt,
defaultModel: getDefaultModel(), defaultModel: getDefaultModel(),
@ -156,7 +156,7 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
/> />
</div> </div>
{showKnowledgeIcon && ( {showKnowledgeIcon && (
<Form.Item name="knowledge_base_id" label={t('agents.add.knowledge_base')} rules={[{ required: false }]}> <Form.Item name="knowledge_base_ids" label={t('agents.add.knowledge_base')} rules={[{ required: false }]}>
<Select <Select
mode="multiple" mode="multiple"
allowClear allowClear

View File

@ -27,6 +27,7 @@ import store, { useAppDispatch, useAppSelector } from '@renderer/store'
import { setGenerating, setSearching } from '@renderer/store/runtime' import { setGenerating, setSearching } from '@renderer/store/runtime'
import { Assistant, FileType, KnowledgeBase, Message, Model, Topic } from '@renderer/types' import { Assistant, FileType, KnowledgeBase, Message, Model, Topic } from '@renderer/types'
import { classNames, delay, getFileExtension, uuid } from '@renderer/utils' import { classNames, delay, getFileExtension, uuid } from '@renderer/utils'
import { abortCompletion } from '@renderer/utils/abortController'
import { documentExts, imageExts, textExts } from '@shared/config/constant' import { documentExts, imageExts, textExts } from '@shared/config/constant'
import { Button, Popconfirm, Tooltip } from 'antd' import { Button, Popconfirm, Tooltip } from 'antd'
import TextArea, { TextAreaRef } from 'antd/es/input/TextArea' import TextArea, { TextAreaRef } from 'antd/es/input/TextArea'
@ -85,7 +86,7 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
const [selectedKnowledgeBases, setSelectedKnowledgeBases] = useState<KnowledgeBase[]>([]) const [selectedKnowledgeBases, setSelectedKnowledgeBases] = useState<KnowledgeBase[]>([])
const [mentionModels, setMentionModels] = useState<Model[]>([]) const [mentionModels, setMentionModels] = useState<Model[]>([])
const [isMentionPopupOpen, setIsMentionPopupOpen] = useState(false) const [isMentionPopupOpen, setIsMentionPopupOpen] = useState(false)
const currentMessageId = useRef<string>()
const isVision = useMemo(() => isVisionModel(model), [model]) const isVision = useMemo(() => isVisionModel(model), [model])
const supportExts = useMemo(() => [...textExts, ...documentExts, ...(isVision ? imageExts : [])], [isVision]) const supportExts = useMemo(() => [...textExts, ...documentExts, ...(isVision ? imageExts : [])], [isVision])
@ -133,7 +134,7 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
if (mentionModels.length > 0) { if (mentionModels.length > 0) {
message.mentions = mentionModels message.mentions = mentionModels
} }
currentMessageId.current = message.id
EventEmitter.emit(EVENT_NAMES.SEND_MESSAGE, message) EventEmitter.emit(EVENT_NAMES.SEND_MESSAGE, message)
setText('') setText('')
@ -241,6 +242,11 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
sendMessage() sendMessage()
return event.preventDefault() 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 () => { const addNewTopic = useCallback(async () => {
@ -269,6 +275,9 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic }) => {
} }
const onPause = () => { const onPause = () => {
if (currentMessageId.current) {
abortCompletion(currentMessageId.current)
}
window.keyv.set(EVENT_NAMES.CHAT_COMPLETION_PAUSED, true) window.keyv.set(EVENT_NAMES.CHAT_COMPLETION_PAUSED, true)
store.dispatch(setGenerating(false)) store.dispatch(setGenerating(false))
} }

View File

@ -174,12 +174,13 @@ const MentionModelsButton: FC<Props> = ({ mentionModels, onMentionModel: onSelec
loadPinnedModels() loadPinnedModels()
}, []) }, [])
// Scroll to the first menu item when the mode selection menu opens
useLayoutEffect(() => { useLayoutEffect(() => {
if (isOpen && flatModelItems.length > 0 && itemRefs.current[0]) { if (isOpen && selectedIndex > -1 && itemRefs.current[selectedIndex]) {
itemRefs.current[0].scrollIntoView({ block: 'nearest' }) requestAnimationFrame(() => {
itemRefs.current[selectedIndex]?.scrollIntoView({ block: 'nearest' })
})
} }
}, [isOpen, flatModelItems]) }, [isOpen, selectedIndex])
useEffect(() => { useEffect(() => {
const showModelSelector = () => { const showModelSelector = () => {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -202,7 +202,7 @@ const MessageWrapper = styled(Scrollbar)<MessageWrapperProps>`
return props.$selected ? 'block' : 'none' return props.$selected ? 'block' : 'none'
} }
if (props.$layout === 'horizontal') { if (props.$layout === 'horizontal') {
return 'inline-flex' return 'inline-block'
} }
return 'block' return 'block'
}}; }};

View File

@ -1,6 +1,7 @@
import { CheckOutlined } from '@ant-design/icons'
import { useSettings } from '@renderer/hooks/useSettings' import { useSettings } from '@renderer/hooks/useSettings'
import { Message } from '@renderer/types' import { Message } from '@renderer/types'
import { Collapse } from 'antd' import { Collapse, message as antdMessage, Tooltip } from 'antd'
import { FC, useEffect, useMemo, useState } from 'react' import { FC, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import BarLoader from 'react-spinners/BarLoader' import BarLoader from 'react-spinners/BarLoader'
@ -14,9 +15,10 @@ interface Props {
const MessageThought: FC<Props> = ({ message }) => { const MessageThought: FC<Props> = ({ message }) => {
const [activeKey, setActiveKey] = useState<'thought' | ''>('thought') const [activeKey, setActiveKey] = useState<'thought' | ''>('thought')
const [copied, setCopied] = useState(false)
const isThinking = !message.content const isThinking = !message.content
const { t } = useTranslation() const { t } = useTranslation()
const { messageFont, fontSize } = useSettings() const { messageFont, fontSize, thoughtAutoCollapse } = useSettings()
const fontFamily = useMemo(() => { const fontFamily = useMemo(() => {
return messageFont === 'serif' return messageFont === 'serif'
? 'serif' ? 'serif'
@ -24,13 +26,22 @@ const MessageThought: FC<Props> = ({ message }) => {
}, [messageFont]) }, [messageFont])
useEffect(() => { useEffect(() => {
if (!isThinking) setActiveKey('') if (!isThinking && thoughtAutoCollapse) setActiveKey('')
}, [isThinking]) }, [isThinking, thoughtAutoCollapse])
if (!message.reasoning_content) { if (!message.reasoning_content) {
return null 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 thinkingTime = message.metrics?.time_thinking_millsec || 0
const thinkingTimeSeconds = (thinkingTime / 1000).toFixed(1) const thinkingTimeSeconds = (thinkingTime / 1000).toFixed(1)
const isPaused = message.status === 'paused' const isPaused = message.status === 'paused'
@ -50,6 +61,20 @@ const MessageThought: FC<Props> = ({ message }) => {
{isThinking ? t('chat.thinking') : t('chat.deeply_thought', { secounds: thinkingTimeSeconds })} {isThinking ? t('chat.thinking') : t('chat.deeply_thought', { secounds: thinkingTimeSeconds })}
</TinkingText> </TinkingText>
{isThinking && !isPaused && <BarLoader color="#9254de" />} {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>
)}
</MessageTitleLabel> </MessageTitleLabel>
), ),
children: ( children: (
@ -79,4 +104,32 @@ const TinkingText = styled.span`
color: var(--color-text-2); 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 export default MessageThought

View File

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

View File

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

View File

@ -27,7 +27,8 @@ import {
setPasteLongTextThreshold, setPasteLongTextThreshold,
setRenderInputMessageAsMarkdown, setRenderInputMessageAsMarkdown,
setShowInputEstimatedTokens, setShowInputEstimatedTokens,
setShowMessageDivider setShowMessageDivider,
setThoughtAutoCollapse
} from '@renderer/store/settings' } from '@renderer/store/settings'
import { Assistant, AssistantSettings, ThemeMode, TranslateLanguageVarious } from '@renderer/types' import { Assistant, AssistantSettings, ThemeMode, TranslateLanguageVarious } from '@renderer/types'
import { modalConfirm } from '@renderer/utils' import { modalConfirm } from '@renderer/utils'
@ -69,7 +70,8 @@ const SettingsTab: FC<Props> = (props) => {
mathEngine, mathEngine,
autoTranslateWithSpace, autoTranslateWithSpace,
pasteLongTextThreshold, pasteLongTextThreshold,
multiModelMessageStyle multiModelMessageStyle,
thoughtAutoCollapse
} = useSettings() } = useSettings()
const onUpdateAssistantSettings = (settings: Partial<AssistantSettings>) => { const onUpdateAssistantSettings = (settings: Partial<AssistantSettings>) => {
@ -261,6 +263,20 @@ const SettingsTab: FC<Props> = (props) => {
/> />
</SettingRow> </SettingRow>
<SettingDivider /> <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> <SettingRow>
<SettingRowTitleSmall>{t('message.message.style')}</SettingRowTitleSmall> <SettingRowTitleSmall>{t('message.message.style')}</SettingRowTitleSmall>
<Select <Select

View File

@ -11,6 +11,7 @@ import {
import DragableList from '@renderer/components/DragableList' import DragableList from '@renderer/components/DragableList'
import PromptPopup from '@renderer/components/Popups/PromptPopup' import PromptPopup from '@renderer/components/Popups/PromptPopup'
import Scrollbar from '@renderer/components/Scrollbar' import Scrollbar from '@renderer/components/Scrollbar'
import { isMac } from '@renderer/config/constant'
import { useAssistant, useAssistants } from '@renderer/hooks/useAssistant' import { useAssistant, useAssistants } from '@renderer/hooks/useAssistant'
import { modelGenerating } from '@renderer/hooks/useRuntime' import { modelGenerating } from '@renderer/hooks/useRuntime'
import { useSettings } from '@renderer/hooks/useSettings' import { useSettings } from '@renderer/hooks/useSettings'
@ -24,7 +25,7 @@ import { exportTopicAsMarkdown, exportTopicToNotion, topicToMarkdown } from '@re
import { Dropdown, MenuProps, Tooltip } from 'antd' import { Dropdown, MenuProps, Tooltip } from 'antd'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { findIndex } from 'lodash' import { findIndex } from 'lodash'
import { FC, useCallback } from 'react' import { FC, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import styled from 'styled-components' import styled from 'styled-components'
@ -42,6 +43,42 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
const borderRadius = showTopicTime ? 12 : 'var(--list-item-border-radius)' 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( const onPinTopic = useCallback(
(topic: Topic) => { (topic: Topic) => {
const updatedTopic = { ...topic, pinned: !topic.pinned } const updatedTopic = { ...topic, pinned: !topic.pinned }
@ -54,7 +91,7 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
async (topic: Topic) => { async (topic: Topic) => {
await modelGenerating() await modelGenerating()
const index = findIndex(assistant.topics, (t) => t.id === topic.id) const index = findIndex(assistant.topics, (t) => t.id === topic.id)
setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? 0 : index + 1]) setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? index - 1 : index + 1])
removeTopic(topic) removeTopic(topic)
}, },
[assistant.topics, removeTopic, setActiveTopic] [assistant.topics, removeTopic, setActiveTopic]
@ -78,12 +115,6 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
[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( const getTopicMenuItems = useCallback(
(topic: Topic) => { (topic: Topic) => {
const menus: MenuProps['items'] = [ const menus: MenuProps['items'] = [
@ -219,7 +250,7 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
return menus return menus
}, },
[assistant, assistants, onClearMessages, onPinTopic, onDeleteTopic, onMoveTopic, t, updateTopic] [assistant, assistants, onClearMessages, onDeleteTopic, onPinTopic, onMoveTopic, t, updateTopic]
) )
return ( return (
@ -244,17 +275,34 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
)} )}
<MenuButton className="pin">{topic.pinned && <PushpinOutlined />}</MenuButton> <MenuButton className="pin">{topic.pinned && <PushpinOutlined />}</MenuButton>
{isActive && !topic.pinned && ( {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 <MenuButton
className="menu" className="menu"
onClick={(e) => { onClick={(e) => {
e.stopPropagation() if (e.ctrlKey || e.metaKey) {
if (assistant.topics.length === 1) { handleConfirmDelete(topic, e)
return onClearMessages() } else if (deletingTopicId === topic.id) {
handleConfirmDelete(topic, e)
} else {
handleDeleteClick(topic.id, e)
} }
onDeleteTopic(topic)
}}> }}>
{deletingTopicId === topic.id ? (
<DeleteOutlined style={{ color: 'var(--color-error)' }} />
) : (
<CloseOutlined /> <CloseOutlined />
)}
</MenuButton> </MenuButton>
</Tooltip>
)} )}
</TopicListItem> </TopicListItem>
</Dropdown> </Dropdown>

View File

@ -53,6 +53,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
addSitemap, addSitemap,
removeItem, removeItem,
getProcessingStatus, getProcessingStatus,
getDirectoryProcessingPercent,
addNote, addNote,
addDirectory addDirectory
} = useKnowledge(selectedBase.id || '') } = useKnowledge(selectedBase.id || '')
@ -64,6 +65,8 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
return null return null
} }
const progressingPercent = getDirectoryProcessingPercent(base?.id)
const handleAddFile = () => { const handleAddFile = () => {
if (disabled) { if (disabled) {
return return
@ -239,7 +242,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter> <FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />} {item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper> <StatusIconWrapper>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} /> <StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} type="file" />
</StatusIconWrapper> </StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} /> <Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter> </FlexAlignCenter>
@ -271,7 +274,13 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter> <FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />} {item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper> <StatusIconWrapper>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} /> <StatusIcon
sourceId={item.id}
base={base}
getProcessingStatus={getProcessingStatus}
progressingPercent={progressingPercent}
type="directory"
/>
</StatusIconWrapper> </StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} /> <Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter> </FlexAlignCenter>
@ -303,7 +312,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter> <FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />} {item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper> <StatusIconWrapper>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} /> <StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} type="url" />
</StatusIconWrapper> </StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} /> <Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter> </FlexAlignCenter>
@ -335,7 +344,12 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter> <FlexAlignCenter>
{item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />} {item.uniqueId && <Button type="text" icon={<RefreshIcon />} onClick={() => refreshItem(item)} />}
<StatusIconWrapper> <StatusIconWrapper>
<StatusIcon sourceId={item.id} base={base} getProcessingStatus={getProcessingStatus} /> <StatusIcon
sourceId={item.id}
base={base}
getProcessingStatus={getProcessingStatus}
type="sitemap"
/>
</StatusIconWrapper> </StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} /> <Button type="text" danger onClick={() => removeItem(item)} icon={<DeleteOutlined />} />
</FlexAlignCenter> </FlexAlignCenter>
@ -362,7 +376,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
<FlexAlignCenter> <FlexAlignCenter>
<Button type="text" onClick={() => handleEditNote(note)} icon={<EditOutlined />} /> <Button type="text" onClick={() => handleEditNote(note)} icon={<EditOutlined />} />
<StatusIconWrapper> <StatusIconWrapper>
<StatusIcon sourceId={note.id} base={base} getProcessingStatus={getProcessingStatus} /> <StatusIcon sourceId={note.id} base={base} getProcessingStatus={getProcessingStatus} type="note" />
</StatusIconWrapper> </StatusIconWrapper>
<Button type="text" danger onClick={() => removeItem(note)} icon={<DeleteOutlined />} /> <Button type="text" danger onClick={() => removeItem(note)} icon={<DeleteOutlined />} />
</FlexAlignCenter> </FlexAlignCenter>

View File

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

View File

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

View File

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

View File

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

View File

@ -5,9 +5,9 @@ import MinApp from '@renderer/components/MinApp'
import { useTheme } from '@renderer/context/ThemeProvider' import { useTheme } from '@renderer/context/ThemeProvider'
import { backup, reset, restore } from '@renderer/services/BackupService' import { backup, reset, restore } from '@renderer/services/BackupService'
import { RootState, useAppDispatch } from '@renderer/store' import { RootState, useAppDispatch } from '@renderer/store'
import { setNotionApiKey, setNotionDatabaseID } from '@renderer/store/settings' import { setNotionApiKey, setNotionDatabaseID, setNotionPageNameKey } from '@renderer/store/settings'
import { AppInfo } from '@renderer/types' import { AppInfo } from '@renderer/types'
import { Button, Modal, Typography } from 'antd' import { Button, Modal, Tooltip, Typography } from 'antd'
import Input from 'antd/es/input/Input' import Input from 'antd/es/input/Input'
import { FC, useEffect, useState } from 'react' import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@ -23,10 +23,9 @@ const NotionSettings: FC = () => {
const { theme } = useTheme() const { theme } = useTheme()
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
// 这里可以添加 Notion 相关的状态和逻辑
// 例如:
const notionApiKey = useSelector((state: RootState) => state.settings.notionApiKey) const notionApiKey = useSelector((state: RootState) => state.settings.notionApiKey)
const notionDatabaseID = useSelector((state: RootState) => state.settings.notionDatabaseID) const notionDatabaseID = useSelector((state: RootState) => state.settings.notionDatabaseID)
const notionPageNameKey = useSelector((state: RootState) => state.settings.notionPageNameKey)
const handleNotionTokenChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleNotionTokenChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(setNotionApiKey(e.target.value)) dispatch(setNotionApiKey(e.target.value))
@ -35,6 +34,11 @@ const NotionSettings: FC = () => {
const handleNotionDatabaseIdChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleNotionDatabaseIdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(setNotionDatabaseID(e.target.value)) dispatch(setNotionDatabaseID(e.target.value))
} }
const handleNotionPageNameKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(setNotionPageNameKey(e.target.value))
}
const handleNotionConnectionCheck = () => { const handleNotionConnectionCheck = () => {
if (notionApiKey === null) { if (notionApiKey === null) {
window.message.error(t('settings.data.notion.check.empty_api_key')) window.message.error(t('settings.data.notion.check.empty_api_key'))
@ -73,15 +77,17 @@ const NotionSettings: FC = () => {
<SettingGroup theme={theme}> <SettingGroup theme={theme}>
<SettingTitle style={{ justifyContent: 'flex-start', gap: 10 }}> <SettingTitle style={{ justifyContent: 'flex-start', gap: 10 }}>
{t('settings.data.notion.title')} {t('settings.data.notion.title')}
<Tooltip title={t('settings.data.notion.help')} placement="right">
<InfoCircleOutlined <InfoCircleOutlined
style={{ color: 'var(--color-text-2)', cursor: 'pointer' }} style={{ color: 'var(--color-text-2)', cursor: 'pointer' }}
onClick={handleNotionTitleClick} onClick={handleNotionTitleClick}
/> />
</Tooltip>
</SettingTitle> </SettingTitle>
<SettingDivider /> <SettingDivider />
<SettingRow> <SettingRow>
<SettingRowTitle>{t('settings.data.notion.database_id')}</SettingRowTitle> <SettingRowTitle>{t('settings.data.notion.database_id')}</SettingRowTitle>
<HStack alignItems="center" gap="5px"> <HStack alignItems="center" gap="5px" style={{ width: 315 }}>
<Input <Input
type="text" type="text"
value={notionDatabaseID || ''} value={notionDatabaseID || ''}
@ -93,9 +99,23 @@ const NotionSettings: FC = () => {
</HStack> </HStack>
</SettingRow> </SettingRow>
<SettingDivider /> <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> <SettingRow>
<SettingRowTitle>{t('settings.data.notion.api_key')}</SettingRowTitle> <SettingRowTitle>{t('settings.data.notion.api_key')}</SettingRowTitle>
<HStack alignItems="center" gap="5px"> <HStack alignItems="center" gap="5px" style={{ width: 315 }}>
<Input <Input
type="password" type="password"
value={notionApiKey || ''} value={notionApiKey || ''}
@ -104,9 +124,7 @@ const NotionSettings: FC = () => {
style={{ width: 250 }} style={{ width: 250 }}
placeholder={t('settings.data.notion.api_key_placeholder')} placeholder={t('settings.data.notion.api_key_placeholder')}
/> />
<Button onClick={handleNotionConnectionCheck} style={{ width: 60 }}> <Button onClick={handleNotionConnectionCheck}>{t('settings.data.notion.check.button')}</Button>
{t('settings.data.notion.check.button')}
</Button>
</HStack> </HStack>
</SettingRow> </SettingRow>
<SettingDivider /> {/* 添加分割线 */} <SettingDivider /> {/* 添加分割线 */}

View File

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

View File

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

View File

@ -1,18 +1,27 @@
import { CheckOutlined, SendOutlined, SettingOutlined, SwapOutlined, WarningOutlined } from '@ant-design/icons' import {
CheckOutlined,
DeleteOutlined,
HistoryOutlined,
SendOutlined,
SettingOutlined,
WarningOutlined
} from '@ant-design/icons'
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar' import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
import CopyIcon from '@renderer/components/Icons/CopyIcon' import CopyIcon from '@renderer/components/Icons/CopyIcon'
import { isLocalAi } from '@renderer/config/env' import { isLocalAi } from '@renderer/config/env'
import { TranslateLanguageOptions } from '@renderer/config/translate' import { translateLanguageOptions } from '@renderer/config/translate'
import db from '@renderer/databases' import db from '@renderer/databases'
import { useDefaultModel } from '@renderer/hooks/useAssistant' import { useDefaultModel } from '@renderer/hooks/useAssistant'
import { fetchTranslate } from '@renderer/services/ApiService' import { fetchTranslate } from '@renderer/services/ApiService'
import { getDefaultTranslateAssistant } from '@renderer/services/AssistantService' import { getDefaultTranslateAssistant } from '@renderer/services/AssistantService'
import { Assistant, Message } from '@renderer/types' import { Assistant, Message, TranslateHistory } from '@renderer/types'
import { runAsyncFunction, uuid } from '@renderer/utils' import { runAsyncFunction, uuid } from '@renderer/utils'
import { Button, Select, Space } from 'antd' import { Button, Dropdown, Empty, Flex, Popconfirm, Select, Space, Tooltip } from 'antd'
import TextArea from 'antd/es/input/TextArea' import TextArea, { TextAreaRef } from 'antd/es/input/TextArea'
import dayjs from 'dayjs'
import { useLiveQuery } from 'dexie-react-hooks'
import { isEmpty } from 'lodash' import { isEmpty } from 'lodash'
import { FC, useEffect, useState } from 'react' import { FC, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import styled from 'styled-components' import styled from 'styled-components'
@ -29,11 +38,42 @@ const TranslatePage: FC = () => {
const { translateModel } = useDefaultModel() const { translateModel } = useDefaultModel()
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [copied, setCopied] = 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 _text = text
_result = result _result = result
_targetLanguage = targetLanguage _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 () => { const onTranslate = async () => {
if (!text.trim()) { if (!text.trim()) {
return return
@ -62,7 +102,17 @@ const TranslatePage: FC = () => {
} }
setLoading(true) setLoading(true)
await fetchTranslate({ message, assistant, onResponse: (text) => setResult(text) }) let translatedText = ''
await fetchTranslate({
message,
assistant,
onResponse: (text) => {
translatedText = text
setResult(text)
}
})
await saveTranslateHistory(text, translatedText, 'any', targetLanguage)
setLoading(false) setLoading(false)
} }
@ -72,6 +122,12 @@ const TranslatePage: FC = () => {
setTimeout(() => setCopied(false), 2000) setTimeout(() => setCopied(false), 2000)
} }
const onHistoryItemClick = (history: TranslateHistory) => {
setText(history.sourceText)
setResult(history.targetText)
setTargetLanguage(history.targetLanguage)
}
useEffect(() => { useEffect(() => {
isEmpty(text) && setResult('') isEmpty(text) && setResult('')
}, [text]) }, [text])
@ -83,6 +139,13 @@ const TranslatePage: FC = () => {
}) })
}, []) }, [])
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
e.preventDefault()
onTranslate()
}
}
const SettingButton = () => { const SettingButton = () => {
if (isLocalAi) { if (isLocalAi) {
return null return null
@ -109,12 +172,72 @@ const TranslatePage: FC = () => {
} }
return ( return (
<Container> <Container id="translate-page">
<Navbar> <Navbar>
<NavbarCenter style={{ borderRight: 'none' }}>{t('translate.title')}</NavbarCenter> <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>
</Navbar> </Navbar>
<ContentContainer id="content-container"> <ContentContainer id="content-container" ref={contentContainerRef} $historyDrawerVisible={historyDrawerVisible}>
<MenuContainer> <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 <Select
showSearch showSearch
value="any" value="any"
@ -123,13 +246,51 @@ const TranslatePage: FC = () => {
disabled disabled
options={[{ label: t('translate.any.language'), value: 'any' }]} options={[{ label: t('translate.any.language'), value: 'any' }]}
/> />
<SwapOutlined /> <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
/>
</InputContainer>
<OutputContainer>
<OperationBar>
<Select <Select
showSearch showSearch
value={targetLanguage} value={targetLanguage}
style={{ width: 180 }} style={{ width: 180 }}
optionFilterProp="label" optionFilterProp="label"
options={TranslateLanguageOptions} options={translateLanguageOptions()}
onChange={(value) => { onChange={(value) => {
setTargetLanguage(value) setTargetLanguage(value)
db.settings.put({ id: 'translate:target:language', value }) db.settings.put({ id: 'translate:target:language', value })
@ -143,70 +304,31 @@ const TranslatePage: FC = () => {
</Space> </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 <CopyButton
onClick={onCopy} onClick={onCopy}
disabled={!result} disabled={!result}
icon={copied ? <CheckOutlined style={{ color: 'var(--color-primary)' }} /> : <CopyIcon />} icon={copied ? <CheckOutlined style={{ color: 'var(--color-primary)' }} /> : <CopyIcon />}
/> />
</OperationBar>
<OutputText>{result || t('translate.output.placeholder')}</OutputText>
</OutputContainer> </OutputContainer>
</TranslateInputWrapper>
</ContentContainer> </ContentContainer>
</Container> </Container>
) )
} }
const Container = styled.div` const Container = styled.div`
display: flex;
flex: 1; flex: 1;
flex-direction: column;
height: 100%;
` `
const ContentContainer = styled.div` const ContentContainer = styled.div<{ $historyDrawerVisible: boolean }>`
display: flex; height: calc(100vh - var(--navbar-height));
display: grid;
grid-template-columns: auto 1fr 1fr;
flex: 1; flex: 1;
flex-direction: column; padding: 20px 15px;
height: 100%; position: relative;
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` const InputContainer = styled.div`
@ -214,52 +336,136 @@ const InputContainer = styled.div`
display: flex; display: flex;
flex: 1; flex: 1;
flex-direction: column; flex-direction: column;
height: 100%;
border: 1px solid var(--color-border-soft); border: 1px solid var(--color-border-soft);
border-radius: 10px; 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)` const Textarea = styled(TextArea)`
display: flex; display: flex;
flex: 1; flex: 1;
padding: 20px;
font-size: 16px; font-size: 16px;
overflow: auto; border-radius: 0;
.ant-input { .ant-input {
resize: none; resize: none;
padding: 15px 20px; padding: 5px 16px;
}
.ant-input-clear-icon {
font-size: 16px;
} }
` `
const OutputContainer = styled.div` const OutputContainer = styled.div`
min-height: 0;
position: relative; position: relative;
display: flex; display: flex;
flex: 1;
flex-direction: column; flex-direction: column;
height: 100%;
padding: 10px;
background-color: var(--color-background-soft); background-color: var(--color-background-soft);
border-radius: 10px; border-radius: 10px;
padding-bottom: 5px;
padding-right: 2px;
` `
const OutputText = styled.div` const OutputText = styled.div`
padding: 5px 10px; min-height: 0;
max-height: calc(100vh - var(--navbar-height) - 120px); flex: 1;
overflow: auto; padding: 5px 16px;
overflow-y: auto;
white-space: pre-wrap; white-space: pre-wrap;
` `
const TranslateButton = styled(Button)` const TranslateButton = styled(Button)``
position: absolute;
right: 15px; const CopyButton = styled(Button)``
bottom: 15px;
z-index: 10; 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 CopyButton = styled(Button)` 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; position: absolute;
right: 15px; bottom: -8px;
bottom: 15px; 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);
` `
export default TranslatePage export default TranslatePage

View File

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

View File

@ -3,12 +3,13 @@ import { getLMStudioKeepAliveTime } from '@renderer/hooks/useLMStudio'
import { getOllamaKeepAliveTime } from '@renderer/hooks/useOllama' import { getOllamaKeepAliveTime } from '@renderer/hooks/useOllama'
import { getKnowledgeReferences } from '@renderer/services/KnowledgeService' import { getKnowledgeReferences } from '@renderer/services/KnowledgeService'
import store from '@renderer/store' import store from '@renderer/store'
import { Assistant, GenerateImageParams, Message, Model, Provider, Suggestion } from '@renderer/types' import type { Assistant, GenerateImageParams, Message, Model, Provider, Suggestion } from '@renderer/types'
import { delay, isJSON, parseJSON } from '@renderer/utils' import { delay, isJSON, parseJSON } from '@renderer/utils'
import { addAbortController, removeAbortController } from '@renderer/utils/abortController'
import { t } from 'i18next' import { t } from 'i18next'
import OpenAI from 'openai' import type OpenAI from 'openai'
import { CompletionsParams } from '.' import type { CompletionsParams } from '.'
export default abstract class BaseProvider { export default abstract class BaseProvider {
protected provider: Provider protected provider: Provider
@ -135,4 +136,21 @@ 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,7 +24,6 @@ import OpenAI from 'openai'
import { CompletionsParams } from '.' import { CompletionsParams } from '.'
import BaseProvider from './BaseProvider' import BaseProvider from './BaseProvider'
export default class GeminiProvider extends BaseProvider { export default class GeminiProvider extends BaseProvider {
private sdk: GoogleGenerativeAI private sdk: GoogleGenerativeAI
private requestOptions: RequestOptions private requestOptions: RequestOptions
@ -204,7 +203,11 @@ export default class GeminiProvider extends BaseProvider {
return return
} }
const userMessagesStream = await chat.sendMessageStream(messageContents.parts) 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)
let time_first_token_millsec = 0 let time_first_token_millsec = 0
for await (const chunk of userMessagesStream.stream) { for await (const chunk of userMessagesStream.stream) {

View File

@ -213,9 +213,14 @@ export default class OpenAIProvider extends BaseProvider {
let time_first_token_millsec = 0 let time_first_token_millsec = 0
let time_first_content_millsec = 0 let time_first_content_millsec = 0
const start_time_millsec = new Date().getTime() 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 // @ts-ignore key is not typed
const stream = await this.sdk.chat.completions.create({ .create(
{
model: model.id, model: model.id,
messages: [systemMessage, ...userMessages].filter(Boolean) as ChatCompletionMessageParam[], messages: [systemMessage, ...userMessages].filter(Boolean) as ChatCompletionMessageParam[],
temperature: this.getTemperature(assistant, model), temperature: this.getTemperature(assistant, model),
@ -227,7 +232,12 @@ export default class OpenAIProvider extends BaseProvider {
...getOpenAIWebSearchParams(assistant, model), ...getOpenAIWebSearchParams(assistant, model),
...this.getProviderSpecificParameters(assistant, model), ...this.getProviderSpecificParameters(assistant, model),
...this.getCustomParameters(assistant) ...this.getCustomParameters(assistant)
}) },
{
signal
}
)
.finally(cleanup)
if (!isSupportStreamOutput()) { if (!isSupportStreamOutput()) {
const time_completion_millsec = new Date().getTime() - start_time_millsec const time_completion_millsec = new Date().getTime() - start_time_millsec

View File

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

View File

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

View File

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

View File

@ -1073,6 +1073,30 @@ const migrateConfig = {
} }
state.settings.gridColumns = 2 state.settings.gridColumns = 2
state.settings.gridPopoverTrigger = 'hover' 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 return state
} }
} }

View File

@ -69,6 +69,8 @@ export interface SettingsState {
multiModelMessageStyle: MultiModelMessageStyle multiModelMessageStyle: MultiModelMessageStyle
notionDatabaseID: string | null notionDatabaseID: string | null
notionApiKey: string | null notionApiKey: string | null
notionPageNameKey: string | null
thoughtAutoCollapse: boolean
} }
export type MultiModelMessageStyle = 'horizontal' | 'vertical' | 'fold' | 'grid' export type MultiModelMessageStyle = 'horizontal' | 'vertical' | 'fold' | 'grid'
@ -123,7 +125,9 @@ const initialState: SettingsState = {
clickTrayToShowQuickAssistant: false, clickTrayToShowQuickAssistant: false,
multiModelMessageStyle: 'fold', multiModelMessageStyle: 'fold',
notionDatabaseID: '', notionDatabaseID: '',
notionApiKey: '' notionApiKey: '',
notionPageNameKey: 'Name',
thoughtAutoCollapse: true
} }
const settingsSlice = createSlice({ const settingsSlice = createSlice({
@ -283,6 +287,12 @@ const settingsSlice = createSlice({
}, },
setNotionApiKey: (state, action: PayloadAction<string>) => { setNotionApiKey: (state, action: PayloadAction<string>) => {
state.notionApiKey = action.payload state.notionApiKey = action.payload
},
setNotionPageNameKey: (state, action: PayloadAction<string>) => {
state.notionPageNameKey = action.payload
},
setThoughtAutoCollapse: (state, action: PayloadAction<boolean>) => {
state.thoughtAutoCollapse = action.payload
} }
} }
}) })
@ -336,7 +346,9 @@ export const {
setEnableQuickAssistant, setEnableQuickAssistant,
setMultiModelMessageStyle, setMultiModelMessageStyle,
setNotionDatabaseID, setNotionDatabaseID,
setNotionApiKey setNotionApiKey,
setNotionPageNameKey,
setThoughtAutoCollapse
} = settingsSlice.actions } = settingsSlice.actions
export default settingsSlice.reducer export default settingsSlice.reducer

View File

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

View File

@ -271,4 +271,13 @@ export type GenerateImageParams = {
promptEnhancement?: boolean 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' export type SidebarIcon = 'assistants' | 'agents' | 'paintings' | 'translate' | 'minapp' | 'knowledge' | 'files'

View File

@ -0,0 +1,25 @@
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({ const response = await notion.pages.create({
parent: { database_id: notionDatabaseID }, parent: { database_id: notionDatabaseID },
properties: { properties: {
Name: { [store.getState().settings.notionPageNameKey || 'Name']: {
title: [{ text: { content: topic.name } }] title: [{ text: { content: topic.name } }]
} }
}, },

View File

@ -2677,6 +2677,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@types/pako@npm:^1.0.2":
version: 1.0.7
resolution: "@types/pako@npm:1.0.7"
checksum: 10c0/1ba133db0b30a974c3d651c85651fd30135f629727b4b4d7ef2649c8f8b01014d5ef41f75399d939e320a50bfa87c32beccbb513badfeaf85d74ea6d5370fdcc
languageName: node
linkType: hard
"@types/plist@npm:^3.0.1": "@types/plist@npm:^3.0.1":
version: 3.0.5 version: 3.0.5
resolution: "@types/plist@npm:3.0.5" resolution: "@types/plist@npm:3.0.5"
@ -3013,6 +3020,7 @@ __metadata:
"@types/markdown-it": "npm:^14" "@types/markdown-it": "npm:^14"
"@types/md5": "npm:^2.3.5" "@types/md5": "npm:^2.3.5"
"@types/node": "npm:^18.19.9" "@types/node": "npm:^18.19.9"
"@types/pako": "npm:^1.0.2"
"@types/react": "npm:^18.2.48" "@types/react": "npm:^18.2.48"
"@types/react-dom": "npm:^18.2.18" "@types/react-dom": "npm:^18.2.18"
"@types/react-infinite-scroll-component": "npm:^5.0.0" "@types/react-infinite-scroll-component": "npm:^5.0.0"