Compare commits
82 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8350ac037e | ||
|
|
74b80b474e | ||
|
|
be4bf5b510 | ||
|
|
fdb610736d | ||
|
|
82e9baf211 | ||
|
|
e34d4be6f2 | ||
|
|
e7f7f8509e | ||
|
|
fa1f00f4f5 | ||
|
|
cee373bb6f | ||
|
|
01acdeb777 | ||
|
|
a654ccc25e | ||
|
|
71a35ccd44 | ||
|
|
29826ff091 | ||
|
|
8566476d91 | ||
|
|
a173a87f29 | ||
|
|
cb068d71ca | ||
|
|
66210d1d2e | ||
|
|
aa427c9911 | ||
|
|
9ae9fdf392 | ||
|
|
0ddef31ed8 | ||
|
|
617af8b12a | ||
|
|
71876e6a70 | ||
|
|
4f250cdcb1 | ||
|
|
9268ab845e | ||
|
|
0337c6649b | ||
|
|
8781388760 | ||
|
|
2016ba7062 | ||
|
|
a03d619e2f | ||
|
|
76d1f0bb1e | ||
|
|
2bad5a1184 | ||
|
|
94ba3aee05 | ||
|
|
563758f69f | ||
|
|
56af85cc3e | ||
|
|
6a1a861ecc | ||
|
|
ceab574a22 | ||
|
|
98704fdb28 | ||
|
|
fd5cba5219 | ||
|
|
be5aaa2b66 | ||
|
|
7e8687decd | ||
|
|
4c96324ef7 | ||
|
|
dd3c81ec5f | ||
|
|
42f0b5f8fc | ||
|
|
11b2cd88b7 | ||
|
|
6bf98f6db3 | ||
|
|
10b4e3c634 | ||
|
|
a3f5223b4c | ||
|
|
2855575b36 | ||
|
|
1f0ba20523 | ||
|
|
2f53416e09 | ||
|
|
ddbf266a3f | ||
|
|
d815415f36 | ||
|
|
cdacc56fd7 | ||
|
|
455d909c74 | ||
|
|
52d84afed6 | ||
|
|
f06d1d4d9a | ||
|
|
805a65bbaa | ||
|
|
f217950b13 | ||
|
|
9ff65441ef | ||
|
|
2b20282a41 | ||
|
|
96ad2de896 | ||
|
|
e1ea875c21 | ||
|
|
500e91977c | ||
|
|
bd194ff955 | ||
|
|
828bd71f22 | ||
|
|
5991f692b2 | ||
|
|
200d78a140 | ||
|
|
9a502b5e47 | ||
|
|
97ef3772ea | ||
|
|
eb18be200e | ||
|
|
467e97ff4b | ||
|
|
27b802d3c2 | ||
|
|
37b0a175f7 | ||
|
|
b2b79f12a2 | ||
|
|
885c578582 | ||
|
|
e61e4b109a | ||
|
|
f3bafbeb52 | ||
|
|
e55c0cdcef | ||
|
|
e73bbf4d6a | ||
|
|
3859289218 | ||
|
|
591bb45a4e | ||
|
|
b31f518fca | ||
|
|
dfbdb989db |
@@ -15,6 +15,7 @@ module.exports = {
|
||||
'@typescript-eslint/no-non-null-asserted-optional-chain': 'off',
|
||||
'react/prop-types': 'off',
|
||||
'simple-import-sort/imports': 'error',
|
||||
'simple-import-sort/exports': 'error'
|
||||
'simple-import-sort/exports': 'error',
|
||||
'react/no-is-mounted': 'off'
|
||||
}
|
||||
}
|
||||
|
||||
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
@@ -29,5 +29,6 @@
|
||||
},
|
||||
"[markdown]": {
|
||||
"files.trimTrailingWhitespace": false
|
||||
}
|
||||
},
|
||||
"i18n-ally.localesPaths": ["src/renderer/src/i18n"]
|
||||
}
|
||||
|
||||
@@ -8,8 +8,10 @@ files:
|
||||
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
|
||||
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
|
||||
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
|
||||
- '!src/*'
|
||||
- '!src'
|
||||
- '!local'
|
||||
- '!scripts'
|
||||
- '!resources'
|
||||
asarUnpack:
|
||||
- resources/**
|
||||
win:
|
||||
@@ -57,6 +59,14 @@ electronDownload:
|
||||
afterSign: scripts/notarize.js
|
||||
releaseInfo:
|
||||
releaseNotes: |
|
||||
本次更新:
|
||||
数据结构调整,更新后会自动迁移数据
|
||||
支持从特定消息创建新分支
|
||||
长代码添加底部复制按钮
|
||||
AI 回复过程中支持复制代码
|
||||
优化消息列表渲染性能
|
||||
近期更新:
|
||||
支持 Vision 模型
|
||||
新增文件功能
|
||||
智能助理和消息列表合并
|
||||
优化输入框样式
|
||||
提升小程序稳定性
|
||||
支持行内公式
|
||||
|
||||
@@ -7,7 +7,8 @@ export default defineConfig({
|
||||
plugins: [externalizeDepsPlugin()],
|
||||
resolve: {
|
||||
alias: {
|
||||
ollama: resolve('ollama/src')
|
||||
'@types': resolve('src/renderer/src/types'),
|
||||
'@main': resolve('src/main')
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
10
package.json
10
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "CherryStudio",
|
||||
"version": "0.6.7",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"description": "A powerful AI assistant for producer.",
|
||||
"main": "./out/main/index.js",
|
||||
@@ -54,6 +54,8 @@
|
||||
"axios": "^1.7.3",
|
||||
"browser-image-compression": "^2.0.2",
|
||||
"dayjs": "^1.11.11",
|
||||
"dexie": "^4.0.8",
|
||||
"dexie-react-hooks": "^1.1.7",
|
||||
"dotenv-cli": "^7.4.2",
|
||||
"electron": "^28.3.3",
|
||||
"electron-builder": "^24.9.1",
|
||||
@@ -69,6 +71,7 @@
|
||||
"i18next": "^23.11.5",
|
||||
"localforage": "^1.10.0",
|
||||
"lodash": "^4.17.21",
|
||||
"mime": "^4.0.4",
|
||||
"openai": "^4.52.1",
|
||||
"prettier": "^3.2.4",
|
||||
"react": "^18.2.0",
|
||||
@@ -87,7 +90,7 @@
|
||||
"remark-math": "^6.0.0",
|
||||
"sass": "^1.77.2",
|
||||
"styled-components": "^6.1.11",
|
||||
"typescript": "^5.3.3",
|
||||
"typescript": "^5.6.2",
|
||||
"uuid": "^10.0.0",
|
||||
"vite": "^5.0.12"
|
||||
},
|
||||
@@ -96,8 +99,7 @@
|
||||
"react-dom": "^17.0.0 || ^18.0.0"
|
||||
},
|
||||
"resolutions": {
|
||||
"@electron/notarize": "2.3.2",
|
||||
"@electron/notarize@npm:2.2.1": "patch:@electron/notarize@npm%3A2.3.2#~/.yarn/patches/@electron-notarize-npm-2.3.2-535908a4bd.patch"
|
||||
},
|
||||
"packageManager": "yarn@4.3.1"
|
||||
"packageManager": "yarn@4.5.0"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,22 @@
|
||||
import fs from 'node:fs'
|
||||
|
||||
import { app } from 'electron'
|
||||
import Store from 'electron-store'
|
||||
import path from 'path'
|
||||
|
||||
const isDev = process.env.NODE_ENV === 'development'
|
||||
|
||||
isDev && app.setPath('userData', app.getPath('userData') + 'Dev')
|
||||
|
||||
const getDataPath = () => {
|
||||
const dataPath = path.join(app.getPath('userData'), 'Data')
|
||||
if (!fs.existsSync(dataPath)) {
|
||||
fs.mkdirSync(dataPath, { recursive: true })
|
||||
}
|
||||
return dataPath
|
||||
}
|
||||
|
||||
export const DATA_PATH = getDataPath()
|
||||
|
||||
export const appConfig = new Store()
|
||||
|
||||
|
||||
9
src/main/env.d.ts
vendored
Normal file
9
src/main/env.d.ts
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
VITE_MAIN_BUNDLE_ID: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
@@ -12,7 +12,7 @@ app.whenReady().then(async () => {
|
||||
await updateUserDataPath()
|
||||
|
||||
// Set app user model id for windows
|
||||
electronApp.setAppUserModelId('com.kangfenmao.CherryStudio')
|
||||
electronApp.setAppUserModelId(import.meta.env.VITE_MAIN_BUNDLE_ID || 'com.kangfenmao.CherryStudio')
|
||||
|
||||
// Default open or close DevTools by F12 in development
|
||||
// and ignore CommandOrControl + R in production.
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { BrowserWindow, ipcMain, session, shell } from 'electron'
|
||||
import { FileType } from '@types'
|
||||
import { BrowserWindow, ipcMain, OpenDialogOptions, session, shell } from 'electron'
|
||||
import Logger from 'electron-log'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
import { appConfig, titleBarOverlayDark, titleBarOverlayLight } from './config'
|
||||
import AppUpdater from './updater'
|
||||
import AppUpdater from './services/AppUpdater'
|
||||
import File from './services/File'
|
||||
import { openFile, saveFile } from './utils/file'
|
||||
import { compress, decompress } from './utils/zip'
|
||||
import { createMinappWindow } from './window'
|
||||
|
||||
const fileManager = new File()
|
||||
|
||||
export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
|
||||
const { autoUpdater } = new AppUpdater(mainWindow)
|
||||
|
||||
@@ -31,6 +38,30 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
|
||||
ipcMain.handle('zip:compress', (_, text: string) => compress(text))
|
||||
ipcMain.handle('zip:decompress', (_, text: Buffer) => decompress(text))
|
||||
|
||||
ipcMain.handle('image:base64', async (_, filePath) => {
|
||||
try {
|
||||
const data = await fs.promises.readFile(filePath)
|
||||
const base64 = data.toString('base64')
|
||||
const mime = `image/${path.extname(filePath).slice(1)}`
|
||||
return {
|
||||
mime,
|
||||
base64,
|
||||
data: `data:${mime};base64,${base64}`
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.error('Error reading file:', error)
|
||||
return ''
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('file:select', async (_, options?: OpenDialogOptions) => await fileManager.selectFile(options))
|
||||
ipcMain.handle('file:upload', async (_, file: FileType) => await fileManager.uploadFile(file))
|
||||
ipcMain.handle('file:clear', async () => await fileManager.clear())
|
||||
ipcMain.handle('file:delete', async (_, fileId: string) => {
|
||||
await fileManager.deleteFile(fileId)
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
ipcMain.handle('minapp', (_, args) => {
|
||||
createMinappWindow({
|
||||
url: args.url,
|
||||
|
||||
144
src/main/services/File.ts
Normal file
144
src/main/services/File.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import { getFileType } from '@main/utils/file'
|
||||
import { FileType } from '@types'
|
||||
import * as crypto from 'crypto'
|
||||
import { app, dialog, OpenDialogOptions } from 'electron'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
|
||||
class File {
|
||||
private storageDir: string
|
||||
|
||||
constructor() {
|
||||
this.storageDir = path.join(app.getPath('userData'), 'Data', 'Files')
|
||||
this.initStorageDir()
|
||||
}
|
||||
|
||||
private initStorageDir(): void {
|
||||
if (!fs.existsSync(this.storageDir)) {
|
||||
fs.mkdirSync(this.storageDir, { recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async getFileHash(filePath: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = crypto.createHash('md5')
|
||||
const stream = fs.createReadStream(filePath)
|
||||
stream.on('data', (data) => hash.update(data))
|
||||
stream.on('end', () => resolve(hash.digest('hex')))
|
||||
stream.on('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
async findDuplicateFile(filePath: string): Promise<FileType | null> {
|
||||
const stats = fs.statSync(filePath)
|
||||
const fileSize = stats.size
|
||||
|
||||
const files = await fs.promises.readdir(this.storageDir)
|
||||
for (const file of files) {
|
||||
const storedFilePath = path.join(this.storageDir, file)
|
||||
const storedStats = fs.statSync(storedFilePath)
|
||||
|
||||
if (storedStats.size === fileSize) {
|
||||
const [originalHash, storedHash] = await Promise.all([
|
||||
this.getFileHash(filePath),
|
||||
this.getFileHash(storedFilePath)
|
||||
])
|
||||
|
||||
if (originalHash === storedHash) {
|
||||
const ext = path.extname(file)
|
||||
const id = path.basename(file, ext)
|
||||
return {
|
||||
id,
|
||||
origin_name: file,
|
||||
name: file + ext,
|
||||
path: storedFilePath,
|
||||
created_at: storedStats.birthtime,
|
||||
size: storedStats.size,
|
||||
ext,
|
||||
type: getFileType(ext),
|
||||
count: 2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async selectFile(options?: OpenDialogOptions): Promise<FileType[] | null> {
|
||||
const defaultOptions: OpenDialogOptions = {
|
||||
properties: ['openFile']
|
||||
}
|
||||
|
||||
const dialogOptions = { ...defaultOptions, ...options }
|
||||
|
||||
const result = await dialog.showOpenDialog(dialogOptions)
|
||||
|
||||
if (result.canceled || result.filePaths.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const fileMetadataPromises = result.filePaths.map(async (filePath) => {
|
||||
const stats = fs.statSync(filePath)
|
||||
const ext = path.extname(filePath)
|
||||
const fileType = getFileType(ext)
|
||||
|
||||
return {
|
||||
id: uuidv4(),
|
||||
origin_name: path.basename(filePath),
|
||||
name: path.basename(filePath),
|
||||
path: filePath,
|
||||
created_at: stats.birthtime,
|
||||
size: stats.size,
|
||||
ext: ext,
|
||||
type: fileType,
|
||||
count: 1
|
||||
}
|
||||
})
|
||||
|
||||
return Promise.all(fileMetadataPromises)
|
||||
}
|
||||
|
||||
async uploadFile(file: FileType): Promise<FileType> {
|
||||
const duplicateFile = await this.findDuplicateFile(file.path)
|
||||
|
||||
if (duplicateFile) {
|
||||
return duplicateFile
|
||||
}
|
||||
|
||||
const uuid = uuidv4()
|
||||
const origin_name = path.basename(file.path)
|
||||
const ext = path.extname(origin_name)
|
||||
const destPath = path.join(this.storageDir, uuid + ext)
|
||||
|
||||
await fs.promises.copyFile(file.path, destPath)
|
||||
const stats = await fs.promises.stat(destPath)
|
||||
const fileType = getFileType(ext)
|
||||
|
||||
const fileMetadata: FileType = {
|
||||
id: uuid,
|
||||
origin_name,
|
||||
name: uuid + ext,
|
||||
path: destPath,
|
||||
created_at: stats.birthtime,
|
||||
size: stats.size,
|
||||
ext: ext,
|
||||
type: fileType,
|
||||
count: 1
|
||||
}
|
||||
|
||||
return fileMetadata
|
||||
}
|
||||
|
||||
async deleteFile(id: string): Promise<void> {
|
||||
await fs.promises.unlink(path.join(this.storageDir, id))
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
await fs.promises.rmdir(this.storageDir, { recursive: true })
|
||||
await this.initStorageDir()
|
||||
}
|
||||
}
|
||||
|
||||
export default File
|
||||
@@ -1,8 +1,10 @@
|
||||
import { dialog, OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue } from 'electron'
|
||||
import logger from 'electron-log'
|
||||
import { writeFile } from 'fs'
|
||||
import { writeFileSync } from 'fs'
|
||||
import { readFile } from 'fs/promises'
|
||||
|
||||
import { FileTypes } from '../../renderer/src/types'
|
||||
|
||||
export async function saveFile(
|
||||
_: Electron.IpcMainInvokeEvent,
|
||||
fileName: string,
|
||||
@@ -17,11 +19,7 @@ export async function saveFile(
|
||||
})
|
||||
|
||||
if (!result.canceled && result.filePath) {
|
||||
writeFile(result.filePath, content, { encoding: 'utf-8' }, (err) => {
|
||||
if (err) {
|
||||
logger.error('[IPC - Error]', 'An error occurred saving the file:', err)
|
||||
}
|
||||
})
|
||||
await writeFileSync(result.filePath, content, { encoding: 'utf-8' })
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('[IPC - Error]', 'An error occurred saving the file:', err)
|
||||
@@ -53,3 +51,17 @@ export async function openFile(
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function getFileType(ext: string): FileTypes {
|
||||
const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
|
||||
const videoExts = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv']
|
||||
const audioExts = ['.mp3', '.wav', '.ogg', '.flac', '.aac']
|
||||
const documentExts = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt']
|
||||
|
||||
ext = ext.toLowerCase()
|
||||
if (imageExts.includes(ext)) return FileTypes.IMAGE
|
||||
if (videoExts.includes(ext)) return FileTypes.VIDEO
|
||||
if (audioExts.includes(ext)) return FileTypes.AUDIO
|
||||
if (documentExts.includes(ext)) return FileTypes.DOCUMENT
|
||||
return FileTypes.OTHER
|
||||
}
|
||||
|
||||
7
src/main/utils/index.ts
Normal file
7
src/main/utils/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import path from 'node:path'
|
||||
|
||||
import { app } from 'electron'
|
||||
|
||||
export function getResourcePath() {
|
||||
return path.join(app.getAppPath(), 'resources')
|
||||
}
|
||||
10
src/preload/index.d.ts
vendored
10
src/preload/index.d.ts
vendored
@@ -1,4 +1,5 @@
|
||||
import { ElectronAPI } from '@electron-toolkit/preload'
|
||||
import { FileType } from '@renderer/types'
|
||||
import type { OpenDialogOptions } from 'electron'
|
||||
|
||||
declare global {
|
||||
@@ -20,6 +21,15 @@ declare global {
|
||||
reload: () => void
|
||||
compress: (text: string) => Promise<Buffer>
|
||||
decompress: (text: Buffer) => Promise<string>
|
||||
file: {
|
||||
select: (options?: OpenDialogOptions) => Promise<FileType[] | null>
|
||||
upload: (file: FileType) => Promise<FileType>
|
||||
delete: (fileId: string) => Promise<{ success: boolean }>
|
||||
clear: () => Promise<void>
|
||||
}
|
||||
image: {
|
||||
base64: (filePath: string) => Promise<{ mime: string; base64: string; data: string }>
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { electronAPI } from '@electron-toolkit/preload'
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
import { contextBridge, ipcRenderer, OpenDialogOptions } from 'electron'
|
||||
|
||||
// Custom APIs for renderer
|
||||
const api = {
|
||||
@@ -12,10 +12,19 @@ const api = {
|
||||
openFile: (options?: { decompress: boolean }) => ipcRenderer.invoke('open-file', options),
|
||||
reload: () => ipcRenderer.invoke('reload'),
|
||||
saveFile: (path: string, content: string, options?: { compress: boolean }) => {
|
||||
ipcRenderer.invoke('save-file', path, content, options)
|
||||
return ipcRenderer.invoke('save-file', path, content, options)
|
||||
},
|
||||
compress: (text: string) => ipcRenderer.invoke('zip:compress', text),
|
||||
decompress: (text: Buffer) => ipcRenderer.invoke('zip:decompress', text)
|
||||
decompress: (text: Buffer) => ipcRenderer.invoke('zip:decompress', text),
|
||||
file: {
|
||||
select: (options?: OpenDialogOptions) => ipcRenderer.invoke('file:select', options),
|
||||
upload: (filePath: string) => ipcRenderer.invoke('file:upload', filePath),
|
||||
delete: (fileId: string) => ipcRenderer.invoke('file:delete', fileId),
|
||||
clear: () => ipcRenderer.invoke('file:clear')
|
||||
},
|
||||
image: {
|
||||
base64: (filePath: string) => ipcRenderer.invoke('image:base64', filePath)
|
||||
}
|
||||
}
|
||||
|
||||
// Use `contextBridge` APIs to expose Electron APIs to
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="initial-scale=1, width=device-width" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; connect-src *; script-src 'self' *; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' *; font-src 'self' data: *; img-src 'self' data: *; frame-src * file:" />
|
||||
content="default-src 'self'; connect-src *; script-src 'self' *; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' *; font-src 'self' data: *; img-src 'self' data: file: *; frame-src * file:" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import '@renderer/databases'
|
||||
|
||||
import store, { persistor } from '@renderer/store'
|
||||
import { Provider } from 'react-redux'
|
||||
import { HashRouter, Route, Routes } from 'react-router-dom'
|
||||
@@ -9,6 +11,7 @@ import AntdProvider from './context/AntdProvider'
|
||||
import { ThemeProvider } from './context/ThemeProvider'
|
||||
import AgentsPage from './pages/agents/AgentsPage'
|
||||
import AppsPage from './pages/apps/AppsPage'
|
||||
import FilesPage from './pages/files/FilesPage'
|
||||
import HomePage from './pages/home/HomePage'
|
||||
import SettingsPage from './pages/settings/SettingsPage'
|
||||
import TranslatePage from './pages/translate/TranslatePage'
|
||||
@@ -24,6 +27,7 @@ function App(): JSX.Element {
|
||||
<Sidebar />
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/files" element={<FilesPage />} />
|
||||
<Route path="/agents" element={<AgentsPage />} />
|
||||
<Route path="/translate" element={<TranslatePage />} />
|
||||
<Route path="/apps" element={<AppsPage />} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
@font-face {
|
||||
font-family: 'iconfont'; /* Project id 4563475 */
|
||||
src: url('iconfont.woff2?t=1725450669049') format('woff2');
|
||||
src: url('iconfont.woff2?t=1725606177995') format('woff2');
|
||||
}
|
||||
|
||||
.iconfont {
|
||||
@@ -11,26 +11,26 @@
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
.icon-a-darkmode:before {
|
||||
content: '\e6cd';
|
||||
}
|
||||
|
||||
.icon-ai-model:before {
|
||||
content: '\e827';
|
||||
}
|
||||
|
||||
.icon-ai-model1:before {
|
||||
content: '\ec09';
|
||||
}
|
||||
|
||||
.icon-gridlines:before {
|
||||
content: '\e942';
|
||||
}
|
||||
|
||||
.icon-grid-frame:before {
|
||||
content: '\e680';
|
||||
}
|
||||
|
||||
.icon-grid-row-2copy:before {
|
||||
content: '\e681';
|
||||
}
|
||||
|
||||
.icon-sidebar-left:before {
|
||||
content: '\e6ab';
|
||||
}
|
||||
|
||||
.icon-sidebar-right:before {
|
||||
content: '\e6ac';
|
||||
}
|
||||
|
||||
.icon-inbox:before {
|
||||
content: '\e869';
|
||||
}
|
||||
@@ -63,6 +63,14 @@
|
||||
content: '\e758';
|
||||
}
|
||||
|
||||
.icon-hide-sidebar:before {
|
||||
content: '\e8eb';
|
||||
}
|
||||
|
||||
.icon-show-sidebar:before {
|
||||
content: '\e944';
|
||||
}
|
||||
|
||||
.icon-a-addchat:before {
|
||||
content: '\e658';
|
||||
}
|
||||
|
||||
Binary file not shown.
BIN
src/renderer/src/assets/images/apps/poe.webp
Normal file
BIN
src/renderer/src/assets/images/apps/poe.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.1 KiB |
BIN
src/renderer/src/assets/images/apps/zhihu.png
Normal file
BIN
src/renderer/src/assets/images/apps/zhihu.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
BIN
src/renderer/src/assets/images/models/cohere.webp
Normal file
BIN
src/renderer/src/assets/images/models/cohere.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.6 KiB |
3
src/renderer/src/assets/images/providers/github.svg
Normal file
3
src/renderer/src/assets/images/providers/github.svg
Normal file
@@ -0,0 +1,3 @@
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M16 0C7.16 0 0 7.16 0 16C0 23.08 4.58 29.06 10.94 31.18C11.74 31.32 12.04 30.84 12.04 30.42C12.04 30.04 12.02 28.78 12.02 27.44C8 28.18 6.96 26.46 6.64 25.56C6.46 25.1 5.68 23.68 5 23.3C4.44 23 3.64 22.26 4.98 22.24C6.24 22.22 7.14 23.4 7.44 23.88C8.88 26.3 11.18 25.62 12.1 25.2C12.24 24.16 12.66 23.46 13.12 23.06C9.56 22.66 5.84 21.28 5.84 15.16C5.84 13.42 6.46 11.98 7.48 10.86C7.32 10.46 6.76 8.82 7.64 6.62C7.64 6.62 8.98 6.2 12.04 8.26C13.32 7.9 14.68 7.72 16.04 7.72C17.4 7.72 18.76 7.9 20.04 8.26C23.1 6.18 24.44 6.62 24.44 6.62C25.32 8.82 24.76 10.46 24.6 10.86C25.62 11.98 26.24 13.4 26.24 15.16C26.24 21.3 22.5 22.66 18.94 23.06C19.52 23.56 20.02 24.52 20.02 26.02C20.02 28.16 20 29.88 20 30.42C20 30.84 20.3 31.34 21.1 31.18C27.42 29.06 32 23.06 32 16C32 7.16 24.84 0 16 0V0Z" fill="#24292E"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 959 B |
@@ -24,14 +24,14 @@
|
||||
--color-background-soft: var(--color-black-soft);
|
||||
--color-background-mute: var(--color-black-mute);
|
||||
|
||||
--color-primary: #135200;
|
||||
--color-primary-soft: #13520099;
|
||||
--color-primary-mute: #13520033;
|
||||
--color-primary: #00b96b;
|
||||
--color-primary-soft: #00b96b99;
|
||||
--color-primary-mute: #00b96b33;
|
||||
|
||||
--color-text: var(--color-text-1);
|
||||
--color-icon: #ffffff99;
|
||||
--color-icon-white: #ffffff;
|
||||
--color-border: #000;
|
||||
--color-border: #ffffff20;
|
||||
--color-border-soft: #ffffff20;
|
||||
--color-error: #f44336;
|
||||
--color-link: #1677ff;
|
||||
@@ -48,9 +48,9 @@
|
||||
--status-bar-height: 40px;
|
||||
--input-bar-height: 85px;
|
||||
|
||||
--assistants-width: 240px;
|
||||
--topic-list-width: 270px;
|
||||
--settings-width: var(--assistants-width);
|
||||
--assistants-width: 280px;
|
||||
--topic-list-width: 280px;
|
||||
--settings-width: 260px;
|
||||
}
|
||||
|
||||
body[theme-mode='light'] {
|
||||
@@ -208,3 +208,26 @@ body,
|
||||
.ant-drawer-header {
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
|
||||
.segmented-tab {
|
||||
.ant-segmented-item-label {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
font-size: 13px;
|
||||
}
|
||||
.iconfont {
|
||||
font-size: 13px;
|
||||
margin-left: -2px;
|
||||
}
|
||||
.anticon-setting {
|
||||
font-size: 12px;
|
||||
}
|
||||
.icon-business-smart-assistant {
|
||||
margin-right: -2px;
|
||||
}
|
||||
.ant-segmented-item-icon + * {
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,9 @@
|
||||
|
||||
li {
|
||||
margin-bottom: 0.5em;
|
||||
pre {
|
||||
margin: 1.5em 0;
|
||||
}
|
||||
&::marker {
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
@@ -98,7 +101,8 @@
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
}
|
||||
|
||||
p code {
|
||||
p code,
|
||||
li code {
|
||||
background: var(--color-background-mute);
|
||||
padding: 3px 5px;
|
||||
border-radius: 5px;
|
||||
@@ -106,19 +110,29 @@
|
||||
|
||||
pre {
|
||||
white-space: pre-wrap !important;
|
||||
padding: 1em 0;
|
||||
border-radius: 5px;
|
||||
overflow-x: auto;
|
||||
font-family: 'Fira Code', 'Courier New', Courier, monospace;
|
||||
background-color: var(--color-background-mute);
|
||||
&:not(pre pre) {
|
||||
> code:not(pre pre > code) {
|
||||
padding: 15px;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
pre {
|
||||
margin: 0 !important;
|
||||
}
|
||||
code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pre + pre {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
margin: 1em 0;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
DragDropContext,
|
||||
Draggable,
|
||||
Droppable,
|
||||
DroppableProps,
|
||||
DropResult,
|
||||
OnDragEndResponder,
|
||||
OnDragStartResponder,
|
||||
@@ -13,13 +14,24 @@ import { FC } from 'react'
|
||||
interface Props<T> {
|
||||
list: T[]
|
||||
style?: React.CSSProperties
|
||||
listStyle?: React.CSSProperties
|
||||
children: (item: T, index: number) => React.ReactNode
|
||||
onUpdate: (list: T[]) => void
|
||||
onDragStart?: OnDragStartResponder
|
||||
onDragEnd?: OnDragEndResponder
|
||||
droppableProps?: Partial<DroppableProps>
|
||||
}
|
||||
|
||||
const DragableList: FC<Props<any>> = ({ children, list, style, onDragStart, onUpdate, onDragEnd }) => {
|
||||
const DragableList: FC<Props<any>> = ({
|
||||
children,
|
||||
list,
|
||||
style,
|
||||
listStyle,
|
||||
droppableProps,
|
||||
onDragStart,
|
||||
onUpdate,
|
||||
onDragEnd
|
||||
}) => {
|
||||
const _onDragEnd = (result: DropResult, provided: ResponderProvided) => {
|
||||
onDragEnd?.(result, provided)
|
||||
if (result.destination) {
|
||||
@@ -32,17 +44,17 @@ const DragableList: FC<Props<any>> = ({ children, list, style, onDragStart, onUp
|
||||
|
||||
return (
|
||||
<DragDropContext onDragStart={onDragStart} onDragEnd={_onDragEnd}>
|
||||
<Droppable droppableId="droppable">
|
||||
<Droppable droppableId="droppable" {...droppableProps}>
|
||||
{(provided) => (
|
||||
<div {...provided.droppableProps} ref={provided.innerRef}>
|
||||
<div {...provided.droppableProps} ref={provided.innerRef} style={{ ...style }}>
|
||||
{list.map((item, index) => (
|
||||
<Draggable key={`draggable_${item.id}_${index}`} draggableId={item.id} index={index}>
|
||||
<Draggable key={`draggable_${item.id}_${index}`} draggableId={item.id} index={index} {...droppableProps}>
|
||||
{(provided) => (
|
||||
<div
|
||||
ref={provided.innerRef}
|
||||
{...provided.draggableProps}
|
||||
{...provided.dragHandleProps}
|
||||
style={{ ...provided.draggableProps.style, marginBottom: 8, ...style }}>
|
||||
style={{ ...provided.draggableProps.style, marginBottom: 8, ...listStyle }}>
|
||||
{children(item, index)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
15
src/renderer/src/components/Icons/VisionIcon.tsx
Normal file
15
src/renderer/src/components/Icons/VisionIcon.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import { EyeOutlined } from '@ant-design/icons'
|
||||
import React, { FC } from 'react'
|
||||
import styled from 'styled-components'
|
||||
|
||||
const VisionIcon: FC<React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>> = (props) => {
|
||||
return <Icon {...(props as any)} />
|
||||
}
|
||||
|
||||
const Icon = styled(EyeOutlined)`
|
||||
color: var(--color-primary);
|
||||
font-size: 14px;
|
||||
margin-left: 4px;
|
||||
`
|
||||
|
||||
export default VisionIcon
|
||||
@@ -3,6 +3,7 @@ import systemAgents from '@renderer/config/agents.json'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { useAssistants, useDefaultAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { covertAgentToAssistant } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { Agent, Assistant } from '@renderer/types'
|
||||
import { Input, Modal, Tag } from 'antd'
|
||||
import { useMemo, useState } from 'react'
|
||||
@@ -50,6 +51,7 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
|
||||
const assistant = covertAgentToAssistant(agent)
|
||||
|
||||
addAssistant(assistant)
|
||||
setTimeout(() => EventEmitter.emit(EVENT_NAMES.SHOW_ASSISTANTS), 0)
|
||||
resolve(assistant)
|
||||
setOpen(false)
|
||||
}
|
||||
@@ -65,7 +67,7 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
|
||||
|
||||
return (
|
||||
<Modal
|
||||
style={{ marginTop: '5vh' }}
|
||||
centered
|
||||
title={t('chat.add.assistant.title')}
|
||||
open={open}
|
||||
onCancel={onCancel}
|
||||
|
||||
@@ -41,7 +41,8 @@ const AssistantSettingPopupContainer: React.FC<Props> = ({ assistant, resolve })
|
||||
onCancel={handleCancel}
|
||||
afterClose={onClose}
|
||||
transitionName="ant-move-down"
|
||||
maskTransitionName="ant-fade">
|
||||
maskTransitionName="ant-fade"
|
||||
centered>
|
||||
<Box mb={8}>{t('common.name')}</Box>
|
||||
<Input
|
||||
placeholder={t('common.assistant') + t('common.name')}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import useAvatar from '@renderer/hooks/useAvatar'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import LocalStorage from '@renderer/services/storage'
|
||||
import ImageStorage from '@renderer/services/storage'
|
||||
import { useAppDispatch } from '@renderer/store'
|
||||
import { setAvatar } from '@renderer/store/runtime'
|
||||
import { setUserName } from '@renderer/store/settings'
|
||||
@@ -55,8 +55,8 @@ const PopupContainer: React.FC<Props> = ({ resolve }) => {
|
||||
try {
|
||||
const _file = file.originFileObj as File
|
||||
const compressedFile = await compressImage(_file)
|
||||
await LocalStorage.storeImage('avatar', compressedFile)
|
||||
dispatch(setAvatar(await LocalStorage.getImage('avatar')))
|
||||
await ImageStorage.set('avatar', compressedFile)
|
||||
dispatch(setAvatar(await ImageStorage.get('avatar')))
|
||||
} catch (error: any) {
|
||||
window.message.error(error.message)
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ const NavbarCenterContainer = styled.div`
|
||||
`
|
||||
|
||||
const NavbarRightContainer = styled.div`
|
||||
min-width: var(--settings-width);
|
||||
min-width: var(--topic-list-width);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 12px;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TranslationOutlined } from '@ant-design/icons'
|
||||
import { FolderOutlined, TranslationOutlined } from '@ant-design/icons'
|
||||
import { isMac } from '@renderer/config/constant'
|
||||
import { isLocalAi, UserAvatar } from '@renderer/config/env'
|
||||
import useAvatar from '@renderer/hooks/useAvatar'
|
||||
@@ -66,6 +66,11 @@ const Sidebar: FC = () => {
|
||||
<i className="iconfont icon-appstore"></i>
|
||||
</Icon>
|
||||
</StyledLink>
|
||||
<StyledLink onClick={() => to('/files')}>
|
||||
<Icon className={isRoute('/files')}>
|
||||
<FolderOutlined />
|
||||
</Icon>
|
||||
</StyledLink>
|
||||
</Menus>
|
||||
</MainMenus>
|
||||
<Menus>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export const DEFAULT_TEMPERATURE = 0.7
|
||||
export const DEFAULT_CONEXTCOUNT = 5
|
||||
export const DEFAULT_CONEXTCOUNT = 6
|
||||
export const DEFAULT_MAX_TOKENS = 4096
|
||||
export const FONT_FAMILY =
|
||||
"Ubuntu, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif"
|
||||
|
||||
@@ -2,5 +2,4 @@ export { default as UserAvatar } from '@renderer/assets/images/avatar.png'
|
||||
export { default as AppLogo } from '@renderer/assets/images/logo.png'
|
||||
|
||||
export const APP_NAME = 'Cherry Studio'
|
||||
|
||||
export const isLocalAi = false
|
||||
|
||||
@@ -4,64 +4,88 @@ import BaiduAiAppLogo from '@renderer/assets/images/apps/baidu-ai.png'
|
||||
import DevvAppLogo from '@renderer/assets/images/apps/devv.png'
|
||||
import MetasoAppLogo from '@renderer/assets/images/apps/metaso.webp'
|
||||
import PerplexityAppLogo from '@renderer/assets/images/apps/perplexity.webp'
|
||||
import PoeAppLogo from '@renderer/assets/images/apps/poe.webp'
|
||||
import SensetimeAppLogo from '@renderer/assets/images/apps/sensetime.png'
|
||||
import SparkDeskAppLogo from '@renderer/assets/images/apps/sparkdesk.png'
|
||||
import TiangongAiLogo from '@renderer/assets/images/apps/tiangong.png'
|
||||
import TencentYuanbaoAppLogo from '@renderer/assets/images/apps/yuanbao.png'
|
||||
import ZhihuAppLogo from '@renderer/assets/images/apps/zhihu.png'
|
||||
import MinApp from '@renderer/components/MinApp'
|
||||
import { PROVIDER_CONFIG } from '@renderer/config/provider'
|
||||
import { MinAppType } from '@renderer/types'
|
||||
|
||||
const _apps: MinAppType[] = [
|
||||
{
|
||||
name: 'AI 助手',
|
||||
logo: AiAssistantAppLogo,
|
||||
url: 'https://bot.360.com/'
|
||||
},
|
||||
{
|
||||
name: '文心一言',
|
||||
logo: BaiduAiAppLogo,
|
||||
url: 'https://yiyan.baidu.com/'
|
||||
},
|
||||
{
|
||||
name: 'SparkDesk',
|
||||
logo: SparkDeskAppLogo,
|
||||
url: 'https://xinghuo.xfyun.cn/desk'
|
||||
},
|
||||
{
|
||||
name: '腾讯元宝',
|
||||
logo: TencentYuanbaoAppLogo,
|
||||
url: 'https://yuanbao.tencent.com/chat'
|
||||
},
|
||||
{
|
||||
name: '商量',
|
||||
logo: SensetimeAppLogo,
|
||||
url: 'https://chat.sensetime.com/wb/chat'
|
||||
},
|
||||
{
|
||||
id: '360-ai-so',
|
||||
name: '360AI搜索',
|
||||
logo: AiSearchAppLogo,
|
||||
url: 'https://so.360.com/'
|
||||
},
|
||||
{
|
||||
id: '360-ai-bot',
|
||||
name: 'AI 助手',
|
||||
logo: AiAssistantAppLogo,
|
||||
url: 'https://bot.360.com/'
|
||||
},
|
||||
{
|
||||
id: 'baidu-ai-chat',
|
||||
name: '文心一言',
|
||||
logo: BaiduAiAppLogo,
|
||||
url: 'https://yiyan.baidu.com/'
|
||||
},
|
||||
{
|
||||
id: 'tencent-yuanbao',
|
||||
name: '腾讯元宝',
|
||||
logo: TencentYuanbaoAppLogo,
|
||||
url: 'https://yuanbao.tencent.com/chat'
|
||||
},
|
||||
{
|
||||
id: 'sensetime-chat',
|
||||
name: '商量',
|
||||
logo: SensetimeAppLogo,
|
||||
url: 'https://chat.sensetime.com/wb/chat'
|
||||
},
|
||||
{
|
||||
id: 'spark-desk',
|
||||
name: 'SparkDesk',
|
||||
logo: SparkDeskAppLogo,
|
||||
url: 'https://xinghuo.xfyun.cn/desk'
|
||||
},
|
||||
{
|
||||
id: 'metaso',
|
||||
name: '秘塔AI搜索',
|
||||
logo: MetasoAppLogo,
|
||||
url: 'https://metaso.cn/'
|
||||
},
|
||||
{
|
||||
name: '天工AI',
|
||||
logo: TiangongAiLogo,
|
||||
url: 'https://www.tiangong.cn/'
|
||||
id: 'poe',
|
||||
name: 'Poe',
|
||||
logo: PoeAppLogo,
|
||||
url: 'https://poe.com'
|
||||
},
|
||||
{
|
||||
id: 'perplexity',
|
||||
name: 'perplexity',
|
||||
logo: PerplexityAppLogo,
|
||||
url: 'https://www.perplexity.ai/'
|
||||
},
|
||||
{
|
||||
id: 'devv',
|
||||
name: 'DEVV_',
|
||||
logo: DevvAppLogo,
|
||||
url: 'https://devv.ai/'
|
||||
},
|
||||
{
|
||||
name: 'perplexity',
|
||||
logo: PerplexityAppLogo,
|
||||
url: 'https://www.perplexity.ai/'
|
||||
id: 'tiangong-ai',
|
||||
name: '天工AI',
|
||||
logo: TiangongAiLogo,
|
||||
url: 'https://www.tiangong.cn/'
|
||||
},
|
||||
{
|
||||
id: 'zhihu-zhiada',
|
||||
name: '知乎直答',
|
||||
logo: ZhihuAppLogo,
|
||||
url: 'https://zhida.zhihu.com/'
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Model } from '@renderer/types'
|
||||
|
||||
const TEXT_TO_IMAGE_REGEX = /flux|diffusion|stabilityai|sd-turbo|dall|cogview/i
|
||||
const VISION_REGEX = /llava|moondream|minicpm|gemini-1.5|claude-3|vision|glm-4v|gpt-4|qwen-vl/i
|
||||
const EMBEDDING_REGEX = /embedding/i
|
||||
|
||||
export const SYSTEM_MODELS: Record<string, Model[]> = {
|
||||
@@ -117,6 +118,14 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
|
||||
group: 'DeepSeek Coder'
|
||||
}
|
||||
],
|
||||
github: [
|
||||
{
|
||||
id: 'gpt-4o',
|
||||
provider: 'github',
|
||||
name: 'OpenAI GPT-4o',
|
||||
group: 'OpenAI'
|
||||
}
|
||||
],
|
||||
yi: [
|
||||
{
|
||||
id: 'yi-large',
|
||||
@@ -387,3 +396,7 @@ export function isTextToImageModel(model: Model): boolean {
|
||||
export function isEmbeddingModel(model: Model): boolean {
|
||||
return EMBEDDING_REGEX.test(model.id)
|
||||
}
|
||||
|
||||
export function isVisionModel(model: Model): boolean {
|
||||
return VISION_REGEX.test(model.id)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import BaichuanModelLogo from '@renderer/assets/images/models/baichuan.png'
|
||||
import ChatGLMModelLogo from '@renderer/assets/images/models/chatglm.png'
|
||||
import ChatGPTModelLogo from '@renderer/assets/images/models/chatgpt.jpeg'
|
||||
import ClaudeModelLogo from '@renderer/assets/images/models/claude.png'
|
||||
import CohereModelLogo from '@renderer/assets/images/models/cohere.webp'
|
||||
import DeepSeekModelLogo from '@renderer/assets/images/models/deepseek.png'
|
||||
import DoubaoModelLogo from '@renderer/assets/images/models/doubao.png'
|
||||
import EmbeddingModelLogo from '@renderer/assets/images/models/embedding.png'
|
||||
@@ -25,6 +26,7 @@ import DashScopeProviderLogo from '@renderer/assets/images/providers/dashscope.p
|
||||
import DeepSeekProviderLogo from '@renderer/assets/images/providers/deepseek.png'
|
||||
import DoubaoProviderLogo from '@renderer/assets/images/providers/doubao.png'
|
||||
import GeminiProviderLogo from '@renderer/assets/images/providers/gemini.png'
|
||||
import GithubProviderLogo from '@renderer/assets/images/providers/github.svg'
|
||||
import GraphRagProviderLogo from '@renderer/assets/images/providers/graph-rag.png'
|
||||
import GroqProviderLogo from '@renderer/assets/images/providers/groq.png'
|
||||
import MinimaxProviderLogo from '@renderer/assets/images/providers/minimax.png'
|
||||
@@ -76,6 +78,8 @@ export function getProviderLogo(providerId: string) {
|
||||
return GraphRagProviderLogo
|
||||
case 'minimax':
|
||||
return MinimaxProviderLogo
|
||||
case 'github':
|
||||
return GithubProviderLogo
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
@@ -106,7 +110,9 @@ export function getModelLogo(modelId: string) {
|
||||
palm: PalmModelLogo,
|
||||
step: StepModelLogo,
|
||||
abab: HailuoModelLogo,
|
||||
'ep-202': DoubaoModelLogo
|
||||
'ep-202': DoubaoModelLogo,
|
||||
cohere: CohereModelLogo,
|
||||
command: CohereModelLogo
|
||||
}
|
||||
|
||||
for (const key in logoMap) {
|
||||
@@ -121,8 +127,7 @@ export function getModelLogo(modelId: string) {
|
||||
export const PROVIDER_CONFIG = {
|
||||
openai: {
|
||||
api: {
|
||||
url: 'https://api.openai.com',
|
||||
editable: true
|
||||
url: 'https://api.openai.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://openai.com/',
|
||||
@@ -131,6 +136,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://platform.openai.com/docs/models'
|
||||
},
|
||||
app: {
|
||||
id: 'openai',
|
||||
name: 'ChatGPT',
|
||||
url: 'https://chatgpt.com/',
|
||||
logo: OpenAiProviderLogo
|
||||
@@ -138,8 +144,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
gemini: {
|
||||
api: {
|
||||
url: 'https://generativelanguage.googleapis.com',
|
||||
editable: false
|
||||
url: 'https://generativelanguage.googleapis.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://gemini.google.com/',
|
||||
@@ -148,6 +153,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://ai.google.dev/gemini-api/docs/models/gemini'
|
||||
},
|
||||
app: {
|
||||
id: 'gemini',
|
||||
name: 'Gemini',
|
||||
url: 'https://gemini.google.com/',
|
||||
logo: GeminiProviderLogo
|
||||
@@ -155,8 +161,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
silicon: {
|
||||
api: {
|
||||
url: 'https://cloud.siliconflow.cn',
|
||||
editable: false
|
||||
url: 'https://cloud.siliconflow.cn'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://www.siliconflow.cn/',
|
||||
@@ -165,6 +170,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://docs.siliconflow.cn/docs/model-names'
|
||||
},
|
||||
app: {
|
||||
id: 'silicon',
|
||||
name: 'SiliconFlow',
|
||||
url: 'https://cloud.siliconflow.cn/playground/chat',
|
||||
logo: SiliconFlowProviderLogo
|
||||
@@ -172,8 +178,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
deepseek: {
|
||||
api: {
|
||||
url: 'https://api.deepseek.com',
|
||||
editable: false
|
||||
url: 'https://api.deepseek.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://deepseek.com/',
|
||||
@@ -182,15 +187,26 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://platform.deepseek.com/api-docs/'
|
||||
},
|
||||
app: {
|
||||
id: 'deepseek',
|
||||
name: 'DeepSeek',
|
||||
url: 'https://chat.deepseek.com/',
|
||||
logo: DeepSeekProviderLogo
|
||||
}
|
||||
},
|
||||
github: {
|
||||
api: {
|
||||
url: 'https://models.inference.ai.azure.com/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://github.com/marketplace/models',
|
||||
apiKey: 'https://github.com/settings/tokens',
|
||||
docs: 'https://docs.github.com/en/github-models',
|
||||
models: 'https://github.com/marketplace/models'
|
||||
}
|
||||
},
|
||||
yi: {
|
||||
api: {
|
||||
url: 'https://api.lingyiwanwu.com',
|
||||
editable: false
|
||||
url: 'https://api.lingyiwanwu.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://platform.lingyiwanwu.com/',
|
||||
@@ -199,6 +215,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://platform.lingyiwanwu.com/docs#%E6%A8%A1%E5%9E%8B'
|
||||
},
|
||||
app: {
|
||||
id: 'yi',
|
||||
name: 'Yi',
|
||||
url: 'https://www.wanzhi.com/',
|
||||
logo: YiProviderLogo
|
||||
@@ -206,8 +223,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
zhipu: {
|
||||
api: {
|
||||
url: 'https://open.bigmodel.cn/api/paas/v4/',
|
||||
editable: false
|
||||
url: 'https://open.bigmodel.cn/api/paas/v4/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://open.bigmodel.cn/',
|
||||
@@ -216,6 +232,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://open.bigmodel.cn/modelcenter/square'
|
||||
},
|
||||
app: {
|
||||
id: 'zhipu',
|
||||
name: '智谱',
|
||||
url: 'https://chatglm.cn/main/alltoolsdetail',
|
||||
logo: ZhipuProviderLogo
|
||||
@@ -223,8 +240,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
moonshot: {
|
||||
api: {
|
||||
url: 'https://api.moonshot.cn',
|
||||
editable: false
|
||||
url: 'https://api.moonshot.cn'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://moonshot.ai/',
|
||||
@@ -233,6 +249,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://platform.moonshot.cn/docs/intro#%E6%A8%A1%E5%9E%8B%E5%88%97%E8%A1%A8'
|
||||
},
|
||||
app: {
|
||||
id: 'moonshot',
|
||||
name: 'Kimi',
|
||||
url: 'https://kimi.moonshot.cn/',
|
||||
logo: KimiAppLogo
|
||||
@@ -240,8 +257,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
baichuan: {
|
||||
api: {
|
||||
url: 'https://api.baichuan-ai.com',
|
||||
editable: false
|
||||
url: 'https://api.baichuan-ai.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://www.baichuan-ai.com/',
|
||||
@@ -250,6 +266,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://platform.baichuan-ai.com/price'
|
||||
},
|
||||
app: {
|
||||
id: 'baichuan',
|
||||
name: '百小应',
|
||||
url: 'https://ying.baichuan-ai.com/chat',
|
||||
logo: BaicuanAppLogo
|
||||
@@ -257,8 +274,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
dashscope: {
|
||||
api: {
|
||||
url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/',
|
||||
editable: false
|
||||
url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://dashscope.aliyun.com/',
|
||||
@@ -267,6 +283,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://dashscope.console.aliyun.com/model'
|
||||
},
|
||||
app: {
|
||||
id: 'dashscope',
|
||||
name: '通义千问',
|
||||
url: 'https://tongyi.aliyun.com/qianwen/',
|
||||
logo: QwenModelLogo
|
||||
@@ -274,8 +291,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
stepfun: {
|
||||
api: {
|
||||
url: 'https://api.stepfun.com',
|
||||
editable: false
|
||||
url: 'https://api.stepfun.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://platform.stepfun.com/',
|
||||
@@ -284,6 +300,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://platform.stepfun.com/docs/llm/text'
|
||||
},
|
||||
app: {
|
||||
id: 'stepfun',
|
||||
name: '跃问',
|
||||
url: 'https://yuewen.cn/chats/new',
|
||||
logo: YuewenAppLogo
|
||||
@@ -291,8 +308,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
doubao: {
|
||||
api: {
|
||||
url: 'https://ark.cn-beijing.volces.com/api/v3/',
|
||||
editable: true
|
||||
url: 'https://ark.cn-beijing.volces.com/api/v3/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://console.volcengine.com/ark/',
|
||||
@@ -301,6 +317,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://console.volcengine.com/ark/region:ark+cn-beijing/endpoint'
|
||||
},
|
||||
app: {
|
||||
id: 'doubao',
|
||||
name: '豆包',
|
||||
url: 'https://www.doubao.com/chat/',
|
||||
logo: DoubaoProviderLogo
|
||||
@@ -308,8 +325,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
minimax: {
|
||||
api: {
|
||||
url: 'https://api.minimax.chat/v1/',
|
||||
editable: true
|
||||
url: 'https://api.minimax.chat/v1/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://platform.minimaxi.com/',
|
||||
@@ -318,6 +334,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://platform.minimaxi.com/document/Models'
|
||||
},
|
||||
app: {
|
||||
id: 'minimax',
|
||||
name: '海螺',
|
||||
url: 'https://hailuoai.com/',
|
||||
logo: HailuoModelLogo
|
||||
@@ -325,14 +342,12 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
'graphrag-kylin-mountain': {
|
||||
api: {
|
||||
url: '',
|
||||
editable: true
|
||||
url: ''
|
||||
}
|
||||
},
|
||||
openrouter: {
|
||||
api: {
|
||||
url: 'https://openrouter.ai/api/v1/',
|
||||
editable: false
|
||||
url: 'https://openrouter.ai/api/v1/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://openrouter.ai/',
|
||||
@@ -343,8 +358,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
groq: {
|
||||
api: {
|
||||
url: 'https://api.groq.com/openai',
|
||||
editable: false
|
||||
url: 'https://api.groq.com/openai'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://groq.com/',
|
||||
@@ -353,6 +367,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://console.groq.com/docs/models'
|
||||
},
|
||||
app: {
|
||||
id: 'groq',
|
||||
name: 'Groq',
|
||||
url: 'https://chat.groq.com/',
|
||||
logo: GroqProviderLogo
|
||||
@@ -360,8 +375,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
ollama: {
|
||||
api: {
|
||||
url: 'http://localhost:11434/v1/',
|
||||
editable: true
|
||||
url: 'http://localhost:11434/v1/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://ollama.com/',
|
||||
@@ -371,8 +385,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
anthropic: {
|
||||
api: {
|
||||
url: 'https://api.anthropic.com/',
|
||||
editable: true
|
||||
url: 'https://api.anthropic.com/'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://anthropic.com/',
|
||||
@@ -381,6 +394,7 @@ export const PROVIDER_CONFIG = {
|
||||
models: 'https://docs.anthropic.com/en/docs/about-claude/models'
|
||||
},
|
||||
app: {
|
||||
id: 'anthropic',
|
||||
name: 'Claude',
|
||||
url: 'https://claude.ai/',
|
||||
logo: AnthropicProviderLogo
|
||||
@@ -388,8 +402,7 @@ export const PROVIDER_CONFIG = {
|
||||
},
|
||||
aihubmix: {
|
||||
api: {
|
||||
url: 'https://aihubmix.com',
|
||||
editable: false
|
||||
url: 'https://aihubmix.com'
|
||||
},
|
||||
websites: {
|
||||
official: 'https://aihubmix.com/',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { ThemeMode } from '@renderer/store/settings'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
import React, { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
|
||||
|
||||
interface ThemeContextType {
|
||||
|
||||
27
src/renderer/src/databases/index.ts
Normal file
27
src/renderer/src/databases/index.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { FileType, Topic } from '@renderer/types'
|
||||
import { Dexie, type EntityTable } from 'dexie'
|
||||
|
||||
import { populateTopics } from './populate'
|
||||
|
||||
// Database declaration (move this to its own module also)
|
||||
export const db = new Dexie('CherryStudio') as Dexie & {
|
||||
files: EntityTable<FileType, 'id'>
|
||||
topics: EntityTable<Pick<Topic, 'id' | 'messages'>, 'id'>
|
||||
settings: EntityTable<{ id: string; value: any }, 'id'>
|
||||
}
|
||||
|
||||
db.version(1).stores({
|
||||
files: 'id, name, origin_name, path, size, ext, type, created_at, count'
|
||||
})
|
||||
|
||||
db.version(2)
|
||||
.stores({
|
||||
files: 'id, name, origin_name, path, size, ext, type, created_at, count',
|
||||
topics: '&id, messages',
|
||||
settings: '&id, value'
|
||||
})
|
||||
.upgrade(populateTopics)
|
||||
|
||||
db.on('populate', populateTopics)
|
||||
|
||||
export default db
|
||||
27
src/renderer/src/databases/populate.ts
Normal file
27
src/renderer/src/databases/populate.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import i18n from '@renderer/i18n'
|
||||
import { Transaction } from 'dexie'
|
||||
import localforage from 'localforage'
|
||||
|
||||
export async function populateTopics(trans: Transaction) {
|
||||
const indexedKeys = await localforage.keys()
|
||||
|
||||
if (indexedKeys.length > 0) {
|
||||
for (const key of indexedKeys) {
|
||||
const value: any = await localforage.getItem(key)
|
||||
if (key.startsWith('topic:')) {
|
||||
await trans.db.table('topics').add({ id: value.id, messages: value.messages })
|
||||
}
|
||||
if (key === 'image://avatar') {
|
||||
await trans.db.table('settings').add({ id: key, value: await localforage.getItem(key) })
|
||||
}
|
||||
}
|
||||
|
||||
window.modal.success({
|
||||
title: i18n.t('message.upgrade.success.title'),
|
||||
content: i18n.t('message.upgrade.success.content'),
|
||||
okText: i18n.t('message.upgrade.success.button'),
|
||||
centered: true,
|
||||
onOk: () => window.api.reload()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { isLocalAi } from '@renderer/config/env'
|
||||
import db from '@renderer/databases'
|
||||
import i18n from '@renderer/i18n'
|
||||
import LocalStorage from '@renderer/services/storage'
|
||||
import { useAppDispatch } from '@renderer/store'
|
||||
import { setAvatar } from '@renderer/store/runtime'
|
||||
import { runAsyncFunction } from '@renderer/utils'
|
||||
import { useLiveQuery } from 'dexie-react-hooks'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
import { useDefaultModel } from './useAssistant'
|
||||
@@ -11,16 +12,13 @@ import { useSettings } from './useSettings'
|
||||
|
||||
export function useAppInit() {
|
||||
const dispatch = useAppDispatch()
|
||||
const { proxyUrl } = useSettings()
|
||||
const { language } = useSettings()
|
||||
const { proxyUrl, language } = useSettings()
|
||||
const { setDefaultModel, setTopicNamingModel, setTranslateModel } = useDefaultModel()
|
||||
const avatar = useLiveQuery(() => db.settings.get('image://avatar'))
|
||||
|
||||
useEffect(() => {
|
||||
runAsyncFunction(async () => {
|
||||
const storedImage = await LocalStorage.getImage('avatar')
|
||||
storedImage && dispatch(setAvatar(storedImage))
|
||||
})
|
||||
}, [dispatch])
|
||||
avatar?.value && dispatch(setAvatar(avatar.value))
|
||||
}, [avatar, dispatch])
|
||||
|
||||
useEffect(() => {
|
||||
runAsyncFunction(async () => {
|
||||
|
||||
@@ -16,7 +16,8 @@ import {
|
||||
} from '@renderer/store/assistants'
|
||||
import { setDefaultModel, setTopicNamingModel, setTranslateModel } from '@renderer/store/llm'
|
||||
import { Assistant, AssistantSettings, Model, Topic } from '@renderer/types'
|
||||
import localforage from 'localforage'
|
||||
|
||||
import { TopicManager } from './useTopic'
|
||||
|
||||
export function useAssistants() {
|
||||
const { assistants } = useAppSelector((state) => state.assistants)
|
||||
@@ -29,9 +30,8 @@ export function useAssistants() {
|
||||
removeAssistant: (id: string) => {
|
||||
dispatch(removeAssistant({ id }))
|
||||
const assistant = assistants.find((a) => a.id === id)
|
||||
if (assistant) {
|
||||
assistant.topics.forEach((id) => localforage.removeItem(`topic:${id}`))
|
||||
}
|
||||
const topics = assistant?.topics || []
|
||||
topics.forEach(({ id }) => TopicManager.removeTopic(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,10 @@ export function useAssistant(id: string) {
|
||||
assistant,
|
||||
model: assistant?.model ?? defaultModel,
|
||||
addTopic: (topic: Topic) => dispatch(addTopic({ assistantId: assistant.id, topic })),
|
||||
removeTopic: (topic: Topic) => dispatch(removeTopic({ assistantId: assistant.id, topic })),
|
||||
removeTopic: (topic: Topic) => {
|
||||
TopicManager.removeTopic(topic.id)
|
||||
dispatch(removeTopic({ assistantId: assistant.id, topic }))
|
||||
},
|
||||
updateTopic: (topic: Topic) => dispatch(updateTopic({ assistantId: assistant.id, topic })),
|
||||
updateTopics: (topics: Topic[]) => dispatch(updateTopics({ assistantId: assistant.id, topics })),
|
||||
removeAllTopics: () => dispatch(removeAllTopics({ assistantId: assistant.id })),
|
||||
|
||||
@@ -4,9 +4,9 @@ import {
|
||||
setSendMessageShortcut as _setSendMessageShortcut,
|
||||
setTheme,
|
||||
setTopicPosition,
|
||||
setWindowStyle,
|
||||
ThemeMode
|
||||
setWindowStyle
|
||||
} from '@renderer/store/settings'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
|
||||
export function useSettings() {
|
||||
const settings = useAppSelector((state) => state.settings)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import db from '@renderer/databases'
|
||||
import { deleteMessageFiles } from '@renderer/services/messages'
|
||||
import { Assistant, Topic } from '@renderer/types'
|
||||
import { find } from 'lodash'
|
||||
import { useEffect, useState } from 'react'
|
||||
@@ -10,6 +12,8 @@ export function useActiveTopic(_assistant: Assistant) {
|
||||
const { assistant } = useAssistant(_assistant.id)
|
||||
const [activeTopic, setActiveTopic] = useState(_activeTopic || assistant?.topics[0])
|
||||
|
||||
_activeTopic = activeTopic
|
||||
|
||||
useEffect(() => {
|
||||
// activeTopic not in assistant.topics
|
||||
if (assistant && !find(assistant.topics, { id: activeTopic?.id })) {
|
||||
@@ -23,3 +27,38 @@ export function useActiveTopic(_assistant: Assistant) {
|
||||
export function getTopic(assistant: Assistant, topicId: string) {
|
||||
return assistant?.topics.find((topic) => topic.id === topicId)
|
||||
}
|
||||
|
||||
export class TopicManager {
|
||||
static async getTopic(id: string) {
|
||||
return await db.topics.get(id)
|
||||
}
|
||||
|
||||
static async getTopicMessages(id: string) {
|
||||
const topic = await this.getTopic(id)
|
||||
return topic ? topic.messages : []
|
||||
}
|
||||
|
||||
static async removeTopic(id: string) {
|
||||
const messages = await this.getTopicMessages(id)
|
||||
|
||||
for (const message of messages) {
|
||||
await deleteMessageFiles(message)
|
||||
}
|
||||
|
||||
db.topics.delete(id)
|
||||
}
|
||||
|
||||
static async clearTopicMessages(id: string) {
|
||||
const topic = await this.getTopic(id)
|
||||
|
||||
if (topic) {
|
||||
for (const message of topic?.messages ?? []) {
|
||||
await deleteMessageFiles(message)
|
||||
}
|
||||
|
||||
topic.messages = []
|
||||
|
||||
await db.topics.update(id, topic)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,9 @@ const resources = {
|
||||
add: 'Add',
|
||||
added: 'Added',
|
||||
manage: 'Manage',
|
||||
select_model: 'Select Model'
|
||||
select_model: 'Select Model',
|
||||
'show.all': 'Show All',
|
||||
collapse: 'Collapse'
|
||||
},
|
||||
message: {
|
||||
copied: 'Copied!',
|
||||
@@ -53,9 +55,13 @@ const resources = {
|
||||
'chat.completion.paused': 'Chat completion paused',
|
||||
'switch.disabled': 'Switching is disabled while the assistant is generating',
|
||||
'restore.success': 'Restored successfully',
|
||||
'backup.success': 'Backup successful',
|
||||
'reset.confirm.content': 'Are you sure you want to clear all data?',
|
||||
'reset.double.confirm.title': 'DATA LOST !!!',
|
||||
'reset.double.confirm.content': 'All data will be lost, do you want to continue?'
|
||||
'reset.double.confirm.content': 'All data will be lost, do you want to continue?',
|
||||
'upgrade.success.title': 'Upgrade successfully',
|
||||
'upgrade.success.content': 'Please restart the application to complete the upgrade',
|
||||
'upgrade.success.button': 'Restart'
|
||||
},
|
||||
chat: {
|
||||
save: 'Save',
|
||||
@@ -72,10 +78,11 @@ const resources = {
|
||||
'input.new_topic': 'New Topic',
|
||||
'input.topics': ' Topics ',
|
||||
'input.clear': 'Clear',
|
||||
'input.new.context': 'Clear Context',
|
||||
'input.expand': 'Expand',
|
||||
'input.collapse': 'Collapse',
|
||||
'input.clear.title': 'Clear all messages?',
|
||||
'input.clear.content': 'Are you sure to clear all messages?',
|
||||
'input.clear.content': 'Do you want to clear all messages of the current topic?',
|
||||
'input.placeholder': 'Type your message here...',
|
||||
'input.send': 'Send',
|
||||
'input.pause': 'Pause',
|
||||
@@ -95,20 +102,30 @@ const resources = {
|
||||
'settings.set_as_default': 'Apply to default assistant',
|
||||
'settings.max': 'Max',
|
||||
'suggestions.title': 'Suggested Questions',
|
||||
'add.assistant.title': 'Add Assistant'
|
||||
'add.assistant.title': 'Add Assistant',
|
||||
'message.new.context': 'New Context',
|
||||
'message.new.branch': 'New Branch',
|
||||
'assistant.search.placeholder': 'Search'
|
||||
},
|
||||
files: {
|
||||
title: 'Files',
|
||||
file: 'File',
|
||||
name: 'Name',
|
||||
size: 'Size',
|
||||
created_at: 'Created At'
|
||||
},
|
||||
agents: {
|
||||
title: 'Agents',
|
||||
my_agents: 'My Agents',
|
||||
'add.title': 'Add Agent',
|
||||
'edit.title': 'Edit Agent',
|
||||
title: 'Assistants',
|
||||
my_agents: 'My Assistants',
|
||||
'add.title': 'Add Assistant',
|
||||
'edit.title': 'Edit Assistant',
|
||||
'add.name': 'Name',
|
||||
'add.name.placeholder': 'Enter name',
|
||||
'add.prompt': 'Prompt',
|
||||
'add.prompt.placeholder': 'Enter prompt',
|
||||
'add.button': 'Add',
|
||||
'manage.title': 'Manage Agents',
|
||||
'delete.popup.content': 'Are you sure you want to delete this agent?',
|
||||
'manage.title': 'Manage Assistants',
|
||||
'delete.popup.content': 'Are you sure you want to delete this assistant?',
|
||||
'tag.default': 'Default',
|
||||
'tag.system': 'System',
|
||||
'tag.user': 'Mine'
|
||||
@@ -131,7 +148,8 @@ const resources = {
|
||||
stepfun: 'StepFun',
|
||||
doubao: 'Doubao',
|
||||
minimax: 'MiniMax',
|
||||
'graphrag-kylin-mountain': 'GraphRAG'
|
||||
'graphrag-kylin-mountain': 'GraphRAG',
|
||||
github: 'GitHub Models'
|
||||
},
|
||||
settings: {
|
||||
title: 'Settings',
|
||||
@@ -286,7 +304,9 @@ const resources = {
|
||||
add: '添加',
|
||||
added: '已添加',
|
||||
manage: '管理',
|
||||
select_model: '选择模型'
|
||||
select_model: '选择模型',
|
||||
'show.all': '显示全部',
|
||||
collapse: '收起'
|
||||
},
|
||||
message: {
|
||||
copied: '已复制',
|
||||
@@ -302,9 +322,13 @@ const resources = {
|
||||
'chat.completion.paused': '会话已停止',
|
||||
'switch.disabled': '模型回复完成后才能切换',
|
||||
'restore.success': '恢复成功',
|
||||
'backup.success': '备份成功',
|
||||
'reset.confirm.content': '确定要重置所有数据吗?',
|
||||
'reset.double.confirm.title': '数据丢失!!!',
|
||||
'reset.double.confirm.content': '你的全部数据都会丢失,如果没有备份数据,将无法恢复,确定要继续吗?'
|
||||
'reset.double.confirm.content': '你的全部数据都会丢失,如果没有备份数据,将无法恢复,确定要继续吗?',
|
||||
'upgrade.success.title': '升级成功',
|
||||
'upgrade.success.content': '重启应用以完成升级',
|
||||
'upgrade.success.button': '重启'
|
||||
},
|
||||
chat: {
|
||||
save: '保存',
|
||||
@@ -320,11 +344,12 @@ const resources = {
|
||||
'topics.list': '话题列表',
|
||||
'input.new_topic': '新话题',
|
||||
'input.topics': ' 话题 ',
|
||||
'input.clear': '清除',
|
||||
'input.clear': '清除会话消息',
|
||||
'input.new.context': '清除上下文',
|
||||
'input.expand': '展开',
|
||||
'input.collapse': '收起',
|
||||
'input.clear.title': '清除所有消息?',
|
||||
'input.clear.content': '确定要清除所有消息吗?',
|
||||
'input.clear.title': '清除消息?',
|
||||
'input.clear.content': '确定要清除当前会话所有消息吗?',
|
||||
'input.placeholder': '在这里输入消息...',
|
||||
'input.send': '发送',
|
||||
'input.pause': '暂停',
|
||||
@@ -345,7 +370,17 @@ const resources = {
|
||||
'settings.set_as_default': '应用到默认助手',
|
||||
'settings.max': '不限',
|
||||
'suggestions.title': '建议的问题',
|
||||
'add.assistant.title': '添加智能体'
|
||||
'add.assistant.title': '添加智能体',
|
||||
'message.new.context': '清除上下文',
|
||||
'message.new.branch': '新分支',
|
||||
'assistant.search.placeholder': '搜索'
|
||||
},
|
||||
files: {
|
||||
title: '文件',
|
||||
file: '文件',
|
||||
name: '文件名',
|
||||
size: '大小',
|
||||
created_at: '创建时间'
|
||||
},
|
||||
agents: {
|
||||
title: '智能体',
|
||||
@@ -381,7 +416,8 @@ const resources = {
|
||||
stepfun: '阶跃星辰',
|
||||
doubao: '豆包',
|
||||
minimax: 'MiniMax',
|
||||
'graphrag-kylin-mountain': 'GraphRAG'
|
||||
'graphrag-kylin-mountain': 'GraphRAG',
|
||||
github: 'GitHub Models'
|
||||
},
|
||||
settings: {
|
||||
title: '设置',
|
||||
|
||||
@@ -2,7 +2,7 @@ import KeyvStorage from '@kangfenmao/keyv-storage'
|
||||
import localforage from 'localforage'
|
||||
|
||||
import { APP_NAME } from './config/env'
|
||||
import { ThemeMode } from './store/settings'
|
||||
import { ThemeMode } from './types'
|
||||
import { loadScript } from './utils'
|
||||
|
||||
export async function initMermaid(theme: ThemeMode) {
|
||||
|
||||
@@ -33,6 +33,7 @@ const AppsPage: FC = () => {
|
||||
icon: null,
|
||||
closable: true,
|
||||
maskClosable: true,
|
||||
centered: true,
|
||||
okButtonProps: { type: 'primary', disabled: Boolean(added) },
|
||||
okText: added ? t('button.added') : t('button.add'),
|
||||
onOk: () => onAddAgent(agent)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import 'emoji-picker-element'
|
||||
|
||||
import { LoadingOutlined, ThunderboltOutlined } from '@ant-design/icons'
|
||||
import EmojiPicker from '@renderer/components/EmojiPicker'
|
||||
import { TopView } from '@renderer/components/TopView'
|
||||
import { useAgents } from '@renderer/hooks/useAgents'
|
||||
import { fetchGenerate } from '@renderer/services/api'
|
||||
import { syncAgentToAssistant } from '@renderer/services/assistant'
|
||||
import { Agent } from '@renderer/types'
|
||||
import { getLeadingEmoji, uuid } from '@renderer/utils'
|
||||
@@ -29,6 +31,7 @@ const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
const { addAgent, updateAgent } = useAgents()
|
||||
const formRef = useRef<FormInstance>(null)
|
||||
const [emoji, setEmoji] = useState(agent?.emoji)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const onFinish = (values: FieldType) => {
|
||||
const _emoji = emoji || getLeadingEmoji(values.name)
|
||||
@@ -81,16 +84,44 @@ const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
}
|
||||
}, [agent, form])
|
||||
|
||||
const handleButtonClick = async () => {
|
||||
const prompt = `你是一个专业的 prompt 优化助手,我会给你一段prompt,你需要帮我优化它,仅回复优化后的 prompt 不要添加任何解释,使用 [CRISPE提示框架] 回复。`
|
||||
|
||||
const name = formRef.current?.getFieldValue('name')
|
||||
const content = formRef.current?.getFieldValue('prompt')
|
||||
const promptText = content || name
|
||||
|
||||
if (!promptText) {
|
||||
return
|
||||
}
|
||||
|
||||
if (content) {
|
||||
navigator.clipboard.writeText(content)
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const prefixedContent = `请帮我优化下面这段 prompt,使用 CRISPE 提示框架,请使用 Markdown 格式回复,不要使用 codeblock: ${promptText}`
|
||||
const generatedText = await fetchGenerate({ prompt, content: prefixedContent })
|
||||
formRef.current?.setFieldValue('prompt', generatedText)
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error)
|
||||
}
|
||||
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
style={{ marginTop: '10vh' }}
|
||||
title={agent ? t('agents.edit.title') : t('agents.add.title')}
|
||||
open={open}
|
||||
onOk={() => formRef.current?.submit()}
|
||||
onCancel={onCancel}
|
||||
maskClosable={false}
|
||||
afterClose={onClose}
|
||||
okText={agent ? t('common.save') : t('agents.add.button')}>
|
||||
okText={agent ? t('common.save') : t('agents.add.button')}
|
||||
centered>
|
||||
<Form
|
||||
ref={formRef}
|
||||
form={form}
|
||||
@@ -100,16 +131,28 @@ const PopupContainer: React.FC<Props> = ({ agent, resolve }) => {
|
||||
style={{ marginTop: 25 }}
|
||||
onFinish={onFinish}>
|
||||
<Form.Item name="name" label="Emoji">
|
||||
<Popover content={<EmojiPicker onEmojiClick={setEmoji} />} trigger="click" arrow>
|
||||
<Popover content={<EmojiPicker onEmojiClick={setEmoji} />} arrow>
|
||||
<Button icon={emoji && <span style={{ fontSize: 20 }}>{emoji}</span>}>{t('common.select')}</Button>
|
||||
</Popover>
|
||||
</Form.Item>
|
||||
<Form.Item name="name" label={t('agents.add.name')} rules={[{ required: true }]}>
|
||||
<Input placeholder={t('agents.add.name.placeholder')} spellCheck={false} allowClear />
|
||||
</Form.Item>
|
||||
<Form.Item name="prompt" label={t('agents.add.prompt')} rules={[{ required: true }]}>
|
||||
<TextArea placeholder={t('agents.add.prompt.placeholder')} spellCheck={false} rows={4} />
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Form.Item
|
||||
name="prompt"
|
||||
label={t('agents.add.prompt')}
|
||||
rules={[{ required: true }]}
|
||||
style={{ position: 'relative' }}>
|
||||
<TextArea placeholder={t('agents.add.prompt.placeholder')} spellCheck={false} rows={10} />
|
||||
</Form.Item>
|
||||
<Button
|
||||
icon={loading ? <LoadingOutlined /> : <ThunderboltOutlined />}
|
||||
onClick={handleButtonClick}
|
||||
style={{ position: 'absolute', top: 8, right: 8 }}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
)
|
||||
|
||||
@@ -35,13 +35,13 @@ const PopupContainer: React.FC = () => {
|
||||
|
||||
return (
|
||||
<Modal
|
||||
style={{ marginTop: '10vh' }}
|
||||
title={t('agents.manage.title')}
|
||||
open={open}
|
||||
onOk={onOk}
|
||||
onCancel={onCancel}
|
||||
afterClose={onClose}
|
||||
footer={null}>
|
||||
footer={null}
|
||||
centered>
|
||||
<Container>
|
||||
{agents.length > 0 && (
|
||||
<DragableList list={agents} onUpdate={updateAgents}>
|
||||
|
||||
@@ -4,23 +4,22 @@ import { Center } from '@renderer/components/Layout'
|
||||
import { getAllMinApps } from '@renderer/config/minapp'
|
||||
import { Empty, Input } from 'antd'
|
||||
import { isEmpty } from 'lodash'
|
||||
import { FC, useState } from 'react'
|
||||
import { FC, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import App from './App'
|
||||
|
||||
const list = getAllMinApps()
|
||||
|
||||
const AppsPage: FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const [search, setSearch] = useState('')
|
||||
const apps = useMemo(() => getAllMinApps(), [])
|
||||
|
||||
const apps = search
|
||||
? list.filter(
|
||||
const filteredApps = search
|
||||
? apps.filter(
|
||||
(app) => app.name.toLowerCase().includes(search.toLowerCase()) || app.url.includes(search.toLowerCase())
|
||||
)
|
||||
: list
|
||||
: apps
|
||||
|
||||
return (
|
||||
<Container>
|
||||
@@ -42,10 +41,10 @@ const AppsPage: FC = () => {
|
||||
</Navbar>
|
||||
<ContentContainer>
|
||||
<AppsContainer>
|
||||
{apps.map((app) => (
|
||||
<App key={app.name} app={app} />
|
||||
{filteredApps.map((app) => (
|
||||
<App key={app.id} app={app} />
|
||||
))}
|
||||
{isEmpty(apps) && (
|
||||
{isEmpty(filteredApps) && (
|
||||
<Center style={{ flex: 1 }}>
|
||||
<Empty />
|
||||
</Center>
|
||||
|
||||
82
src/renderer/src/pages/files/FilesPage.tsx
Normal file
82
src/renderer/src/pages/files/FilesPage.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
|
||||
import { VStack } from '@renderer/components/Layout'
|
||||
import db from '@renderer/databases'
|
||||
import { FileType } from '@renderer/types'
|
||||
import { Image, Table } from 'antd'
|
||||
import dayjs from 'dayjs'
|
||||
import { useLiveQuery } from 'dexie-react-hooks'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
const FilesPage: FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const files = useLiveQuery<FileType[]>(() => db.files.toArray())
|
||||
|
||||
const dataSource = files?.map((file) => ({
|
||||
key: file.id,
|
||||
file: <Image src={'file://' + file.path} preview={false} style={{ maxHeight: '40px' }} />,
|
||||
name: <a href={'file://' + file.path}>{file.origin_name}</a>,
|
||||
size: `${(file.size / 1024 / 1024).toFixed(2)} MB`,
|
||||
created_at: dayjs(file.created_at).format('MM-DD HH:mm')
|
||||
}))
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('files.file'),
|
||||
dataIndex: 'file',
|
||||
key: 'file',
|
||||
width: '300px'
|
||||
},
|
||||
{
|
||||
title: t('files.name'),
|
||||
dataIndex: 'name',
|
||||
key: 'name'
|
||||
},
|
||||
{
|
||||
title: t('files.size'),
|
||||
dataIndex: 'size',
|
||||
key: 'size',
|
||||
width: '100px'
|
||||
},
|
||||
{
|
||||
title: t('files.created_at'),
|
||||
dataIndex: 'created_at',
|
||||
key: 'created_at',
|
||||
width: '120px'
|
||||
}
|
||||
]
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Navbar>
|
||||
<NavbarCenter style={{ borderRight: 'none' }}>{t('files.title')}</NavbarCenter>
|
||||
</Navbar>
|
||||
<ContentContainer>
|
||||
<VStack style={{ flex: 1 }}>
|
||||
<Table dataSource={dataSource} columns={columns} style={{ width: '100%', height: '100%' }} size="small" />
|
||||
</VStack>
|
||||
</ContentContainer>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
`
|
||||
|
||||
const ContentContainer = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
overflow-y: scroll;
|
||||
background-color: var(--color-background);
|
||||
padding: 20px;
|
||||
`
|
||||
|
||||
export default FilesPage
|
||||
@@ -1,17 +1,18 @@
|
||||
import { CopyOutlined, DeleteOutlined, EditOutlined, MinusCircleOutlined } from '@ant-design/icons'
|
||||
import { DeleteOutlined, EditOutlined, MinusCircleOutlined } from '@ant-design/icons'
|
||||
import DragableList from '@renderer/components/DragableList'
|
||||
import CopyIcon from '@renderer/components/Icons/CopyIcon'
|
||||
import AssistantSettingPopup from '@renderer/components/Popups/AssistantSettingPopup'
|
||||
import { useAssistant, useAssistants } from '@renderer/hooks/useAssistant'
|
||||
import { useShowTopics } from '@renderer/hooks/useStore'
|
||||
import { getDefaultTopic, syncAsistantToAgent } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { useAppSelector } from '@renderer/store'
|
||||
import { useAppDispatch, useAppSelector } from '@renderer/store'
|
||||
import { setSearching } from '@renderer/store/runtime'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import { uuid } from '@renderer/utils'
|
||||
import { Dropdown } from 'antd'
|
||||
import { Dropdown, Input, InputRef } from 'antd'
|
||||
import { ItemType } from 'antd/es/menu/interface'
|
||||
import { last } from 'lodash'
|
||||
import { FC, useCallback } from 'react'
|
||||
import { isEmpty, last } from 'lodash'
|
||||
import { FC, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
@@ -24,9 +25,11 @@ interface Props {
|
||||
const Assistants: FC<Props> = ({ activeAssistant, setActiveAssistant, onCreateAssistant }) => {
|
||||
const { assistants, removeAssistant, addAssistant, updateAssistants } = useAssistants()
|
||||
const generating = useAppSelector((state) => state.runtime.generating)
|
||||
const [search, setSearch] = useState('')
|
||||
const { updateAssistant, removeAllTopics } = useAssistant(activeAssistant.id)
|
||||
const { showTopics, toggleShowTopics } = useShowTopics()
|
||||
const searchRef = useRef<InputRef>(null)
|
||||
const { t } = useTranslation()
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
const onDelete = useCallback(
|
||||
(assistant: Assistant) => {
|
||||
@@ -58,7 +61,7 @@ const Assistants: FC<Props> = ({ activeAssistant, setActiveAssistant, onCreateAs
|
||||
{
|
||||
label: t('common.duplicate'),
|
||||
key: 'duplicate',
|
||||
icon: <CopyOutlined />,
|
||||
icon: <CopyIcon />,
|
||||
onClick: async () => {
|
||||
const _assistant: Assistant = { ...assistant, id: uuid(), topics: [getDefaultTopic()] }
|
||||
addAssistant(_assistant)
|
||||
@@ -73,6 +76,7 @@ const Assistants: FC<Props> = ({ activeAssistant, setActiveAssistant, onCreateAs
|
||||
window.modal.confirm({
|
||||
title: t('chat.topics.delete.all.title'),
|
||||
content: t('chat.topics.delete.all.content'),
|
||||
centered: true,
|
||||
okButtonProps: { danger: true },
|
||||
onOk: removeAllTopics
|
||||
})
|
||||
@@ -99,15 +103,73 @@ const Assistants: FC<Props> = ({ activeAssistant, setActiveAssistant, onCreateAs
|
||||
})
|
||||
}
|
||||
|
||||
EventEmitter.emit(EVENT_NAMES.SWITCH_TOPIC_SIDEBAR)
|
||||
setActiveAssistant(assistant)
|
||||
},
|
||||
[generating, setActiveAssistant, t]
|
||||
)
|
||||
|
||||
const list = assistants.filter((assistant) => assistant.name?.toLowerCase().includes(search.toLowerCase().trim()))
|
||||
|
||||
const onSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
const isEnterPressed = e.keyCode == 13
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
return searchRef.current?.blur()
|
||||
}
|
||||
|
||||
if (isEnterPressed) {
|
||||
if (list.length > 0) {
|
||||
if (list.length === 1) {
|
||||
onSwitchAssistant(list[0])
|
||||
setSearch('')
|
||||
setTimeout(() => searchRef.current?.blur(), 0)
|
||||
return
|
||||
}
|
||||
const index = list.findIndex((a) => a.id === activeAssistant?.id)
|
||||
onSwitchAssistant(index === list.length - 1 ? list[0] : list[index + 1])
|
||||
}
|
||||
}
|
||||
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
|
||||
searchRef.current?.focus()
|
||||
searchRef.current?.select()
|
||||
}
|
||||
}
|
||||
|
||||
// Command or Ctrl + K create new topic
|
||||
useEffect(() => {
|
||||
const onKeydown = (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
|
||||
searchRef.current?.focus()
|
||||
searchRef.current?.select()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', onKeydown)
|
||||
return () => document.removeEventListener('keydown', onKeydown)
|
||||
}, [activeAssistant?.id, list, onSwitchAssistant])
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<DragableList list={assistants} onUpdate={updateAssistants}>
|
||||
{assistants.length >= 10 && (
|
||||
<SearchContainer>
|
||||
<Input
|
||||
placeholder={t('chat.assistant.search.placeholder')}
|
||||
suffix={<CommandKey>⌘+K</CommandKey>}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
style={{ borderRadius: 4, borderWidth: 0.5 }}
|
||||
onKeyDown={onSearch}
|
||||
ref={searchRef}
|
||||
onFocus={() => dispatch(setSearching(true))}
|
||||
onBlur={() => {
|
||||
dispatch(setSearching(false))
|
||||
setSearch('')
|
||||
}}
|
||||
allowClear
|
||||
/>
|
||||
</SearchContainer>
|
||||
)}
|
||||
<DragableList list={list} onUpdate={updateAssistants} droppableProps={{ isDropDisabled: !isEmpty(search) }}>
|
||||
{(assistant) => {
|
||||
const isCurrent = assistant.id === activeAssistant?.id
|
||||
return (
|
||||
@@ -115,8 +177,8 @@ const Assistants: FC<Props> = ({ activeAssistant, setActiveAssistant, onCreateAs
|
||||
<AssistantItem onClick={() => onSwitchAssistant(assistant)} className={isCurrent ? 'active' : ''}>
|
||||
<AssistantName className="name">{assistant.name || t('chat.default.name')}</AssistantName>
|
||||
<ArrowRightButton
|
||||
className={`arrow-button ${isCurrent && showTopics ? 'active' : ''}`}
|
||||
onClick={() => isCurrent && toggleShowTopics()}>
|
||||
className={`arrow-button ${isCurrent ? 'active' : ''}`}
|
||||
onClick={() => EventEmitter.emit(EVENT_NAMES.SWITCH_TOPIC_SIDEBAR)}>
|
||||
<i className="iconfont icon-gridlines" />
|
||||
</ArrowRightButton>
|
||||
{false && <TopicCount className="topics-count">{assistant.topics.length}</TopicCount>}
|
||||
@@ -132,9 +194,6 @@ const Assistants: FC<Props> = ({ activeAssistant, setActiveAssistant, onCreateAs
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: var(--assistants-width);
|
||||
max-width: var(--assistants-width);
|
||||
border-right: 0.5px solid var(--color-border);
|
||||
height: calc(100vh - var(--navbar-height));
|
||||
overflow-y: auto;
|
||||
padding-top: 10px;
|
||||
@@ -185,28 +244,23 @@ const ArrowRightButton = styled.div`
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
min-width: 24px;
|
||||
min-height: 24px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
min-width: 22px;
|
||||
min-height: 22px;
|
||||
border-radius: 4px;
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 5px;
|
||||
.anticon {
|
||||
font-size: 14px;
|
||||
}
|
||||
&:hover {
|
||||
background-color: var(--color-background);
|
||||
}
|
||||
&.active {
|
||||
background-color: var(--color-background);
|
||||
right: 9px;
|
||||
top: 6px;
|
||||
.iconfont {
|
||||
font-size: 12px;
|
||||
}
|
||||
`
|
||||
|
||||
const TopicCount = styled.div`
|
||||
color: var(--color-text-3);
|
||||
font-size: 12px;
|
||||
color: var(--color-text-2);
|
||||
font-size: 10px;
|
||||
margin-right: 3px;
|
||||
background-color: var(--color-background-mute);
|
||||
opacity: 0.8;
|
||||
@@ -219,4 +273,18 @@ const TopicCount = styled.div`
|
||||
align-items: center;
|
||||
`
|
||||
|
||||
const SearchContainer = styled.div`
|
||||
margin: 0 10px;
|
||||
margin-bottom: 10px;
|
||||
`
|
||||
|
||||
const CommandKey = styled.div`
|
||||
color: var(--color-text-2);
|
||||
font-size: 10px;
|
||||
padding: 2px 5px;
|
||||
border-radius: 4px;
|
||||
background-color: var(--color-background);
|
||||
margin-right: -4px;
|
||||
`
|
||||
|
||||
export default Assistants
|
||||
|
||||
@@ -8,30 +8,34 @@ import styled from 'styled-components'
|
||||
|
||||
import Inputbar from './Inputbar/Inputbar'
|
||||
import Messages from './Messages/Messages'
|
||||
import Topics from './Topics'
|
||||
import RightSidebar from './RightSidebar'
|
||||
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
activeTopic: Topic
|
||||
setActiveTopic: (topic: Topic) => void
|
||||
setActiveAssistant: (assistant: Assistant) => void
|
||||
}
|
||||
|
||||
const Chat: FC<Props> = (props) => {
|
||||
const { assistant } = useAssistant(props.assistant.id)
|
||||
const { showTopics } = useShowTopics()
|
||||
const { topicPosition } = useSettings()
|
||||
const { showTopics } = useShowTopics()
|
||||
|
||||
return (
|
||||
<Container id="chat">
|
||||
{showTopics && topicPosition === 'left' && (
|
||||
<Topics assistant={assistant} activeTopic={props.activeTopic} setActiveTopic={props.setActiveTopic} />
|
||||
)}
|
||||
<Main vertical flex={1} justify="space-between">
|
||||
<Messages assistant={assistant} topic={props.activeTopic} setActiveTopic={props.setActiveTopic} />
|
||||
<Inputbar assistant={assistant} setActiveTopic={props.setActiveTopic} />
|
||||
</Main>
|
||||
{showTopics && topicPosition === 'right' && (
|
||||
<Topics assistant={assistant} activeTopic={props.activeTopic} setActiveTopic={props.setActiveTopic} />
|
||||
{topicPosition === 'right' && showTopics && (
|
||||
<RightSidebar
|
||||
activeAssistant={assistant}
|
||||
activeTopic={props.activeTopic}
|
||||
setActiveAssistant={props.setActiveAssistant}
|
||||
setActiveTopic={props.setActiveTopic}
|
||||
position="right"
|
||||
/>
|
||||
)}
|
||||
</Container>
|
||||
)
|
||||
|
||||
@@ -1,54 +1,43 @@
|
||||
import { useAssistants, useDefaultAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useAssistants } from '@renderer/hooks/useAssistant'
|
||||
import { useShowAssistants } from '@renderer/hooks/useStore'
|
||||
import { useActiveTopic } from '@renderer/hooks/useTopic'
|
||||
import { Assistant, Topic } from '@renderer/types'
|
||||
import { uuid } from '@renderer/utils'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import { FC, useState } from 'react'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import Assistants from './Assistants'
|
||||
import Chat from './Chat'
|
||||
import Navbar from './Navbar'
|
||||
import RightSidebar from './RightSidebar'
|
||||
|
||||
let _activeAssistant: Assistant
|
||||
|
||||
const HomePage: FC = () => {
|
||||
const { assistants, addAssistant } = useAssistants()
|
||||
const { assistants } = useAssistants()
|
||||
const [activeAssistant, setActiveAssistant] = useState(_activeAssistant || assistants[0])
|
||||
const { showAssistants } = useShowAssistants()
|
||||
const { defaultAssistant } = useDefaultAssistant()
|
||||
|
||||
const { activeTopic, setActiveTopic } = useActiveTopic(activeAssistant)
|
||||
|
||||
_activeAssistant = activeAssistant
|
||||
|
||||
const onCreateDefaultAssistant = () => {
|
||||
const assistant = { ...defaultAssistant, id: uuid() }
|
||||
addAssistant(assistant)
|
||||
setActiveAssistant(assistant)
|
||||
}
|
||||
|
||||
const onSetActiveTopic = (topic: Topic) => {
|
||||
setActiveTopic(topic)
|
||||
}
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Navbar
|
||||
activeAssistant={activeAssistant}
|
||||
setActiveAssistant={setActiveAssistant}
|
||||
activeTopic={activeTopic}
|
||||
setActiveTopic={onSetActiveTopic}
|
||||
/>
|
||||
<Navbar activeAssistant={activeAssistant} setActiveAssistant={setActiveAssistant} activeTopic={activeTopic} />
|
||||
<ContentContainer>
|
||||
{showAssistants && (
|
||||
<Assistants
|
||||
<RightSidebar
|
||||
activeAssistant={activeAssistant}
|
||||
activeTopic={activeTopic}
|
||||
setActiveAssistant={setActiveAssistant}
|
||||
onCreateAssistant={onCreateDefaultAssistant}
|
||||
setActiveTopic={setActiveTopic}
|
||||
position="left"
|
||||
/>
|
||||
)}
|
||||
<Chat assistant={activeAssistant} activeTopic={activeTopic} setActiveTopic={onSetActiveTopic} />
|
||||
<Chat
|
||||
assistant={activeAssistant}
|
||||
activeTopic={activeTopic}
|
||||
setActiveTopic={setActiveTopic}
|
||||
setActiveAssistant={setActiveAssistant}
|
||||
/>
|
||||
</ContentContainer>
|
||||
</Container>
|
||||
)
|
||||
|
||||
@@ -1,29 +1,36 @@
|
||||
import { PaperClipOutlined } from '@ant-design/icons'
|
||||
import { Tooltip, Upload } from 'antd'
|
||||
import { isVisionModel } from '@renderer/config/models'
|
||||
import { FileType, Model } from '@renderer/types'
|
||||
import { Tooltip } from 'antd'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
interface Props {
|
||||
files: File[]
|
||||
setFiles: (files: File[]) => void
|
||||
model: Model
|
||||
files: FileType[]
|
||||
setFiles: (files: FileType[]) => void
|
||||
ToolbarButton: any
|
||||
}
|
||||
|
||||
const AttachmentButton: FC<Props> = ({ files, setFiles, ToolbarButton }) => {
|
||||
const AttachmentButton: FC<Props> = ({ model, files, setFiles, ToolbarButton }) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const onSelectFile = async () => {
|
||||
const _files = await window.api.file.select({
|
||||
filters: [{ name: 'Files', extensions: ['jpg', 'png', 'jpeg'] }]
|
||||
})
|
||||
_files && setFiles(_files)
|
||||
}
|
||||
|
||||
if (!isVisionModel(model)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip placement="top" title={t('chat.input.upload')} arrow>
|
||||
<Upload
|
||||
customRequest={() => {}}
|
||||
accept="image/*"
|
||||
itemRender={() => null}
|
||||
maxCount={1}
|
||||
onChange={async ({ file }) => file?.originFileObj && setFiles([file.originFileObj as File])}>
|
||||
<ToolbarButton type="text" className={files.length ? 'active' : ''}>
|
||||
<ToolbarButton type="text" className={files.length ? 'active' : ''} onClick={onSelectFile}>
|
||||
<PaperClipOutlined style={{ rotate: '135deg' }} />
|
||||
</ToolbarButton>
|
||||
</Upload>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
36
src/renderer/src/pages/home/Inputbar/AttachmentPreview.tsx
Normal file
36
src/renderer/src/pages/home/Inputbar/AttachmentPreview.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { FileType } from '@renderer/types'
|
||||
import { Upload } from 'antd'
|
||||
import { isEmpty } from 'lodash'
|
||||
import { FC } from 'react'
|
||||
import styled from 'styled-components'
|
||||
|
||||
interface Props {
|
||||
files: FileType[]
|
||||
setFiles: (files: FileType[]) => void
|
||||
}
|
||||
|
||||
const AttachmentPreview: FC<Props> = ({ files, setFiles }) => {
|
||||
if (isEmpty(files)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Upload
|
||||
listType="picture-card"
|
||||
fileList={files.map((file) => ({ uid: file.id, url: 'file://' + file.path, status: 'done', name: file.name }))}
|
||||
onRemove={(item) => setFiles(files.filter((file) => item.uid !== file.id))}
|
||||
/>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 10px;
|
||||
margin: 10px 20px;
|
||||
margin-right: 0;
|
||||
`
|
||||
|
||||
export default AttachmentPreview
|
||||
@@ -8,18 +8,19 @@ import {
|
||||
PauseCircleOutlined,
|
||||
QuestionCircleOutlined
|
||||
} from '@ant-design/icons'
|
||||
import { DEFAULT_CONEXTCOUNT } from '@renderer/config/constant'
|
||||
import db from '@renderer/databases'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { useShowTopics } from '@renderer/hooks/useStore'
|
||||
import { useRuntime, useShowTopics } from '@renderer/hooks/useStore'
|
||||
import { getDefaultTopic } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import FileManager from '@renderer/services/file'
|
||||
import { estimateInputTokenCount } from '@renderer/services/messages'
|
||||
import store, { useAppSelector } from '@renderer/store'
|
||||
import { setGenerating } from '@renderer/store/runtime'
|
||||
import { Assistant, Message, Topic } from '@renderer/types'
|
||||
import store, { useAppDispatch, useAppSelector } from '@renderer/store'
|
||||
import { setGenerating, setSearching } from '@renderer/store/runtime'
|
||||
import { Assistant, FileType, Message, Topic } from '@renderer/types'
|
||||
import { delay, uuid } from '@renderer/utils'
|
||||
import { Button, Divider, Popconfirm, Popover, Tag, Tooltip } from 'antd'
|
||||
import { Button, Popconfirm, Tooltip } from 'antd'
|
||||
import TextArea, { TextAreaRef } from 'antd/es/input/TextArea'
|
||||
import dayjs from 'dayjs'
|
||||
import { debounce, isEmpty } from 'lodash'
|
||||
@@ -27,8 +28,10 @@ import { CSSProperties, FC, useCallback, useEffect, useMemo, useRef, useState }
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import SettingsTab from '../Settings'
|
||||
import AttachmentButton from './AttachmentButton'
|
||||
import AttachmentPreview from './AttachmentPreview'
|
||||
import SendMessageButton from './SendMessageButton'
|
||||
import TokenCount from './TokenCount'
|
||||
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
@@ -40,20 +43,23 @@ let _text = ''
|
||||
const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
const [text, setText] = useState(_text)
|
||||
const [inputFocus, setInputFocus] = useState(false)
|
||||
const { addTopic } = useAssistant(assistant.id)
|
||||
const { sendMessageShortcut, showInputEstimatedTokens, fontSize } = useSettings()
|
||||
const { addTopic, model } = useAssistant(assistant.id)
|
||||
const { sendMessageShortcut, fontSize } = useSettings()
|
||||
const [expended, setExpend] = useState(false)
|
||||
const [estimateTokenCount, setEstimateTokenCount] = useState(0)
|
||||
const [contextCount, setContextCount] = useState(0)
|
||||
const generating = useAppSelector((state) => state.runtime.generating)
|
||||
const textareaRef = useRef<TextAreaRef>(null)
|
||||
const [files, setFiles] = useState<File[]>([])
|
||||
const [files, setFiles] = useState<FileType[]>([])
|
||||
const { t } = useTranslation()
|
||||
const containerRef = useRef(null)
|
||||
const { toggleShowTopics } = useShowTopics()
|
||||
const { showTopics, toggleShowTopics } = useShowTopics()
|
||||
const { searching } = useRuntime()
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
_text = text
|
||||
|
||||
const sendMessage = useCallback(() => {
|
||||
const sendMessage = useCallback(async () => {
|
||||
if (generating) {
|
||||
return
|
||||
}
|
||||
@@ -73,7 +79,7 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
}
|
||||
|
||||
if (files.length > 0) {
|
||||
message.files = files
|
||||
message.files = await FileManager.uploadFiles(files)
|
||||
}
|
||||
|
||||
EventEmitter.emit(EVENT_NAMES.SEND_MESSAGE, message)
|
||||
@@ -89,13 +95,15 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
const inputTokenCount = useMemo(() => estimateInputTokenCount(text), [text])
|
||||
|
||||
const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
const isEnterPressed = event.keyCode == 13
|
||||
|
||||
if (expended) {
|
||||
if (event.key === 'Escape') {
|
||||
return setExpend(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (sendMessageShortcut === 'Enter' && event.key === 'Enter') {
|
||||
if (sendMessageShortcut === 'Enter' && isEnterPressed) {
|
||||
if (event.shiftKey) {
|
||||
return
|
||||
}
|
||||
@@ -103,7 +111,7 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
return event.preventDefault()
|
||||
}
|
||||
|
||||
if (sendMessageShortcut === 'Shift+Enter' && event.key === 'Enter' && event.shiftKey) {
|
||||
if (sendMessageShortcut === 'Shift+Enter' && isEnterPressed && event.shiftKey) {
|
||||
sendMessage()
|
||||
return event.preventDefault()
|
||||
}
|
||||
@@ -113,6 +121,7 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
const topic = getDefaultTopic()
|
||||
addTopic(topic)
|
||||
setActiveTopic(topic)
|
||||
db.topics.add({ id: topic.id, messages: [] })
|
||||
}, [addTopic, setActiveTopic])
|
||||
|
||||
const clearTopic = async () => {
|
||||
@@ -128,6 +137,14 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
store.dispatch(setGenerating(false))
|
||||
}
|
||||
|
||||
const onNewContext = () => {
|
||||
if (generating) {
|
||||
onPause()
|
||||
return
|
||||
}
|
||||
EventEmitter.emit(EVENT_NAMES.NEW_CONTEXT)
|
||||
}
|
||||
|
||||
const resizeTextArea = () => {
|
||||
const textArea = textareaRef.current?.resizableTextArea?.textArea
|
||||
if (textArea) {
|
||||
@@ -175,8 +192,12 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
EventEmitter.on(EVENT_NAMES.EDIT_MESSAGE, (message: Message) => {
|
||||
setText(message.content)
|
||||
textareaRef.current?.focus()
|
||||
setTimeout(() => resizeTextArea(), 0)
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.ESTIMATED_TOKEN_COUNT, _setEstimateTokenCount)
|
||||
EventEmitter.on(EVENT_NAMES.ESTIMATED_TOKEN_COUNT, ({ tokensCount, contextCount }) => {
|
||||
_setEstimateTokenCount(tokensCount)
|
||||
setContextCount(contextCount)
|
||||
})
|
||||
]
|
||||
return () => unsubscribes.forEach((unsub) => unsub())
|
||||
}, [])
|
||||
@@ -186,7 +207,9 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
}, [assistant])
|
||||
|
||||
return (
|
||||
<Container id="inputbar" className={inputFocus ? 'focus' : ''} ref={containerRef}>
|
||||
<Container>
|
||||
<AttachmentPreview files={files} setFiles={setFiles} />
|
||||
<InputBarContainer id="inputbar" className={inputFocus ? 'focus' : ''} ref={containerRef}>
|
||||
<Textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
@@ -202,6 +225,8 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
onFocus={() => setInputFocus(true)}
|
||||
onBlur={() => setInputFocus(false)}
|
||||
onInput={onInput}
|
||||
disabled={searching}
|
||||
onClick={() => searching && dispatch(setSearching(false))}
|
||||
/>
|
||||
<Toolbar>
|
||||
<ToolbarMenu>
|
||||
@@ -224,35 +249,38 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
</Popconfirm>
|
||||
</Tooltip>
|
||||
<Tooltip placement="top" title={t('chat.input.topics')} arrow>
|
||||
<ToolbarButton type="text" onClick={toggleShowTopics}>
|
||||
<ToolbarButton
|
||||
type="text"
|
||||
onClick={() => {
|
||||
!showTopics && toggleShowTopics()
|
||||
setTimeout(() => EventEmitter.emit(EVENT_NAMES.SHOW_TOPIC_SIDEBAR), 0)
|
||||
}}>
|
||||
<HistoryOutlined />
|
||||
</ToolbarButton>
|
||||
</Tooltip>
|
||||
<Popover content={<SettingsTab assistant={assistant} />} trigger="click" placement="topRight">
|
||||
<Tooltip placement="top" title={t('chat.input.settings')} arrow>
|
||||
<ToolbarButton type="text">
|
||||
<ToolbarButton
|
||||
type="text"
|
||||
onClick={() => {
|
||||
!showTopics && toggleShowTopics()
|
||||
setTimeout(() => EventEmitter.emit(EVENT_NAMES.SHOW_CHAT_SETTINGS), 0)
|
||||
}}>
|
||||
<ControlOutlined />
|
||||
</ToolbarButton>
|
||||
</Tooltip>
|
||||
</Popover>
|
||||
{/* <AttachmentButton files={files} setFiles={setFiles} ToolbarButton={ToolbarButton} /> */}
|
||||
<AttachmentButton model={model} files={files} setFiles={setFiles} ToolbarButton={ToolbarButton} />
|
||||
<Tooltip placement="top" title={expended ? t('chat.input.collapse') : t('chat.input.expand')} arrow>
|
||||
<ToolbarButton type="text" onClick={onToggleExpended}>
|
||||
{expended ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
|
||||
</ToolbarButton>
|
||||
</Tooltip>
|
||||
{showInputEstimatedTokens && (
|
||||
<TextCount>
|
||||
<Tooltip title={t('chat.input.context_count.tip') + ' | ' + t('chat.input.estimated_tokens.tip')}>
|
||||
<StyledTag>
|
||||
{assistant?.settings?.contextCount ?? DEFAULT_CONEXTCOUNT}
|
||||
<Divider type="vertical" style={{ marginTop: 2, marginLeft: 5, marginRight: 5 }} />↑{inputTokenCount}
|
||||
<span style={{ margin: '0 2px' }}>/</span>
|
||||
{estimateTokenCount}
|
||||
</StyledTag>
|
||||
</Tooltip>
|
||||
</TextCount>
|
||||
)}
|
||||
<TokenCount
|
||||
estimateTokenCount={estimateTokenCount}
|
||||
inputTokenCount={inputTokenCount}
|
||||
contextCount={contextCount}
|
||||
ToolbarButton={ToolbarButton}
|
||||
onClick={onNewContext}
|
||||
/>
|
||||
</ToolbarMenu>
|
||||
<ToolbarMenu>
|
||||
{generating && (
|
||||
@@ -265,17 +293,22 @@ const Inputbar: FC<Props> = ({ assistant, setActiveTopic }) => {
|
||||
{!generating && <SendMessageButton sendMessage={sendMessage} disabled={generating || !text} />}
|
||||
</ToolbarMenu>
|
||||
</Toolbar>
|
||||
</InputBarContainer>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
`
|
||||
|
||||
const TextareaStyle: CSSProperties = {
|
||||
paddingLeft: 0,
|
||||
padding: '10px 15px 8px',
|
||||
transition: 'all 0.3s ease'
|
||||
padding: '10px 15px 8px'
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
const InputBarContainer = styled.div`
|
||||
border: 1px solid var(--color-border-soft);
|
||||
transition: all 0.3s ease;
|
||||
position: relative;
|
||||
@@ -326,36 +359,28 @@ const ToolbarButton = styled(Button)`
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 0;
|
||||
&.anticon {
|
||||
&.anticon,
|
||||
&.iconfont {
|
||||
transition: all 0.3s ease;
|
||||
color: var(--color-icon);
|
||||
}
|
||||
&:hover,
|
||||
&.active {
|
||||
&:hover {
|
||||
background-color: var(--color-background-soft);
|
||||
.anticon {
|
||||
.anticon,
|
||||
.iconfont {
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const TextCount = styled.div`
|
||||
font-size: 11px;
|
||||
color: var(--color-text-3);
|
||||
z-index: 10;
|
||||
padding: 2px;
|
||||
border-top-left-radius: 7px;
|
||||
user-select: none;
|
||||
`
|
||||
|
||||
const StyledTag = styled(Tag)`
|
||||
cursor: pointer;
|
||||
border-radius: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-width: 0.5;
|
||||
margin: 0;
|
||||
&.active {
|
||||
background-color: var(--color-primary) !important;
|
||||
.anticon,
|
||||
.iconfont {
|
||||
color: var(--color-white-soft);
|
||||
}
|
||||
&:hover {
|
||||
background-color: var(--color-primary);
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default Inputbar
|
||||
|
||||
83
src/renderer/src/pages/home/Inputbar/TokenCount.tsx
Normal file
83
src/renderer/src/pages/home/Inputbar/TokenCount.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import { ArrowUpOutlined, MenuOutlined, PicCenterOutlined } from '@ant-design/icons'
|
||||
import { HStack, VStack } from '@renderer/components/Layout'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { Divider, Popover, Tooltip } from 'antd'
|
||||
import { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
type Props = {
|
||||
estimateTokenCount: number
|
||||
inputTokenCount: number
|
||||
contextCount: number
|
||||
ToolbarButton: any
|
||||
} & React.HTMLAttributes<HTMLDivElement>
|
||||
|
||||
const TokenCount: FC<Props> = ({ estimateTokenCount, inputTokenCount, contextCount, ToolbarButton, ...props }) => {
|
||||
const { t } = useTranslation()
|
||||
const { showInputEstimatedTokens } = useSettings()
|
||||
|
||||
if (!showInputEstimatedTokens) {
|
||||
return null
|
||||
}
|
||||
|
||||
const PopoverContent = () => {
|
||||
return (
|
||||
<VStack w="150px" background="100%">
|
||||
<HStack justifyContent="space-between" w="100%">
|
||||
<Text>{t('chat.input.context_count.tip')}</Text>
|
||||
<Text>{contextCount}</Text>
|
||||
</HStack>
|
||||
<Divider style={{ margin: '5px 0' }} />
|
||||
<HStack justifyContent="space-between" w="100%">
|
||||
<Text>{t('chat.input.estimated_tokens.tip')}</Text>
|
||||
<Text>{estimateTokenCount}</Text>
|
||||
</HStack>
|
||||
</VStack>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ToolbarButton type="text" onClick={props.onClick}>
|
||||
<Tooltip placement="top" title={t('chat.input.new.context')}>
|
||||
<PicCenterOutlined />
|
||||
</Tooltip>
|
||||
</ToolbarButton>
|
||||
<Container {...props}>
|
||||
<Popover content={PopoverContent} title="" mouseEnterDelay={0.6}>
|
||||
<MenuOutlined /> {contextCount}
|
||||
<Divider type="vertical" style={{ marginTop: 0, marginLeft: 5, marginRight: 5 }} />
|
||||
<ArrowUpOutlined />
|
||||
{inputTokenCount} / {estimateTokenCount}
|
||||
</Popover>
|
||||
</Container>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
color: var(--color-text-2);
|
||||
z-index: 10;
|
||||
padding: 3px 10px;
|
||||
user-select: none;
|
||||
font-family: Ubuntu;
|
||||
border: 0.5px solid var(--color-text-3);
|
||||
border-radius: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
.anticon {
|
||||
font-size: 10px;
|
||||
margin-right: 3px;
|
||||
}
|
||||
`
|
||||
|
||||
const Text = styled.div`
|
||||
font-size: 12px;
|
||||
color: var(--color-text-1);
|
||||
`
|
||||
|
||||
export default TokenCount
|
||||
@@ -2,8 +2,8 @@ import { CheckOutlined } from '@ant-design/icons'
|
||||
import CopyIcon from '@renderer/components/Icons/CopyIcon'
|
||||
import { useTheme } from '@renderer/context/ThemeProvider'
|
||||
import { initMermaid } from '@renderer/init'
|
||||
import { ThemeMode } from '@renderer/store/settings'
|
||||
import React, { useState } from 'react'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
import React, { memo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
|
||||
import { atomDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'
|
||||
@@ -17,45 +17,60 @@ interface CodeBlockProps {
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
const CodeBlock: React.FC<CodeBlockProps> = ({ children, className, ...rest }) => {
|
||||
const CodeBlock: React.FC<CodeBlockProps> = ({ children, className }) => {
|
||||
const match = /language-(\w+)/.exec(className || '')
|
||||
const [copied, setCopied] = useState(false)
|
||||
const showFooterCopyButton = children && children.length > 500
|
||||
const { theme } = useTheme()
|
||||
|
||||
const { t } = useTranslation()
|
||||
|
||||
const onCopy = () => {
|
||||
navigator.clipboard.writeText(children)
|
||||
window.message.success({ content: t('message.copied'), key: 'copy-code' })
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
}
|
||||
|
||||
if (match && match[1] === 'mermaid') {
|
||||
initMermaid(theme)
|
||||
return <Mermaid chart={children} />
|
||||
}
|
||||
|
||||
return match ? (
|
||||
<div>
|
||||
<div className="code-block">
|
||||
<CodeHeader>
|
||||
<CodeLanguage>{'<' + match[1].toUpperCase() + '>'}</CodeLanguage>
|
||||
{!copied && <CopyIcon className="copy" onClick={onCopy} />}
|
||||
{copied && <CheckOutlined style={{ color: 'var(--color-primary)' }} />}
|
||||
<CopyButton text={children} />
|
||||
</CodeHeader>
|
||||
<SyntaxHighlighter
|
||||
{...rest}
|
||||
language={match[1]}
|
||||
style={theme === ThemeMode.dark ? atomDark : oneLight}
|
||||
wrapLongLines={true}
|
||||
customStyle={{ borderTopLeftRadius: 0, borderTopRightRadius: 0, marginTop: 0 }}>
|
||||
customStyle={{
|
||||
border: '0.5px solid var(--color-code-background)',
|
||||
borderTopLeftRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
marginTop: 0
|
||||
}}>
|
||||
{String(children).replace(/\n$/, '')}
|
||||
</SyntaxHighlighter>
|
||||
{showFooterCopyButton && (
|
||||
<CodeFooter>
|
||||
<CopyButton text={children} style={{ marginTop: -40, marginRight: 10 }} />
|
||||
</CodeFooter>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<code {...rest} className={className}>
|
||||
{children}
|
||||
</code>
|
||||
<code className={className}>{children}</code>
|
||||
)
|
||||
}
|
||||
|
||||
const CopyButton: React.FC<{ text: string; style?: React.CSSProperties }> = ({ text, style }) => {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const { t } = useTranslation()
|
||||
|
||||
const onCopy = () => {
|
||||
navigator.clipboard.writeText(text)
|
||||
window.message.success({ content: t('message.copied'), key: 'copy-code' })
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
}
|
||||
|
||||
return copied ? (
|
||||
<CheckOutlined style={{ color: 'var(--color-primary)', ...style }} />
|
||||
) : (
|
||||
<CopyIcon className="copy" style={style} onClick={onCopy} />
|
||||
)
|
||||
}
|
||||
|
||||
@@ -67,7 +82,7 @@ const CodeHeader = styled.div`
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
background-color: var(--color-code-background);
|
||||
height: 40px;
|
||||
height: 36px;
|
||||
padding: 0 10px;
|
||||
border-top-left-radius: 8px;
|
||||
border-top-right-radius: 8px;
|
||||
@@ -85,4 +100,19 @@ const CodeLanguage = styled.div`
|
||||
font-weight: bold;
|
||||
`
|
||||
|
||||
export default CodeBlock
|
||||
const CodeFooter = styled.div`
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
.copy {
|
||||
cursor: pointer;
|
||||
color: var(--color-text-3);
|
||||
transition: color 0.3s;
|
||||
}
|
||||
.copy:hover {
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
`
|
||||
|
||||
export default memo(CodeBlock)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import 'katex/dist/katex.min.css'
|
||||
|
||||
import { Message } from '@renderer/types'
|
||||
import { convertMathFormula } from '@renderer/utils'
|
||||
import { isEmpty } from 'lodash'
|
||||
import { FC, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import ReactMarkdown, { Components } from 'react-markdown'
|
||||
import rehypeKatex from 'rehype-katex'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import remarkMath from 'remark-math'
|
||||
@@ -17,6 +16,14 @@ interface Props {
|
||||
message: Message
|
||||
}
|
||||
|
||||
const rehypePlugins = [rehypeKatex]
|
||||
const remarkPlugins = [remarkGfm, remarkMath]
|
||||
|
||||
const components = {
|
||||
code: CodeBlock,
|
||||
a: Link
|
||||
}
|
||||
|
||||
const Markdown: FC<Props> = ({ message }) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
@@ -24,25 +31,23 @@ const Markdown: FC<Props> = ({ message }) => {
|
||||
const empty = isEmpty(message.content)
|
||||
const paused = message.status === 'paused'
|
||||
const content = empty && paused ? t('message.chat.completion.paused') : message.content
|
||||
return convertMathFormula(content)
|
||||
return content
|
||||
}, [message.content, message.status, t])
|
||||
|
||||
return useMemo(() => {
|
||||
return (
|
||||
<ReactMarkdown
|
||||
className="markdown"
|
||||
rehypePlugins={[rehypeKatex]}
|
||||
remarkPlugins={[[remarkMath, { singleDollarTextMath: false }], remarkGfm]}
|
||||
rehypePlugins={rehypePlugins}
|
||||
remarkPlugins={remarkPlugins}
|
||||
components={components as Partial<Components>}
|
||||
remarkRehypeOptions={{
|
||||
footnoteLabel: t('common.footnotes'),
|
||||
footnoteLabelTagName: 'h4',
|
||||
footnoteBackContent: ' '
|
||||
}}
|
||||
components={{ code: CodeBlock as any, a: Link as any }}>
|
||||
}}>
|
||||
{messageContent}
|
||||
</ReactMarkdown>
|
||||
)
|
||||
}, [messageContent, t])
|
||||
}
|
||||
|
||||
export default Markdown
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
CheckOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
ForkOutlined,
|
||||
MenuOutlined,
|
||||
QuestionCircleOutlined,
|
||||
SaveOutlined,
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
} from '@ant-design/icons'
|
||||
import UserPopup from '@renderer/components/Popups/UserPopup'
|
||||
import { FONT_FAMILY } from '@renderer/config/constant'
|
||||
import { APP_NAME, AppLogo, isLocalAi } from '@renderer/config/env'
|
||||
import { startMinAppById } from '@renderer/config/minapp'
|
||||
import { getModelLogo } from '@renderer/config/provider'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
@@ -18,8 +20,8 @@ import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { useRuntime } from '@renderer/hooks/useStore'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { Message, Model } from '@renderer/types'
|
||||
import { firstLetter, removeLeadingEmoji } from '@renderer/utils'
|
||||
import { Alert, Avatar, Dropdown, Popconfirm, Tooltip } from 'antd'
|
||||
import { firstLetter, removeLeadingEmoji, removeTrailingDoubleSpaces } from '@renderer/utils'
|
||||
import { Alert, Avatar, Divider, Dropdown, Popconfirm, Tooltip } from 'antd'
|
||||
import dayjs from 'dayjs'
|
||||
import { upperFirst } from 'lodash'
|
||||
import { FC, memo, useCallback, useMemo, useState } from 'react'
|
||||
@@ -54,7 +56,7 @@ const MessageItem: FC<Props> = ({ message, index, showMenu, onDeleteMessage }) =
|
||||
const showMetadata = Boolean(message.usage) && !generating
|
||||
|
||||
const onCopy = useCallback(() => {
|
||||
navigator.clipboard.writeText(message.content)
|
||||
navigator.clipboard.writeText(removeTrailingDoubleSpaces(message.content))
|
||||
window.message.success({ content: t('message.copied'), key: 'copy-message' })
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
@@ -70,19 +72,29 @@ const MessageItem: FC<Props> = ({ message, index, showMenu, onDeleteMessage }) =
|
||||
[setModel]
|
||||
)
|
||||
|
||||
const onNewBranch = useCallback(() => {
|
||||
EventEmitter.emit(EVENT_NAMES.NEW_BRANCH, index)
|
||||
}, [index])
|
||||
|
||||
const getUserName = useCallback(() => {
|
||||
if (message.id === 'assistant') return assistant?.name
|
||||
if (isLocalAi && message.role !== 'user') return APP_NAME
|
||||
if (message.role === 'assistant') return upperFirst(model?.name || model?.id)
|
||||
return userName || t('common.you')
|
||||
}, [assistant?.name, message.id, message.role, model?.id, model?.name, t, userName])
|
||||
}, [message.role, model?.id, model?.name, t, userName])
|
||||
|
||||
const fontFamily = useMemo(() => {
|
||||
return messageFont === 'serif' ? FONT_FAMILY.replace('sans-serif', 'serif').replace('Ubuntu, ', '') : FONT_FAMILY
|
||||
}, [messageFont])
|
||||
|
||||
const messageBorder = showMessageDivider ? undefined : 'none'
|
||||
const avatarSource = useMemo(() => (message.modelId ? getModelLogo(message.modelId) : undefined), [message.modelId])
|
||||
|
||||
const avatarSource = useMemo(() => {
|
||||
if (isLocalAi) return AppLogo
|
||||
return message.modelId ? getModelLogo(message.modelId) : undefined
|
||||
}, [message.modelId])
|
||||
|
||||
const avatarName = useMemo(() => firstLetter(assistant?.name).toUpperCase(), [assistant?.name])
|
||||
|
||||
const username = useMemo(() => removeLeadingEmoji(getUserName()), [getUserName])
|
||||
|
||||
const dropdownItems = useMemo(
|
||||
@@ -100,36 +112,16 @@ const MessageItem: FC<Props> = ({ message, index, showMenu, onDeleteMessage }) =
|
||||
[t, message]
|
||||
)
|
||||
|
||||
const MessageItem = useCallback(() => {
|
||||
if (message.status === 'sending') {
|
||||
return (
|
||||
<MessageContentLoading>
|
||||
<SyncOutlined spin size={24} />
|
||||
</MessageContentLoading>
|
||||
)
|
||||
}
|
||||
|
||||
if (message.status === 'error') {
|
||||
return (
|
||||
<Alert
|
||||
message={<div style={{ fontSize: 14 }}>{t('error.chat.response')}</div>}
|
||||
description={<Markdown message={message} />}
|
||||
type="error"
|
||||
style={{ marginBottom: 15, padding: 10, fontSize: 12 }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Markdown message={message} />
|
||||
<MessageAttachments message={message} />
|
||||
</>
|
||||
)
|
||||
}, [message, t])
|
||||
|
||||
const showMiniApp = () => model?.provider && startMinAppById(model?.provider)
|
||||
|
||||
if (message.type === 'clear') {
|
||||
return (
|
||||
<Divider dashed style={{ padding: '0 20px' }} plain>
|
||||
{t('chat.message.new.context')}
|
||||
</Divider>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<MessageContainer key={message.id} className="message">
|
||||
<MessageHeader>
|
||||
@@ -138,7 +130,11 @@ const MessageItem: FC<Props> = ({ message, index, showMenu, onDeleteMessage }) =
|
||||
<Avatar
|
||||
src={avatarSource}
|
||||
size={35}
|
||||
style={{ borderRadius: '20%', cursor: 'pointer' }}
|
||||
style={{
|
||||
borderRadius: '20%',
|
||||
cursor: 'pointer',
|
||||
border: isLocalAi ? '1px solid var(--color-border)' : ''
|
||||
}}
|
||||
onClick={showMiniApp}>
|
||||
{avatarName}
|
||||
</Avatar>
|
||||
@@ -156,8 +152,8 @@ const MessageItem: FC<Props> = ({ message, index, showMenu, onDeleteMessage }) =
|
||||
</UserWrap>
|
||||
</AvatarWrapper>
|
||||
</MessageHeader>
|
||||
<MessageContent style={{ fontFamily, fontSize }}>
|
||||
<MessageItem />
|
||||
<MessageContentContainer style={{ fontFamily, fontSize }}>
|
||||
<MessageContent message={message} />
|
||||
<MessageFooter style={{ border: messageBorder }}>
|
||||
{showMenu && (
|
||||
<MenusBar className={`menubar ${isLastMessage && 'show'} ${(!isLastMessage || isUserMessage) && 'user'}`}>
|
||||
@@ -183,6 +179,13 @@ const MessageItem: FC<Props> = ({ message, index, showMenu, onDeleteMessage }) =
|
||||
</Tooltip>
|
||||
</SelectModelDropdown>
|
||||
)}
|
||||
{isAssistantMessage && (
|
||||
<Tooltip title={t('chat.message.new.branch')} mouseEnterDelay={0.8}>
|
||||
<ActionButton onClick={onNewBranch}>
|
||||
<ForkOutlined />
|
||||
</ActionButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Popconfirm
|
||||
title={t('message.message.delete.content')}
|
||||
okButtonProps={{ danger: true }}
|
||||
@@ -210,11 +213,41 @@ const MessageItem: FC<Props> = ({ message, index, showMenu, onDeleteMessage }) =
|
||||
</MessageMetadata>
|
||||
)}
|
||||
</MessageFooter>
|
||||
</MessageContent>
|
||||
</MessageContentContainer>
|
||||
</MessageContainer>
|
||||
)
|
||||
}
|
||||
|
||||
const MessageContent: React.FC<{ message: Message }> = ({ message }) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
if (message.status === 'sending') {
|
||||
return (
|
||||
<MessageContentLoading>
|
||||
<SyncOutlined spin size={24} />
|
||||
</MessageContentLoading>
|
||||
)
|
||||
}
|
||||
|
||||
if (message.status === 'error') {
|
||||
return (
|
||||
<Alert
|
||||
message={<div style={{ fontSize: 14 }}>{t('error.chat.response')}</div>}
|
||||
description={<Markdown message={message} />}
|
||||
type="error"
|
||||
style={{ marginBottom: 15, padding: 10, fontSize: 12 }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Markdown message={message} />
|
||||
<MessageAttachments message={message} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const MessageContainer = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -271,7 +304,7 @@ const MessageTime = styled.div`
|
||||
color: var(--color-text-3);
|
||||
`
|
||||
|
||||
const MessageContent = styled.div`
|
||||
const MessageContentContainer = styled.div`
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -8,7 +8,11 @@ interface Props {
|
||||
}
|
||||
|
||||
const MessageAttachments: FC<Props> = ({ message }) => {
|
||||
return <Container>{message.images?.map((image) => <Image src={image} key={image} width="33%" />)}</Container>
|
||||
return (
|
||||
<Container>
|
||||
{message.files?.map((image) => <Image src={'file://' + image.path} key={image.id} width="33%" />)}
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
||||
const Container = styled.div`
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import db from '@renderer/databases'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useProviderByAssistant } from '@renderer/hooks/useProvider'
|
||||
import { getTopic } from '@renderer/hooks/useTopic'
|
||||
import { getTopic, TopicManager } from '@renderer/hooks/useTopic'
|
||||
import { fetchChatCompletion, fetchMessagesSummary } from '@renderer/services/api'
|
||||
import { getDefaultTopic } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { estimateHistoryTokenCount, filterMessages } from '@renderer/services/messages'
|
||||
import LocalStorage from '@renderer/services/storage'
|
||||
import {
|
||||
deleteMessageFiles,
|
||||
estimateHistoryTokenCount,
|
||||
filterMessages,
|
||||
getContextCount
|
||||
} from '@renderer/services/messages'
|
||||
import { Assistant, Message, Model, Topic } from '@renderer/types'
|
||||
import { getBriefInfo, runAsyncFunction, uuid } from '@renderer/utils'
|
||||
import { t } from 'i18next'
|
||||
import localforage from 'localforage'
|
||||
import { last, reverse } from 'lodash'
|
||||
import { last, reverse, take } from 'lodash'
|
||||
import { FC, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import styled from 'styled-components'
|
||||
|
||||
@@ -26,15 +30,14 @@ interface Props {
|
||||
const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
const [messages, setMessages] = useState<Message[]>([])
|
||||
const [lastMessage, setLastMessage] = useState<Message | null>(null)
|
||||
const provider = useProviderByAssistant(assistant)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const { updateTopic } = useAssistant(assistant.id)
|
||||
const { updateTopic, addTopic } = useAssistant(assistant.id)
|
||||
|
||||
const onSendMessage = useCallback(
|
||||
(message: Message) => {
|
||||
const _messages = [...messages, message]
|
||||
setMessages(_messages)
|
||||
localforage.setItem(`topic:${topic.id}`, { id: topic.id, messages: _messages })
|
||||
db.topics.put({ id: topic.id, messages: _messages })
|
||||
},
|
||||
[messages, topic]
|
||||
)
|
||||
@@ -55,7 +58,8 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
(message: Message) => {
|
||||
const _messages = messages.filter((m) => m.id !== message.id)
|
||||
setMessages(_messages)
|
||||
localforage.setItem(`topic:${topic.id}`, { id: topic.id, messages: _messages })
|
||||
db.topics.update(topic.id, { messages: _messages })
|
||||
deleteMessageFiles(message)
|
||||
},
|
||||
[messages, topic.id]
|
||||
)
|
||||
@@ -88,15 +92,45 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
EventEmitter.on(EVENT_NAMES.CLEAR_MESSAGES, () => {
|
||||
setMessages([])
|
||||
updateTopic({ ...topic, messages: [] })
|
||||
LocalStorage.clearTopicMessages(topic.id)
|
||||
TopicManager.clearTopicMessages(topic.id)
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.NEW_CONTEXT, () => {
|
||||
const lastMessage = last(messages)
|
||||
|
||||
if (lastMessage && lastMessage.type === 'clear') {
|
||||
return
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
onSendMessage({
|
||||
id: uuid(),
|
||||
assistantId: assistant.id,
|
||||
role: 'user',
|
||||
content: '',
|
||||
topicId: topic.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
status: 'success',
|
||||
type: 'clear'
|
||||
} as Message)
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.NEW_BRANCH, async (index: number) => {
|
||||
const _topic = getDefaultTopic()
|
||||
_topic.name = topic.name
|
||||
await db.topics.add({ id: _topic.id, messages: take(messages, messages.length - index) })
|
||||
addTopic(_topic)
|
||||
setActiveTopic(_topic)
|
||||
autoRenameTopic()
|
||||
})
|
||||
]
|
||||
return () => unsubscribes.forEach((unsub) => unsub())
|
||||
}, [assistant, messages, provider, topic, autoRenameTopic, updateTopic, onSendMessage])
|
||||
}, [addTopic, assistant, autoRenameTopic, messages, onSendMessage, setActiveTopic, topic, updateTopic])
|
||||
|
||||
useEffect(() => {
|
||||
runAsyncFunction(async () => {
|
||||
const messages = (await LocalStorage.getTopicMessages(topic.id)) || []
|
||||
const messages = (await TopicManager.getTopicMessages(topic.id)) || []
|
||||
setMessages(messages)
|
||||
})
|
||||
}, [topic.id])
|
||||
@@ -106,13 +140,16 @@ const Messages: FC<Props> = ({ assistant, topic, setActiveTopic }) => {
|
||||
}, [messages])
|
||||
|
||||
useEffect(() => {
|
||||
EventEmitter.emit(EVENT_NAMES.ESTIMATED_TOKEN_COUNT, estimateHistoryTokenCount(assistant, messages))
|
||||
EventEmitter.emit(EVENT_NAMES.ESTIMATED_TOKEN_COUNT, {
|
||||
tokensCount: estimateHistoryTokenCount(assistant, messages),
|
||||
contextCount: getContextCount(assistant, messages)
|
||||
})
|
||||
}, [assistant, messages])
|
||||
|
||||
return (
|
||||
<Container id="messages" key={assistant.id} ref={containerRef}>
|
||||
<Suggestions assistant={assistant} messages={messages} lastMessage={lastMessage} />
|
||||
{lastMessage && <MessageItem message={lastMessage} />}
|
||||
{lastMessage && <MessageItem key={lastMessage.id} message={lastMessage} />}
|
||||
{reverse([...messages]).map((message, index) => (
|
||||
<MessageItem key={message.id} message={message} showMenu index={index} onDeleteMessage={onDeleteMessage} />
|
||||
))}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { FormOutlined } from '@ant-design/icons'
|
||||
import { Navbar, NavbarCenter, NavbarLeft, NavbarRight } from '@renderer/components/app/Navbar'
|
||||
import { Navbar, NavbarLeft, NavbarRight } from '@renderer/components/app/Navbar'
|
||||
import { HStack } from '@renderer/components/Layout'
|
||||
import AddAssistantPopup from '@renderer/components/Popups/AddAssistantPopup'
|
||||
import AssistantSettingPopup from '@renderer/components/Popups/AssistantSettingPopup'
|
||||
@@ -8,11 +7,10 @@ import { useTheme } from '@renderer/context/ThemeProvider'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { useShowAssistants, useShowTopics } from '@renderer/hooks/useStore'
|
||||
import { getDefaultTopic } from '@renderer/services/assistant'
|
||||
import { syncAsistantToAgent } from '@renderer/services/assistant'
|
||||
import { Assistant, Topic } from '@renderer/types'
|
||||
import { Switch } from 'antd'
|
||||
import { FC, useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import SelectModelButton from './components/SelectModelButton'
|
||||
@@ -21,78 +19,48 @@ interface Props {
|
||||
activeAssistant: Assistant
|
||||
activeTopic: Topic
|
||||
setActiveAssistant: (assistant: Assistant) => void
|
||||
setActiveTopic: (topic: Topic) => void
|
||||
}
|
||||
|
||||
const HeaderNavbar: FC<Props> = ({ activeAssistant, setActiveAssistant, setActiveTopic }) => {
|
||||
const { assistant, addTopic } = useAssistant(activeAssistant.id)
|
||||
const { t } = useTranslation()
|
||||
const HeaderNavbar: FC<Props> = ({ activeAssistant, setActiveAssistant }) => {
|
||||
const { assistant, updateAssistant } = useAssistant(activeAssistant.id)
|
||||
const { showAssistants, toggleShowAssistants } = useShowAssistants()
|
||||
const { showTopics, toggleShowTopics } = useShowTopics()
|
||||
const { theme, toggleTheme } = useTheme()
|
||||
const { topicPosition } = useSettings()
|
||||
const { showTopics, toggleShowTopics } = useShowTopics()
|
||||
|
||||
const onCreateAssistant = async () => {
|
||||
const assistant = await AddAssistantPopup.show()
|
||||
assistant && setActiveAssistant(assistant)
|
||||
}
|
||||
|
||||
const addNewTopic = useCallback(() => {
|
||||
const topic = getDefaultTopic()
|
||||
addTopic(topic)
|
||||
setActiveTopic(topic)
|
||||
}, [addTopic, setActiveTopic])
|
||||
const onEditAssistant = useCallback(async () => {
|
||||
const _assistant = await AssistantSettingPopup.show({ assistant })
|
||||
updateAssistant(_assistant)
|
||||
syncAsistantToAgent(_assistant)
|
||||
}, [assistant, updateAssistant])
|
||||
|
||||
return (
|
||||
<Navbar>
|
||||
{showAssistants && (
|
||||
<NavbarLeft style={{ justifyContent: 'space-between', borderRight: 'none', padding: '0 8px' }}>
|
||||
<NewButton onClick={toggleShowAssistants} style={{ marginLeft: isMac ? 8 : 0 }}>
|
||||
<i className="iconfont icon-sidebar-right" />
|
||||
<i className="iconfont icon-hide-sidebar" />
|
||||
</NewButton>
|
||||
<NewButton onClick={onCreateAssistant} style={{ marginRight: 6 }}>
|
||||
<NewButton onClick={onCreateAssistant}>
|
||||
<i className="iconfont icon-a-addchat" />
|
||||
</NewButton>
|
||||
</NavbarLeft>
|
||||
)}
|
||||
{showTopics && topicPosition === 'left' && (
|
||||
<NavbarCenter
|
||||
style={{
|
||||
paddingLeft: isMac && !showAssistants ? 16 : 8,
|
||||
paddingRight: 8,
|
||||
maxWidth: 'var(--topic-list-width)',
|
||||
justifyContent: 'space-between'
|
||||
}}>
|
||||
<NavbarRight style={{ justifyContent: 'space-between', paddingRight: isWindows ? 140 : 12, flex: 1 }}>
|
||||
<HStack alignItems="center">
|
||||
{!showAssistants && (
|
||||
<NewButton onClick={toggleShowAssistants} style={{ marginRight: isMac ? 8 : 25 }}>
|
||||
<i className="iconfont icon-sidebar-left" />
|
||||
</NewButton>
|
||||
)}
|
||||
{showAssistants && (
|
||||
<TitleText>
|
||||
{t('chat.topics.title')} ({assistant.topics.length})
|
||||
</TitleText>
|
||||
)}
|
||||
</HStack>
|
||||
<NewButton onClick={addNewTopic}>
|
||||
<FormOutlined />
|
||||
</NewButton>
|
||||
</NavbarCenter>
|
||||
)}
|
||||
<NavbarRight style={{ justifyContent: 'space-between', paddingRight: isWindows ? 130 : 12, flex: 1 }}>
|
||||
<HStack alignItems="center">
|
||||
{!showAssistants && (topicPosition === 'left' ? !showTopics : true) && (
|
||||
<NewButton
|
||||
onClick={() => toggleShowAssistants()}
|
||||
style={{ marginRight: isMac ? 8 : 25, marginLeft: isMac ? 8 : 0 }}>
|
||||
<i className="iconfont icon-sidebar-left" />
|
||||
style={{ marginRight: isMac ? 8 : 25, marginLeft: isMac ? 4 : 0 }}>
|
||||
<i className="iconfont icon-show-sidebar" />
|
||||
</NewButton>
|
||||
)}
|
||||
<TitleText
|
||||
style={{ marginRight: 10, cursor: 'pointer' }}
|
||||
className="nodrag"
|
||||
onClick={() => AssistantSettingPopup.show({ assistant })}>
|
||||
<TitleText style={{ marginRight: 10, cursor: 'pointer' }} className="nodrag" onClick={onEditAssistant}>
|
||||
{assistant.name}
|
||||
</TitleText>
|
||||
<SelectModelButton assistant={assistant} />
|
||||
@@ -106,7 +74,7 @@ const HeaderNavbar: FC<Props> = ({ activeAssistant, setActiveAssistant, setActiv
|
||||
/>
|
||||
{topicPosition === 'right' && (
|
||||
<NewButton onClick={toggleShowTopics}>
|
||||
<i className={`iconfont icon-sidebar-${showTopics ? 'left' : 'right'}`} />
|
||||
<i className={`iconfont icon-${showTopics ? 'show' : 'hide'}-sidebar`} />
|
||||
</NewButton>
|
||||
)}
|
||||
</HStack>
|
||||
@@ -119,7 +87,7 @@ export const NewButton = styled.div`
|
||||
-webkit-app-region: none;
|
||||
border-radius: 4px;
|
||||
height: 30px;
|
||||
padding: 0 8px;
|
||||
padding: 0 7px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
@@ -127,12 +95,15 @@ export const NewButton = styled.div`
|
||||
transition: all 0.2s ease-in-out;
|
||||
cursor: pointer;
|
||||
.iconfont {
|
||||
font-size: 18px;
|
||||
font-size: 19px;
|
||||
color: var(--color-icon);
|
||||
}
|
||||
.icon-a-addchat {
|
||||
&.icon-a-addchat {
|
||||
font-size: 20px;
|
||||
}
|
||||
&.icon-a-darkmode {
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
.anticon {
|
||||
color: var(--color-icon);
|
||||
font-size: 17px;
|
||||
|
||||
@@ -1,74 +1,120 @@
|
||||
import { BarsOutlined, SettingOutlined } from '@ant-design/icons'
|
||||
import { useAssistants, useDefaultAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { useShowTopics } from '@renderer/hooks/useStore'
|
||||
import { EVENT_NAMES, EventEmitter } from '@renderer/services/event'
|
||||
import { Assistant, Topic } from '@renderer/types'
|
||||
import { Segmented } from 'antd'
|
||||
import { uuid } from '@renderer/utils'
|
||||
import { Segmented, SegmentedProps } from 'antd'
|
||||
import { FC, useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
|
||||
import Assistants from './Assistants'
|
||||
import Settings from './Settings'
|
||||
import Topics from './Topics'
|
||||
|
||||
interface Props {
|
||||
assistant: Assistant
|
||||
activeAssistant: Assistant
|
||||
activeTopic: Topic
|
||||
setActiveAssistant: (assistant: Assistant) => void
|
||||
setActiveTopic: (topic: Topic) => void
|
||||
position: 'left' | 'right'
|
||||
}
|
||||
|
||||
const RightSidebar: FC<Props> = (props) => {
|
||||
const [tab, setTab] = useState<'topic' | 'settings'>('topic')
|
||||
const { showTopics, setShowTopics } = useShowTopics()
|
||||
type Tab = 'assistants' | 'topic' | 'settings'
|
||||
|
||||
let _tab: any = ''
|
||||
|
||||
const RightSidebar: FC<Props> = ({ activeAssistant, activeTopic, setActiveAssistant, setActiveTopic, position }) => {
|
||||
const { addAssistant } = useAssistants()
|
||||
const [tab, setTab] = useState<Tab>(position === 'left' ? _tab || 'assistants' : 'topic')
|
||||
const { topicPosition } = useSettings()
|
||||
const { defaultAssistant } = useDefaultAssistant()
|
||||
const { toggleShowTopics } = useShowTopics()
|
||||
|
||||
const { t } = useTranslation()
|
||||
const isTopicTab = tab === 'topic'
|
||||
const isSettingsTab = tab === 'settings'
|
||||
|
||||
const borderStyle = '0.5px solid var(--color-border)'
|
||||
const border = position === 'left' ? { borderRight: borderStyle } : { borderLeft: borderStyle }
|
||||
|
||||
if (position === 'left' && topicPosition === 'left') {
|
||||
_tab = tab
|
||||
}
|
||||
|
||||
const showTab = !(position === 'left' && topicPosition === 'right')
|
||||
const assistantTab = {
|
||||
label: t('common.assistant'),
|
||||
value: 'assistants',
|
||||
icon: <i className="iconfont icon-business-smart-assistant" />
|
||||
}
|
||||
|
||||
const onCreateDefaultAssistant = () => {
|
||||
const assistant = { ...defaultAssistant, id: uuid() }
|
||||
addAssistant(assistant)
|
||||
setActiveAssistant(assistant)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribes = [
|
||||
EventEmitter.on(EVENT_NAMES.SHOW_ASSISTANTS, (): any => {
|
||||
showTab && setTab('assistants')
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.SHOW_TOPIC_SIDEBAR, (): any => {
|
||||
if (showTopics && isTopicTab) {
|
||||
return setShowTopics(false)
|
||||
}
|
||||
if (showTopics) {
|
||||
return setTab('topic')
|
||||
}
|
||||
setShowTopics(true)
|
||||
setTab('topic')
|
||||
showTab && setTab('topic')
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.SHOW_CHAT_SETTINGS, (): any => {
|
||||
if (showTopics && isSettingsTab) {
|
||||
return setShowTopics(false)
|
||||
}
|
||||
if (showTopics) {
|
||||
return setTab('settings')
|
||||
}
|
||||
setShowTopics(true)
|
||||
setTab('settings')
|
||||
showTab && setTab('settings')
|
||||
}),
|
||||
EventEmitter.on(EVENT_NAMES.SWITCH_TOPIC_SIDEBAR, () => setTab('topic'))
|
||||
EventEmitter.on(EVENT_NAMES.SWITCH_TOPIC_SIDEBAR, () => {
|
||||
showTab && setTab('topic')
|
||||
if (position === 'left' && topicPosition === 'right') {
|
||||
toggleShowTopics()
|
||||
}
|
||||
})
|
||||
]
|
||||
return () => unsubscribes.forEach((unsub) => unsub())
|
||||
}, [isSettingsTab, isTopicTab, showTopics, setShowTopics])
|
||||
}, [position, showTab, tab, toggleShowTopics, topicPosition])
|
||||
|
||||
if (!showTopics) {
|
||||
return null
|
||||
useEffect(() => {
|
||||
if (position === 'right' && topicPosition === 'right' && tab === 'assistants') {
|
||||
setTab('topic')
|
||||
}
|
||||
if (position === 'left' && topicPosition === 'right' && tab !== 'assistants') {
|
||||
setTab('assistants')
|
||||
}
|
||||
}, [position, tab, topicPosition])
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Container style={border}>
|
||||
{showTab && (
|
||||
<Segmented
|
||||
value={tab}
|
||||
style={{ borderRadius: 0, padding: '10px', gap: 5, borderBottom: '0.5px solid var(--color-border)' }}
|
||||
options={[
|
||||
className="segmented-tab"
|
||||
style={{ borderRadius: 0, padding: '10px', gap: 2, borderBottom: borderStyle }}
|
||||
options={
|
||||
[
|
||||
position === 'left' && topicPosition === 'left' ? assistantTab : undefined,
|
||||
{ label: t('common.topics'), value: 'topic', icon: <BarsOutlined /> },
|
||||
{ label: t('settings.title'), value: 'settings', icon: <SettingOutlined /> }
|
||||
]}
|
||||
block
|
||||
].filter(Boolean) as SegmentedProps['options']
|
||||
}
|
||||
onChange={(value) => setTab(value as 'topic' | 'settings')}
|
||||
block
|
||||
/>
|
||||
)}
|
||||
<TabContent>
|
||||
{tab === 'topic' && <Topics {...props} />}
|
||||
{tab === 'settings' && <Settings assistant={props.assistant} />}
|
||||
{tab === 'assistants' && (
|
||||
<Assistants
|
||||
activeAssistant={activeAssistant}
|
||||
setActiveAssistant={setActiveAssistant}
|
||||
onCreateAssistant={onCreateDefaultAssistant}
|
||||
/>
|
||||
)}
|
||||
{tab === 'topic' && (
|
||||
<Topics assistant={activeAssistant} activeTopic={activeTopic} setActiveTopic={setActiveTopic} />
|
||||
)}
|
||||
{tab === 'settings' && <Settings assistant={activeAssistant} />}
|
||||
</TabContent>
|
||||
</Container>
|
||||
)
|
||||
@@ -77,9 +123,8 @@ const RightSidebar: FC<Props> = (props) => {
|
||||
const Container = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: var(--topic-list-width);
|
||||
width: var(--assistants-width);
|
||||
height: calc(100vh - var(--navbar-height));
|
||||
border-left: 0.5px solid var(--color-border);
|
||||
.collapsed {
|
||||
width: 0;
|
||||
border-left: none;
|
||||
@@ -91,6 +136,7 @@ const TabContent = styled.div`
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
`
|
||||
|
||||
export default RightSidebar
|
||||
|
||||
@@ -104,7 +104,7 @@ const SettingsTab: FC<Props> = (props) => {
|
||||
<Col span={24}>
|
||||
<Slider
|
||||
min={0}
|
||||
max={1.2}
|
||||
max={2}
|
||||
onChange={setTemperature}
|
||||
onChangeComplete={onTemperatureChange}
|
||||
value={typeof temperature === 'number' ? temperature : 0}
|
||||
@@ -187,10 +187,7 @@ const SettingsTab: FC<Props> = (props) => {
|
||||
<Slider
|
||||
value={fontSizeValue}
|
||||
onChange={(value) => setFontSizeValue(value)}
|
||||
onChangeComplete={(value) => {
|
||||
dispatch(setFontSize(value))
|
||||
console.debug('set font size', value)
|
||||
}}
|
||||
onChangeComplete={(value) => dispatch(setFontSize(value))}
|
||||
min={12}
|
||||
max={18}
|
||||
step={1}
|
||||
@@ -235,8 +232,8 @@ const Container = styled.div`
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
min-width: 300px;
|
||||
padding-bottom: 10px;
|
||||
padding: 10px 15px;
|
||||
`
|
||||
|
||||
const Label = styled.p`
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { DeleteOutlined, EditOutlined, OpenAIOutlined } from '@ant-design/icons'
|
||||
import { CloseOutlined, DeleteOutlined, EditOutlined, OpenAIOutlined } from '@ant-design/icons'
|
||||
import DragableList from '@renderer/components/DragableList'
|
||||
import PromptPopup from '@renderer/components/Popups/PromptPopup'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import { TopicManager } from '@renderer/hooks/useTopic'
|
||||
import { fetchMessagesSummary } from '@renderer/services/api'
|
||||
import LocalStorage from '@renderer/services/storage'
|
||||
import { useAppSelector } from '@renderer/store'
|
||||
import { Assistant, Topic } from '@renderer/types'
|
||||
import { Dropdown, MenuProps } from 'antd'
|
||||
import { findIndex } from 'lodash'
|
||||
import { FC, useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
@@ -22,9 +22,28 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
const { assistant, removeTopic, updateTopic, updateTopics } = useAssistant(_assistant.id)
|
||||
const { t } = useTranslation()
|
||||
const generating = useAppSelector((state) => state.runtime.generating)
|
||||
const { topicPosition } = useSettings()
|
||||
|
||||
const borderStyle = '0.5px solid var(--color-border)'
|
||||
const onDeleteTopic = useCallback(
|
||||
(topic: Topic) => {
|
||||
if (assistant.topics.length > 1) {
|
||||
const index = findIndex(assistant.topics, (t) => t.id === topic.id)
|
||||
setActiveTopic(assistant.topics[index + 1 === assistant.topics.length ? 0 : index + 1])
|
||||
removeTopic(topic)
|
||||
}
|
||||
},
|
||||
[assistant.topics, removeTopic, setActiveTopic]
|
||||
)
|
||||
|
||||
const onSwitchTopic = useCallback(
|
||||
(topic: Topic) => {
|
||||
if (generating) {
|
||||
window.message.warning({ content: t('message.switch.disabled'), key: 'switch-assistant' })
|
||||
return
|
||||
}
|
||||
setActiveTopic(topic)
|
||||
},
|
||||
[generating, setActiveTopic, t]
|
||||
)
|
||||
|
||||
const getTopicMenuItems = useCallback(
|
||||
(topic: Topic) => {
|
||||
@@ -34,7 +53,7 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
key: 'auto-rename',
|
||||
icon: <OpenAIOutlined />,
|
||||
async onClick() {
|
||||
const messages = await LocalStorage.getTopicMessages(topic.id)
|
||||
const messages = await TopicManager.getTopicMessages(topic.id)
|
||||
if (messages.length >= 2) {
|
||||
const summaryText = await fetchMessagesSummary({ messages, assistant })
|
||||
if (summaryText) {
|
||||
@@ -67,40 +86,34 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
|
||||
danger: true,
|
||||
key: 'delete',
|
||||
icon: <DeleteOutlined />,
|
||||
onClick() {
|
||||
if (assistant.topics.length === 1) return
|
||||
removeTopic(topic)
|
||||
setActiveTopic(assistant.topics[0])
|
||||
}
|
||||
onClick: () => onDeleteTopic(topic)
|
||||
})
|
||||
}
|
||||
|
||||
return menus
|
||||
},
|
||||
[assistant, removeTopic, setActiveTopic, t, updateTopic]
|
||||
)
|
||||
|
||||
const onSwitchTopic = useCallback(
|
||||
(topic: Topic) => {
|
||||
if (generating) {
|
||||
window.message.warning({ content: t('message.switch.disabled'), key: 'switch-assistant' })
|
||||
return
|
||||
}
|
||||
setActiveTopic(topic)
|
||||
},
|
||||
[generating, setActiveTopic, t]
|
||||
[assistant, onDeleteTopic, t, updateTopic]
|
||||
)
|
||||
|
||||
return (
|
||||
<Container style={topicPosition === 'left' ? { borderRight: borderStyle } : { borderLeft: borderStyle }}>
|
||||
<Container>
|
||||
<DragableList list={assistant.topics} onUpdate={updateTopics}>
|
||||
{(topic) => {
|
||||
const isActive = topic.id === activeTopic?.id
|
||||
const activeClass = topicPosition === 'left' ? 'active-left' : 'active-right'
|
||||
return (
|
||||
<Dropdown menu={{ items: getTopicMenuItems(topic) }} trigger={['contextMenu']} key={topic.id}>
|
||||
<TopicListItem className={isActive ? activeClass : ''} onClick={() => onSwitchTopic(topic)}>
|
||||
{topic.name}
|
||||
<TopicListItem className={isActive ? 'active' : ''} onClick={() => onSwitchTopic(topic)}>
|
||||
<TopicName>{topic.name}</TopicName>
|
||||
{assistant.topics.length > 1 && (
|
||||
<MenuButton
|
||||
className="menu"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDeleteTopic(topic)
|
||||
}}>
|
||||
<CloseOutlined />
|
||||
</MenuButton>
|
||||
)}
|
||||
</TopicListItem>
|
||||
</Dropdown>
|
||||
)
|
||||
@@ -115,12 +128,8 @@ const Container = styled.div`
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
padding-top: 10px;
|
||||
min-width: var(--topic-list-width);
|
||||
max-width: var(--topic-list-width);
|
||||
border-right: 0.5px solid var(--color-border);
|
||||
border-left: 0.5px solid var(--color-border);
|
||||
overflow-y: scroll;
|
||||
height: calc(100vh - var(--navbar-height));
|
||||
max-height: calc(100vh - var(--navbar-height) - 140px);
|
||||
`
|
||||
|
||||
const TopicListItem = styled.div`
|
||||
@@ -128,22 +137,54 @@ const TopicListItem = styled.div`
|
||||
margin: 0 10px;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-family: Ubuntu;
|
||||
font-size: 13px;
|
||||
&:hover {
|
||||
background-color: var(--color-background-soft);
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
.menu {
|
||||
opacity: 0;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
&.active-left {
|
||||
background-color: var(--color-primary);
|
||||
color: white;
|
||||
font-weight: 500;
|
||||
}
|
||||
&.active-right {
|
||||
&.active {
|
||||
background-color: var(--color-background-mute);
|
||||
font-weight: 500;
|
||||
.menu {
|
||||
opacity: 1;
|
||||
background-color: var(--color-background-mute);
|
||||
&:hover {
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const TopicName = styled.div`
|
||||
color: var(--color-text);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 1;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
font-size: 13px;
|
||||
`
|
||||
|
||||
const MenuButton = styled.div`
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 30px;
|
||||
height: 24px;
|
||||
min-width: 24px;
|
||||
min-height: 24px;
|
||||
border-radius: 4px;
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 5px;
|
||||
.anticon {
|
||||
font-size: 12px;
|
||||
}
|
||||
`
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import ModelAvatar from '@renderer/components/Avatar/ModelAvatar'
|
||||
import VisionIcon from '@renderer/components/Icons/VisionIcon'
|
||||
import { isLocalAi } from '@renderer/config/env'
|
||||
import { isVisionModel } from '@renderer/config/models'
|
||||
import { useAssistant } from '@renderer/hooks/useAssistant'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import { Button } from 'antd'
|
||||
@@ -27,6 +29,7 @@ const SelectModelButton: FC<Props> = ({ assistant }) => {
|
||||
<DropdownButton size="small" type="default">
|
||||
<ModelAvatar model={model} size={20} />
|
||||
<ModelName>{model ? upperFirst(model.name) : t('button.select_model')}</ModelName>
|
||||
{isVisionModel(model) && <VisionIcon style={{ marginLeft: 0 }} />}
|
||||
</DropdownButton>
|
||||
</SelectModelDropdown>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import VisionIcon from '@renderer/components/Icons/VisionIcon'
|
||||
import { isVisionModel } from '@renderer/config/models'
|
||||
import { getModelLogo } from '@renderer/config/provider'
|
||||
import { useProviders } from '@renderer/hooks/useProvider'
|
||||
import { getModelUniqId } from '@renderer/services/model'
|
||||
import { Model } from '@renderer/types'
|
||||
import { Avatar, Dropdown, DropdownProps, MenuProps } from 'antd'
|
||||
import { first, reverse, sortBy, upperFirst } from 'lodash'
|
||||
@@ -23,9 +26,12 @@ const SelectModelDropdown: FC<Props & PropsWithChildren> = ({ children, model, o
|
||||
label: p.isSystem ? t(`provider.${p.id}`) : p.name,
|
||||
type: 'group',
|
||||
children: reverse(sortBy(p.models, 'name')).map((m) => ({
|
||||
key: m?.id,
|
||||
label: upperFirst(m?.name),
|
||||
defaultSelectedKeys: [model?.id],
|
||||
key: getModelUniqId(m),
|
||||
label: (
|
||||
<div>
|
||||
{upperFirst(m?.name)} {isVisionModel(m) && <VisionIcon />}
|
||||
</div>
|
||||
),
|
||||
icon: (
|
||||
<Avatar src={getModelLogo(m?.id || '')} size={24}>
|
||||
{first(m?.name)}
|
||||
@@ -37,7 +43,11 @@ const SelectModelDropdown: FC<Props & PropsWithChildren> = ({ children, model, o
|
||||
|
||||
return (
|
||||
<DropdownMenu
|
||||
menu={{ items, style: { maxHeight: '80vh', overflow: 'auto' }, selectedKeys: model ? [model.id] : [] }}
|
||||
menu={{
|
||||
items,
|
||||
style: { maxHeight: '55vh', overflow: 'auto' },
|
||||
selectedKeys: model ? [getModelUniqId(model)] : []
|
||||
}}
|
||||
trigger={['click']}
|
||||
arrow
|
||||
placement="bottom"
|
||||
|
||||
@@ -108,18 +108,18 @@ const AssistantSettings: FC = () => {
|
||||
<Col span={21}>
|
||||
<Slider
|
||||
min={0}
|
||||
max={1.2}
|
||||
max={2}
|
||||
onChange={setTemperature}
|
||||
onChangeComplete={onTemperatureChange}
|
||||
value={typeof temperature === 'number' ? temperature : 0}
|
||||
marks={{ 0: '0', 0.7: '0.7', 1: '1', 1.2: '1.2' }}
|
||||
marks={{ 0: '0', 0.7: '0.7', 2: '2' }}
|
||||
step={0.1}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={3}>
|
||||
<InputNumber
|
||||
min={0}
|
||||
max={1.2}
|
||||
max={2}
|
||||
step={0.1}
|
||||
value={temperature}
|
||||
onChange={onTemperatureChange}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { FolderOpenOutlined, SaveOutlined } from '@ant-design/icons'
|
||||
import { HStack } from '@renderer/components/Layout'
|
||||
import { isMac } from '@renderer/config/constant'
|
||||
import { useSettings } from '@renderer/hooks/useSettings'
|
||||
import i18n from '@renderer/i18n'
|
||||
import { backup, reset, restore } from '@renderer/services/backup'
|
||||
import { useAppDispatch } from '@renderer/store'
|
||||
import { setLanguage, setUserName, ThemeMode } from '@renderer/store/settings'
|
||||
import { setLanguage, setUserName } from '@renderer/store/settings'
|
||||
import { setProxyUrl as _setProxyUrl } from '@renderer/store/settings'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
import { isValidProxyUrl } from '@renderer/utils'
|
||||
import { Button, Input, Select } from 'antd'
|
||||
import { FC, useState } from 'react'
|
||||
@@ -76,6 +78,7 @@ const GeneralSettings: FC = () => {
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingDivider />
|
||||
{isMac && (
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.theme.window.style.title')}</SettingRowTitle>
|
||||
<Select
|
||||
@@ -88,6 +91,7 @@ const GeneralSettings: FC = () => {
|
||||
]}
|
||||
/>
|
||||
</SettingRow>
|
||||
)}
|
||||
<SettingDivider />
|
||||
<SettingRow>
|
||||
<SettingRowTitle>{t('settings.topic.position')}</SettingRowTitle>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { EditOutlined, MessageOutlined, TranslationOutlined } from '@ant-design/icons'
|
||||
import { useDefaultModel } from '@renderer/hooks/useAssistant'
|
||||
import { useProviders } from '@renderer/hooks/useProvider'
|
||||
import { getModelUniqId, hasModel } from '@renderer/services/model'
|
||||
import { Model } from '@renderer/types'
|
||||
import { Select } from 'antd'
|
||||
import { find, sortBy, upperFirst } from 'lodash'
|
||||
import { FC } from 'react'
|
||||
import { FC, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { SettingContainer, SettingDivider, SettingTitle } from '.'
|
||||
@@ -23,11 +24,24 @@ const ModelSettings: FC = () => {
|
||||
title: p.name,
|
||||
options: sortBy(p.models, 'name').map((m) => ({
|
||||
label: upperFirst(m.name),
|
||||
value: m.id
|
||||
value: getModelUniqId(m)
|
||||
}))
|
||||
}))
|
||||
|
||||
const iconStyle = { fontSize: 16, marginRight: 8 }
|
||||
const defaultModelValue = useMemo(
|
||||
() => (hasModel(defaultModel) ? getModelUniqId(defaultModel) : undefined),
|
||||
[defaultModel]
|
||||
)
|
||||
|
||||
const defaultTopicNamingModel = useMemo(
|
||||
() => (hasModel(topicNamingModel) ? getModelUniqId(topicNamingModel) : undefined),
|
||||
[topicNamingModel]
|
||||
)
|
||||
|
||||
const defaultTranslateModel = useMemo(
|
||||
() => (hasModel(translateModel) ? getModelUniqId(translateModel) : undefined),
|
||||
[translateModel]
|
||||
)
|
||||
|
||||
return (
|
||||
<SettingContainer>
|
||||
@@ -39,10 +53,12 @@ const ModelSettings: FC = () => {
|
||||
</SettingTitle>
|
||||
<SettingDivider />
|
||||
<Select
|
||||
defaultValue={defaultModel.id}
|
||||
value={defaultModelValue}
|
||||
defaultValue={defaultModelValue}
|
||||
style={{ width: 360 }}
|
||||
onChange={(id) => setDefaultModel(find(allModels, { id }) as Model)}
|
||||
onChange={(value) => setDefaultModel(find(allModels, JSON.parse(value)) as Model)}
|
||||
options={selectOptions}
|
||||
placeholder={t('settings.models.empty')}
|
||||
/>
|
||||
<div style={{ height: 30 }} />
|
||||
<SettingTitle>
|
||||
@@ -53,10 +69,12 @@ const ModelSettings: FC = () => {
|
||||
</SettingTitle>
|
||||
<SettingDivider />
|
||||
<Select
|
||||
defaultValue={topicNamingModel.id}
|
||||
value={defaultTopicNamingModel}
|
||||
defaultValue={defaultTopicNamingModel}
|
||||
style={{ width: 360 }}
|
||||
onChange={(id) => setTopicNamingModel(find(allModels, { id }) as Model)}
|
||||
onChange={(value) => setTopicNamingModel(find(allModels, JSON.parse(value)) as Model)}
|
||||
options={selectOptions}
|
||||
placeholder={t('settings.models.empty')}
|
||||
/>
|
||||
<div style={{ height: 30 }} />
|
||||
<SettingTitle>
|
||||
@@ -67,9 +85,10 @@ const ModelSettings: FC = () => {
|
||||
</SettingTitle>
|
||||
<SettingDivider />
|
||||
<Select
|
||||
defaultValue={translateModel?.id}
|
||||
value={defaultTranslateModel}
|
||||
defaultValue={defaultTranslateModel}
|
||||
style={{ width: 360 }}
|
||||
onChange={(id) => setTranslateModel(find(allModels, { id }) as Model)}
|
||||
onChange={(value) => setTranslateModel(find(allModels, JSON.parse(value)) as Model)}
|
||||
options={selectOptions}
|
||||
placeholder={t('settings.models.empty')}
|
||||
/>
|
||||
@@ -77,4 +96,6 @@ const ModelSettings: FC = () => {
|
||||
)
|
||||
}
|
||||
|
||||
const iconStyle = { fontSize: 16, marginRight: 8 }
|
||||
|
||||
export default ModelSettings
|
||||
|
||||
@@ -67,7 +67,8 @@ const PopupContainer: React.FC<Props> = ({ title, provider, resolve }) => {
|
||||
onCancel={onCancel}
|
||||
maskClosable={false}
|
||||
afterClose={onClose}
|
||||
footer={null}>
|
||||
footer={null}
|
||||
centered>
|
||||
<Form
|
||||
form={form}
|
||||
labelCol={{ flex: '110px' }}
|
||||
|
||||
@@ -38,6 +38,7 @@ const PopupContainer: React.FC<Props> = ({ provider, resolve }) => {
|
||||
afterClose={onClose}
|
||||
width={360}
|
||||
closable={false}
|
||||
centered
|
||||
title={t('settings.provider.edit.name')}
|
||||
okButtonProps={{ disabled: buttonDisabled }}>
|
||||
<Input
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { LoadingOutlined, MinusOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons'
|
||||
import { SYSTEM_MODELS } from '@renderer/config/models'
|
||||
import VisionIcon from '@renderer/components/Icons/VisionIcon'
|
||||
import { isVisionModel, SYSTEM_MODELS } from '@renderer/config/models'
|
||||
import { getModelLogo } from '@renderer/config/provider'
|
||||
import { useProvider } from '@renderer/hooks/useProvider'
|
||||
import { fetchModels } from '@renderer/services/api'
|
||||
@@ -107,7 +108,8 @@ const PopupContainer: React.FC<Props> = ({ provider: _provider, resolve }) => {
|
||||
styles={{
|
||||
content: { padding: 0 },
|
||||
header: { padding: 22, paddingBottom: 15 }
|
||||
}}>
|
||||
}}
|
||||
centered>
|
||||
<SearchContainer>
|
||||
<Search placeholder={t('settings.provider.search_placeholder')} allowClear onSearch={setSearchText} />
|
||||
</SearchContainer>
|
||||
@@ -125,6 +127,7 @@ const PopupContainer: React.FC<Props> = ({ provider: _provider, resolve }) => {
|
||||
</Avatar>
|
||||
<ListItemName>
|
||||
{model.name}
|
||||
{isVisionModel(model) && <VisionIcon />}
|
||||
{isFreeModel(model) && (
|
||||
<Tag style={{ marginLeft: 10 }} color="green">
|
||||
Free
|
||||
@@ -154,7 +157,8 @@ const onShowModelInfo = (model: Model) => {
|
||||
title: model.name,
|
||||
content: model?.description,
|
||||
icon: null,
|
||||
maskClosable: true
|
||||
maskClosable: true,
|
||||
width: 600
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
MinusCircleOutlined,
|
||||
PlusOutlined
|
||||
} from '@ant-design/icons'
|
||||
import VisionIcon from '@renderer/components/Icons/VisionIcon'
|
||||
import { isVisionModel } from '@renderer/config/models'
|
||||
import { getModelLogo } from '@renderer/config/provider'
|
||||
import { PROVIDER_CONFIG } from '@renderer/config/provider'
|
||||
import { useTheme } from '@renderer/context/ThemeProvider'
|
||||
@@ -14,7 +16,7 @@ import { checkApi } from '@renderer/services/api'
|
||||
import { Provider } from '@renderer/types'
|
||||
import { Avatar, Button, Card, Divider, Flex, Input, Space, Switch } from 'antd'
|
||||
import Link from 'antd/es/typography/Link'
|
||||
import { groupBy } from 'lodash'
|
||||
import { groupBy, isEmpty } from 'lodash'
|
||||
import { FC, useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import styled from 'styled-components'
|
||||
@@ -72,7 +74,6 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
|
||||
const docsWebsite = providerConfig?.websites?.docs
|
||||
const modelsWebsite = providerConfig?.websites?.models
|
||||
const configedApiHost = providerConfig?.api?.url
|
||||
const apiEditable = provider.isSystem ? providerConfig?.api?.editable : true
|
||||
|
||||
const onReset = () => {
|
||||
setApiHost(configedApiHost)
|
||||
@@ -131,9 +132,10 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
|
||||
placeholder={t('settings.provider.api_host')}
|
||||
onChange={(e) => setApiHost(e.target.value)}
|
||||
onBlur={onUpdateApiHost}
|
||||
disabled={!apiEditable}
|
||||
/>
|
||||
{apiEditable && <Button onClick={onReset}>{t('settings.provider.api.url.reset')}</Button>}
|
||||
{!isEmpty(configedApiHost) && apiHost !== configedApiHost && (
|
||||
<Button onClick={onReset}>{t('settings.provider.api.url.reset')}</Button>
|
||||
)}
|
||||
</Space.Compact>
|
||||
{provider.id === 'ollama' && <OllamSettings />}
|
||||
{provider.id === 'graphrag-kylin-mountain' && provider.models.length > 0 && (
|
||||
@@ -148,7 +150,7 @@ const ProviderSetting: FC<Props> = ({ provider: _provider }) => {
|
||||
<Avatar src={getModelLogo(model.id)} size={22} style={{ marginRight: '8px' }}>
|
||||
{model.name[0].toUpperCase()}
|
||||
</Avatar>
|
||||
{model.name}
|
||||
{model.name} {isVisionModel(model) && <VisionIcon />}
|
||||
</ModelListHeader>
|
||||
<RemoveIcon onClick={() => removeModel(model)} />
|
||||
</ModelListItem>
|
||||
|
||||
@@ -71,6 +71,7 @@ const ProvidersList: FC = () => {
|
||||
content: t('settings.provider.delete.content'),
|
||||
okButtonProps: { danger: true },
|
||||
okText: t('common.delete'),
|
||||
centered: true,
|
||||
onOk: () => {
|
||||
setSelectedProvider(providers.filter((p) => p.isSystem)[0])
|
||||
removeProvider(provider)
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
CloudOutlined,
|
||||
CodeSandboxOutlined,
|
||||
InfoCircleOutlined,
|
||||
MessageOutlined,
|
||||
SettingOutlined
|
||||
} from '@ant-design/icons'
|
||||
import { CloudOutlined, InfoCircleOutlined, MessageOutlined, SettingOutlined } from '@ant-design/icons'
|
||||
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
|
||||
import { isLocalAi } from '@renderer/config/env'
|
||||
import { FC } from 'react'
|
||||
@@ -41,7 +35,7 @@ const SettingsPage: FC = () => {
|
||||
</MenuItemLink>
|
||||
<MenuItemLink to="/settings/model">
|
||||
<MenuItem className={isRoute('/settings/model')}>
|
||||
<CodeSandboxOutlined />
|
||||
<i className="iconfont icon-ai-model" />
|
||||
{t('settings.model')}
|
||||
</MenuItem>
|
||||
</MenuItemLink>
|
||||
@@ -96,7 +90,7 @@ const ContentContainer = styled.div`
|
||||
const SettingMenus = styled.ul`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: var(--assistants-width);
|
||||
min-width: var(--settings-width);
|
||||
border-right: 0.5px solid var(--color-border);
|
||||
padding: 10px;
|
||||
`
|
||||
@@ -122,6 +116,11 @@ const MenuItem = styled.li`
|
||||
font-size: 16px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
.iconfont {
|
||||
font-size: 18px;
|
||||
opacity: 0.7;
|
||||
margin-left: -1px;
|
||||
}
|
||||
&:hover {
|
||||
background: var(--color-background-soft);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export default class AiProvider {
|
||||
return this.sdk.translate(message, assistant)
|
||||
}
|
||||
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string | null> {
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string> {
|
||||
return this.sdk.summaries(messages, assistant)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,10 @@ export default class AiProvider {
|
||||
return this.sdk.suggestions(messages, assistant)
|
||||
}
|
||||
|
||||
public async generateText({ prompt, content }: { prompt: string; content: string }): Promise<string> {
|
||||
return this.sdk.generateText({ prompt, content })
|
||||
}
|
||||
|
||||
public async check(): Promise<{ valid: boolean; error: Error | null }> {
|
||||
return this.sdk.check()
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { MessageCreateParamsNonStreaming, MessageParam } from '@anthropic-ai/sdk
|
||||
import { DEFAULT_MAX_TOKENS } from '@renderer/config/constant'
|
||||
import { getAssistantSettings, getDefaultModel, getTopNamingModel } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES } from '@renderer/services/event'
|
||||
import { filterContextMessages, filterMessages } from '@renderer/services/messages'
|
||||
import { Assistant, Message, Provider, Suggestion } from '@renderer/types'
|
||||
import { first, sum, takeRight } from 'lodash'
|
||||
import OpenAI from 'openai'
|
||||
@@ -17,6 +18,31 @@ export default class AnthropicProvider extends BaseProvider {
|
||||
this.sdk = new Anthropic({ apiKey: provider.apiKey, baseURL: this.getBaseURL() })
|
||||
}
|
||||
|
||||
private async getMessageContent(message: Message): Promise<MessageParam['content']> {
|
||||
const file = first(message.files)
|
||||
|
||||
if (!file) {
|
||||
return message.content
|
||||
}
|
||||
|
||||
if (file.type === 'image') {
|
||||
const base64Data = await window.api.image.base64(file.path)
|
||||
return [
|
||||
{ type: 'text', text: message.content },
|
||||
{
|
||||
type: 'image',
|
||||
source: {
|
||||
data: base64Data.base64,
|
||||
media_type: base64Data.mime.replace('jpg', 'jpeg') as any,
|
||||
type: 'base64'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return message.content
|
||||
}
|
||||
|
||||
public async completions(
|
||||
messages: Message[],
|
||||
assistant: Assistant,
|
||||
@@ -26,12 +52,14 @@ export default class AnthropicProvider extends BaseProvider {
|
||||
const model = assistant.model || defaultModel
|
||||
const { contextCount, maxTokens } = getAssistantSettings(assistant)
|
||||
|
||||
const userMessages = takeRight(messages, contextCount + 2).map((message) => {
|
||||
return {
|
||||
const userMessages: MessageParam[] = []
|
||||
|
||||
for (const message of filterMessages(filterContextMessages(takeRight(messages, contextCount + 2)))) {
|
||||
userMessages.push({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}
|
||||
content: await this.getMessageContent(message)
|
||||
})
|
||||
}
|
||||
|
||||
if (first(userMessages)?.role === 'assistant') {
|
||||
userMessages.shift()
|
||||
@@ -89,7 +117,7 @@ export default class AnthropicProvider extends BaseProvider {
|
||||
return response.content[0].type === 'text' ? response.content[0].text : ''
|
||||
}
|
||||
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string | null> {
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string> {
|
||||
const model = getTopNamingModel() || assistant.model || getDefaultModel()
|
||||
|
||||
const userMessages = takeRight(messages, 5).map((message) => ({
|
||||
@@ -114,7 +142,26 @@ export default class AnthropicProvider extends BaseProvider {
|
||||
max_tokens: 4096
|
||||
})
|
||||
|
||||
return message.content[0].type === 'text' ? message.content[0].text : null
|
||||
return message.content[0].type === 'text' ? message.content[0].text : ''
|
||||
}
|
||||
|
||||
public async generateText({ prompt, content }: { prompt: string; content: string }): Promise<string> {
|
||||
const model = getDefaultModel()
|
||||
|
||||
const message = await this.sdk.messages.create({
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content
|
||||
}
|
||||
],
|
||||
model: model.id,
|
||||
system: prompt,
|
||||
stream: false,
|
||||
max_tokens: 4096
|
||||
})
|
||||
|
||||
return message.content[0].type === 'text' ? message.content[0].text : ''
|
||||
}
|
||||
|
||||
public async suggestions(): Promise<Suggestion[]> {
|
||||
|
||||
@@ -26,8 +26,9 @@ export default abstract class BaseProvider {
|
||||
onChunk: ({ text, usage }: { text?: string; usage?: OpenAI.Completions.CompletionUsage }) => void
|
||||
): Promise<void>
|
||||
abstract translate(message: Message, assistant: Assistant): Promise<string>
|
||||
abstract summaries(messages: Message[], assistant: Assistant): Promise<string | null>
|
||||
abstract summaries(messages: Message[], assistant: Assistant): Promise<string>
|
||||
abstract suggestions(messages: Message[], assistant: Assistant): Promise<Suggestion[]>
|
||||
abstract generateText({ prompt, content }: { prompt: string; content: string }): Promise<string>
|
||||
abstract check(): Promise<{ valid: boolean; error: Error | null }>
|
||||
abstract models(): Promise<OpenAI.Models.Model[]>
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { GoogleGenerativeAI } from '@google/generative-ai'
|
||||
import { Content, GoogleGenerativeAI, InlineDataPart, Part } from '@google/generative-ai'
|
||||
import { getAssistantSettings, getDefaultModel, getTopNamingModel } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES } from '@renderer/services/event'
|
||||
import { filterContextMessages, filterMessages } from '@renderer/services/messages'
|
||||
import { Assistant, Message, Provider, Suggestion } from '@renderer/types'
|
||||
import axios from 'axios'
|
||||
import { isEmpty, takeRight } from 'lodash'
|
||||
import { first, isEmpty, takeRight } from 'lodash'
|
||||
import OpenAI from 'openai'
|
||||
|
||||
import BaseProvider from './BaseProvider'
|
||||
@@ -16,6 +17,27 @@ export default class GeminiProvider extends BaseProvider {
|
||||
this.sdk = new GoogleGenerativeAI(provider.apiKey)
|
||||
}
|
||||
|
||||
private async getMessageParts(message: Message): Promise<Part[]> {
|
||||
const file = first(message.files)
|
||||
|
||||
if (file && file.type === 'image') {
|
||||
const base64Data = await window.api.image.base64(file.path)
|
||||
return [
|
||||
{
|
||||
text: message.content
|
||||
},
|
||||
{
|
||||
inlineData: {
|
||||
data: base64Data.base64,
|
||||
mimeType: base64Data.mime
|
||||
}
|
||||
} as InlineDataPart
|
||||
]
|
||||
}
|
||||
|
||||
return [{ text: message.content }]
|
||||
}
|
||||
|
||||
public async completions(
|
||||
messages: Message[],
|
||||
assistant: Assistant,
|
||||
@@ -25,10 +47,10 @@ export default class GeminiProvider extends BaseProvider {
|
||||
const model = assistant.model || defaultModel
|
||||
const { contextCount, maxTokens } = getAssistantSettings(assistant)
|
||||
|
||||
const userMessages = takeRight(messages, contextCount + 1).map((message) => {
|
||||
const userMessages = filterMessages(filterContextMessages(takeRight(messages, contextCount + 1))).map((message) => {
|
||||
return {
|
||||
role: message.role,
|
||||
content: message.content
|
||||
message
|
||||
}
|
||||
})
|
||||
|
||||
@@ -43,14 +65,19 @@ export default class GeminiProvider extends BaseProvider {
|
||||
|
||||
const userLastMessage = userMessages.pop()
|
||||
|
||||
const chat = geminiModel.startChat({
|
||||
history: userMessages.map((message) => ({
|
||||
role: message.role === 'user' ? 'user' : 'model',
|
||||
parts: [{ text: message.content }]
|
||||
}))
|
||||
})
|
||||
const history: Content[] = []
|
||||
|
||||
const userMessagesStream = await chat.sendMessageStream(userLastMessage?.content!)
|
||||
for (const message of userMessages) {
|
||||
history.push({
|
||||
role: message.role === 'user' ? 'user' : 'model',
|
||||
parts: await this.getMessageParts(message.message)
|
||||
})
|
||||
}
|
||||
|
||||
const chat = geminiModel.startChat({ history })
|
||||
const message = await this.getMessageParts(userLastMessage?.message!)
|
||||
|
||||
const userMessagesStream = await chat.sendMessageStream(message)
|
||||
|
||||
for await (const chunk of userMessagesStream.stream) {
|
||||
if (window.keyv.get(EVENT_NAMES.CHAT_COMPLETION_PAUSED)) break
|
||||
@@ -84,7 +111,7 @@ export default class GeminiProvider extends BaseProvider {
|
||||
return response.text()
|
||||
}
|
||||
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string | null> {
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string> {
|
||||
const model = getTopNamingModel() || assistant.model || getDefaultModel()
|
||||
|
||||
const userMessages = takeRight(messages, 5).map((message) => ({
|
||||
@@ -119,6 +146,18 @@ export default class GeminiProvider extends BaseProvider {
|
||||
return response.text()
|
||||
}
|
||||
|
||||
public async generateText({ prompt, content }: { prompt: string; content: string }): Promise<string> {
|
||||
const model = getDefaultModel()
|
||||
const systemMessage = { role: 'system', content: prompt }
|
||||
|
||||
const geminiModel = this.sdk.getGenerativeModel({ model: model.id })
|
||||
|
||||
const chat = await geminiModel.startChat({ systemInstruction: systemMessage.content })
|
||||
const { response } = await chat.sendMessage(content)
|
||||
|
||||
return response.text()
|
||||
}
|
||||
|
||||
public async suggestions(): Promise<Suggestion[]> {
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { isLocalAi } from '@renderer/config/env'
|
||||
import { getAssistantSettings, getDefaultModel, getTopNamingModel } from '@renderer/services/assistant'
|
||||
import { EVENT_NAMES } from '@renderer/services/event'
|
||||
import { filterContextMessages, filterMessages } from '@renderer/services/messages'
|
||||
import { Assistant, Message, Provider, Suggestion } from '@renderer/types'
|
||||
import { fileToBase64, removeQuotes } from '@renderer/utils'
|
||||
import { removeQuotes } from '@renderer/utils'
|
||||
import { first, takeRight } from 'lodash'
|
||||
import OpenAI from 'openai'
|
||||
import {
|
||||
@@ -32,13 +33,14 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
return message.content
|
||||
}
|
||||
|
||||
if (file.type.includes('image')) {
|
||||
if (file.type === 'image') {
|
||||
const base64Data = await window.api.image.base64(file.path)
|
||||
return [
|
||||
{ type: 'text', text: message.content },
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: {
|
||||
url: await fileToBase64(file)
|
||||
url: base64Data.data
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -57,10 +59,9 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
const { contextCount, maxTokens } = getAssistantSettings(assistant)
|
||||
|
||||
const systemMessage = assistant.prompt ? { role: 'system', content: assistant.prompt } : undefined
|
||||
|
||||
const userMessages: ChatCompletionMessageParam[] = []
|
||||
|
||||
for (const message of takeRight(messages, contextCount + 1)) {
|
||||
for (const message of filterMessages(filterContextMessages(takeRight(messages, contextCount + 1)))) {
|
||||
userMessages.push({
|
||||
role: message.role,
|
||||
content: await this.getMessageContent(message)
|
||||
@@ -102,7 +103,7 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
return response.choices[0].message?.content || ''
|
||||
}
|
||||
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string | null> {
|
||||
public async summaries(messages: Message[], assistant: Assistant): Promise<string> {
|
||||
const model = getTopNamingModel() || assistant.model || getDefaultModel()
|
||||
|
||||
const userMessages = takeRight(messages, 5).map((message) => ({
|
||||
@@ -127,6 +128,21 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
return removeQuotes(response.choices[0].message?.content?.substring(0, 50) || '')
|
||||
}
|
||||
|
||||
public async generateText({ prompt, content }: { prompt: string; content: string }): Promise<string> {
|
||||
const model = getDefaultModel()
|
||||
|
||||
const response = await this.sdk.chat.completions.create({
|
||||
model: model.id,
|
||||
stream: false,
|
||||
messages: [
|
||||
{ role: 'user', content },
|
||||
{ role: 'system', content: prompt }
|
||||
]
|
||||
})
|
||||
|
||||
return response.choices[0].message?.content || ''
|
||||
}
|
||||
|
||||
async suggestions(messages: Message[], assistant: Assistant): Promise<Suggestion[]> {
|
||||
const model = assistant.model
|
||||
|
||||
@@ -177,6 +193,17 @@ export default class OpenAIProvider extends BaseProvider {
|
||||
public async models(): Promise<OpenAI.Models.Model[]> {
|
||||
try {
|
||||
const response = await this.sdk.models.list()
|
||||
|
||||
if (this.provider.id === 'github') {
|
||||
// @ts-ignore key is not typed
|
||||
return response.body.map((model) => ({
|
||||
id: model.name,
|
||||
description: model.summary,
|
||||
object: 'model',
|
||||
owned_by: model.publisher
|
||||
}))
|
||||
}
|
||||
|
||||
return response.data
|
||||
} catch (error) {
|
||||
return []
|
||||
|
||||
@@ -61,7 +61,7 @@ export async function fetchChatCompletion({
|
||||
}, 1000)
|
||||
|
||||
try {
|
||||
await AI.completions(filterMessages(messages), assistant, ({ text, usage }) => {
|
||||
await AI.completions(messages, assistant, ({ text, usage }) => {
|
||||
message.content = message.content + text || ''
|
||||
message.usage = usage
|
||||
onResponse({ ...message, status: 'pending' })
|
||||
@@ -129,6 +129,23 @@ export async function fetchMessagesSummary({ messages, assistant }: { messages:
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchGenerate({ prompt, content }: { prompt: string; content: string }): Promise<string> {
|
||||
const model = getDefaultModel()
|
||||
const provider = getProviderByModel(model)
|
||||
|
||||
if (!hasApiKey(provider)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const AI = new AiProvider(provider)
|
||||
|
||||
try {
|
||||
return await AI.generateText({ prompt, content })
|
||||
} catch (error: any) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchSuggestions({
|
||||
messages,
|
||||
assistant
|
||||
@@ -153,7 +170,7 @@ export async function fetchSuggestions({
|
||||
}
|
||||
|
||||
try {
|
||||
return await AI.suggestions(messages, assistant)
|
||||
return await AI.suggestions(filterMessages(messages), assistant)
|
||||
} catch (error: any) {
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ export function getDefaultAssistant(): Assistant {
|
||||
}
|
||||
}
|
||||
|
||||
export function getDefaultAssistantSettings() {
|
||||
return store.getState().assistants.defaultAssistant.settings
|
||||
}
|
||||
|
||||
export function getDefaultTopic(): Topic {
|
||||
return {
|
||||
id: uuid(),
|
||||
@@ -84,8 +88,9 @@ export function covertAgentToAssistant(agent: Agent): Assistant {
|
||||
return {
|
||||
...getDefaultAssistant(),
|
||||
...agent,
|
||||
id: agent.group === 'system' ? uuid() : String(agent.id),
|
||||
name: getAssistantNameWithAgent(agent),
|
||||
id: agent.group === 'system' ? uuid() : String(agent.id)
|
||||
settings: getDefaultAssistantSettings()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +1,26 @@
|
||||
import db from '@renderer/databases'
|
||||
import i18n from '@renderer/i18n'
|
||||
import dayjs from 'dayjs'
|
||||
import localforage from 'localforage'
|
||||
|
||||
export async function backup() {
|
||||
const indexedKeys = await localforage.keys()
|
||||
const version = 1
|
||||
const version = 2
|
||||
const time = new Date().getTime()
|
||||
|
||||
const data = {
|
||||
time,
|
||||
version,
|
||||
localStorage,
|
||||
indexedDB: [] as { key: string; value: any }[]
|
||||
}
|
||||
|
||||
for (const key of indexedKeys) {
|
||||
data.indexedDB.push({
|
||||
key,
|
||||
value: await localforage.getItem(key)
|
||||
})
|
||||
indexedDB: await backupDatabase()
|
||||
}
|
||||
|
||||
const filename = `cherry-studio.${dayjs().format('YYYYMMDD')}.bak`
|
||||
const fileContnet = JSON.stringify(data)
|
||||
const file = await window.api.compress(fileContnet)
|
||||
|
||||
window.api.saveFile(filename, file)
|
||||
await window.api.saveFile(filename, file)
|
||||
|
||||
window.message.success({ content: i18n.t('message.backup.success'), key: 'backup' })
|
||||
}
|
||||
|
||||
export async function restore() {
|
||||
@@ -37,17 +32,32 @@ export async function restore() {
|
||||
const data = JSON.parse(content)
|
||||
|
||||
if (data.version === 1) {
|
||||
localStorage.setItem('persist:cherry-studio', data.localStorage['persist:cherry-studio'])
|
||||
await clearDatabase()
|
||||
|
||||
for (const { key, value } of data.indexedDB) {
|
||||
await localforage.setItem(key, value)
|
||||
if (key.startsWith('topic:')) {
|
||||
await db.table('topics').add({ id: value.id, messages: value.messages })
|
||||
}
|
||||
if (key === 'image://avatar') {
|
||||
await db.table('settings').add({ id: key, value })
|
||||
}
|
||||
}
|
||||
|
||||
await localStorage.setItem('persist:cherry-studio', data.localStorage['persist:cherry-studio'])
|
||||
window.message.success({ content: i18n.t('message.restore.success'), key: 'restore' })
|
||||
setTimeout(() => window.api.reload(), 1500)
|
||||
} else {
|
||||
window.message.error({ content: i18n.t('error.backup.file_format'), key: 'restore' })
|
||||
setTimeout(() => window.api.reload(), 1000)
|
||||
return
|
||||
}
|
||||
|
||||
if (data.version === 2) {
|
||||
localStorage.setItem('persist:cherry-studio', data.localStorage['persist:cherry-studio'])
|
||||
await restoreDatabase(data.indexedDB)
|
||||
window.message.success({ content: i18n.t('message.restore.success'), key: 'restore' })
|
||||
setTimeout(() => window.api.reload(), 1000)
|
||||
return
|
||||
}
|
||||
|
||||
window.message.error({ content: i18n.t('error.backup.file_format'), key: 'restore' })
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
window.message.error({ content: i18n.t('error.backup.file_format'), key: 'restore' })
|
||||
@@ -59,16 +69,52 @@ export async function reset() {
|
||||
window.modal.confirm({
|
||||
title: i18n.t('common.warning'),
|
||||
content: i18n.t('message.reset.confirm.content'),
|
||||
centered: true,
|
||||
onOk: async () => {
|
||||
window.modal.confirm({
|
||||
title: i18n.t('message.reset.double.confirm.title'),
|
||||
content: i18n.t('message.reset.double.confirm.content'),
|
||||
centered: true,
|
||||
onOk: async () => {
|
||||
await localStorage.clear()
|
||||
await localforage.clear()
|
||||
await clearDatabase()
|
||||
await window.api.file.clear()
|
||||
window.api.reload()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/************************************* Backup Utils ************************************** */
|
||||
|
||||
async function backupDatabase() {
|
||||
const tables = db.tables
|
||||
const backup = {}
|
||||
|
||||
for (const table of tables) {
|
||||
backup[table.name] = await table.toArray()
|
||||
}
|
||||
|
||||
return backup
|
||||
}
|
||||
|
||||
async function restoreDatabase(backup: Record<string, any>) {
|
||||
await db.transaction('rw', db.tables, async () => {
|
||||
for (const tableName in backup) {
|
||||
await db.table(tableName).clear()
|
||||
await db.table(tableName).bulkAdd(backup[tableName])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function clearDatabase() {
|
||||
const storeNames = await db.tables.map((table) => table.name)
|
||||
|
||||
await db.transaction('rw', db.tables, async () => {
|
||||
for (const storeName of storeNames) {
|
||||
await db[storeName].clear()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ export const EVENT_NAMES = {
|
||||
REGENERATE_MESSAGE: 'REGENERATE_MESSAGE',
|
||||
CHAT_COMPLETION_PAUSED: 'CHAT_COMPLETION_PAUSED',
|
||||
ESTIMATED_TOKEN_COUNT: 'ESTIMATED_TOKEN_COUNT',
|
||||
SHOW_ASSISTANTS: 'SHOW_ASSISTANTS',
|
||||
SHOW_CHAT_SETTINGS: 'SHOW_CHAT_SETTINGS',
|
||||
SHOW_TOPIC_SIDEBAR: 'SHOW_TOPIC_SIDEBAR',
|
||||
SWITCH_TOPIC_SIDEBAR: 'SWITCH_TOPIC_SIDEBAR'
|
||||
SWITCH_TOPIC_SIDEBAR: 'SWITCH_TOPIC_SIDEBAR',
|
||||
NEW_CONTEXT: 'NEW_CONTEXT',
|
||||
NEW_BRANCH: 'NEW_BRANCH'
|
||||
}
|
||||
|
||||
57
src/renderer/src/services/file.ts
Normal file
57
src/renderer/src/services/file.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import db from '@renderer/databases'
|
||||
import { FileType } from '@renderer/types'
|
||||
|
||||
class FileManager {
|
||||
static async selectFiles(options?: Electron.OpenDialogOptions): Promise<FileType[] | null> {
|
||||
const files = await window.api.file.select(options)
|
||||
return files
|
||||
}
|
||||
|
||||
static async uploadFile(file: FileType): Promise<FileType> {
|
||||
const uploadFile = await window.api.file.upload(file)
|
||||
const fileRecord = await db.files.get(uploadFile.id)
|
||||
|
||||
if (fileRecord) {
|
||||
await db.files.update(fileRecord.id, { ...fileRecord, count: fileRecord.count + 1 })
|
||||
return fileRecord
|
||||
}
|
||||
|
||||
await db.files.add(uploadFile)
|
||||
|
||||
return uploadFile
|
||||
}
|
||||
|
||||
static async uploadFiles(files: FileType[]): Promise<FileType[]> {
|
||||
return Promise.all(files.map((file) => this.uploadFile(file)))
|
||||
}
|
||||
|
||||
static async getFile(id: string): Promise<FileType | undefined> {
|
||||
return db.files.get(id)
|
||||
}
|
||||
|
||||
static async deleteFile(id: string): Promise<void> {
|
||||
const file = await this.getFile(id)
|
||||
|
||||
if (!file) {
|
||||
return
|
||||
}
|
||||
|
||||
if (file.count > 1) {
|
||||
await db.files.update(id, { ...file, count: file.count - 1 })
|
||||
return
|
||||
}
|
||||
|
||||
db.files.delete(id)
|
||||
await window.api.file.delete(id + file.ext)
|
||||
}
|
||||
|
||||
static async deleteFiles(ids: string[]): Promise<void> {
|
||||
await Promise.all(ids.map((id) => this.deleteFile(id)))
|
||||
}
|
||||
|
||||
static async allFiles(): Promise<FileType[]> {
|
||||
return db.files.toArray()
|
||||
}
|
||||
}
|
||||
|
||||
export default FileManager
|
||||
@@ -1,11 +1,38 @@
|
||||
import { DEFAULT_CONEXTCOUNT } from '@renderer/config/constant'
|
||||
import { Assistant, Message } from '@renderer/types'
|
||||
import { GPTTokens } from 'gpt-tokens'
|
||||
import { isEmpty, takeRight } from 'lodash'
|
||||
|
||||
import { getAssistantSettings } from './assistant'
|
||||
import FileManager from './file'
|
||||
|
||||
export const filterMessages = (messages: Message[]) => {
|
||||
return messages.filter((message) => message.type !== '@').filter((message) => !isEmpty(message.content.trim()))
|
||||
return messages
|
||||
.filter((message) => !['@', 'clear'].includes(message.type!))
|
||||
.filter((message) => !isEmpty(message.content.trim()))
|
||||
}
|
||||
|
||||
export function filterContextMessages(messages: Message[]): Message[] {
|
||||
const clearIndex = messages.findLastIndex((message) => message.type === 'clear')
|
||||
|
||||
if (clearIndex === -1) {
|
||||
return messages
|
||||
}
|
||||
|
||||
return messages.slice(clearIndex + 1)
|
||||
}
|
||||
|
||||
export function getContextCount(assistant: Assistant, messages: Message[]) {
|
||||
const contextCount = assistant?.settings?.contextCount ?? DEFAULT_CONEXTCOUNT
|
||||
const _messages = takeRight(messages, contextCount)
|
||||
const clearIndex = _messages.findLastIndex((message) => message.type === 'clear')
|
||||
const messagesCount = _messages.length
|
||||
|
||||
if (clearIndex === -1) {
|
||||
return contextCount
|
||||
}
|
||||
|
||||
return messagesCount - (clearIndex + 1)
|
||||
}
|
||||
|
||||
export function estimateInputTokenCount(text: string) {
|
||||
@@ -24,7 +51,7 @@ export function estimateHistoryTokenCount(assistant: Assistant, msgs: Message[])
|
||||
model: 'gpt-4o',
|
||||
messages: [
|
||||
{ role: 'system', content: assistant.prompt },
|
||||
...filterMessages(takeRight(msgs, contextCount)).map((message) => ({
|
||||
...filterMessages(filterContextMessages(takeRight(msgs, contextCount))).map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content
|
||||
}))
|
||||
@@ -33,3 +60,7 @@ export function estimateHistoryTokenCount(assistant: Assistant, msgs: Message[])
|
||||
|
||||
return all.usedTokens - 7
|
||||
}
|
||||
|
||||
export function deleteMessageFiles(message: Message) {
|
||||
message.files && FileManager.deleteFiles(message.files.map((f) => f.id))
|
||||
}
|
||||
|
||||
16
src/renderer/src/services/model.ts
Normal file
16
src/renderer/src/services/model.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import store from '@renderer/store'
|
||||
import { Model } from '@renderer/types'
|
||||
import { pick } from 'lodash'
|
||||
|
||||
export const getModelUniqId = (m?: Model) => {
|
||||
return m?.id ? JSON.stringify(pick(m, ['id', 'provider'])) : ''
|
||||
}
|
||||
|
||||
export const hasModel = (m?: Model) => {
|
||||
const allModels = store
|
||||
.getState()
|
||||
.llm.providers.map((p) => p.models)
|
||||
.flat()
|
||||
|
||||
return allModels.find((model) => model.id === m?.id)
|
||||
}
|
||||
@@ -1,47 +1,27 @@
|
||||
import { Topic } from '@renderer/types'
|
||||
import db from '@renderer/databases'
|
||||
import { convertToBase64 } from '@renderer/utils'
|
||||
import localforage from 'localforage'
|
||||
|
||||
const IMAGE_PREFIX = 'image://'
|
||||
|
||||
export default class LocalStorage {
|
||||
static async getTopic(id: string) {
|
||||
return localforage.getItem<Topic>(`topic:${id}`)
|
||||
}
|
||||
|
||||
static async getTopicMessages(id: string) {
|
||||
const topic = await this.getTopic(id)
|
||||
return topic ? topic.messages : []
|
||||
}
|
||||
|
||||
static async removeTopic(id: string) {
|
||||
localforage.removeItem(`topic:${id}`)
|
||||
}
|
||||
|
||||
static async clearTopicMessages(id: string) {
|
||||
const topic = await this.getTopic(id)
|
||||
if (topic) {
|
||||
topic.messages = []
|
||||
await localforage.setItem(`topic:${id}`, topic)
|
||||
}
|
||||
}
|
||||
|
||||
static async storeImage(name: string, file: File) {
|
||||
export default class ImageStorage {
|
||||
static async set(key: string, file: File) {
|
||||
const id = IMAGE_PREFIX + key
|
||||
try {
|
||||
const base64Image = await convertToBase64(file)
|
||||
if (typeof base64Image === 'string') {
|
||||
await localforage.setItem(IMAGE_PREFIX + name, base64Image)
|
||||
if (await db.settings.get(id)) {
|
||||
db.settings.update(id, { value: base64Image })
|
||||
return
|
||||
}
|
||||
await db.settings.add({ id, value: base64Image })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error storing the image', error)
|
||||
}
|
||||
}
|
||||
|
||||
static async getImage(name: string) {
|
||||
return localforage.getItem<string>(IMAGE_PREFIX + name)
|
||||
}
|
||||
|
||||
static async removeImage(name: string) {
|
||||
await localforage.removeItem(IMAGE_PREFIX + name)
|
||||
static async get(key: string): Promise<string> {
|
||||
const id = IMAGE_PREFIX + key
|
||||
return (await db.settings.get(id))?.value
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { TopicManager } from '@renderer/hooks/useTopic'
|
||||
import { getDefaultAssistant, getDefaultTopic } from '@renderer/services/assistant'
|
||||
import LocalStorage from '@renderer/services/storage'
|
||||
import { Assistant, AssistantSettings, Model, Topic } from '@renderer/types'
|
||||
import { uniqBy } from 'lodash'
|
||||
|
||||
@@ -91,7 +91,7 @@ const assistantsSlice = createSlice({
|
||||
removeAllTopics: (state, action: PayloadAction<{ assistantId: string }>) => {
|
||||
state.assistants = state.assistants.map((assistant) => {
|
||||
if (assistant.id === action.payload.assistantId) {
|
||||
assistant.topics.forEach((topic) => LocalStorage.removeTopic(topic.id))
|
||||
assistant.topics.forEach((topic) => TopicManager.removeTopic(topic.id))
|
||||
return {
|
||||
...assistant,
|
||||
topics: [getDefaultTopic()]
|
||||
|
||||
@@ -22,7 +22,7 @@ const persistedReducer = persistReducer(
|
||||
{
|
||||
key: 'cherry-studio',
|
||||
storage,
|
||||
version: 24,
|
||||
version: 25,
|
||||
blacklist: ['runtime'],
|
||||
migrate
|
||||
},
|
||||
|
||||
@@ -77,6 +77,15 @@ const initialState: LlmState = {
|
||||
isSystem: true,
|
||||
enabled: false
|
||||
},
|
||||
{
|
||||
id: 'github',
|
||||
name: 'Github Models',
|
||||
apiKey: '',
|
||||
apiHost: 'https://models.inference.ai.azure.com/',
|
||||
models: SYSTEM_MODELS.github,
|
||||
isSystem: true,
|
||||
enabled: false
|
||||
},
|
||||
{
|
||||
id: 'yi',
|
||||
name: 'Yi',
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { SYSTEM_MODELS } from '@renderer/config/models'
|
||||
import i18n from '@renderer/i18n'
|
||||
import { Assistant } from '@renderer/types'
|
||||
import localforage from 'localforage'
|
||||
import { isEmpty, pick } from 'lodash'
|
||||
import { isEmpty } from 'lodash'
|
||||
import { createMigrate } from 'redux-persist'
|
||||
|
||||
import { RootState } from '.'
|
||||
@@ -375,12 +374,7 @@ const migrateConfig = {
|
||||
}
|
||||
}
|
||||
},
|
||||
'24': async (state: RootState) => {
|
||||
for (const key of await localforage.keys()) {
|
||||
if (key.startsWith('topic:')) {
|
||||
localforage.getItem(key).then((topic) => localforage.setItem(key, pick(topic, ['id', 'messages'])))
|
||||
}
|
||||
}
|
||||
'24': (state: RootState) => {
|
||||
return {
|
||||
...state,
|
||||
assistants: {
|
||||
@@ -399,6 +393,26 @@ const migrateConfig = {
|
||||
topicPosition: 'right'
|
||||
}
|
||||
}
|
||||
},
|
||||
'25': (state: RootState) => {
|
||||
return {
|
||||
...state,
|
||||
llm: {
|
||||
...state.llm,
|
||||
providers: [
|
||||
...state.llm.providers,
|
||||
{
|
||||
id: 'github',
|
||||
name: 'Github Models',
|
||||
apiKey: '',
|
||||
apiHost: 'https://models.inference.ai.azure.com/',
|
||||
models: SYSTEM_MODELS.github,
|
||||
isSystem: true,
|
||||
enabled: false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,14 @@ export interface RuntimeState {
|
||||
avatar: string
|
||||
generating: boolean
|
||||
minappShow: boolean
|
||||
searching: boolean
|
||||
}
|
||||
|
||||
const initialState: RuntimeState = {
|
||||
avatar: UserAvatar,
|
||||
generating: false,
|
||||
minappShow: false
|
||||
minappShow: false,
|
||||
searching: false
|
||||
}
|
||||
|
||||
const runtimeSlice = createSlice({
|
||||
@@ -25,10 +27,13 @@ const runtimeSlice = createSlice({
|
||||
},
|
||||
setMinappShow: (state, action: PayloadAction<boolean>) => {
|
||||
state.minappShow = action.payload
|
||||
},
|
||||
setSearching: (state, action: PayloadAction<boolean>) => {
|
||||
state.searching = action.payload
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const { setAvatar, setGenerating, setMinappShow } = runtimeSlice.actions
|
||||
export const { setAvatar, setGenerating, setMinappShow, setSearching } = runtimeSlice.actions
|
||||
|
||||
export default runtimeSlice.reducer
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import { ThemeMode } from '@renderer/types'
|
||||
|
||||
export type SendMessageShortcut = 'Enter' | 'Shift+Enter'
|
||||
|
||||
export enum ThemeMode {
|
||||
light = 'light',
|
||||
dark = 'dark',
|
||||
auto = 'auto'
|
||||
}
|
||||
|
||||
export interface SettingsState {
|
||||
showAssistants: boolean
|
||||
showTopics: boolean
|
||||
|
||||
@@ -27,10 +27,10 @@ export type Message = {
|
||||
createdAt: string
|
||||
status: 'sending' | 'pending' | 'success' | 'paused' | 'error'
|
||||
modelId?: string
|
||||
files?: File[]
|
||||
files?: FileType[]
|
||||
images?: string[]
|
||||
usage?: OpenAI.Completions.CompletionUsage
|
||||
type?: 'text' | '@'
|
||||
type?: 'text' | '@' | 'clear'
|
||||
}
|
||||
|
||||
export type Topic = {
|
||||
@@ -86,3 +86,29 @@ export type MinAppType = {
|
||||
logo: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface FileType {
|
||||
id: string
|
||||
name: string
|
||||
origin_name: string
|
||||
path: string
|
||||
size: number
|
||||
ext: string
|
||||
type: FileTypes
|
||||
created_at: Date
|
||||
count: number
|
||||
}
|
||||
|
||||
export enum FileTypes {
|
||||
IMAGE = 'image',
|
||||
VIDEO = 'video',
|
||||
AUDIO = 'audio',
|
||||
DOCUMENT = 'document',
|
||||
OTHER = 'other'
|
||||
}
|
||||
|
||||
export enum ThemeMode {
|
||||
light = 'light',
|
||||
dark = 'dark',
|
||||
auto = 'auto'
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Model } from '@renderer/types'
|
||||
import imageCompression from 'browser-image-compression'
|
||||
// @ts-ignore next-line`
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
|
||||
export const runAsyncFunction = async (fn: () => void) => {
|
||||
@@ -224,17 +225,7 @@ export function getBriefInfo(text: string, maxLength: number = 50): string {
|
||||
return truncatedText + '...'
|
||||
}
|
||||
|
||||
export async function fileToBase64(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e: ProgressEvent<FileReader>) => {
|
||||
const result = e.target?.result
|
||||
resolve(typeof result === 'string' ? result : '')
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
} catch (error: any) {
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
export function removeTrailingDoubleSpaces(markdown: string): string {
|
||||
// 使用正则表达式匹配末尾的两个空格,并替换为空字符串
|
||||
return markdown.replace(/ {2}$/gm, '')
|
||||
}
|
||||
|
||||
@@ -5,11 +5,20 @@
|
||||
"src/main/**/*",
|
||||
"src/preload/**/*",
|
||||
"src/main/env.d.ts",
|
||||
"src/renderer/src/types/index.ts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": [
|
||||
"electron-vite/node"
|
||||
],
|
||||
"paths": {
|
||||
"@types": [
|
||||
"./src/renderer/src/types/index.ts"
|
||||
],
|
||||
"@main/*": [
|
||||
"./src/main/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user