Compare commits

..

2 Commits

Author SHA1 Message Date
qiuqiu
7d74a2330e Windows7 support V1.4.1 (#7111)
* feat: Add-aihubmix-ideogram-v3 (#5958)

* chore: update Yarn version to 4.9.1 and add rendering speed option for V3 model

* Discard changes to .yarnrc.yml

* Discard changes to .yarn/releases/yarn-4.6.0.cjs

* Update package.json

* Delete .yarn/releases/yarn-4.9.1.cjs

* Discard changes to .yarn/releases/yarn-4.6.0.cjs

* docs: Update README.zh.md add GitCode✖️Cherry Studio【新源力】贡献挑战赛

GitCode✖️Cherry Studio【新源力】贡献挑战赛

* fix: Update the file permissions for yarn-4.6.0.cjs, modify image links and formatting in README.zh.md

* clean

* refactor: improve switch case blocks and update config parameters in AihubmixPage

* feat: add error handling for empty image URLs and update localization messages

* refactor: replace modal error handling with warning messages for empty image URLs

* feat: update localization for rendering speed and translating messages in Japanese, Russian, and Traditional Chinese

* feat: add style types and rendering speed options to localization files

---------

Co-authored-by: 亢奋猫 <kangfenmao@qq.com>
Co-authored-by: suyao <sy20010504@gmail.com>

* refactor(Scrollbar): Optimize scroll handling logic to support external scroll events (#6047)

* refactor(Scrollbar): Optimize scroll handling logic to support external scroll events

- Refactor `onScroll` logic to support external scroll events
- Integrate with `useScrollPosition` hook for better scroll state management
- Memorize the scoll state for better user experience
- Fix type definition for `ref` attribute
- Remove unnecessary `ref` type overrides
- Improve component compatibility and maintainability

* perf(useScrollPosition): Optimize scroll position updates using requestAnimationFrame

- Wrap the `window.keyv.set` call in `requestAnimationFrame` to reduce unnecessary performance overhead and improve responsiveness during scrolling.

* fix(Messages): Remove unused FC imports and add onComponentUpdate and onFirstUpdate properties

* hotfix: enhance reasoning summary handling in OpenAI response processing (#6037)

* feat: add zoom factor handling on window restore in WindowService (#6169)

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* Hotfix/gemini-para-bug (#6173)

* fix(OpenAIProvider): enhance model support and formatting logic

* fix(OpenAIProvider): Gemini OpenAI Compatible

* hotfix: respect user-defined model group name (#6174)

* feat(settings): add OpenAI alert (#6164)

* hotfix: add OpenAI settings tab and related functionality (#6040)

* feat: add OpenAI settings tab and related functionality

* fix: update related logic to support flexible service layer.

* fix(OpenAIResponseProvider): remove unused isOpenAILLMModel import

* feat: support default Quick Assistant model (#6150)

* feat: support default Quick Assistant model

- support the configuration of the quick assistant model.
- manage the models independently in Quick Assistant and Default Assistant.

* docs(i18n): Add translation for quick assistant model

* fix(llm): fix the default value of quickAssistantModel to silicon[1]

* refactor(i18n): uniformly the terms, changing "快速助手" to "快捷助手"

* refactor: remove constructor from KnowledgeQueue and invoke checkAllBases in useAppInit hook

* feat: add resolveFilePath functionality to resolve restoring from different computer (#5980)

* feat: add resolveFilePath functionality to file management

* Added new IPC channel for resolving file paths.
* Implemented resolveFilePath method in FileStorage service.
* Updated FileManager to utilize the new resolveFilePath method.
* Enhanced preload API to expose resolveFilePath to the renderer.
* Updated KnowledgeService to ensure file paths are correctly resolved in knowledge bases.

* refactor: remove unused path import from preload index

* Removed the unused 'resolve' import to clean up the codebase.
* Improved code readability by eliminating unnecessary dependencies.

---------

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* docs: update branching strategy documentation and add English and Chinese versions

- Updated the README to link to the new English branching strategy document.
- Added a new English version of the branching strategy document.
- Removed the outdated branching strategy document.
- Added a Chinese version of the branching strategy document.

* fix: update file path resolution in new Electron

* fix: update default values and improve component structure

- Changed default value for `getTrayOnClose` to true in `ConfigManager`.
- Removed fullscreen toggle logic from `WindowService`.
- Adjusted styles in `OpenAIAlert` for better spacing.
- Reorganized imports in `Navbar` and updated component paths in `AssistantsTab` and `SettingsTab`.
- Added new components `AssistantItem` and `OpenAISettingsGroup` for better modularity.
- Enhanced `SettingGroup` styles for improved UI consistency.
- Updated `QuickPhraseSettings` to utilize theme context.
- Minor fixes and refactoring across various services and components.

* feat: add MCP servers via JSON quickly (#6099)

* feat: add MCP servers via JSON quickly

* refactor(MCPSettings): Extract JSON parsing logic into a helper function

* feat: json linter for EditMcpJsonPopup

* feat(mcp): confirm the MCP server status as connection

* refactor(AddMcpServerModal): 移除冗余注释并修复加载状态

* feat(MCPSettings): Add support for SSE and streamableHttp formats and optimize server configuration parsing

- Add server type validation to ensure the type is stdio, SSE, or streamableHttp
- Optimize JSON parsing logic to ensure server configuration completeness and validity
- Update example text to provide more detailed configuration examples

* fix(MCPSettings): fix AddMcpServerModal default baseUrl login

移除serverToAdd.url作为baseUrl的备选值,确保baseUrl仅使用serverToAdd.baseUrl的值

* feat(MCPSettings): support CodeEditor in AddMcpServerModal

* fix: Remove unnecessary type checks for JSON parsing login

* fix(MCPSettings): fix compatibility issues with the URL field when parsing server data

* refactor: remove unnessary cdoe

* chore: Add a server dropdown button to integrate new features in UI

- Integrate the two buttons for adding a server into a single dropdown menu to enhance user experience and simplify the interface

* chroe: modify the Dropdown items' name of addServer

* refactor(i18n): unify the translation for the MCP server import function

---------

Co-authored-by: one <wangan.cs@gmail.com>

* fix: set default initial values for rendering speed in aihubmixConfig

- Added initialValue 'DEFAULT' for renderingSpeed in multiple mode configurations to ensure consistent default behavior across the application.

* chore(version): 1.3.7

* refactor: centralize paste handling logic with PasteService (#6199)

- Integrated PasteService for handling paste events in Inputbar and MessageEditor components.
- Removed redundant paste handling code and improved maintainability.
- Registered paste handlers and set last focused component for better user experience.
- Ensured consistent behavior for text and file pasting across components.

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* chore: update Hailuo logo (#6208)

* feat: update Hailuo model configuration with new logo property and border option

* chore: update hailuo_dark model image

* feat: add new model provider BurnCloud

* fix(mcp): mcp result preview is missing parameters (#6165)

* fix: knowledge icon consistency across components (#6209)

feat: knowledge icon consistency across components

* feat: enhance ContentSearch and MessageTools components

- Added placeholder and adjusted styles for the Input in ContentSearch.
- Updated SearchBarContainer to use fixed positioning and improved padding.
- Refactored MessageTools to render raw content correctly and added a new MarkdownContainer for better styling.
- Minor adjustments to other components for improved layout and user experience.

* fix: add context menu trigger to FloatingSidebar component

* refactor: improve FloatingSidebar and HomeTabs components

- Simplified the onOpenChange handler in FloatingSidebar for better readability.
- Added style prop to HomeTabs for enhanced customization.
- Adjusted Container style in HomeTabs to merge with existing border styles.

* Revert "feat: add resolveFilePath functionality to resolve restoring from different computer (#5980)"

This reverts commit 3abe0e803c.

* feat: implement getFilePath method in FileManager and update KnowledgeContent to use it

- Added getFilePath method in FileManager to construct file paths based on file ID and extension.
- Updated KnowledgeContent to utilize the new getFilePath method for opening file paths, improving code clarity and maintainability.

* chore(version): 1.3.8

* refactor(PasteService): optimize handler registration logic (#6223)

- Updated registerHandler to only log and update the handler if it changes, reducing unnecessary operations.
- Removed logging from unregisterHandler for cleaner code.

* Feat/mcp run python (#6151)

* feat: add MCP Run Python server and integrate Pyodide for executing Python code

* fix: comment out unused polyfill imports in MCP Run Python server

* fix: handle undefined html title (#6229)

* fix: improve CodeEditor controlled mode, prevent unnecessary trimming (#6221)

* fix: improve CodeEditor controlled mode, prevent unnecessary trimming

* fix: useEffect dependency

* fix: sse mcp 404 not found

* feat: add message multiple select (#6085)

* feat: add message multiple select

* fix: build error

* feat: add drag-and-drop multi-selection

* fix: code review

* Revert "fix: code review"

This reverts commit 7e29d5147c.

* fix: hide input bar display

* fix: extract the ChatContext

* fix: eventemitter

* feat: enhance multi-select functionality with message registration

* fix: history page message search

* fix: build error

* fix: remove Event Emitter

* fix: build error

* feat: add hideMenuBar prop to MessageItem and integrate MessageEditingProvider

* fix: improve message selection logic and handle drag events

* fix: update translation keys for multiple select functionality

* fix: refactor message deletion logic and enhance message selection handling

* fix: replace useSelector with useStore for message selection in ChatContext

* fix: refactor MessageGroup to utilize context for multi-select handling and message registration

* Revert "fix: refactor MessageGroup to utilize context for multi-select handling and message registration"

This reverts commit f4d1454525.

* fix: simplify MessageGroup props and utilize context for message selection handling

* fix: streamline multi-select handling by consolidating context usage and simplifying component props

* feat/notification (#6144)

* WIP

* feat: integrate notification system using Electron's Notification API

- Replaced the previous notification implementation with Electron's Notification API for better integration.
- Updated notification types and structures to support new features.
- Added translations for notification messages in multiple languages.
- Cleaned up unused dependencies related to notifications.

* refactor: remove unused node-notifier dependency from Electron config

* clean: remove node-notifier from asarUnpack in Electron config

* fix: update notification type in preload script to align with new structure

* feat: Integrate NotificationService for user notifications across various components

- Implemented NotificationService in useUpdateHandler to notify users of available updates.
- Enhanced KnowledgeQueue to send success and error notifications during item processing.
- Updated BackupService to notify users upon successful restoration and backup completion.
- Added error notifications in message handling to improve user feedback on assistant responses.

This update improves user experience by providing timely notifications for important actions and events.

* feat: Refactor notification handling and integrate new notification settings

- Moved SYSTEM_MODELS to a new file for better organization.
- Enhanced notification handling across various components, including BackupService and KnowledgeQueue, to include a source attribute for better context.
- Introduced notification settings in the GeneralSettings component, allowing users to toggle notifications for assistant messages, backups, and knowledge embedding.
- Updated the Redux store to manage notification settings and added migration logic for the new settings structure.
- Improved user feedback by ensuring notifications are sent based on user preferences.

This update enhances the user experience by providing customizable notification options and clearer context for notifications.

* feat: Add 'update' source to NotificationSource type for enhanced notification context

* feat: Integrate electron-notification-state for improved notification handling

- Added electron-notification-state package to manage Do Not Disturb settings.
- Updated NotificationService to respect user DND preferences when sending notifications.
- Adjusted notification settings in various components (BackupService, KnowledgeQueue, useUpdateHandler) to ensure notifications are sent based on user preferences.
- Enhanced user feedback by allowing notifications to be silenced based on DND status.

* feat: Add notification icon to Electron notifications

* fix: import SYSTEM_MODELS in EditModelsPopup for improved model handling

* feat(i18n): add knowledge base notifications in multiple languages

- Added success and error messages for knowledge base operations in English, Japanese, Russian, Chinese (Simplified and Traditional).
- Updated the KnowledgeQueue to utilize the new notification messages for better user feedback.

* feat(notification): introduce NotificationProvider and integrate into App component

- Added NotificationProvider to manage notifications within the application.
- Updated App component to include NotificationProvider, enhancing user feedback through notifications.
- Refactored NotificationQueue to support multiple listeners for notification handling.

* refactor: update MultiSelectionPopup icons and improve styling

- Replaced Ant Design icons with Lucide icons for a more modern look.
- Adjusted ActionButton styling to have a circular border radius.
- Updated translation keys in Chinese locales for better formatting.
- Enhanced event handling in ChatContext to manage multi-select mode more effectively.
- Cleaned up unused imports and props in MessageGroup and MessageSelect components.

* feat: add Google miniapp

* fix: enhance OpenAI service tier handling and initialize settings during migration

- Updated getServiceTier method to ensure proper handling of undefined OpenAI models.
- Added initialization for OpenAI settings in the migration process to set default values if not present.

* refactor: simplify MCP service integration and cleanup logic

- Replaced singleton pattern with direct instantiation of McpService for cleaner code.
- Updated IPC handlers to use the new mcpService instance directly.
- Removed unnecessary logging in Inputbar and MCPToolsButton components to streamline functionality.
- Cleaned up error handling in McpSettings to improve user experience.

* fix: topic deletion button covering the text

* fix: message content width will exceed the bubble limit in narrow layout mode

* fix: settings -> openAI -> summaryText undefined

* chore: remove electron-notification-state dependency and update notification settings

- Removed the electron-notification-state package from dependencies as it is no longer used.
- Updated NotificationService to eliminate Do Not Disturb handling.
- Changed default notification settings in the Redux store to false for assistant messages, backups, and knowledge embedding.

* fix: topic prompt not working #6226

close #6226

* fix: english serif font rendering issue #6224

close #6224

* chore(version): 1.3.9

* fix: increase the upper limit of issue-management operations-per-run (#6257)

* refactor: reuse shiki highlighter utils (#6235)

* refactor: improve shiki highlighter utils and reuse it in ShikiStreamService

* refactor: reuse shiki highlighter and markdown-it renderer

* refactor: import shiki/markdown-it/core dynamically

* chore: update shiki

* refactor: improve ContextMenu and Message components layout

- Replaced the div in ContextMenu with a styled component for better styling control.
- Enhanced Message component to handle editing state more cleanly, separating the editor from the message display.
- Adjusted styling for the MessageEditor and FileBlocksContainer for improved layout and responsiveness.

* refactor: migrate chat context to a custom hook and enhance multi-selection functionality

- Replaced the ChatContext with a custom hook `useChatContext` for better modularity and reusability.
- Updated components to utilize the new hook, passing the active topic as an argument.
- Enhanced multi-selection logic and state management for messages, improving user experience in the chat interface.
- Removed the old ChatContext file to streamline the codebase.

* refactor: enhance multi-selection handling in Inputbar and MessageEditor

- Integrated `useAppSelector` in Inputbar to manage multi-selection state.
- Updated Inputbar to conditionally render based on multi-selection mode.
- Modified MessageEditor to display the resend button only for assistant messages, improving UI clarity.

* style: update border color in SearchBarContainer for improved UI consistency

* fix: handle user cancellation and improve error reporting in file saving process

- Added a check for user cancellation in the file save dialog, rejecting the promise if canceled.
- Enhanced error handling to reject the promise with a detailed error message instead of returning null.

* refactor: update IPC channel names for notifications

- Renamed IPC channels for notifications to improve clarity and consistency.
- Updated related handlers in the main process and preload scripts to reflect the new naming convention.
- Enhanced notification service to respect user settings before sending notifications.

* refactor: enhance notification handling based on page context

- Updated NotificationProvider to truncate long messages for better display.
- Modified message sending logic in messageThunk to prevent notifications on the home page, improving user experience.

* chore: update release notes in electron-builder.yml

- Added new features including message notification functionality and support for Google Mini Programs.
- Improved MCP capabilities to run Python code and fixed several issues related to message editing and display.
- Updated release notes to reflect these changes and enhancements.

* fix: update service tier check to exclude GitHub and Copilot models

* refactor: improve shiki highlighter utils and reuse it in ShikiStreamService

* refactor: reuse shiki highlighter and markdown-it renderer

* hotfix: exclude GitHub and Copilot models

* fix: update service tier check to exclude GitHub and Copilot models

---------

Co-authored-by: one <wangan.cs@gmail.com>

* fix: show x-scrollbar in codeblock if unwrapped, simplify style definitions (#6266)

* fix: show x-scrollbar in codeblock if unwrapped, simplify style definitions

* chore: clean up useless code

* revert: mcp run python (#6151)

This reverts commit c468c3cfd5.

* refactor: CodePreview fade in on the first highlighting (#6228)

* refactor(CodePreview): fade in on the first highlighting

* refactor: improve code placeholder style

* refactor: update Gemini file upload method to accept baseURL parameter

- Modified the uploadFile method in GeminiService to include baseURL in the parameters.
- Updated the corresponding calls in the preload and renderer layers to pass the baseURL along with the apiKey.

* fix: enhance message loading and search functionality in HistoryPage and SearchResults

- Integrated Redux dispatch to load topic messages when a message is clicked in HistoryPage.
- Updated SearchResults to utilize message blocks for improved search results, including content extraction.
- Refactored state management to accommodate new content structure in search results.

* fix: token 取整 (#6300)

* fix: Use effective theme for code style in SettingsTab (#6305)

* Fix: Use effective theme for code style in SettingsTab

The SettingsTab component was previously using the theme setting directly from useSettings to determine whether to apply the light or dark code style. This caused an issue when the theme was set to 'auto', as it wouldn't correctly reflect the actual system theme (light or dark).

This commit modifies SettingsTab.tsx to use the `theme` from the `useTheme` hook (which provides the effective theme) for the logic that determines the code editor and preview styles. This ensures that the code style accurately reflects your current effective theme, including when 'auto' theme is selected and the OS theme changes.

* Refactor: Remove unnecessary comments in SettingsTab

This commit removes non-essential comments that were added during a previous refactoring of `SettingsTab.tsx`. The core logic for using the effective theme for code style selection remains unchanged. This change is purely for code cleanliness.

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>

* fix: aihubmix provider model proxy rule (#6293)

Update AihubmixProvider.ts

Co-authored-by: zhaochenxue <zhaochenxue@bixin.cn>

* feat: add functionality to insert messages at a specific index in the… (#6299)

* feat: add functionality to insert messages at a specific index in the Redux store

- Introduced a new interface for inserting messages at a specified index.
- Implemented the insertMessageAtIndex reducer to handle message insertion.
- Updated saveMessageAndBlocksToDB to support message insertion logic.
- Modified appendAssistantResponseThunk to utilize the new insertion functionality.

* feat: integrate multi-select mode handling in MessageGroup component

- Added useChatContext hook to access multi-select mode state.
- Updated isGrouped logic to account for multi-select mode, ensuring proper message grouping behavior.
- Enhanced MessageWrapper styles for better layout management in different modes.

---------

Co-authored-by: kangfenmao <kangfenmao@qq.com>

* feat: implement message location functionality and refactor multi-select handling

- Added event listeners for LOCATE_MESSAGE events to scroll to specific messages in the MessageGroup component.
- Introduced a new SelectionBox component to handle multi-select functionality, allowing users to select multiple messages with drag actions.
- Refactored Messages component to remove unused multi-select logic and improve overall structure.
- Cleaned up code by removing commented-out sections and unnecessary state management related to dragging.

* chore: upgrade yarn version to v4.9.1

* build: add win-sign script

* fix: enhance backup and restore functionality with skip option (#6294)

* fix: enhance backup and restore functionality with skip option

- Updated `restore` and `restoreFromWebdav` methods in `BackupManager` to include a `skipBackupFile` parameter, allowing users to skip restoring the Data directory if desired.
- Modified corresponding IPC calls in `preload` and `BackupService` to support the new parameter.
- Added success message translations in multiple languages for improved user feedback.

* fix: integrate skipBackupFile option in RestorePopup for enhanced restore functionality

* refactor: remove skipBackupFile parameter from restore methods for simplified usage

- Updated `restore` and `restoreFromWebdav` methods in `BackupManager`, `BackupService`, and `NutstoreService` to remove the `skipBackupFile` parameter, streamlining the restore process.
- Adjusted corresponding IPC calls in `preload` and `RestorePopup` to reflect the changes, ensuring consistent functionality across the application.

* fix: handle empty block content in MessageTranslate component

* fix: non-streaming reasoning_content (#6308)

* fix: non-streaming reasoning_content

* fix: streamline reasoning handling in OpenAIProvider

* fix: #6301 (#6317)

* fix: #6301

* fix: update dependencies in useUpdateHandler and add eslint comment in ContentSearch

* fix: shiki does not load language as a fallback & themes error (#6281)

* fix: shiki does not load language as a fallback & themes error

* feat: shiki automatic loading language

* fix: adjusted max-width in McpDescription.tsx

* fix: handle proxy environment variables for bun command in MCPService

- Added logic to remove proxy environment variables when the command ends with 'bun'.
- Introduced a new private method `removeProxyEnv` to clean up the environment variables before starting the server.

* feat: add support for 'grok' provider in web search functionality

- Enhanced `isWebSearchModel` to recognize 'grok' as a valid web search model.
- Updated `getOpenAIWebSearchParams` to return specific search parameters for 'grok'.
- Modified `OpenAIProvider` to handle citations from 'grok' in web search results.
- Added 'grok' to the `WebSearchSource` enum for citation formatting.

* feat: toggle MCP servers on the card list (#6232)

* feat: Support Claude 4 (#6328)

* feat: gemini thinking summary support

- Removed unnecessary content accumulation and streamlined chunk processing logic.
- Introduced distinct handling for 'thinking' and 'text' parts, ensuring accurate onChunk calls for both types.
- Enhanced timing tracking for reasoning content, improving overall responsiveness in streaming scenarios.

* chore(version): 1.3.10

* fix: editing user messages is not re-sent; it can only be saved#6327

* feat: support pin topic to the top

Signed-off-by: jtsang4 <info@jtsang.me>

* fix: minapp search error

* fix: ensure correct PATH assignment in shell environment

- Updated the environment variable initialization to use a consistent type.
- Added logic to set the PATH variable correctly, ensuring it falls back to existing values if necessary.

* feat: add navigation buttons for webview history in MinApp popup (#6342)

* feat: add navigation buttons for webview history in MinApp popup

- Implemented 'Go Back' and 'Go Forward' functionality in the MinApp popup.
- Added corresponding translations for English, Japanese, Russian, and Chinese locales.
- Included icons for navigation buttons to enhance user experience.

* fix: update Russian and Traditional Chinese translations for UI elements

- Revised translations for "rightclick_copyurl", "close", and "minimize" to improve clarity and consistency in the Russian and Traditional Chinese locales.
- Ensured that the translations align better with user expectations and common usage.

* fix: update Russian translations for MinApp popup UI elements

- Revised translations for "close" and "minimize" to specify their context within the MinApp, enhancing clarity for users.
- Ensured consistency with existing translations and improved user understanding of the interface.

---------

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* chore: update electron version to 35.4.0 in package.json and yarn.lock

* feat: support tokenflux provider (#6358)

* feat: add Cherry Cloud provider with associated assets and localization support

* feat: add Cherry Cloud provider support with OAuth integration and IPC handling

* fix: add success message for Cherry Cloud API key update

* feat: enhance provider navigation with dynamic ID in URL and update selected provider state

* feat: implement Cherry Cloud server synchronization with token management and error handling

* feat: add CherryCloud provider configuration and token management

* feat: integrate TokenFlux provider support and update related configurations

fix: update redux-persist version to 104

refactor: remove redundant tokenflux provider model assignment in migration

fix: update migration to add TokenFlux provider instead of CherryCloud

* feat: enhance TokenFlux server synchronization with API key authentication support

* feat: update TokenFlux provider assets and add new models

* feat: update migration logic for version 106 to add TokenFlux provider

* feat: disable TokenFlux provider by default in INITIAL_PROVIDERS

* feat: add TokenFlux billing URLs to providerCharge and providerBills functions

* refactor: remove manual chunking logic from Vite configuration

- Eliminated custom output chunking strategy for worker files and node_modules from the electron Vite configuration.
- Streamlined the configuration for improved maintainability and clarity.

* chore: update release notes and improve README assets

- Updated release notes to include new features such as TokenFlux service support, Claude 4 model integration, and fixes for various issues including Windows user startup problems and search crashes.
- Replaced outdated screenshots in README files with new images across English, Japanese, and Chinese documentation.
- Enhanced the 'Related Projects' section for better visibility.

* chore(version): 1.3.11

* chore: disable code signature verification for Windows updates in electron-builder configuration

* feat: add support for Windows ARM64 architecture in bun installation script

- Included package mappings for 'win32-arm64' and 'win32-arm64-baseline' to the BUN_PACKAGES object in install-bun.js, enhancing compatibility with ARM64 devices on Windows.

* fix: floating-sidebar header sticky (#6371)

* chore: add dependabot (#6369)

* fix: improve multi-select functionality in Messages and SelectionBox components

* feat: add disable MCP server functionality and update translations (#6398)

* feat: add disable MCP server functionality and update translations

* feat: update MCPToolsButton and WebSearchButton to use CircleX icon and change labels to 'close'

---------

Co-authored-by: kangfenmao <kangfenmao@qq.com>

* feat: 文字生成图新增提供商DMXAPI (#6352)

dmxapi文字生成图

Co-authored-by: 亢奋猫 <kangfenmao@qq.com>

* fix: update MainTextBlock to use a class for markdown styling

- Changed the paragraph element in MainTextBlock to include a "markdown" class for improved styling consistency.

* fix: handle optional usage properties in AnthropicProvider (#6418)

* fix: ensure args are an array in AddMcpServerModal and MCPService com… (#6413)

fix: ensure args are an array in AddMcpServerModal and MCPService components

* fix: update dimensions handling in KnowledgeBaseParams (#6417)

fix: update dimensions handling in KnowledgeBaseParams and add supported dimension providers

* fix: MessageMenubar copy uses latest content (#6435)

* Fix: MessageMenubar copy uses latest content

The 'Copy' button in MessageMenubar was previously using memoized content
derived from component props. This could lead to copying stale content if
you edited a message (e.g., a code block), saved it, and then
immediately clicked 'Copy', because the asynchronous Redux store update
might not have completed and propagated to the props yet.

This commit modifies the onCopy function in MessageMenubar.tsx to
fetch the latest version of the message directly from the Redux store
(store.getState().messages.entities[message.id]) at the moment the
copy action is performed. This ensures that the most up-to-date content
is always copied, resolving the stale content issue.

* Chore: Remove unnecessary comments from MessageMenubar

Removes a few explanatory comments from the onCopy function in
MessageMenubar.tsx that were deemed unnecessary, to keep the code
cleaner.

The comments originated from an example provided in a previous description. The core logic of the function remains unchanged.

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>

* refactor(CodeTool): use hook for codeblock tools rather than context (#6273)

* refactor(CodeTool): use hook for codeblock tools rather than context

* fix: codeblock overflow behaviour

* fix: CodePreview scrollbar

* refactor: move margin to CodeHeader

* refactor: add min-width to codeblock

* 修复DMXAPI文生成画bug

* feat: enhance citation handling in message export functionality (#6422)

* feat: enhance citation handling in message export functionality

- Refactored message export functions to include citation content in markdown output.
- Introduced a new utility function to extract and format citations from messages.
- Updated related imports and adjusted existing markdown generation logic for improved clarity and maintainability.

* feat: enhance message export tests to include citation and reasoning content

- Added tests to verify inclusion of citation content in markdown output when citation blocks exist.
- Ensured proper formatting with double newlines between sections in exported markdown.
- Updated existing tests to handle cases with reasoning content and no main text block gracefully.

* fix: update citation mapping in export tests for consistency

- Modified the citation mapping in export tests to use the index parameter directly, improving clarity and consistency in the generated markdown output.

* fix: enhance ExportService to support nested bold and italic formatting (#6420)

* fix: enhance ExportService to support nested bold and italic formatting

- Added tracking for nested bold and italic tags in the ExportService.
- Updated text rendering logic to apply bold and italic styles based on the nesting level of the tags.

* fix: remove unused citation variable in messageToMarkdown function

* fix: enhance web search recognization in AI providers (#6423)

* fix: escape special characters in search pattern for improved filtering

* feat: throttle updateTranslationBlock dispatch for improved performance (#6442)

- Introduced throttling to the updateTranslationBlock dispatch function to limit the frequency of updates, enhancing performance during message operations.
- Utilized lodash's throttle function to ensure efficient handling of accumulated text updates.

* fix: Chinese input issue in AddProviderPopup (#6445)

* chore: remove postinstall script from package.json

* fix: improve header styling in CustomCollapse component (#6449)

* fix: return value from appUpdater.checkForUpdates in IPC handler

* docs: update README files to reflect new roadmap and feature enhancements

- Revised the TODO section to a comprehensive roadmap outlining core features, knowledge management, platform support, and advanced features.
- Added links to the project board and GitHub Discussions for community engagement and feedback.

* fix: update popup content to improve user interaction in MessageGroup component

* fix: change display style of .shiki class to flex for improved layout in CodePreview component

* docs: update README files to enhance feature listings and organization

- Renumbered feature sections for clarity and consistency across English, Japanese, and Chinese README files.
- Improved formatting by removing unnecessary bullet points for a cleaner presentation of core features, knowledge management, platform support, and advanced features.

* fix: 修复Nutstore设置中的自动同步状态和错误消息内容 (#6452)

- 在NutstoreSettings组件中,添加了设置Nutstore自动同步状态的逻辑。
- 更新NutstoreService中的错误消息内容,确保使用正确的国际化键。

* feat: add dark mode support for DMXAPI logo in settings

- Introduced a new dark mode logo for DMXAPI and updated the logo rendering logic in the DMXAPISettings component to switch between light and dark logos based on the current theme.

* chore: update electron configuration and add debug script (#6361)

* chore: update electron configuration and add debug script

- Added sourcemap generation for development builds in electron.vite.config.ts.
- Introduced a new debug script in package.json for easier debugging with remote inspection.

* docs: add debug section to development documentation

- Introduced a new section for debugging instructions, including the command to run the debug script and how to access the Chrome inspect tool.

* Feat: Supports sorting of textarea function buttons by dragging (#6268)

* feat(inputbar): add collapsible tools and localization for tool actions

* refactor(inputbar): simplify tool rendering logic in InputbarTools

* refactor(inputbar): enhance tool visibility logic and improve rendering structure in InputbarTools

* fix(inputbar): correct tooltip text for collapse/expand action in InputbarTools

* refactor(Inputbar): simplify Toolbar structure and improve styling

* chore: update release notes and fix various issues

- Updated release notes to include new DMXAPI service and fixed knowledge base search results issue.
- Enhanced drag-and-drop functionality for message selection and resolved memory exceptions in translation replies.
- Added styling adjustments for context menu and improved layout in CodeBlockView and MessageGroup components.

* chore: remove gitee provider

* refactor: streamline provider menu logic in settings

- Consolidated edit and delete menu items for providers into separate constants for improved readability and maintainability.
- Enhanced the logic for displaying menus based on provider status, ensuring correct options are presented for system providers and initial providers.

* chore(version): 1.3.12

* refactor: remove early return for empty MCP servers in MCPToolsButton

- Eliminated the conditional return for empty active MCP servers to streamline the component rendering logic.

* chore: update electron-builder configuration and package dependencies

- Modified electron-builder.yml to refine file inclusion/exclusion patterns.
- Removed and re-added dependencies in package.json for consistency and updated yarn.lock to reflect these changes.
- Cleaned up unnecessary entries in yarn.lock to streamline the dependency tree.

* test: more unit tests (#5130)

* test: more unit tests

- Adjust vitest configuration to handle main process and renderer process tests separately
- Add unit tests for main process utils
- Add unit tests for the renderer process
- Add three component tests to verify vitest usage: `DragableList`, `Scrollbar`, `QuickPanelView`
- Add an e2e startup test to verify playwright usage
- Extract `splitApiKeyString` and add tests for it
- Add and format some comments

* fix: mock individual properties

* test: add tests for CustomTag

* test: add tests for ExpandableText

* test: conditional rendering tooltip of tag

* chore: update dependencies

* feat: Selection Assistant / 划词助手 (#5900)

* feat(selection): implement selection assistant with toolbar and action management

- Added selection assistant functionality including a toolbar for actions.
- Introduced new settings for enabling/disabling the selection assistant and configuring its behavior.
- Implemented action items for built-in functionalities like translate, explain, and copy.
- Integrated selection service to manage selection events and actions.
- Updated localization files to support new selection assistant features in multiple languages.
- Added new components for action management and user interaction within the selection assistant.

* chore: update selection-hook to version 0.9.10 and exclude prebuilds from packaging

* fix: toolbar hiding

* feat: enhance error handling and service management in main index

* fix: improve logical coordinate handling in SelectionService

* fix: update URL loading and coordinate conversion in SelectionService

* fix: replace console.error with Logger for error handling in SelectionService

* refactor(SelectionService): enhance preloaded action window management

* chore(electron-builder): add filter for .node build files in configuration

* fix: toolbar position calculating for multi monitor

* fix: update selection assistant configuration and improve error handling in SelectionService

* fix: SelectionActionUserModal layout

* feat: add hints for custom search URL in multiple languages

* fix: update calculateToolbarPosition to ensure integer return type and round position values

* feat: add action window opacity setting and update related UI components

refactor: SelectionActionsList

* chore: enhance tooltip for trigger mode settings

* fix: console.log

* chore: update selection-hook to version 0.9.12

* fix: integrate language settings into selection components

* fix: filter out default assistant from user predefined assistants in selection modal

* chore: update selection-hook package version to 0.9.13

* chore: update selection-hook package version to 0.9.14

* chore:  removed unused dependencies to reduce size (#6464)

* chore: update package dependencies and refactor BackupManager to use fs.promises

- Removed unused dependencies: fetch-socks and fs-extra from package.json and yarn.lock.
- Updated BackupManager to utilize fs.promises for file system operations, improving consistency and modernizing the codebase.
- Ensured all file operations in BackupManager are handled with promises for better error handling and readability.

* chore: add fs-extra dependency and refactor BackupManager for improved file handling

- Added fs-extra to package.json and updated yarn.lock to enhance file system operations.
- Refactored BackupManager to utilize fs-extra methods for better readability and functionality, replacing fs.promises with fs-extra equivalents for directory and file operations.

---------

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* fix: cannot run from yarn dev (#6468)

* fix[SelectionAssistant]: remove console.log (#6474)

fix: remove console.log

* feat: integrate custom CSS support in SelectionAssistant

* fix: adjust order of tools in CodeToolbar constants for correct display

* chore: update @google/genai to version 1.0.1 and remove GeminiService references

- Updated the @google/genai dependency in package.json and yarn.lock to version 1.0.1.
- Removed the GeminiService and its related references from the codebase to streamline functionality.
- Introduced a new CacheService for managing cached data effectively.

* chore: update electron-builder configuration to refine file exclusion patterns

- Added exclusions for various distribution directories and module types to optimize the build process.
- Updated license file exclusions to be more inclusive of different casing variations.

* fix(MainTextBlock): adjust whiteSpace style for user role messages (#6501)

* feat: add title to selection action button in compact mode (#6498)

* feat: add title prototype to selection action button in compact mode

* fix: optimize the display name logic for action buttons in the selection toolbar

* fix: remove tiktoken

* chore: remove electron-icon-builder

* feat: painting aihubmix support model: gpt-image-1 (#6486)

* update select style

* add openai painting

* support base64 response

* update config

* fix upload preview bug

* fix remix default model

* fix history data

* feat: optimize structure

* fix history data

---------

Co-authored-by: zhaochenxue <zhaochenxue@bixin.cn>

* feat: add default painting provider support and update routing

- Introduced defaultPaintingProvider in settings to manage selected painting provider.
- Updated Sidebar component to reflect the selected painting provider in the route.
- Enhanced PaintingsRoutePage to dispatch the default painting provider based on URL parameters.
- Added PaintingProvider type to define available options for painting providers.

* feat: aihubmix painting support imagen (#6525)

* add imagen

* feat: support imagen model

* update proxy notice

---------

Co-authored-by: zhaochenxue <zhaochenxue@bixin.cn>

* refactor: TrayService & ConfigManager (#6526)

* refactor: TrayService

- Removed the App_RestartTray channel from IpcChannel and its usage in ipc.ts and preload/index.ts.
- Updated TrayService to handle configuration changes without the need for a restart.
- Enhanced ConfigManager to notify subscribers on language and quick assistant settings changes.
- Adjusted QuickAssistantSettings to close the mini window based on the quick assistant's enable state.

* refactor: enhance configuration management

- Updated ConfigManager to consolidate setting and notification logic into a single method, setAndNotify.
- Modified IPC handler to accept an additional parameter for notification control.
- Adjusted QuickAssistantSettings to utilize the new parameter for enabling notifications during configuration changes.

* fix: Optimize error message formatting (#5988)

* fix: Optimize error message formatting

* fix: improve error unit test

* refactor: simplify error handling in ErrorBlock component

- Replaced custom StyledAlert with a more streamlined Alert component for error messages.
- Reduced complexity by removing unnecessary JSX wrappers and improving readability.
- Adjusted styling for the Alert component to maintain visual consistency.

* fix: update error handling in ErrorBlock component

- Removed unnecessary message prop from Alert component to simplify error display.
- Maintained existing error handling logic while improving code clarity.

* feat[SelectionAssistant]: add faq&feedback link (#6531)

feat: add FAQ button to Selection Assistant settings

* chore: refine file exclusion patterns in electron-builder configuration (#6502)

- Updated exclusion patterns to ensure more comprehensive filtering of unnecessary files and directories during the build process.
- Added additional file types and configurations to the exclusion list for better optimization.

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* feat: support system prompt variables (#5995)

* feat: support system prompt variables

* feat: add tip

* fix ci test fail

* feat: Assistant add tag (#6065)

* feat: 添加助手标签显示逻辑
-增加助手的标签属性
-能够删除,修改,调整助手的标签
Signed-off-by: LeeSH <shuhao_lin@fzzixun.com>

* fix: 修复不能输入新增标签的问题

* feat: 完善不同状态下,提示文本展示

* feat: 调整标签展示逻辑
1,左键调整列表页展示逻辑
2,新增标签改为使用+号提示

* feat: 移除搜索栏可以直接增加tag值的功能
Signed-off-by: LeeSH <shuhao_lin@fzzixun.com>

* fix: 修复点击不能切换话题的bug

* feat:  调整了标签修改的交互
1,添加和管理分开处理
2,可以点击标签之间切换
3,点击删除可以之间移除所有关联助手的标签

tips:为了简单实现,标签本身不具有具体类,都是助手的子属性。所以如果关联的所有助手都没了该属性,标签会直接消失,而且标签目前无法排序

Signed-off-by: LeeSH <shuhao_lin@fzzixun.com>

* feat:优化标签管理
1,列表状态管理向上提,切换左侧列表不会影响原来的列表状态
2,标签名称增加最大宽度
3,标签内的助手顺序,参照原顺序排列
4,增加标签ui,提示语调整
5,标签管理ui,提示语调整
6,标签管理增加标签暂时态,防止误删没有其他助手的标签项的时候,标签在弹窗内整个消失(如果关闭弹窗那标签就无法找回)
7,如果没有标签的时候,右键仅展示添加标签

Signed-off-by: LeeSH <shuhao_lin@fzzixun.com>

---------

Signed-off-by: LeeSH <shuhao_lin@fzzixun.com>
Co-authored-by: linshuhao <nmnm1996>
Co-authored-by: Lee SH <shuhao_lin@fzzixun.com>

* fix: increase max cache limit and update slider marks in MiniAppSettings (#6414)

* fix: increase max cache limit and update slider marks in MiniAppSettings

* fix: adjust max cache limit and update slider marks in MiniAppSettings

* Update MiniAppSettings.tsx

---------

Co-authored-by: George Zhao <georgezhao@SKJLAB>

* fix: update TikToken implementation and remove js-tiktoken dependency

- Replaced the existing TikToken implementation with a placeholder error message indicating it is not implemented.
- Removed the js-tiktoken dependency from package.json to streamline the project.
- Updated yarn.lock to reflect changes in dependencies and checksums.

* fix: update token limits for Claude-4 models and refine reasoning checks in OpenAIProvider

- Adjusted max token limit for 'claude-sonnet-4' and 'claude-opus-4' models from 64000 to 32000.
- Simplified reasoning checks in OpenAIProvider to combine conditions for supported models, enhancing code clarity.

* fix[SelectionAssistant]: interrupting in terminal apps (#6549)

fix: interrupting in terminal apps

* fix: add custom parameters to OpenAI generateImageByChat requests

* chore(version): 1.4.0-rc.1

* fix: update artifact patterns in release workflow

- Modified the artifact patterns in the GitHub Actions release workflow to include 'dist/rc*.yml' for better versioning support.

* fix(OpenAIProvider): adjust reasoning effort setting to default to 'medium' when set to 'auto'

* fix: suppress exhaustive-deps warnings in multiple components

- Added eslint-disable comments for react-hooks/exhaustive-deps in CustomCollapse, DmxapiPage, SelectionActionApp, ActionGeneral, and ActionTranslate components to prevent warnings related to missing dependencies in useEffect hooks.

* feat(SelectionAssistant): App Filter / 应用筛选 (#6519)

feat: add filter mode and list functionality to selection assistant

- Introduced new filter mode options (default, whitelist, blacklist) for the selection assistant.
- Added methods to set and get filter mode and filter list in ConfigManager.
- Enhanced SelectionService to manage filter mode and list, affecting text selection processing.
- Updated UI components to allow users to configure filter settings.
- Localized new filter settings in multiple languages.

* fix: Repair abnormal line break display

* Revert "fix: Repair abnormal line break display"

This reverts commit 3d7fd5a30c.

* fix(HealthCheck): add a disclaimer (#6570)

* fix(HealthCheck): add a disclaimer

* fix: remove duplicates in zh-tw.json

* refactor: chat navigation triggering (#6576)

* refactor(ChatNavigation): move down the navigation bar

* refactor: attach listeners to MessagesContainer for better triggering experience

* refactor: add delay to Tooltips

* refactor: exclude some toolbars areas from triggering

* fix(style): global cursor style for scrollbar thumb

* fix(SvgPreview): dragging and sanitizing (#6568)

* fix(SvgPreview): dragging

* fix(SvgPreview): sanitize svg content

* feat(SelectionAssistant): support Shift+Click & enhance Ctrl key mode (#6566)

* feat: add filter mode and list functionality to selection assistant

- Introduced new filter mode options (default, whitelist, blacklist) for the selection assistant.
- Added methods to set and get filter mode and filter list in ConfigManager.
- Enhanced SelectionService to manage filter mode and list, affecting text selection processing.
- Updated UI components to allow users to configure filter settings.
- Localized new filter settings in multiple languages.

* feat: support Shift+Click & enhance Ctrl key method

* fix: remove comments

* fix(PROVIDER_CONFIG): update website URLs from ppinfra.com to ppio.cn

* fix(provider): update Qiniu's name and logo, fix gitee typo (#6593)

* fix(provider): update Qiniu's name and logo

* fix(provider): typo

* feat(theme): 用户自定义主题色 (#4613)

* feat(theme): 用户自定义主题色

* refactor(QuickPanel): integrate user theme for dynamic color handling

* refactor(ThemeProvider): separate user theme initialization into its own useEffect

* refactor(useUserTheme): move theme initialization logic into a dedicated function

* feat(settings): enhance color picker with presets and update styles for ant-collapse

* feat: Refactor theme management to use userTheme object for colorPrimary

* refactor(Chat, Messages): simplify maxWidth calculations and remove unused showAssistants variable

* refactor(Scrollbar, Chat, Messages): improve scroll handling and clean up component structure

* refactor(Messages): enhance message rendering and navigation exclusions

- Updated styles for message content and group containers to improve layout.
- Added new selectors to exclude additional elements from navigation.
- Implemented conditional rendering for mentions in message content.
- Simplified token display logic in message tokens component.

* feat(DisplaySettings): add theme color presets and zoom settings

- Introduced a new color selection feature in DisplaySettings, allowing users to choose from predefined theme color presets.
- Added a dedicated section for zoom settings in the DisplaySettings component, enhancing user customization options.
- Updated localization files to include new zoom settings titles in multiple languages.

* feat: 调整分组的效果 (#6561)

1,未分组标签改为未分组
2,列表展示效果持久化
3,增加一个管理列表展示效过的store

Co-authored-by: linshuhao <nmnm1996>

* refactor: standardize variable naming and improve tag calculation logic

- Renamed variables for consistency, changing `AssistantsTabSortType` to `assistantsTabSortType`.
- Refactored tag calculation in `useTags` to utilize `uniq` and `flatMap` for better performance and readability.
- Updated localization files to remove unnecessary characters in quick trigger messages.
- Enhanced the `AssistantItem` component by extracting menu item creation logic and sorting functions for better maintainability.

* test(QuickPanelView): integrate Redux store into tests and refactor rendering logic

- Added a mock Redux store to the QuickPanelView tests for better state management.
- Refactored test rendering to use a wrapper function for consistent provider usage.
- Updated Scrollbar test to verify throttle behavior with new delay and options.

* revert: fix: english serif font rendering issue #6224

This reverts commit 5dd508b4f4.

* feat(SelectionAssistant): add "Remember Window Size" functionality

- Introduced a new setting to remember the last adjusted size of the action window.
- Updated ConfigManager, SelectionService, and IPC channels to handle the new feature.
- Enhanced UI components to allow users to toggle the "Remember Size" option.
- Localized the new setting in multiple languages.

* feat: add "Regenerate" in action window

* chore(version): 1.4.0-rc.2

* feat(SelectionAssistant): improve selection in browsers and pdf readers (#6618)

fix: improve browsers and pdf readers selection

* refactor(Scrollbar, Messages): clean up scrollbar component and styles

- Removed unused 'right' prop from Scrollbar component.
- Increased scrolling timeout duration for better user experience.
- Updated scrollbar styles to simplify color handling.
- Adjusted Messages component to remove unnecessary props and added margin for better layout.
- Added responsive styles to CitationBlock for improved mobile display.

* fix: setting tab font size

* feat: dmxapi generate multiple image (#6632)

* chore(version): 1.3.8

* 新增自动添加

* 图片自增功能优化

---------

Co-authored-by: kangfenmao <kangfenmao@qq.com>

* refactor(SvgPreview): use shadow dom

* test(scrollbar): fix snapshot mismatched

* fix(MainTextBlock): update whiteSpace style for user messages to 'pre-wrap'

* fix(Messages, WebSearchProviderSetting): remove unused variables and update provider logo styling

* lint: fix eslint error and build:check

* feat: improve translation setting logic (#6463)

* feat: add auto-detect language option and improve translation logic

* feat: remove auto-detect language option and add bidirectional translation settings

* fix: remove unused model removal function from TranslatePage component

* feat: add language detection and bidirectional translation utilities

* feat: update translation settings to include bidirectional translation tips and remove deprecated options

* fix: improve interaction

* fix: change cld3-asm to franc

* fix: ui/ux

* fix: change eslint

* fix: update

* Revert "fix: update"

This reverts commit 1126a5cce9.

* Reapply "fix: update"

This reverts commit 82b7890f92.

* fix: setloading missing

* refactor: Theme improve (#6619)

* refactor(IpcChannel): rename theme change event and streamline theme handling

- Updated the IpcChannel enum to rename 'theme:change' to 'theme:updated' for clarity.
- Refactored theme handling in ipc.ts to utilize a new ThemeService, simplifying theme updates and event broadcasting.
- Adjusted various components to consistently use the updated theme variable naming convention.

* refactor(Theme): standardize theme handling across components

- Updated theme retrieval to use 'actualTheme' instead of 'theme' for consistency.
- Changed default theme setting from 'auto' to 'system' in ConfigManager and related components.
- Adjusted theme handling in various components to reflect the new naming convention and ensure proper theme application.

* fix(Theme): improve theme handling and migration logic

- Added a console log for debugging theme transitions in ThemeProvider.
- Updated ThemeService to ensure theme is set correctly when changed.
- Incremented version number in store configuration to reflect changes.
- Enhanced migration logic to convert 'auto' theme setting to 'system' for better consistency.

* feat(Theme): add getTheme IPC channel and improve theme management

- Introduced a new IPC channel 'App_GetTheme' to retrieve the current theme.
- Updated ThemeService to include a method for getting the current theme.
- Refactored theme initialization in WindowService to ensure proper theme setup.
- Enhanced theme handling in various components to utilize the new theme retrieval method.

* fix(ThemeService): improve theme initialization and retrieval logic

- Set default theme to 'system' and updated theme initialization to handle legacy versions.
- Enhanced getTheme method to return both the current theme and the actual theme based on nativeTheme settings.
- Removed redundant initTheme method from ThemeService and ensured themeService is imported in WindowService for proper initialization.
- Updated ThemeProvider to handle the new structure of the theme retrieval response.

* refactor(Settings): remove theme management from settings

- Eliminated theme-related state and actions from the settings slice.
- Updated useSettings hook to remove theme handling functionality.
- Cleaned up imports by removing unused ThemeMode type.

* refactor(Theme): update theme retrieval in GeneralSettings and HomeWindow

- Restored theme retrieval in GeneralSettings and HomeWindow components.
- Adjusted imports to ensure proper theme management.
- Updated theme condition checks to utilize the ThemeMode enumeration for consistency.

* refactor(Theme): update theme terminology and retrieval in Sidebar and DisplaySettings

- Changed theme label from 'auto' to 'system' in multiple localization files for consistency.
- Updated Sidebar component to reflect the new theme terminology.
- Adjusted DisplaySettings to display the updated theme label.

* refactor(ThemeProvider): initialize theme state from API response

* refactor(ThemeProvider): reset theme state to default values and streamline initialization logic

* refactor(Theme): enhance theme management by incorporating 'system' mode and updating state handling

- Updated ThemeService to include 'system' as a valid theme option.
- Refactored ThemeProvider to utilize useSettings for theme state management and ensure proper initialization.
- Adjusted useSettings to include theme setting functionality.
- Modified settings slice to manage theme state effectively.

* refactor(WindowService, ThemeProvider, Messages, HomeWindow): streamline imports and clean up unused variables

- Removed duplicate import of ThemeService in WindowService.
- Adjusted import order in ThemeProvider for clarity.
- Simplified useSettings destructuring in Messages component.
- Cleaned up unused ThemeMode import in HomeWindow.

* refactor(Theme): standardize theme usage across components by replacing 'actualTheme' with 'theme'

- Updated components to consistently use 'theme' instead of 'actualTheme' for better clarity and maintainability.
- Adjusted ThemeProvider to reflect changes in theme state management.
- Ensured all relevant components are aligned with the new theme structure.

* refactor(Theme): remove unused theme retrieval functionality

- Eliminated the App_GetTheme channel and associated methods from ThemeService and IPC handling.
- Updated components to use the new theme structure, replacing 'actualTheme' with 'settedTheme' for consistency.
- Ensured all theme-related functionalities are streamlined and aligned with the latest changes.

* refactor(Theme): update theme variable usage in ChatFlowHistory and GeneralSettings

- Replaced 'theme' with 'settedTheme' in ChatFlowHistory for consistency with recent theme structure changes.
- Simplified theme destructuring in GeneralSettings by removing unused 'themeMode' variable.
- Ensured alignment with the latest theme management updates across components.

* refactor(Theme): update theme variable in GeneralSettings component

- Replaced 'themeMode' with 'theme' in GeneralSettings for consistency with recent theme structure changes.
- Ensured alignment with the latest theme management updates across components.

---------

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* fix: interrupting in shell and improve pdf readers

* fix: The edit button cannot be used after using MCP. 修复对话中使用 MCP 后编辑按钮消失的问题 (#6623)

fix: The edit button cannot be used after using MCP.

* chore(version): 1.4.0-rc.3

* fix: thinking time reset (#6665)

* fix: thinking time reset

* fix: update theme listener to properly handle theme updates

---------

Co-authored-by: Pleasurecruise <3196812536@qq.com>

* feat(SelectionAssistant): predefined apps filter list (#6662)

* feat: predefined app blacklist

* fix

* fix

* fix

* fix: improve filter list processing in SelectionFilterListModal

* chore(version): 1.4.0

* refactor: sort mentioned models in QuickPanel (#6666)

* fix(OpenAIProvider): prevent atob error with non-base64 image URLs (#6673)

Signed-off-by: Chan Lee <Leetimemp@gmail.com>

* fix: replace franc with franc-min for improved performance

* fix: provider o3 docs not found

* feat(SelectionService): enhance trigger mode handling and update predefined blacklist

* fix: adjust sidebar icon margins based on fullscreen state

* test: more unit tests for message rendering (#6663)

* refactor(encodeHTML): remove duplicate definition

* test(Scrollbar): update snapshot

* test: add more tests

Add tests for
- MainTextBlock
- ThinkingBlock
- Markdown
- CitationTooltip

* fix: token usage not updated after editing message (#6725)

fix: update token usage when edit message

* fix: qwen3 cannot name a topic (#6722)

* fix: qwen3 cannot name a topic

* feat: Display error message when topic naming fails

* fix: assistant emoji displaying incorrectly in specific situations #6243 (#6280)

* fix:  ssistant emoji displaying incorrectly in specific situations

* chore: remove unuse import

* fix: ensure default emoji

* fix: remove redundant min-width in AssistantItem and EmojiIcon components; enhance emoji click handling

---------

Co-authored-by: 自由的世界人 <3196812536@qq.com>

* fix: mcp uv&bun installation status icon in nav bar not updated after… (#6654)

fix: mcp uv&bun installation status icon in nav bar not updated after installed

Signed-off-by: aprilandjan <merlin.ye@qq.com>

* hotfix(OpenAIProvider): remove redundant 'unkown' chunk (#6737)

fix(OpenAIProvider): remove redundant 'unknown' yield case in chunk processing

* hotfix: update qwen3 model identification logic to use startsWith for im… (#6738)

fix: update qwen3 model identification logic to use startsWith for improved accuracy

* feat(AppUpdater): implement localized update dialog (#6742)

feat(AppUpdater): implement localized update dialog with new translations for multiple languages

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* Fix: outdated provider websites and models (#6766)

* fix: inappropriate provider websites (openrouter, grok)

* fix: outdated model list (grok)

* chore(gitignore): exclude cursor settings (#6779)

* fix: prevent message overflow when minimized width (#6775)

* refactor(BackupManager, WebDav): streamline WebDAV client initialization and enhance directory listing functionality (#6784)

Co-authored-by: beyondkmp <beyondkmkp@gmail.com>

* fix(SelectionAssistant): customCSS should not override background (#6746)

fix: customCSS should not override background

* feat(SelectionAssistant): Smart Translation ( aka BiDirectionTranslate) (#6715)

* feat(Translation): enhance translation functionality and UI improvements

- Added secondary text color variables in color.scss for better UI contrast.
- Updated translation configuration to include language codes for better language handling.
- Enhanced translation UI with new language selection options and improved loading indicators.
- Implemented smart translation tips in multiple language JSON files for user guidance.
- Refactored translation logic to streamline message processing and error handling.

* feat(Translation): expand language options and update localization files

- Added new languages (Polish, Turkish, Thai, Vietnamese, Indonesian, Urdu, Malay) to translation options in translate.ts.
- Updated localization JSON files (en-us, ja-jp, ru-ru, zh-cn, zh-tw) to include translations for the new languages.
- Enhanced language detection logic in translate.ts to support new language codes.

* fix: chat navigation triggering (#6774)

* fix: exclude MessageEditor

* fix: more accurate triggering area

* fix(ci): Update the nightly-build workflow (#6791)

Update the branch name from `develop` to `main`

* fix: optimize multilingual display of documents (#6793)

Update Sidebar.tsx

* fix: correct variable name obsidianVault in Obsidian export (#6796)

* fix: transparent window flashing when show (#6755)

* fix: avoid SelectionAssistant toolbar flashing

* add comments

* feat(SelectionAssistant): fullscreen game/presentation mode

* fix: codeblock overflow in bubble style (#6773)

* refactor: revert CodeBlockView style change

* fix: codeblock width and overflow

* refactor: improve CodeEditor border

* revert: context-menu-container width for message group

* fix(MermaidPreview): debounce mermaid rendering to alleviate flickering (#6675)

* hotfix: gemini auto thinking (#6810)

* fix(SelectionAssistant): JetBrains IDEs, Remote desktop, Gaming, PDF views, etc (#6809)

fix: jetbrains ides, remote desktop, pdf views, etcs

* fix: use monospace font for theme colorpicker (#6816)

* fix(AnthropicProvider): update usage and metrics handling to prevent TypeError  (#6813)

* fix: sync active topic after rename (#6804)

Co-authored-by: Chen Tao <70054568+eeee0717@users.noreply.github.com>

* fix: OpenAI provider api check doesn't handle error (#6769)

* feat(constants): expand supported file extensions and categorize text… (#6815)

* feat(constants): expand supported file extensions and categorize text file types

* refactor(constants): remove binary file extensions

* refactor(constants): remove Xcode project

* feat(Settings): Add token count display toggle (#6772)

* feat(Settings): add token count toggle

* fix(i18n): update token usage messages for zh-cn and zh-tw locales

* fix(InstallNpxUv): optimize checkBinaries function with useCallback for better performance

---------

Co-authored-by: Pleasurecruise <3196812536@qq.com>

* hotfix: ensure show token usage setting defaults to true (#6828)

Hotfix: ensure show token usage setting defaults to true

* fix(SelectionAssistant): ignore ctrl pressing when user is zooming in/out (#6822)

* fix(SelectionService): ignore ctrl pressing when user is zomming in/out

* chore: rename function

* fix: reset listener status

* refactor: enhance export functions (#5854)

* feat(markdown-export): add option to show model name in export

* refactor(export): Refactor the Obsidian export modal to Ant Design style

* refactor(obsidian-export): export to obsidian using markdown interface & support COT

* feat(markdown-export): optimize COT export style, support export model & provider name

Add a new setting to toggle displaying the model provider alongside the
model name in markdown exports. Update the export logic to include the
provider name when enabled, improving context and clarity of exported
messages. Also fix invalid filename character removal regex for Mac.

* feat(export): add option to export reasoning in Joplin notes

Introduce a new setting to toggle exporting reasoning details when
exporting topics or messages to Joplin. Update the export function to
handle raw messages and convert them to markdown with or without
reasoning based on the setting. This improves the export feature by
allowing users to include more detailed context in their Joplin notes.

* feat(export): update i18n for new export options

* fix(settings): remove duplicate showModelNameInMarkdown state

* feat(export): add CoT export for notion & optmize notion export

* feat(export): update Notion settings i18n

* fix(utils): correct citation markdown formatting

Swap citation title and URL positions in markdown links to ensure
the link text displays the title (or URL if title is missing) and
the link points to the correct URL. This improves citation clarity.

* fix: add blank lines between reasoning summary parts (#6827)

Co-authored-by: Chen Tao <70054568+eeee0717@users.noreply.github.com>

* support tokenflux image generation for [Flux.1 Kontext] (#6705)

* Add support for TokenFlux image generation service

This commit integrates TokenFlux as a new painting provider with dynamic
form generation based on model schemas, real-time generation polling,
and full painting history management.

Key features:
- Dynamic form rendering from JSON schema input parameters
- Model selection with pricing display
- Real-time generation status polling
- Integration with existing painting workflow and file management
- Provider-specific painting state management

The implementation follows existing patterns from other painting pages
while adding TokenFlux-specific functionality like schema-based form
generation and asynchronous polling for generation results.

* Add image upload support and comparison view to TokenFlux

Implements file upload handling for image parameters with base64
conversion, random seed generation, and side-by-side comparison
layout when input images are present.

* Refactor TokenFlux to use service class and components

Extract form rendering logic to DynamicFormRender component and API
logic to TokenFluxService class. Simplifies the main component by
removing duplicate code for model fetching, image generation polling,
and form field rendering.

* Refactor TokenFlux to fix state management and polling

- Change painting field from modelId to model for consistency
- Fix updatePaintingState to use functional state updates
- Add automatic polling for in-progress generations on mount
- Group models by provider in the selection dropdown
- Separate prompt from other input params in form data handling
- Improve error handling in the paintings store

* Auto-select first model when models are loaded

* Add image generation UI localization strings

Add translation keys for model selection, input parameters, image
labels, pricing display, and form validation across all supported
locales (en-us, ja-jp, ru-ru, zh-cn, zh-tw). Update TokenFluxPage
component to use localized strings instead of hardcoded English text.

* fix: Add a right border to the first child of the ImageComparisonSection

* style: Remove padding from UploadedImageContainer in TokenFluxPage

* feat: Implement caching for TokenFlux model fetching and update image upload handling

* feat: Enhance localization support by adding language context handling in TokenFluxPage

* refactor: Simplify layout structure in TokenFluxPage by removing unnecessary SectionGroup components and improving section title styling

---------

Co-authored-by: kangfenmao <kangfenmao@qq.com>

* feat: optimize UI interface display

* refactor(i18n): reorganize Notion settings localization strings in ja-jp.json

This commit restructures the localization strings for Notion settings in the Japanese language file, moving them from a nested structure to a more accessible format. This change improves clarity and maintainability of the localization data.

* chore: update OpenAI package to version 5.1.0 and adjust related patches (#6838)

* chore: update OpenAI package to version 5.1.0 and adjust related patches

- Updated OpenAI dependency from version 4.96.0 to 5.1.0 in package.json and yarn.lock.
- Removed obsolete patch for OpenAI 4.96.0 and added new patch for OpenAI 5.1.0.
- Adjusted types for image handling in OpenAIResponseProvider to use Uploadable instead of FileLike.
- Minor code refactoring for better clarity and maintainability.

* refactor(OpenAIResponseProvider): remove logging for image generation process

* fix(AssistantsTab): remove untagged group title

This commit updates the AssistantsTab component to only display group titles for tagged assistants, excluding the 'untagged' category. This change enhances the UI by reducing clutter and improving clarity in the display of assistant groups.

* chore: remove unused Delete tokenflux_painting_page.md (#6840)

Delete tokenflux_painting_page.md

* fix: Improve the switching logic in multi-tab state

* chore(version): 1.4.1

* 更新版本

* 解决冲突

---------

Signed-off-by: jtsang4 <info@jtsang.me>
Signed-off-by: LeeSH <shuhao_lin@fzzixun.com>
Signed-off-by: Chan Lee <Leetimemp@gmail.com>
Signed-off-by: aprilandjan <merlin.ye@qq.com>
Co-authored-by: Morax <100508620+fzlzjerry@users.noreply.github.com>
Co-authored-by: 亢奋猫 <kangfenmao@qq.com>
Co-authored-by: suyao <sy20010504@gmail.com>
Co-authored-by: jwcrystal <121911854+jwcrystal@users.noreply.github.com>
Co-authored-by: beyondkmp <beyondkmp@gmail.com>
Co-authored-by: beyondkmp <beyondkmkp@gmail.com>
Co-authored-by: one <wangan.cs@gmail.com>
Co-authored-by: fullex <106392080+0xfullex@users.noreply.github.com>
Co-authored-by: Wei <huangwei@burncloud.com>
Co-authored-by: karl <jialongkou@163.com>
Co-authored-by: Zhaker <0x149527@gmail.com>
Co-authored-by: George Zhao <georgezhao@SKJLAB>
Co-authored-by: LiuVaayne <10231735+vaayne@users.noreply.github.com>
Co-authored-by: 自由的世界人 <3196812536@qq.com>
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: chenxue <DDU1222@users.noreply.github.com>
Co-authored-by: zhaochenxue <zhaochenxue@bixin.cn>
Co-authored-by: MyPrototypeWhat <43230886+MyPrototypeWhat@users.noreply.github.com>
Co-authored-by: hutchisr <42283663+hutchisr@users.noreply.github.com>
Co-authored-by: jtsang4 <info@jtsang.me>
Co-authored-by: Caelan <79105826+jin-wang-c@users.noreply.github.com>
Co-authored-by: w <772814125@qq.com>
Co-authored-by: iola1999 <iola1999@foxmail.com>
Co-authored-by: fullex <0xfullex@gmail.com>
Co-authored-by: Konv Suu <2583695112@qq.com>
Co-authored-by: kanweiwei <kanweiwei@nutstore.net>
Co-authored-by: Roland <shlroland1995@gmail.com>
Co-authored-by: Teo <cheesen.xu@gmail.com>
Co-authored-by: shiquda <czy1847259360@gmail.com>
Co-authored-by: purefkh <purefkh@gmail.com>
Co-authored-by: nmnmtttt <34001432+nmnmtttt@users.noreply.github.com>
Co-authored-by: Lee SH <shuhao_lin@fzzixun.com>
Co-authored-by: George Zhao <38124587+CreatorZZY@users.noreply.github.com>
Co-authored-by: FunJim <xunjin.zheng@outlook.com>
Co-authored-by: stevending1st <stevending1st@163.com>
Co-authored-by: Alain <yinxulai@hotmail.com>
Co-authored-by: MyPrototypeWhat <daoquqiexing@gmail.com>
Co-authored-by: Rudbeckia.hirta.L <83773602@qq.com>
Co-authored-by: Doekin <105162544+Doekin@users.noreply.github.com>
Co-authored-by: icarus <eurfelux@gmail.com>
Co-authored-by: Wang Jiyuan <59059173+EurFelux@users.noreply.github.com>
Co-authored-by: May <aprilandjan@users.noreply.github.com>
Co-authored-by: Lucas <lucas04@foxmail.com>
Co-authored-by: Murphy <69335326+MurphyLo@users.noreply.github.com>
Co-authored-by: Chen Tao <70054568+eeee0717@users.noreply.github.com>
Co-authored-by: 熊可狸 <me@korin.im>
Co-authored-by: George·Dong <98630204+GeorgeDong32@users.noreply.github.com>
2025-06-24 13:32:15 +08:00
kangfenmao
8fd57d0271 refactor: windows7 support 2025-05-07 10:14:27 +08:00
153 changed files with 2713 additions and 5363 deletions

View File

@@ -115,38 +115,3 @@ jobs:
tag: ${{ steps.get-tag.outputs.tag }}
artifacts: 'dist/*.exe,dist/*.zip,dist/*.dmg,dist/*.AppImage,dist/*.snap,dist/*.deb,dist/*.rpm,dist/*.tar.gz,dist/latest*.yml,dist/rc*.yml,dist/*.blockmap'
token: ${{ secrets.GITHUB_TOKEN }}
dispatch-docs-update:
needs: release
if: success() && github.repository == 'CherryHQ/cherry-studio' # 确保所有构建成功且在主仓库中运行
runs-on: ubuntu-latest
steps:
- name: Get release tag
id: get-tag
shell: bash
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "tag=${{ github.event.inputs.tag }}" >> $GITHUB_OUTPUT
else
echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
fi
- name: Check if tag is pre-release
id: check-tag
shell: bash
run: |
TAG="${{ steps.get-tag.outputs.tag }}"
if [[ "$TAG" == *"rc"* || "$TAG" == *"pre-release"* ]]; then
echo "is_pre_release=true" >> $GITHUB_OUTPUT
else
echo "is_pre_release=false" >> $GITHUB_OUTPUT
fi
- name: Dispatch update-download-version workflow to cherry-studio-docs
if: steps.check-tag.outputs.is_pre_release == 'false'
uses: peter-evans/repository-dispatch@v3
with:
token: ${{ secrets.REPO_DISPATCH_TOKEN }}
repository: CherryHQ/cherry-studio-docs
event-type: update-download-version
client-payload: '{"version": "${{ steps.get-tag.outputs.tag }}"}'

View File

@@ -151,7 +151,7 @@ index 2404264d4ba0204322548945ebb7eab3bea82173..8f1bc45cc45e0797d50989d96b51147b
+ "embeddings/decoding base64 embeddings from base64"
+ );
+ return response._thenUnwrap((response) => {
+ if (response && response.data && typeof response.data[0]?.embedding === 'string') {
+ if (response && response.data) {
+ response.data.forEach((embeddingBase64Obj) => {
+ const embeddingBase64Str = embeddingBase64Obj.embedding;
+ embeddingBase64Obj.embedding = (0, utils_1.toFloat32Array)(
@@ -266,7 +266,7 @@ index 19dcaef578c194a89759c4360073cfd4f7dd2cbf..0284e9cc615c900eff508eb595f7360a
+ "embeddings/decoding base64 embeddings from base64"
+ );
+ return response._thenUnwrap((response) => {
+ if (response && response.data && typeof response.data[0]?.embedding === 'string') {
+ if (response && response.data) {
+ response.data.forEach((embeddingBase64Obj) => {
+ const embeddingBase64Str = embeddingBase64Obj.embedding;
+ embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str);

View File

@@ -3,42 +3,10 @@
<img src="https://github.com/CherryHQ/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" /><br>
</a>
</h1>
<p align="center">English | <a href="./docs/README.zh.md">中文</a> | <a href="./docs/README.ja.md">日本語</a> | <a href="https://cherry-ai.com">Official Site</a> | <a href="https://docs.cherry-ai.com/cherry-studio-wen-dang/en-us">Documents</a> | <a href="./docs/dev.md">Development</a> | <a href="https://github.com/CherryHQ/cherry-studio/issues">Feedback</a><br></p>
<!-- 题头徽章组合 -->
<p align="center">English | <a href="./docs/README.zh.md">中文</a> | <a href="./docs/README.ja.md">日本語</a><br></p>
<div align="center">
[![][deepwiki-shield]][deepwiki-link]
[![][twitter-shield]][twitter-link]
[![][discord-shield]][discord-link]
[![][telegram-shield]][telegram-link]
</div>
<!-- 项目统计徽章 -->
<div align="center">
[![][github-stars-shield]][github-stars-link]
[![][github-forks-shield]][github-forks-link]
[![][github-release-shield]][github-release-link]
[![][github-contributors-shield]][github-contributors-link]
</div>
<div align="center">
[![][license-shield]][license-link]
[![][commercial-shield]][commercial-link]
[![][sponsor-shield]][sponsor-link]
</div>
<div align="center">
<a href="https://hellogithub.com/repository/1605492e1e2a4df3be07abfa4578dd37" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=1605492e1e2a4df3be07abfa4578dd37" alt="FeaturedHelloGitHub" style="width: 200px; height: 43px;" width="200" height="43" /></a>
<a href="https://trendshift.io/repositories/11772" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11772" alt="kangfenmao%2Fcherry-studio | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 200px; height: 43px;" width="200" height="43" /></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
</div>
# 🍒 Cherry Studio
@@ -49,6 +17,10 @@ Cherry Studio is a desktop client that supports for multiple LLM providers, avai
❤️ Like Cherry Studio? Give it a star 🌟 or [Sponsor](docs/sponsor.md) to support the development!
# 📖 Guide
<https://docs.cherry-ai.com>
# 🌠 Screenshot
![](https://github.com/user-attachments/assets/36dddb2c-e0fb-4a5f-9411-91447bab6e18)
@@ -142,6 +114,14 @@ Want to influence our roadmap? Join our [GitHub Discussions](https://github.com/
Welcome PR for more themes
# 🖥️ Develop
Refer to the [development documentation](docs/dev.md)
Refer to the [Architecture overview documentation](https://deepwiki.com/CherryHQ/cherry-studio)
Refer to the [Branching Strategy](docs/branching-strategy-en.md) for contribution guidelines
# 🤝 Contributing
We welcome contributions to Cherry Studio! Here are some ways you can contribute:
@@ -154,8 +134,6 @@ We welcome contributions to Cherry Studio! Here are some ways you can contribute
6. **Community Engagement**: Join discussions and help users.
7. **Promote Usage**: Spread the word about Cherry Studio.
Refer to the [Branching Strategy](docs/branching-strategy-en.md) for contribution guidelines
## Getting Started
1. **Fork the Repository**: Fork and clone it to your local machine.
@@ -180,34 +158,22 @@ Thank you for your support and contributions!
</a>
<br /><br />
# 🌐 Community
[Telegram](https://t.me/CherryStudioAI) | [Email](mailto:support@cherry-ai.com) | [Twitter](https://x.com/kangfenmao)
# ☕ Sponsor
[Buy Me a Coffee](docs/sponsor.md)
# 📃 License
[LICENSE](./LICENSE)
# ✉️ Contact
<yinsenho@cherry-ai.com>
# ⭐️ Star History
[![Star History Chart](https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Timeline)](https://star-history.com/#CherryHQ/cherry-studio&Timeline)
<!-- Links & Images -->
[deepwiki-shield]: https://img.shields.io/badge/Deepwiki-CherryHQ-0088CC?style=plastic
[deepwiki-link]: https://deepwiki.com/CherryHQ/cherry-studio
[twitter-shield]: https://img.shields.io/badge/Twitter-CherryStudioApp-0088CC?style=plastic&logo=x
[twitter-link]: https://twitter.com/CherryStudioHQ
[discord-shield]: https://img.shields.io/badge/Discord-@CherryStudio-0088CC?style=plastic&logo=discord
[discord-link]: https://discord.gg/wez8HtpxqQ
[telegram-shield]: https://img.shields.io/badge/Telegram-@CherryStudioAI-0088CC?style=plastic&logo=telegram
[telegram-link]: https://t.me/CherryStudioAI
<!-- Links & Images -->
[github-stars-shield]: https://img.shields.io/github/stars/CherryHQ/cherry-studio?style=social
[github-stars-link]: https://github.com/CherryHQ/cherry-studio/stargazers
[github-forks-shield]: https://img.shields.io/github/forks/CherryHQ/cherry-studio?style=social
[github-forks-link]: https://github.com/CherryHQ/cherry-studio/network
[github-release-shield]: https://img.shields.io/github/v/release/CherryHQ/cherry-studio
[github-release-link]: https://github.com/CherryHQ/cherry-studio/releases
[github-contributors-shield]: https://img.shields.io/github/contributors/CherryHQ/cherry-studio
[github-contributors-link]: https://github.com/CherryHQ/cherry-studio/graphs/contributors
<!-- Links & Images -->
[license-shield]: https://img.shields.io/badge/License-AGPLv3-important.svg?style=plastic&logo=gnu
[license-link]: https://www.gnu.org/licenses/agpl-3.0
[commercial-shield]: https://img.shields.io/badge/License-Contact-white.svg?style=plastic&logoColor=white&logo=telegram&color=blue
[commercial-link]: mailto:license@cherry-ai.com?subject=Commercial%20License%20Inquiry
[sponsor-shield]: https://img.shields.io/badge/Sponsor-FF6699.svg?style=plastic&logo=githubsponsors&logoColor=white
[sponsor-link]: https://github.com/CherryHQ/cherry-studio/blob/main/docs/sponsor.md
[![Star History Chart](https://api.star-history.com/svg?repos=kangfenmao/cherry-studio&type=Timeline)](https://star-history.com/#kangfenmao/cherry-studio&Timeline)

View File

@@ -1,46 +1,15 @@
<h1 align="center">
<a href="https://github.com/CherryHQ/cherry-studio/releases">
<img src="https://github.com/CherryHQ/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" /><br>
<img src="https://github.com/CherryHQ/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" />
</a>
</h1>
<p align="center">
<a href="https://github.com/CherryHQ/cherry-studio">English</a> | <a href="./README.zh.md">中文</a> | 日本語 | <a href="https://cherry-ai.com">公式サイト</a> | <a href="https://docs.cherry-ai.com/cherry-studio-wen-dang/ja">ドキュメント</a> | <a href="./dev.md">開発</a> | <a href="https://github.com/CherryHQ/cherry-studio/issues">フィードバック</a><br>
<a href="https://github.com/CherryHQ/cherry-studio">English</a> | <a href="./README.zh.md">中文</a> | 日本語 <br>
</p>
<!-- バッジコレクション -->
<div align="center">
[![][deepwiki-shield]][deepwiki-link]
[![][twitter-shield]][twitter-link]
[![][discord-shield]][discord-link]
[![][telegram-shield]][telegram-link]
</div>
<!-- プロジェクト統計 -->
<div align="center">
[![][github-stars-shield]][github-stars-link]
[![][github-forks-shield]][github-forks-link]
[![][github-release-shield]][github-release-link]
[![][github-contributors-shield]][github-contributors-link]
</div>
<div align="center">
[![][license-shield]][license-link]
[![][commercial-shield]][commercial-link]
[![][sponsor-shield]][sponsor-link]
</div>
<div align="center">
<a href="https://hellogithub.com/repository/1605492e1e2a4df3be07abfa4578dd37" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=1605492e1e2a4df3be07abfa4578dd37" alt="FeaturedHelloGitHub" style="width: 200px; height: 43px;" width="200" height="43" /></a>
<a href="https://trendshift.io/repositories/11772" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11772" alt="kangfenmao%2Fcherry-studio | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 200px; height: 43px;" width="200" height="43" /></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
</div>
# 🍒 Cherry Studio
@@ -51,6 +20,10 @@ Cherry Studio は、複数の LLM プロバイダーをサポートするデス
❤️ Cherry Studio をお気に入りにしましたか?小さな星をつけてください 🌟 または [スポンサー](sponsor.md) をして開発をサポートしてください!
# 📖 ガイド
https://docs.cherry-ai.com
# 🌠 スクリーンショット
![](https://github.com/user-attachments/assets/36dddb2c-e0fb-4a5f-9411-91447bab6e18)
@@ -144,6 +117,14 @@ Cherry Studio は、複数の LLM プロバイダーをサポートするデス
より多くのテーマの PR を歓迎します
# 🖥️ 開発
[開発ドキュメント](dev.md)を参照してください
[アーキテクチャ概要ドキュメント](https://deepwiki.com/CherryHQ/cherry-studio)を参照してください
[ブランチ戦略](branching-strategy-en.md)を参照して貢献ガイドラインを確認してください
# 🤝 貢献
Cherry Studio への貢献を歓迎します!以下の方法で貢献できます:
@@ -156,8 +137,6 @@ Cherry Studio への貢献を歓迎します!以下の方法で貢献できま
6. **コミュニティの参加**:ディスカッションに参加し、ユーザーを支援します
7. **使用の促進**Cherry Studio を広めます
[ブランチ戦略](branching-strategy-en.md)を参照して貢献ガイドラインを確認してください
## 始め方
1. **リポジトリをフォーク**:フォークしてローカルマシンにクローンします
@@ -182,34 +161,22 @@ Cherry Studio への貢献を歓迎します!以下の方法で貢献できま
</a>
<br /><br />
# 🌐 コミュニティ
[Telegram](https://t.me/CherryStudioAI) | [Email](mailto:support@cherry-ai.com) | [Twitter](https://x.com/kangfenmao)
# ☕ スポンサー
[開発者を支援する](sponsor.md)
# 📃 ライセンス
[LICENSE](../LICENSE)
# ✉️ お問い合わせ
yinsenho@cherry-ai.com
# ⭐️ スター履歴
[![Star History Chart](https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Timeline)](https://star-history.com/#CherryHQ/cherry-studio&Timeline)
<!-- リンクと画像 -->
[deepwiki-shield]: https://img.shields.io/badge/Deepwiki-CherryHQ-0088CC?style=plastic
[deepwiki-link]: https://deepwiki.com/CherryHQ/cherry-studio
[twitter-shield]: https://img.shields.io/badge/Twitter-CherryStudioApp-0088CC?style=plastic&logo=x
[twitter-link]: https://twitter.com/CherryStudioHQ
[discord-shield]: https://img.shields.io/badge/Discord-@CherryStudio-0088CC?style=plastic&logo=discord
[discord-link]: https://discord.gg/wez8HtpxqQ
[telegram-shield]: https://img.shields.io/badge/Telegram-@CherryStudioAI-0088CC?style=plastic&logo=telegram
[telegram-link]: https://t.me/CherryStudioAI
<!-- プロジェクト統計 -->
[github-stars-shield]: https://img.shields.io/github/stars/CherryHQ/cherry-studio?style=social
[github-stars-link]: https://github.com/CherryHQ/cherry-studio/stargazers
[github-forks-shield]: https://img.shields.io/github/forks/CherryHQ/cherry-studio?style=social
[github-forks-link]: https://github.com/CherryHQ/cherry-studio/network
[github-release-shield]: https://img.shields.io/github/v/release/CherryHQ/cherry-studio
[github-release-link]: https://github.com/CherryHQ/cherry-studio/releases
[github-contributors-shield]: https://img.shields.io/github/contributors/CherryHQ/cherry-studio
[github-contributors-link]: https://github.com/CherryHQ/cherry-studio/graphs/contributors
<!-- ライセンスとスポンサー -->
[license-shield]: https://img.shields.io/badge/License-AGPLv3-important.svg?style=plastic&logo=gnu
[license-link]: https://www.gnu.org/licenses/agpl-3.0
[commercial-shield]: https://img.shields.io/badge/商用ライセンス-お問い合わせ-white.svg?style=plastic&logoColor=white&logo=telegram&color=blue
[commercial-link]: mailto:license@cherry-ai.com?subject=商業ライセンスについて
[sponsor-shield]: https://img.shields.io/badge/スポンサー-FF6699.svg?style=plastic&logo=githubsponsors&logoColor=white
[sponsor-link]: https://github.com/CherryHQ/cherry-studio/blob/main/docs/sponsor.md
[![Star History Chart](https://api.star-history.com/svg?repos=kangfenmao/cherry-studio&type=Timeline)](https://star-history.com/#kangfenmao/cherry-studio&Timeline)

View File

@@ -1,46 +1,14 @@
<h1 align="center">
<a href="https://github.com/CherryHQ/cherry-studio/releases">
<img src="https://github.com/CherryHQ/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" /><br>
<img src="https://github.com/CherryHQ/cherry-studio/blob/main/build/icon.png?raw=true" width="150" height="150" alt="banner" />
</a>
</h1>
<p align="center">
<a href="https://github.com/CherryHQ/cherry-studio">English</a> | 中文 | <a href="./README.ja.md">日本語</a> | <a href="https://cherry-ai.com">官方网站</a> | <a href="https://docs.cherry-ai.com/cherry-studio-wen-dang/zh-cn">文档</a> | <a href="./dev.md">开发</a> | <a href="https://github.com/CherryHQ/cherry-studio/issues">反馈</a><br>
<a href="https://github.com/CherryHQ/cherry-studio">English</a> | 中文 | <a href="./README.ja.md">日本語</a><br>
</p>
<!-- 题头徽章组合 -->
<div align="center">
[![][deepwiki-shield]][deepwiki-link]
[![][twitter-shield]][twitter-link]
[![][discord-shield]][discord-link]
[![][telegram-shield]][telegram-link]
</div>
<!-- 项目统计徽章 -->
<div align="center">
[![][github-stars-shield]][github-stars-link]
[![][github-forks-shield]][github-forks-link]
[![][github-release-shield]][github-release-link]
[![][github-contributors-shield]][github-contributors-link]
</div>
<div align="center">
[![][license-shield]][license-link]
[![][commercial-shield]][commercial-link]
[![][sponsor-shield]][sponsor-link]
</div>
<div align="center">
<a href="https://hellogithub.com/repository/1605492e1e2a4df3be07abfa4578dd37" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=1605492e1e2a4df3be07abfa4578dd37" alt="FeaturedHelloGitHub" style="width: 200px; height: 43px;" width="200" height="43" /></a>
<a href="https://trendshift.io/repositories/11772" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11772" alt="kangfenmao%2Fcherry-studio | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 200px; height: 43px;" width="200" height="43" /></a>
<a href="https://www.producthunt.com/posts/cherry-studio?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cherry&#0045;studio" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=496640&theme=light" alt="Cherry&#0032;Studio - AI&#0032;Chatbots&#0044;&#0032;AI&#0032;Desktop&#0032;Client | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
</div>
# 🍒 Cherry Studio
@@ -156,6 +124,14 @@ https://docs.cherry-ai.com
欢迎 PR 更多主题
# 🖥️ 开发
参考[开发文档](dev.md)
参考[架构概览文档](https://deepwiki.com/CherryHQ/cherry-studio)
参考[分支策略](branching-strategy-zh.md)了解贡献指南
# 🤝 贡献
我们欢迎对 Cherry Studio 的贡献!您可以通过以下方式贡献:
@@ -168,8 +144,6 @@ https://docs.cherry-ai.com
6. **社区参与**:加入讨论并帮助用户
7. **推广使用**:宣传 Cherry Studio
参考[分支策略](branching-strategy-zh.md)了解贡献指南
## 入门
1. **Fork 仓库**Fork 并克隆到您的本地机器
@@ -194,34 +168,22 @@ https://docs.cherry-ai.com
</a>
<br /><br />
# 🌐 社区
[Telegram](https://t.me/CherryStudioAI) | [Email](mailto:support@cherry-ai.com) | [Twitter](https://x.com/kangfenmao)
# ☕ 赞助
[赞助开发者](sponsor.md)
# 📃 许可证
[LICENSE](../LICENSE)
# ✉️ 联系我们
yinsenho@cherry-ai.com
# ⭐️ Star 记录
[![Star History Chart](https://api.star-history.com/svg?repos=CherryHQ/cherry-studio&type=Timeline)](https://star-history.com/#CherryHQ/cherry-studio&Timeline)
<!-- Links & Images -->
[deepwiki-shield]: https://img.shields.io/badge/Deepwiki-CherryHQ-0088CC?style=plastic
[deepwiki-link]: https://deepwiki.com/CherryHQ/cherry-studio
[twitter-shield]: https://img.shields.io/badge/Twitter-CherryStudioApp-0088CC?style=plastic&logo=x
[twitter-link]: https://twitter.com/CherryStudioHQ
[discord-shield]: https://img.shields.io/badge/Discord-@CherryStudio-0088CC?style=plastic&logo=discord
[discord-link]: https://discord.gg/wez8HtpxqQ
[telegram-shield]: https://img.shields.io/badge/Telegram-@CherryStudioAI-0088CC?style=plastic&logo=telegram
[telegram-link]: https://t.me/CherryStudioAI
<!-- 项目统计徽章 -->
[github-stars-shield]: https://img.shields.io/github/stars/CherryHQ/cherry-studio?style=social
[github-stars-link]: https://github.com/CherryHQ/cherry-studio/stargazers
[github-forks-shield]: https://img.shields.io/github/forks/CherryHQ/cherry-studio?style=social
[github-forks-link]: https://github.com/CherryHQ/cherry-studio/network
[github-release-shield]: https://img.shields.io/github/v/release/CherryHQ/cherry-studio
[github-release-link]: https://github.com/CherryHQ/cherry-studio/releases
[github-contributors-shield]: https://img.shields.io/github/contributors/CherryHQ/cherry-studio
[github-contributors-link]: https://github.com/CherryHQ/cherry-studio/graphs/contributors
<!-- 许可和赞助徽章 -->
[license-shield]: https://img.shields.io/badge/License-AGPLv3-important.svg?style=plastic&logo=gnu
[license-link]: https://www.gnu.org/licenses/agpl-3.0
[commercial-shield]: https://img.shields.io/badge/商用授权-联系-white.svg?style=plastic&logoColor=white&logo=telegram&color=blue
[commercial-link]: mailto:license@cherry-ai.com?subject=商业授权咨询
[sponsor-shield]: https://img.shields.io/badge/赞助支持-FF6699.svg?style=plastic&logo=githubsponsors&logoColor=white
[sponsor-link]: https://github.com/CherryHQ/cherry-studio/blob/main/docs/sponsor.md
[![Star History Chart](https://api.star-history.com/svg?repos=kangfenmao/cherry-studio&type=Timeline)](https://star-history.com/#kangfenmao/cherry-studio&Timeline)

View File

@@ -1,635 +0,0 @@
# 消息历史版本管理系统设计技术报告(最终版 - 含多模型支持)
## 1. 系统概述
基于现有扁平化架构的最小化扩展,通过 **Topic快照 + Message字段扩展含siblingIds** 实现版本管理、分支对话和多模型并行回复功能。
### 1.1 核心设计理念
- **最小破坏性**:只扩展现有实体,不新增表
- **快照渲染**通过Topic简单快照管理主线渲染顺序
- **关系扩展**通过Message字段实现树状分支、双向链表版本、多模型兄弟关系
## 2. 数据结构设计
### 2.1 实体定义
```typescript
interface Topic {
// === 现有字段保持不变 ===
id: string
name: string
createdAt: string
updatedAt: string
// === 保持简单快照 ===
activeMessageIds: string[] // 当前活跃对话主线的消息ID顺序
}
interface Message {
// === 现有字段保持不变 ===
id: string
role: 'user' | 'assistant' | 'system'
topicId: string
blocks: MessageBlock['id'][]
// === 新增:关系字段 ===
askId?: string // 问答关系assistant指向对应的user消息
parentMessageId?: string // 分支关系:指向回复的目标消息
version?: number // 版本号assistant消息专用
prevVersionId?: string // 版本链表:前一版本
nextVersionId?: string // 版本链表:后一版本
groupRequestId?: string // 请求分组同次API请求的标识
siblingIds?: string[] // 兄弟关系同级多模型回复的ID列表
}
interface MessageBlock {
// === 完全不变 ===
id: string
messageId: string
type: MessageBlockType
content: string
// ...其他现有字段
}
```
### 2.2 数据关系图
```mermaid
graph TB
subgraph "Topic快照层 (主线)"
T[Topic.activeMessageIds: user1→asst1-gpt→user2]
end
subgraph "消息实体层"
U1[User Message 1<br/>id: user1]
A1G["GPT-4 回复<br/>id: asst1-gpt, askId: user1<br/>siblingIds: [asst1-claude]"]
A1C["Claude 回复<br/>id: asst1-claude, askId: user1<br/>siblingIds: [asst1-gpt]"]
U2["User Message 2<br/>id: user2, parentMessageId: asst1-gpt"]
end
subgraph "版本链表层 (隐藏)"
A1GV0[GPT-4 v0<br/>askId: user1, version: 0]
A1GV1[GPT-4 v1<br/>askId: user1, version: 1]
A1GV0 -.->|nextVersionId| A1GV1
A1GV1 -.->|prevVersionId| A1GV0
end
subgraph "分支树层 (隐藏)"
U1B[User Branch 1<br/>parentMessageId: asst1-gpt]
A1B[Assistant Branch 1<br/>askId: user1b]
end
T --> U1
T --> A1G
T --> U2
A1G -.->|askId| U1
A1C -.->|askId| U1
A1G -.->|siblingIds| A1C
A1C -.->|siblingIds| A1G
U2 -.->|parentMessageId| A1G
U1B -.->|parentMessageId| A1G
A1B -.->|askId| U1B
```
## 3. 核心操作流程
### 3.1 发送新消息(多模型)
```mermaid
sequenceDiagram
participant UI
participant Redux
participant DB
participant API
UI->>Redux: sendMessage(userContent, models[])
Note over Redux: 1. 创建用户消息
Redux->>Redux: userMessage = { id: uuid(), role: 'user', ... }
Note over Redux: 2. 创建助手消息(多模型)
Redux->>Redux: groupRequestId = uuid()
Redux->>Redux: assistantMessages = models.map(m => createAssistant(userMessage.id, m))
Note over Redux: 3. 设置兄弟关系
Redux->>Redux: assistantIds = assistantMessages.map(m => m.id)
loop 每个助手消息
Redux->>Redux: msg.siblingIds = assistantIds.filter(id => id !== msg.id)
end
Note over Redux: 4. 更新Topic快照
Redux->>Redux: newActiveMessageIds = [<br/>...oldIds,<br/>userMessage.id,<br/>assistantMessages[0].id<br/>]
Note over Redux: 5. 原子保存
Redux->>DB: transaction([messages, topics])
DB->>DB: messages.bulkPut([userMessage, ...assistantMessages])
DB->>DB: topics.update(topicId, { activeMessageIds })
Note over Redux: 6. 发送API请求
loop 每个模型
Redux->>API: generateResponse(model, userContent)
end
Redux->>UI: 更新状态
```
**复杂度**O(M) where M = 模型数量
### 3.2 重发消息(版本管理)
```mermaid
sequenceDiagram
participant UI
participant Redux
participant DB
UI->>Redux: resendMessage(userMessageId)
Note over Redux: 1. 查找现有版本
Redux->>DB: messages.where('askId').equals(userMessageId)
DB-->>Redux: existingVersions[]
Note over Redux: 2. 计算新版本号
Redux->>Redux: latestVersion = max(versions.map(v => v.version))
Redux->>Redux: newVersion = latestVersion + 1
Note over Redux: 3. 创建新版本消息(可能多模型)
Redux->>Redux: newGroupRequestId = uuid()
Redux->>Redux: newVersionMessages = models.map(m => createNewVersion(prevMsg, newVersion, newGroupRequestId))
Note over Redux: 4. 设置新版本的兄弟关系
Redux->>Redux: newVersionIds = newVersionMessages.map(m => m.id)
loop 每个新版本消息
Redux->>Redux: msg.siblingIds = newVersionIds.filter(id => id !== msg.id)
end
Note over Redux: 5. 更新版本链表
Redux->>DB: transaction(messages)
DB->>DB: messages.update(prevMessage.id, { nextVersionId })
DB->>DB: messages.bulkPut(newVersionMessages)
Redux->>UI: 更新状态
```
**复杂度**O(V) 查找 + O(M) 创建
### 3.3 切换活跃模型UI交互
```mermaid
flowchart TD
A[用户在UI上选择其他模型] --> B[获取当前快照]
B --> C[找到当前助手消息在快照中的位置]
C --> D[用新选择的模型消息ID替换快照中的ID]
D --> E[保存到数据库]
E --> F[Redux自动重新渲染]
style A fill:#e1f5fe
style F fill:#c8e6c9
```
```typescript
const switchActiveModel = async (topicId: string, messageIndex: number, newModelMessageId: string) => {
const topic = await db.topics.get(topicId)
const newActiveMessageIds = [...topic.activeMessageIds]
newActiveMessageIds[messageIndex] = newModelMessageId
await db.topics.update(topicId, { activeMessageIds: newActiveMessageIds })
}
```
**复杂度**O(1)
## 4. 字段作用详解
### 4.1 关键字段关系图
```mermaid
graph LR
subgraph "问答关系"
askId[askId<br/>assistant → user<br/>逻辑关系,永久不变]
end
subgraph "分支关系"
parentId[parentMessageId<br/>message → message<br/>分支对话,树状结构]
end
subgraph "版本关系"
version[version + prevVersionId + nextVersionId<br/>同askId下的版本链表]
end
subgraph "请求分组"
groupId[groupRequestId<br/>同次API请求标识<br/>一次性,每次重发都变]
end
subgraph "兄弟关系"
siblingId[siblingIds<br/>同级多模型回复<br/>双向引用]
end
askId -.-> version
askId -.-> siblingId
parentId -.-> askId
groupId -.-> askId
```
### 4.2 字段使用场景
| 字段 | 用途 | 查询场景 | 生命周期 |
| -------------------------------- | ---------- | -------------------------- | -------- |
| **askId** | 问答映射 | 查找用户问题的所有回复版本 | 永久不变 |
| **parentMessageId** | 分支对话 | 查找某消息的回复分支 | 永久不变 |
| **version + prev/nextVersionId** | 版本管理 | 版本历史导航 | 永久不变 |
| **groupRequestId** | 请求追踪 | 批量状态更新、请求监控 | 一次性 |
| **siblingIds** | 多模型并行 | 渲染同级多模型回复 | 永久不变 |
### 4.3 多模型并行渲染示例
```mermaid
graph TD
U1[User: 帮我写个函数<br/>id: user1]
subgraph "第一次请求 (groupRequestId: req1)"
A1["GPT-4 回复<br/>id: asst1-gpt, askId: user1<br/>siblingIds: [asst1-claude]"]
A2["Claude 回复<br/>id: asst1-claude, askId: user1<br/>siblingIds: [asst1-gpt]"]
end
subgraph "Topic快照 (主线)"
T["activeMessageIds: [user1, asst1-gpt]"]
end
subgraph "UI渲染 (通过siblingIds扩展)"
UI_U1[User: 帮我写个函数]
UI_A1["GPT-4 回复 (活跃)"]
UI_A2["Claude 回复 (可选)"]
end
U1 --> A1
U1 --> A2
T --> U1
T --> A1
A1 -.->|siblingIds| A2
A2 -.->|siblingIds| A1
UI_U1 -.-> UI_A1
UI_U1 -.-> UI_A2
```
## 5. 数据查询与状态管理
### 5.1 话题加载流程
```mermaid
sequenceDiagram
participant UI
participant Redux
participant DB
participant Selector
UI->>Redux: loadTopic(topicId)
Redux->>DB: 并行查询
par 查询消息
DB->>DB: messages.where('topicId').equals(topicId)
and 查询块
DB->>DB: messageBlocks.where('topicId').equals(topicId)
end
DB-->>Redux: { messages[], blocks[] }
Redux->>Redux: 更新实体状态
UI->>Selector: selectActiveConversationWithSiblings(topicId)
Selector->>Redux: 获取Topic.activeMessageIds
Selector->>Redux: 获取messages实体
Selector-->>UI: 按快照顺序的消息列表 (含兄弟节点)
Note over UI: 渲染对话界面 (支持多模型)
```
### 5.2 渲染选择器(含兄弟节点)
```typescript
export const selectActiveConversationWithSiblings = createSelector(
[
(state: RootState, topicId: string) => state.topics.entities[topicId]?.activeMessageIds || [],
(state: RootState) => state.messages.entities,
(state: RootState) => state.messageBlocks.entities
],
(activeMessageIds, messagesEntities, blocksEntities) => {
return activeMessageIds
.map((messageId) => {
const message = messagesEntities[messageId]
if (!message) return null
if (message.role === 'user') {
return { type: 'user', message, blocks: getMessageBlocks(message, blocksEntities) }
} else if (message.role === 'assistant') {
const siblingMessages = (message.siblingIds || []).map((id) => messagesEntities[id]).filter(Boolean)
const allAssistantMessages = [message, ...siblingMessages]
return {
type: 'assistant_group',
messages: allAssistantMessages.map((msg) => ({
message: msg,
blocks: getMessageBlocks(msg, blocksEntities),
isActive: msg.id === messageId
})),
activeMessageId: messageId
}
}
})
.filter(Boolean)
}
)
```
**复杂度**O(N + S) where N = 快照长度, S = 兄弟节点总数
## 6. 时空复杂度分析
### 6.1 核心操作复杂度对比
```mermaid
graph LR
subgraph "现有架构"
A1[加载话题: O(M+B)]
A2[渲染对话: O(M) 需要过滤排序]
A3[发送消息: O(1)]
end
subgraph "新架构 (含多模型)"
B1[加载话题: O(M+B) ✅相同]
B2[渲染对话: O(N+S) ✅更优]
B3[发送消息: O(M_models) ✅相同]
B4[版本切换: O(1) ➕新功能]
B5[重发消息: O(V)+O(M_models) ➕新功能]
B6[模型切换: O(1) ➕新功能]
end
style B1 fill:#c8e6c9
style B2 fill:#c8e6c9
style B3 fill:#c8e6c9
style B4 fill:#fff3e0
style B5 fill:#fff3e0
style B6 fill:#fff3e0
```
### 6.2 性能优势分析
| 操作 | 现有架构 | 新架构 | 优势说明 |
| ------------ | -------------- | ---------------------------- | -------------------- |
| **话题加载** | O(M + B) | O(M + B) | 性能保持不变 |
| **对话渲染** | O(M) 过滤+排序 | **O(N+S)** 直接索引+兄弟扩展 | N << MS通常较小 |
| **发送消息** | O(1) | O(M_models) | 支持多模型,合理增长 |
| **版本切换** | 不支持 | **O(1)** | 新功能,极佳性能 |
| **模型切换** | 不支持 | **O(1)** | 新功能,极佳性能 |
**关键优势**
- **渲染性能提升**:从 O(M) 优化到 O(N+S),长对话场景收益显著
- **多模型支持**:通过 siblingIds 优雅实现
- **版本管理**O(1) 的版本/模型切换,用户体验极佳
- **向后兼容**:现有核心操作性能保持不变
## 7. 数据库Schema演进
### 7.1 Migration策略
```mermaid
flowchart TD
A[现有Schema] --> B[添加字段]
B --> C[创建索引]
C --> D[数据迁移]
D --> E[验证完整性]
B1[Topic: +activeMessageIds]
B2[Message: +askId, +parentMessageId<br/>+version, +prevVersionId<br/>+nextVersionId, +groupRequestId<br/>+siblingIds]
C1[idx_messages_askid_version]
C2[idx_messages_parent]
C3[idx_messages_group_request]
D1[生成activeMessageIds快照]
D2[设置现有assistant消息version=0]
B --> B1
B --> B2
C --> C1
C --> C2
C --> C3
D --> D1
D --> D2
```
### 7.2 SQL Migration
```sql
-- 1. 添加字段
ALTER TABLE topics ADD COLUMN activeMessageIds TEXT; -- JSON数组
ALTER TABLE messages ADD COLUMN askId TEXT;
ALTER TABLE messages ADD COLUMN parentMessageId TEXT;
ALTER TABLE messages ADD COLUMN version INTEGER;
ALTER TABLE messages ADD COLUMN prevVersionId TEXT;
ALTER TABLE messages ADD COLUMN nextVersionId TEXT;
ALTER TABLE messages ADD COLUMN groupRequestId TEXT;
ALTER TABLE messages ADD COLUMN siblingIds TEXT; -- JSON数组
-- 2. 创建索引
CREATE INDEX idx_messages_askid_version ON messages(askId, version);
CREATE INDEX idx_messages_parent ON messages(parentMessageId);
CREATE INDEX idx_messages_group_request ON messages(groupRequestId);
-- 3. 数据迁移
UPDATE messages SET version = 0 WHERE role = 'assistant';
```
## 8. 流式更新兼容性
### 8.1 MessageBlock更新流程
```mermaid
sequenceDiagram
participant Stream
participant Redux
participant DB
participant UI
Note over Stream: 流式内容到达
Stream->>Redux: updateBlock(blockId, content)
Redux->>Redux: updateOneBlock({ id, changes })
Redux->>UI: 立即更新显示
Note over Redux: 节流数据库写入
Redux->>DB: throttledDbUpdate(blockId, content)
Note over Stream,UI: 版本/兄弟关系不影响块更新
```
**关键点**
- MessageBlock 仍然直接关联到 Message
- 版本/兄弟关系在 Message 层面,不影响 Block 的流式更新
- 现有的节流机制和更新逻辑完全保持不变
## 9. 系统架构总览
### 9.1 整体架构图
```mermaid
graph TB
subgraph "UI层"
UI1[对话界面]
UI2[版本选择器]
UI3[分支导航]
UI4[模型切换器]
end
subgraph "Redux状态层"
R1[topics: EntityAdapter]
R2[messages: EntityAdapter]
R3[messageBlocks: EntityAdapter]
S1[selectActiveConversationWithSiblings]
S2[selectVersionHistory]
end
subgraph "数据库层"
DB1[(topics表)]
DB2[(messages表)]
DB3[(messageBlocks表)]
end
subgraph "API层"
API1[多模型并行请求]
API2[流式响应处理]
end
UI1 --> S1
UI2 --> S2
UI4 --> S1
S1 --> R1
S1 --> R2
S2 --> R2
R1 <--> DB1
R2 <--> DB2
R3 <--> DB3
R2 --> API1
API2 --> R3
style UI1 fill:#e3f2fd
style R1 fill:#f3e5f5
style R2 fill:#f3e5f5
style R3 fill:#f3e5f5
style DB1 fill:#e8f5e8
style DB2 fill:#e8f5e8
style DB3 fill:#e8f5e8
```
### 9.2 数据流向
```mermaid
flowchart LR
A[用户输入] --> B[创建User Message]
B --> C["创建Assistant Messages (多模型)"]
C --> C1[设置Sibling关系]
C1 --> D["更新Topic快照 (主线)"]
D --> E[API并行请求]
E --> F[流式更新Blocks]
F --> G["UI实时渲染 (含多模型)"]
H[版本切换] --> I[更新快照指针]
I --> G
J[分支对话] --> K[创建分支消息]
K --> D
L[模型切换] --> I
style A fill:#ffebee
style G fill:#e8f5e8
style H fill:#fff3e0
style J fill:#f3e5f5
style L fill:#e1f5fe
```
## 10. Redux Slice 实现范例
根据上述架构设计,`messages` slice 将演变为一个纯粹的、由 `createEntityAdapter` 管理的"消息池"。它只负责高效地存储和访问单个消息实体,而不再关心对话的顺序。
### `store/messagesSlice.ts`
```typescript
import { createSlice, createEntityAdapter, PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from './store' // 你的store类型定义
import type { Message } from '@renderer/types/newMessage' // 假设 Message 类型定义在外部
// 1. 创建 Entity Adapter
// 它会自动生成管理实体的reducer逻辑实现一个高效的消息池。
const messagesAdapter = createEntityAdapter<Message>()
// 2. 定义 Slice 的初始状态
// adapter.getInitialState() 会自动创建 { ids: [], entities: {} } 结构
const initialState = messagesAdapter.getInitialState()
// 3. 创建 Slice
const messagesSlice = createSlice({
name: 'messages',
initialState,
// Reducers被极大简化多数直接引用adapter提供的方法
reducers: {
// Action: 添加一条消息
messageAdded: messagesAdapter.addOne,
// Action: 一次性添加或更新多个消息 (高性能)
// 用途: 加载话题历史、发送新一轮问答(user+assistants)
messagesUpserted: messagesAdapter.upsertMany,
// Action: 更新单个消息
// 用途: 流式更新结束、状态变更等
messageUpdated: messagesAdapter.updateOne,
// Action: 删除单个消息
messageRemoved: messagesAdapter.removeOne,
// Action: 删除多个消息
messagesRemoved: messagesAdapter.removeMany,
// Action: 用新数据完全替换消息池
// 用途: 首次加载或强制刷新
messagesSet: messagesAdapter.setAll
}
})
// 4. 导出 Actions
export const { messageAdded, messagesUpserted, messageUpdated, messageRemoved, messagesRemoved, messagesSet } =
messagesSlice.actions
// 5. 导出 Selectors
// Adapter 会自动创建高效的查询函数 (e.g., O(1) by ID)
export const messagesSelectors = messagesAdapter.getSelectors((state: RootState) => state.messages)
// 6. 导出 Reducer
export default messagesSlice.reducer
```
### 核心思想总结
1. **职责单一**: 此 Slice 只做一件事——管理 `Message` 实体。它像一个数据库表,高效地处理增删改查,但对业务逻辑(如对话顺序)一无所知。
2. **逻辑上移**: 所有涉及多个 Slice 的复杂业务逻辑(如发送消息、切换版本)都应封装在 **Thunks** 或其他中间件中。Thunk 作为流程协调者,会 `dispatch` 多个原子化的 Action 给 `messagesSlice``topicsSlice`,以完成一次完整的业务操作并保证数据一致性。
3. **性能保证**: `createEntityAdapter` 内部使用哈希表(对象)来存储实体,确保通过 ID 查询消息的操作为 O(1) 复杂度,性能极佳。
### 旧状态属性迁移
为了完成 `messagesSlice` 向纯粹"消息池"的演进,原有的混合状态属性需要被迁移或废弃,以实现彻底的职责分离。
| 原属性 (`newMessage.ts`) | 处理方式 | 新的归宿 / 说明 |
| :----------------------- | :------------ | :-------------------------------------------------------------------------------------------- |
| `messageIdsByTopic` | **废弃** | 核心职责转移。由 `topicsSlice` 中的 `activeMessageIds` 字段接管,作为渲染快照。 |
| `currentTopicId` | **迁移** | 属于UI当前上下文状态应迁移至 `topicsSlice`。 |
| `loadingByTopic` | **迁移** | 话题的加载状态与话题本身更相关,应迁移至 `topicsSlice`。 |
| `displayCount` | **废弃/迁移** | UI相关的显示逻辑不属于消息数据层。建议迁移至专门的 `Slice` 或在相关组件中作为本地状态管理。 |

Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

View File

@@ -12,72 +12,51 @@ electronLanguages:
directories:
buildResources: build
files:
- '**/*'
- '!**/{.vscode,.yarn,.yarn-lock,.github,.cursorrules,.prettierrc}'
- '!electron.vite.config.{js,ts,mjs,cjs}}'
- '!**/{.eslintignore,.eslintrc.js,.eslintrc.json,.eslintcache,root.eslint.config.js,eslint.config.js,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,eslint.config.mjs,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!**/{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!**/{tsconfig.json,tsconfig.tsbuildinfo,tsconfig.node.json,tsconfig.web.json}'
- '!**/{.editorconfig,.jekyll-metadata}'
- '!{.vscode,.yarn,.github}'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!{.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'
- '!scripts'
- '!local'
- '!docs'
- '!packages'
- '!.swc'
- '!.bin'
- '!._*'
- '!*.log'
- '!stats.html'
- '!*.md'
- '!**/*.{iml,o,hprof,orig,pyc,pyo,rbc,swp,csproj,sln,xproj}'
- '!**/*.{map,ts,tsx,jsx,less,scss,sass,css.d.ts,d.cts,d.mts,md,markdown,yaml,yml}'
- '!**/{test,tests,__tests__,powered-test,coverage}/**'
- '!**/{example,examples}/**'
- '!**/{test,tests,__tests__,coverage}/**'
- '!**/*.{spec,test}.{js,jsx,ts,tsx}'
- '!**/*.min.*.map'
- '!**/*.d.ts'
- '!**/dist/es6/**'
- '!**/dist/demo/**'
- '!**/amd/**'
- '!**/{.DS_Store,Thumbs.db,thumbs.db,__pycache__}'
- '!**/{LICENSE,license,LICENSE.*,*.LICENSE.txt,NOTICE.txt,README.md,readme.md,CHANGELOG.md}'
- '!**/{.DS_Store,Thumbs.db}'
- '!**/{LICENSE,LICENSE.txt,LICENSE-MIT.txt,*.LICENSE.txt,NOTICE.txt,README.md,CHANGELOG.md}'
- '!node_modules/rollup-plugin-visualizer'
- '!node_modules/js-tiktoken'
- '!node_modules/@tavily/core/node_modules/js-tiktoken'
- '!node_modules/pdf-parse/lib/pdf.js/{v1.9.426,v1.10.88,v2.0.550}'
- '!node_modules/mammoth/{mammoth.browser.js,mammoth.browser.min.js}'
- '!node_modules/selection-hook/prebuilds/**/*' # we rebuild .node, don't use prebuilds
- '!**/*.{h,iobj,ipdb,tlog,recipe,vcxproj,vcxproj.filters}' # filter .node build files
asarUnpack:
- resources/**
- '**/*.{metal,exp,lib}'
- '**/*.{node,dll,metal,exp,lib}'
win:
executableName: Cherry Studio
artifactName: ${productName}-${version}-${arch}-setup.${ext}
artifactName: ${productName}-${version}-portable.${ext}
target:
- target: nsis
- target: portable
signtoolOptions:
sign: scripts/win-sign.js
verifyUpdateCodeSignature: false
nsis:
artifactName: ${productName}-${version}-${arch}-setup.${ext}
artifactName: ${productName}-${version}-setup.${ext}
shortcutName: ${productName}
uninstallDisplayName: ${productName}
createDesktopShortcut: always
allowToChangeInstallationDirectory: true
oneClick: false
include: build/nsis-installer.nsh
buildUniversalInstaller: false
portable:
artifactName: ${productName}-${version}-${arch}-portable.${ext}
buildUniversalInstaller: false
mac:
entitlementsInherit: build/entitlements.mac.plist
notarize: false
artifactName: ${productName}-${version}-${arch}.${ext}
minimumSystemVersion: '20.1.0' # 最低支持 macOS 11.0
extendInfo:
- NSCameraUsageDescription: Application requests access to the device's camera.
- NSMicrophoneUsageDescription: Application requests access to the device's microphone.
@@ -85,11 +64,20 @@ mac:
- NSDownloadsFolderUsageDescription: Application requests access to the user's Downloads folder.
target:
- target: dmg
arch:
- arm64
- x64
- target: zip
arch:
- arm64
- x64
linux:
artifactName: ${productName}-${version}-${arch}.${ext}
target:
- target: AppImage
arch:
- arm64
- x64
maintainer: electronjs.org
category: Utility
desktop:
@@ -98,20 +86,19 @@ linux:
mimeTypes:
- x-scheme-handler/cherrystudio
publish:
provider: generic
url: https://releases.cherry-ai.com
# provider: generic
# url: https://cherrystudio.ocool.online
provider: github
repo: cherry-studio
owner: CherryHQ
electronDownload:
mirror: https://npmmirror.com/mirrors/electron/
afterPack: scripts/after-pack.js
afterSign: scripts/notarize.js
artifactBuildCompleted: scripts/artifact-build-completed.js
releaseInfo:
releaseNotes: |
划词助手:支持文本选择快捷键、开关快捷键、思考块支持和引用功能
复制功能新增纯文本复制去除Markdown格式符号
知识库支持设置向量维度修复Ollama分数错误和维度编辑问题
多语言:增加模型名称多语言提示和翻译源语言手动选择
文件管理:修复主题/消息删除时文件未清理问题,优化文件选择流程
模型修复Gemini模型推理预算、Voyage AI嵌入问题和DeepSeek翻译模型更新
图像功能统一图片查看器支持Base64图片渲染修复图片预览相关问题
UI实现标签折叠/拖拽排序,修复气泡溢出,增加引文索引显示
新增划词助手
助手支持分组
支持主题颜色切换
划词助手支持应用过滤
翻译模块功能改进

View File

@@ -1,5 +1,6 @@
import react from '@vitejs/plugin-react-swc'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import fs from 'fs'
import { resolve } from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
@@ -9,7 +10,22 @@ const visualizerPlugin = (type: 'renderer' | 'main') => {
export default defineConfig({
main: {
plugins: [externalizeDepsPlugin(), ...visualizerPlugin('main')],
plugins: [externalizeDepsPlugin({
exclude: [
'@cherrystudio/embedjs',
'@cherrystudio/embedjs-openai',
'@cherrystudio/embedjs-loader-web',
'@cherrystudio/embedjs-loader-markdown',
'@cherrystudio/embedjs-loader-msoffice',
'@cherrystudio/embedjs-loader-xml',
'@cherrystudio/embedjs-loader-pdf',
'@cherrystudio/embedjs-loader-sitemap',
'@cherrystudio/embedjs-libsql',
'@cherrystudio/embedjs-loader-image',
'p-queue',
'webdav'
]
}), ...visualizerPlugin('main')],
resolve: {
alias: {
'@main': resolve('src/main'),
@@ -19,12 +35,28 @@ export default defineConfig({
},
build: {
rollupOptions: {
external: ['@libsql/client', 'bufferutil', 'utf-8-validate']
},
sourcemap: process.env.NODE_ENV === 'development'
},
optimizeDeps: {
noDiscovery: process.env.NODE_ENV === 'development'
external: ['@libsql/client', 'bufferutil', 'utf-8-validate'],
plugins: [
{
name: 'inject-windows7-polyfill',
generateBundle(_, bundle) {
// 遍历所有生成的文件
for (const fileName in bundle) {
const chunk = bundle[fileName]
if (
chunk.type === 'chunk' &&
chunk.isEntry &&
chunk.fileName.includes('index.js') // 匹配主进程入口文件
) {
const code = fs.readFileSync('src/main/polyfill/windows7-patch.js', 'utf-8')
// 在文件末尾插入自定义代码
chunk.code = code + '\r\n' + chunk.code
}
}
}
}
]
}
}
},
preload: {
@@ -39,6 +71,10 @@ export default defineConfig({
}
},
renderer: {
define: {
// 使用方法 (Windows CMD): set CUSTOM_APP_NAME=AppName && yarn run dev
'process.env.CUSTOM_APP_NAME': JSON.stringify(process.env.CUSTOM_APP_NAME)
},
plugins: [
react({
plugins: [

View File

@@ -1,6 +1,6 @@
{
"name": "CherryStudio",
"version": "1.4.2",
"version": "1.4.1",
"private": true,
"description": "A powerful AI assistant for producer.",
"main": "./out/main/index.js",
@@ -27,6 +27,7 @@
"build:win": "dotenv npm run build && electron-builder --win --x64 --arm64",
"build:win:x64": "dotenv npm run build && electron-builder --win --x64",
"build:win:arm64": "dotenv npm run build && electron-builder --win --arm64",
"build:win7": "xcopy \"src\\patch\\windows7\\\" \"node_modules\\\" /E /Y && dotenv npm run build && electron-builder --win --x64",
"build:mac": "dotenv electron-vite build && electron-builder --mac --arm64 --x64",
"build:mac:arm64": "dotenv electron-vite build && electron-builder --mac --arm64",
"build:mac:x64": "dotenv electron-vite build && electron-builder --mac --x64",
@@ -68,36 +69,47 @@
"@cherrystudio/embedjs-loader-sitemap": "^0.1.31",
"@cherrystudio/embedjs-loader-web": "^0.1.31",
"@cherrystudio/embedjs-loader-xml": "^0.1.31",
"@cherrystudio/embedjs-ollama": "^0.1.31",
"@cherrystudio/embedjs-openai": "^0.1.31",
"@electron-toolkit/utils": "^3.0.0",
"@langchain/community": "^0.3.36",
"@langchain/ollama": "^0.2.1",
"@libsql/client": "^0.15.2",
"@libsql/win32-x64-msvc": "^0.5.4",
"@mozilla/readability": "^0.6.0",
"@notionhq/client": "^2.2.15",
"@peculiar/webcrypto": "^1.5.0",
"@strongtz/win32-arm64-msvc": "^0.4.7",
"@tanstack/react-query": "^5.27.0",
"@types/react-infinite-scroll-component": "^5.0.0",
"archiver": "^7.0.1",
"async-mutex": "^0.5.0",
"blob-polyfill": "^9.0.20240710",
"bufferutil": "^4.0.9",
"color": "^5.0.0",
"diff": "^7.0.0",
"docx": "^9.0.2",
"domexception": "^4.0.0",
"electron-log": "^5.1.5",
"electron-store": "^8.2.0",
"electron-updater": "6.6.4",
"electron-updater": "6.6.2",
"electron-window-state": "^5.0.3",
"epub": "patch:epub@npm%3A1.3.0#~/.yarn/patches/epub-npm-1.3.0-8325494ffe.patch",
"fast-xml-parser": "^5.2.0",
"franc-min": "^6.2.0",
"fs-extra": "^11.2.0",
"jsdom": "^26.0.0",
"libsql": "^0.5.4",
"markdown-it": "^14.1.0",
"node-fetch": "2",
"node-stream-zip": "^1.15.0",
"officeparser": "^4.1.1",
"os-proxy-config": "^1.1.2",
"proxy-agent": "^6.5.0",
"remove-markdown": "^0.6.2",
"selection-hook": "^0.9.23",
"selection-hook": "^0.9.21",
"tar": "^7.4.3",
"turndown": "^7.2.0",
"turndown-plugin-gfm": "^1.0.2",
"undici": "^7.4.0",
"web-streams-polyfill": "^4.1.0",
"webdav": "^5.8.0",
"zipread": "^1.3.3"
},
@@ -121,7 +133,7 @@
"@modelcontextprotocol/sdk": "^1.11.4",
"@mozilla/readability": "^0.6.0",
"@notionhq/client": "^2.2.15",
"@playwright/test": "^1.52.0",
"@peculiar/webcrypto": "^1.5.0",
"@reduxjs/toolkit": "^2.2.5",
"@shikijs/markdown-it": "^3.4.2",
"@swc/plugin-styled-components": "^7.1.5",
@@ -158,8 +170,8 @@
"dexie": "^4.0.8",
"dexie-react-hooks": "^1.1.7",
"dotenv-cli": "^7.4.2",
"electron": "35.4.0",
"electron-builder": "26.0.15",
"electron": "22.3.23",
"electron-builder": "^24.9.1",
"electron-devtools-installer": "^3.2.0",
"electron-vite": "^3.1.0",
"emittery": "^1.0.3",
@@ -224,6 +236,9 @@
"libsql@npm:^0.4.4": "patch:libsql@npm%3A0.4.7#~/.yarn/patches/libsql-npm-0.4.7-444e260fb1.patch",
"openai@npm:^4.77.0": "patch:openai@npm%3A5.1.0#~/.yarn/patches/openai-npm-5.1.0-0e7b3ccb07.patch",
"pkce-challenge@npm:^4.1.0": "patch:pkce-challenge@npm%3A4.1.0#~/.yarn/patches/pkce-challenge-npm-4.1.0-fbc51695a3.patch",
"@types/domexception": "^4",
"electron": "22.3.23",
"electron-builder": "^24.9.1",
"app-builder-lib@npm:26.0.13": "patch:app-builder-lib@npm%3A26.0.13#~/.yarn/patches/app-builder-lib-npm-26.0.13-a064c9e1d0.patch",
"openai@npm:^4.87.3": "patch:openai@npm%3A5.1.0#~/.yarn/patches/openai-npm-5.1.0-0e7b3ccb07.patch",
"app-builder-lib@npm:26.0.15": "patch:app-builder-lib@npm%3A26.0.15#~/.yarn/patches/app-builder-lib-npm-26.0.15-360e5b0476.patch",

View File

@@ -13,7 +13,6 @@ export enum IpcChannel {
App_SetTrayOnClose = 'app:set-tray-on-close',
App_SetTheme = 'app:set-theme',
App_SetAutoUpdate = 'app:set-auto-update',
App_SetFeedUrl = 'app:set-feed-url',
App_HandleZoomFactor = 'app:handle-zoom-factor',
App_IsBinaryExist = 'app:is-binary-exist',
@@ -21,8 +20,6 @@ export enum IpcChannel {
App_InstallUvBinary = 'app:install-uv-binary',
App_InstallBunBinary = 'app:install-bun-binary',
App_QuoteToMain = 'app:quote-to-main',
Notification_Send = 'notification:send',
Notification_OnClick = 'notification:on-click',

View File

@@ -403,8 +403,3 @@ export const KB = 1024
export const MB = 1024 * KB
export const GB = 1024 * MB
export const defaultLanguage = 'en-US'
export enum FeedUrl {
PRODUCTION = 'https://releases.cherry-ai.com',
EARLY_ACCESS = 'https://github.com/CherryHQ/cherry-studio/releases/latest/download'
}

View File

@@ -1,6 +1,7 @@
import { app } from 'electron'
import { getDataPath } from './utils'
import { isWindows7 } from './utils/runtime'
const isDev = process.env.NODE_ENV === 'development'
@@ -12,12 +13,12 @@ export const DATA_PATH = getDataPath()
export const titleBarOverlayDark = {
height: 40,
color: 'rgba(255,255,255,0)',
symbolColor: '#fff'
color: isWindows7() ? '#1c1c1c' : 'rgba(0,0,0,0)',
symbolColor: '#ffffff'
}
export const titleBarOverlayLight = {
height: 40,
color: 'rgba(255,255,255,0)',
symbolColor: '#000'
color: isWindows7() ? '#f4f4f4' : 'rgba(255,255,255,0)',
symbolColor: '#000000'
}

View File

@@ -20,7 +20,6 @@ interface IFinetunedList {
*************************************************************************/
export const SELECTION_PREDEFINED_BLACKLIST: IFilterList = {
WINDOWS: [
'explorer.exe',
// Screenshot
'snipaste.exe',
'pixpin.exe',

View File

@@ -5,15 +5,8 @@ import EmbeddingsFactory from './EmbeddingsFactory'
export default class Embeddings {
private sdk: BaseEmbeddings
constructor({ model, provider, apiKey, apiVersion, baseURL, dimensions }: KnowledgeBaseParams) {
this.sdk = EmbeddingsFactory.create({
model,
provider,
apiKey,
apiVersion,
baseURL,
dimensions
} as KnowledgeBaseParams)
constructor({ model, apiKey, apiVersion, baseURL, dimensions }: KnowledgeBaseParams) {
this.sdk = EmbeddingsFactory.create({ model, apiKey, apiVersion, baseURL, dimensions } as KnowledgeBaseParams)
}
public async init(): Promise<void> {
return this.sdk.init()

View File

@@ -1,49 +1,20 @@
import type { BaseEmbeddings } from '@cherrystudio/embedjs-interfaces'
import { OllamaEmbeddings } from '@cherrystudio/embedjs-ollama'
import { OpenAiEmbeddings } from '@cherrystudio/embedjs-openai'
import { AzureOpenAiEmbeddings } from '@cherrystudio/embedjs-openai/src/azure-openai-embeddings'
import { getInstanceName } from '@main/utils'
import { KnowledgeBaseParams } from '@types'
import { SUPPORTED_DIM_MODELS as VOYAGE_SUPPORTED_DIM_MODELS, VoyageEmbeddings } from './VoyageEmbeddings'
import VoyageEmbeddings from './VoyageEmbeddings'
export default class EmbeddingsFactory {
static create({ model, provider, apiKey, apiVersion, baseURL, dimensions }: KnowledgeBaseParams): BaseEmbeddings {
static create({ model, apiKey, apiVersion, baseURL, dimensions }: KnowledgeBaseParams): BaseEmbeddings {
const batchSize = 10
if (provider === 'voyageai') {
if (VOYAGE_SUPPORTED_DIM_MODELS.includes(model)) {
return new VoyageEmbeddings({
modelName: model,
apiKey,
outputDimension: dimensions,
batchSize: 8
})
} else {
return new VoyageEmbeddings({
modelName: model,
apiKey,
batchSize: 8
})
}
}
if (provider === 'ollama') {
if (baseURL.includes('v1/')) {
return new OllamaEmbeddings({
model: model,
baseUrl: baseURL.replace('v1/', ''),
requestOptions: {
// @ts-ignore expected
'encoding-format': 'float'
}
})
}
return new OllamaEmbeddings({
model: model,
baseUrl: baseURL,
requestOptions: {
// @ts-ignore expected
'encoding-format': 'float'
}
if (model.includes('voyage')) {
return new VoyageEmbeddings({
modelName: model,
apiKey,
outputDimension: dimensions,
batchSize: 8
})
}
if (apiVersion !== undefined) {

View File

@@ -1,20 +1,16 @@
import { BaseEmbeddings } from '@cherrystudio/embedjs-interfaces'
import { VoyageEmbeddings as _VoyageEmbeddings } from '@langchain/community/embeddings/voyage'
/**
* 支持设置嵌入维度的模型
*/
export const SUPPORTED_DIM_MODELS = ['voyage-3-large', 'voyage-3.5', 'voyage-3.5-lite', 'voyage-code-3']
export class VoyageEmbeddings extends BaseEmbeddings {
export default class VoyageEmbeddings extends BaseEmbeddings {
private model: _VoyageEmbeddings
constructor(private readonly configuration?: ConstructorParameters<typeof _VoyageEmbeddings>[0]) {
super()
if (!this.configuration) this.configuration = {}
if (!this.configuration.modelName) this.configuration.modelName = 'voyage-3'
if (!SUPPORTED_DIM_MODELS.includes(this.configuration.modelName) && this.configuration.outputDimension) {
throw new Error(`VoyageEmbeddings only supports ${SUPPORTED_DIM_MODELS.join(', ')}`)
}
if (!this.configuration.outputDimension) {
throw new Error('You need to pass in the optional dimensions parameter for this model')
}
this.model = new _VoyageEmbeddings(this.configuration)
}
override async getDimensions(): Promise<number> {

View File

@@ -34,26 +34,6 @@ if (isWin) {
app.commandLine.appendSwitch('wm-window-animations-disabled')
}
// Enable features for unresponsive renderer js call stacks
app.commandLine.appendSwitch('enable-features', 'DocumentPolicyIncludeJSCallStacksInCrashReports')
app.on('web-contents-created', (_, webContents) => {
webContents.session.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Document-Policy': ['include-js-call-stacks-in-crash-reports']
}
})
})
webContents.on('unresponsive', async () => {
// Interrupt execution and collect call stack from unresponsive renderer
Logger.error('Renderer unresponsive start')
const callStack = await webContents.mainFrame.collectJavaScriptCallStack()
Logger.error('Renderer unresponsive js call stack\n', callStack)
})
})
// in production mode, handle uncaught exception and unhandled rejection globally
if (!isDev) {
// handle uncaught exception

File diff suppressed because one or more lines are too long

View File

@@ -34,7 +34,6 @@ import { calculateDirectorySize, getResourcePath } from './utils'
import { decrypt, encrypt } from './utils/aes'
import { getCacheDir, getConfigDir, getFilesDir } from './utils/file'
import { compress, decompress } from './utils/zip'
import { FeedUrl } from '@shared/config/constant'
const fileManager = new FileStorage()
const backupManager = new BackupManager()
@@ -113,10 +112,6 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
configManager.setAutoUpdate(isActive)
})
ipcMain.handle(IpcChannel.App_SetFeedUrl, (_, feedUrl: FeedUrl) => {
appUpdater.setFeedUrl(feedUrl)
})
ipcMain.handle(IpcChannel.Config_Set, (_, key: string, value: any, isNotify: boolean = false) => {
configManager.set(key, value, isNotify)
})
@@ -351,6 +346,4 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
// selection assistant
SelectionService.registerIpcHandler()
ipcMain.handle(IpcChannel.App_QuoteToMain, (_, text: string) => windowService.quoteToMainWindow(text))
}

View File

@@ -0,0 +1,36 @@
console.info('inject polyfill win7')
// fix for node_modules\@libsql\isomorphic-fetch\node.cjs
if (!globalThis.fetch) {
globalThis.fetch = require('node-fetch')
}
if (!globalThis.Request) {
const { Request, Headers } = require('node-fetch')
globalThis.Request = Request
globalThis.Headers = Headers
}
// fix for node_modules/undici/lib/web/fetch/webidl.js
if (!globalThis.Blob) {
const { Blob } = require('blob-polyfill')
globalThis.Blob = Blob
}
// fix for node_modules/undici/lib/web/fetch/webidl.js
if (!globalThis.ReadableStream) {
const { ReadableStream, TransformStream } = require('web-streams-polyfill')
globalThis.ReadableStream = ReadableStream
globalThis.TransformStream = TransformStream
console.log('ReadableStream', ReadableStream)
}
if (!globalThis.DOMException) {
globalThis.DOMException = require('domexception')
}
if (!globalThis.crypto) {
const { Crypto } = require('@peculiar/webcrypto')
globalThis.crypto = new Crypto()
}
console.info('inject polyfill win7 ok')

View File

@@ -1,7 +1,6 @@
import { isWin } from '@main/constant'
import { locales } from '@main/utils/locales'
import { IpcChannel } from '@shared/IpcChannel'
import { FeedUrl } from '@shared/config/constant'
import { UpdateInfo } from 'builder-util-runtime'
import { app, BrowserWindow, dialog } from 'electron'
import logger from 'electron-log'
@@ -21,7 +20,6 @@ export default class AppUpdater {
autoUpdater.forceDevUpdateConfig = !app.isPackaged
autoUpdater.autoDownload = configManager.getAutoUpdate()
autoUpdater.autoInstallOnAppQuit = configManager.getAutoUpdate()
autoUpdater.setFeedURL(configManager.getFeedUrl())
// 检测下载错误
autoUpdater.on('error', (error) => {
@@ -64,11 +62,6 @@ export default class AppUpdater {
autoUpdater.autoInstallOnAppQuit = isActive
}
public setFeedUrl(feedUrl: FeedUrl) {
autoUpdater.setFeedURL(feedUrl)
configManager.setFeedUrl(feedUrl)
}
public async checkForUpdates() {
if (isWin && 'PORTABLE_EXECUTABLE_DIR' in process.env) {
return {

View File

@@ -295,12 +295,10 @@ class BackupManager {
async backupToWebdav(_: Electron.IpcMainInvokeEvent, data: string, webdavConfig: WebDavConfig) {
const filename = webdavConfig.fileName || 'cherry-studio.backup.zip'
const backupedFilePath = await this.backup(_, filename, data, undefined, webdavConfig.skipBackupFile)
const contentLength = (await fs.stat(backupedFilePath)).size
const webdavClient = new WebDav(webdavConfig)
try {
const result = await webdavClient.putFileContents(filename, fs.createReadStream(backupedFilePath), {
overwrite: true,
contentLength
overwrite: true
})
// 上传成功后删除本地备份文件
await fs.remove(backupedFilePath)

View File

@@ -1,4 +1,4 @@
import { defaultLanguage, FeedUrl, ZOOM_SHORTCUTS } from '@shared/config/constant'
import { defaultLanguage, ZOOM_SHORTCUTS } from '@shared/config/constant'
import { LanguageVarious, Shortcut, ThemeMode } from '@types'
import { app } from 'electron'
import Store from 'electron-store'
@@ -16,7 +16,6 @@ export enum ConfigKeys {
ClickTrayToShowQuickAssistant = 'clickTrayToShowQuickAssistant',
EnableQuickAssistant = 'enableQuickAssistant',
AutoUpdate = 'autoUpdate',
FeedUrl = 'feedUrl',
EnableDataCollection = 'enableDataCollection',
SelectionAssistantEnabled = 'selectionAssistantEnabled',
SelectionAssistantTriggerMode = 'selectionAssistantTriggerMode',
@@ -142,14 +141,6 @@ export class ConfigManager {
this.set(ConfigKeys.AutoUpdate, value)
}
getFeedUrl(): string {
return this.get<string>(ConfigKeys.FeedUrl, FeedUrl.PRODUCTION)
}
setFeedUrl(value: FeedUrl) {
this.set(ConfigKeys.FeedUrl, value)
}
getEnableDataCollection(): boolean {
return this.get<boolean>(ConfigKeys.EnableDataCollection, true)
}
@@ -160,7 +151,7 @@ export class ConfigManager {
// Selection Assistant: is enabled the selection assistant
getSelectionAssistantEnabled(): boolean {
return this.get<boolean>(ConfigKeys.SelectionAssistantEnabled, false)
return this.get<boolean>(ConfigKeys.SelectionAssistantEnabled, true)
}
setSelectionAssistantEnabled(value: boolean) {

View File

@@ -1,9 +1,7 @@
import fs from 'fs/promises'
import fs from 'node:fs'
export default class FileService {
public static async readFile(_: Electron.IpcMainInvokeEvent, pathOrUrl: string, encoding?: BufferEncoding) {
const path = pathOrUrl.startsWith('file://') ? new URL(pathOrUrl) : pathOrUrl
if (encoding) return fs.readFile(path, { encoding })
return fs.readFile(path)
public static async readFile(_: Electron.IpcMainInvokeEvent, path: string) {
return fs.readFileSync(path, 'utf8')
}
}

View File

@@ -373,7 +373,7 @@ class FileStorage {
fileName: string,
content: string,
options?: SaveDialogOptions
): Promise<string> => {
): Promise<string | null | undefined> => {
try {
const result: SaveDialogReturnValue = await dialog.showSaveDialog({
title: '保存文件',

View File

@@ -110,21 +110,13 @@ class KnowledgeService {
private getRagApplication = async ({
id,
model,
provider,
apiKey,
apiVersion,
baseURL,
dimensions
}: KnowledgeBaseParams): Promise<RAGApplication> => {
let ragApplication: RAGApplication
const embeddings = new Embeddings({
model,
provider,
apiKey,
apiVersion,
baseURL,
dimensions
} as KnowledgeBaseParams)
const embeddings = new Embeddings({ model, apiKey, apiVersion, baseURL, dimensions } as KnowledgeBaseParams)
try {
ragApplication = await new RAGApplicationBuilder()
.setModel('NO_MODEL')

View File

@@ -1,4 +1,9 @@
import { ProxyConfig as _ProxyConfig, session } from 'electron'
// import { ProxyConfig as _ProxyConfig, session } from 'electron'
import { session } from 'electron'
declare type _ProxyConfig = any
// import { socksDispatcher } from 'fetch-socks'
import { getSystemProxy } from 'os-proxy-config'
import { ProxyAgent as GeneralProxyAgent } from 'proxy-agent'
// import { ProxyAgent, setGlobalDispatcher } from 'undici'

View File

@@ -14,7 +14,6 @@ import type {
import type { ActionItem } from '../../renderer/src/types/selectionTypes'
import { ConfigKeys, configManager } from './ConfigManager'
import storeSyncService from './StoreSyncService'
let SelectionHook: SelectionHookConstructor | null = null
try {
@@ -40,8 +39,7 @@ type RelativeOrientation =
enum TriggerMode {
Selected = 'selected',
Ctrlkey = 'ctrlkey',
Shortcut = 'shortcut'
Ctrlkey = 'ctrlkey'
}
/** SelectionService is a singleton class that manages the selection hook and the toolbar window
@@ -316,8 +314,6 @@ export class SelectionService {
this.toolbarWindow.close()
this.toolbarWindow = null
}
this.closePreloadedActionWindows()
this.started = false
this.logInfo('SelectionService Stopped')
return true
@@ -338,21 +334,6 @@ export class SelectionService {
this.logInfo('SelectionService Quitted')
}
/**
* Toggle the enabled state of the selection service
* Will sync the new enabled store to all renderer windows
*/
public toggleEnabled(enabled: boolean | undefined = undefined) {
if (!this.selectionHook) return
const newEnabled = enabled === undefined ? !configManager.getSelectionAssistantEnabled() : enabled
configManager.setSelectionAssistantEnabled(newEnabled)
//sync the new enabled state to all renderer windows
storeSyncService.syncToRenderer('selectionStore/setSelectionEnabled', newEnabled)
}
/**
* Create and configure the toolbar window
* Sets up window properties, event handlers, and loads the toolbar UI
@@ -378,7 +359,7 @@ export class SelectionService {
hasShadow: false,
thickFrame: false,
roundedCorners: true,
backgroundMaterial: 'none',
// backgroundMaterial: 'none',
type: 'toolbar',
show: false,
webPreferences: {
@@ -397,9 +378,6 @@ export class SelectionService {
// Clean up when closed
this.toolbarWindow.on('closed', () => {
if (!this.toolbarWindow?.isDestroyed()) {
this.toolbarWindow?.destroy()
}
this.toolbarWindow = null
})
@@ -585,21 +563,6 @@ export class SelectionService {
return startTop.y === endTop.y && startBottom.y === endBottom.y
}
/**
* Get the user selected text and process it (trigger by shortcut)
*
* it's a public method used by shortcut service
*/
public processSelectTextByShortcut(): void {
if (!this.selectionHook || !this.started || this.triggerMode !== TriggerMode.Shortcut) return
const selectionData = this.selectionHook.getCurrentSelection()
if (selectionData) {
this.processTextSelection(selectionData)
}
}
/**
* Determine if the text selection should be processed by filter mode&list
* @param selectionData Text selection information and coordinates
@@ -849,8 +812,8 @@ export class SelectionService {
if (this.triggerMode === TriggerMode.Ctrlkey && this.isCtrlkey(data.vkCode)) {
return
}
//dont hide toolbar when shiftkey or altkey is pressed, because it's used for selection
if (this.isShiftkey(data.vkCode) || this.isAltkey(data.vkCode)) {
//dont hide toolbar when shiftkey is pressed, because it's used for selection
if (this.isShiftkey(data.vkCode)) {
return
}
@@ -878,9 +841,8 @@ export class SelectionService {
//ctrlkey pressed
if (this.lastCtrlkeyDownTime === 0) {
this.lastCtrlkeyDownTime = Date.now()
//add the mouse-wheel&mouse-down listener, detect if user is zooming in/out or multi-selecting
//add the mouse-wheel listener, detect if user is zooming in/out
this.selectionHook!.on('mouse-wheel', this.handleMouseWheelCtrlkeyMode)
this.selectionHook!.on('mouse-down', this.handleMouseDownCtrlkeyMode)
return
}
@@ -891,6 +853,7 @@ export class SelectionService {
this.lastCtrlkeyDownTime = -1
const selectionData = this.selectionHook!.getCurrentSelection()
if (selectionData) {
this.processTextSelection(selectionData)
}
@@ -903,9 +866,8 @@ export class SelectionService {
*/
private handleKeyUpCtrlkeyMode = (data: KeyboardEventData) => {
if (!this.isCtrlkey(data.vkCode)) return
//remove the mouse-wheel&mouse-down listener
//remove the mouse-wheel listener
this.selectionHook!.off('mouse-wheel', this.handleMouseWheelCtrlkeyMode)
this.selectionHook!.off('mouse-down', this.handleMouseDownCtrlkeyMode)
this.lastCtrlkeyDownTime = 0
}
@@ -918,15 +880,6 @@ export class SelectionService {
this.lastCtrlkeyDownTime = -1
}
/**
* Handle mouse down events in ctrlkey trigger mode
* ignore CtrlKey pressing when mouse down is used
* because user is multi-selecting
*/
private handleMouseDownCtrlkeyMode = () => {
this.lastCtrlkeyDownTime = -1
}
//check if the key is ctrl key
private isCtrlkey(vkCode: number) {
return vkCode === 162 || vkCode === 163
@@ -937,11 +890,6 @@ export class SelectionService {
return vkCode === 160 || vkCode === 161
}
//check if the key is alt key
private isAltkey(vkCode: number) {
return vkCode === 164 || vkCode === 165
}
/**
* Create a preloaded action window for quick response
* Action windows handle specific operations on selected text
@@ -994,17 +942,6 @@ export class SelectionService {
}
}
/**
* Close all preloaded action windows
*/
private closePreloadedActionWindows() {
for (const actionWindow of this.preloadedActionWindows) {
if (!actionWindow.isDestroyed()) {
actionWindow.destroy()
}
}
}
/**
* Preload a new action window asynchronously
* This method is called after popping a window to ensure we always have windows ready
@@ -1153,44 +1090,29 @@ export class SelectionService {
* Manages appropriate event listeners for each mode
*/
private processTriggerMode() {
switch (this.triggerMode) {
case TriggerMode.Selected:
if (this.isCtrlkeyListenerActive) {
this.selectionHook!.off('key-down', this.handleKeyDownCtrlkeyMode)
this.selectionHook!.off('key-up', this.handleKeyUpCtrlkeyMode)
if (this.triggerMode === TriggerMode.Selected) {
if (this.isCtrlkeyListenerActive) {
this.selectionHook!.off('key-down', this.handleKeyDownCtrlkeyMode)
this.selectionHook!.off('key-up', this.handleKeyUpCtrlkeyMode)
this.isCtrlkeyListenerActive = false
}
this.isCtrlkeyListenerActive = false
}
this.selectionHook!.setSelectionPassiveMode(false)
break
case TriggerMode.Ctrlkey:
if (!this.isCtrlkeyListenerActive) {
this.selectionHook!.on('key-down', this.handleKeyDownCtrlkeyMode)
this.selectionHook!.on('key-up', this.handleKeyUpCtrlkeyMode)
this.selectionHook!.setSelectionPassiveMode(false)
} else if (this.triggerMode === TriggerMode.Ctrlkey) {
if (!this.isCtrlkeyListenerActive) {
this.selectionHook!.on('key-down', this.handleKeyDownCtrlkeyMode)
this.selectionHook!.on('key-up', this.handleKeyUpCtrlkeyMode)
this.isCtrlkeyListenerActive = true
}
this.isCtrlkeyListenerActive = true
}
this.selectionHook!.setSelectionPassiveMode(true)
break
case TriggerMode.Shortcut:
//remove the ctrlkey listener, don't need any key listener for shortcut mode
if (this.isCtrlkeyListenerActive) {
this.selectionHook!.off('key-down', this.handleKeyDownCtrlkeyMode)
this.selectionHook!.off('key-up', this.handleKeyUpCtrlkeyMode)
this.isCtrlkeyListenerActive = false
}
this.selectionHook!.setSelectionPassiveMode(true)
break
this.selectionHook!.setSelectionPassiveMode(true)
}
}
public writeToClipboard(text: string): boolean {
if (!this.selectionHook || !this.started) return false
return this.selectionHook.writeToClipboard(text)
return this.selectionHook?.writeToClipboard(text) ?? false
}
/**

View File

@@ -4,16 +4,10 @@ import { BrowserWindow, globalShortcut } from 'electron'
import Logger from 'electron-log'
import { configManager } from './ConfigManager'
import selectionService from './SelectionService'
import { windowService } from './WindowService'
let showAppAccelerator: string | null = null
let showMiniWindowAccelerator: string | null = null
let selectionAssistantToggleAccelerator: string | null = null
let selectionAssistantSelectTextAccelerator: string | null = null
//indicate if the shortcuts are registered on app boot time
let isRegisterOnBoot = true
// store the focus and blur handlers for each window to unregister them later
const windowOnHandlers = new Map<BrowserWindow, { onFocusHandler: () => void; onBlurHandler: () => void }>()
@@ -34,18 +28,6 @@ function getShortcutHandler(shortcut: Shortcut) {
return () => {
windowService.toggleMiniWindow()
}
case 'selection_assistant_toggle':
return () => {
if (selectionService) {
selectionService.toggleEnabled()
}
}
case 'selection_assistant_select_text':
return () => {
if (selectionService) {
selectionService.processSelectTextByShortcut()
}
}
default:
return null
}
@@ -55,8 +37,9 @@ function formatShortcutKey(shortcut: string[]): string {
return shortcut.join('+')
}
// convert the shortcut recorded by keyboard event key value to electron global shortcut format
const convertShortcutFormat = (shortcut: string | string[]): string => {
const convertShortcutRecordedByKeyboardEventKeyValueToElectronGlobalShortcutFormat = (
shortcut: string | string[]
): string => {
const accelerator = (() => {
if (Array.isArray(shortcut)) {
return shortcut
@@ -110,14 +93,11 @@ const convertShortcutFormat = (shortcut: string | string[]): string => {
}
export function registerShortcuts(window: BrowserWindow) {
if (isRegisterOnBoot) {
window.once('ready-to-show', () => {
if (configManager.getLaunchToTray()) {
registerOnlyUniversalShortcuts()
}
})
isRegisterOnBoot = false
}
window.once('ready-to-show', () => {
if (configManager.getLaunchToTray()) {
registerOnlyUniversalShortcuts()
}
})
//only for clearer code
const registerOnlyUniversalShortcuts = () => {
@@ -144,12 +124,7 @@ export function registerShortcuts(window: BrowserWindow) {
}
// only register universal shortcuts when needed
if (
onlyUniversalShortcuts &&
!['show_app', 'mini_window', 'selection_assistant_toggle', 'selection_assistant_select_text'].includes(
shortcut.key
)
) {
if (onlyUniversalShortcuts && !['show_app', 'mini_window'].includes(shortcut.key)) {
return
}
@@ -171,14 +146,6 @@ export function registerShortcuts(window: BrowserWindow) {
showMiniWindowAccelerator = formatShortcutKey(shortcut.shortcut)
break
case 'selection_assistant_toggle':
selectionAssistantToggleAccelerator = formatShortcutKey(shortcut.shortcut)
break
case 'selection_assistant_select_text':
selectionAssistantSelectTextAccelerator = formatShortcutKey(shortcut.shortcut)
break
//the following ZOOMs will register shortcuts seperately, so will return
case 'zoom_in':
globalShortcut.register('CommandOrControl+=', () => handler(window))
@@ -195,7 +162,9 @@ export function registerShortcuts(window: BrowserWindow) {
return
}
const accelerator = convertShortcutFormat(shortcut.shortcut)
const accelerator = convertShortcutRecordedByKeyboardEventKeyValueToElectronGlobalShortcutFormat(
shortcut.shortcut
)
globalShortcut.register(accelerator, () => handler(window))
} catch (error) {
@@ -212,25 +181,15 @@ export function registerShortcuts(window: BrowserWindow) {
if (showAppAccelerator) {
const handler = getShortcutHandler({ key: 'show_app' } as Shortcut)
const accelerator = convertShortcutFormat(showAppAccelerator)
const accelerator =
convertShortcutRecordedByKeyboardEventKeyValueToElectronGlobalShortcutFormat(showAppAccelerator)
handler && globalShortcut.register(accelerator, () => handler(window))
}
if (showMiniWindowAccelerator) {
const handler = getShortcutHandler({ key: 'mini_window' } as Shortcut)
const accelerator = convertShortcutFormat(showMiniWindowAccelerator)
handler && globalShortcut.register(accelerator, () => handler(window))
}
if (selectionAssistantToggleAccelerator) {
const handler = getShortcutHandler({ key: 'selection_assistant_toggle' } as Shortcut)
const accelerator = convertShortcutFormat(selectionAssistantToggleAccelerator)
handler && globalShortcut.register(accelerator, () => handler(window))
}
if (selectionAssistantSelectTextAccelerator) {
const handler = getShortcutHandler({ key: 'selection_assistant_select_text' } as Shortcut)
const accelerator = convertShortcutFormat(selectionAssistantSelectTextAccelerator)
const accelerator =
convertShortcutRecordedByKeyboardEventKeyValueToElectronGlobalShortcutFormat(showMiniWindowAccelerator)
handler && globalShortcut.register(accelerator, () => handler(window))
}
} catch (error) {
@@ -258,8 +217,6 @@ export function unregisterAllShortcuts() {
try {
showAppAccelerator = null
showMiniWindowAccelerator = null
selectionAssistantToggleAccelerator = null
selectionAssistantSelectTextAccelerator = null
windowOnHandlers.forEach((handlers, window) => {
window.off('focus', handlers.onFocusHandler)
window.off('blur', handlers.onBlurHandler)

View File

@@ -49,23 +49,6 @@ export class StoreSyncService {
this.windowIds = this.windowIds.filter((id) => id !== windowId)
}
/**
* Sync an action to all renderer windows
* @param type Action type, like 'settings/setTray'
* @param payload Action payload
*
* NOTICE: DO NOT use directly in ConfigManager, may cause infinite sync loop
*/
public syncToRenderer(type: string, payload: any): void {
const action: StoreSyncAction = {
type,
payload
}
//-1 means the action is from the main process, will be broadcast to all windows
this.broadcastToOtherWindows(-1, action)
}
/**
* Register IPC handlers for store sync communication
* Handles window subscription, unsubscription and action broadcasting

View File

@@ -1,8 +1,7 @@
import { WebDavConfig } from '@types'
import Logger from 'electron-log'
import https from 'https'
import path from 'path'
import Stream from 'stream'
import https from 'https'
import {
BufferLike,
createClient,
@@ -16,7 +15,7 @@ export default class WebDav {
private webdavPath: string
constructor(params: WebDavConfig) {
this.webdavPath = params.webdavPath || '/'
this.webdavPath = params.webdavPath
this.instance = createClient(params.webdavHost, {
username: params.webdavUser,
@@ -52,7 +51,7 @@ export default class WebDav {
throw error
}
const remoteFilePath = path.posix.join(this.webdavPath, filename)
const remoteFilePath = `${this.webdavPath}/${filename}`
try {
return await this.instance.putFileContents(remoteFilePath, data, options)
@@ -67,7 +66,7 @@ export default class WebDav {
throw new Error('WebDAV client not initialized')
}
const remoteFilePath = path.posix.join(this.webdavPath, filename)
const remoteFilePath = `${this.webdavPath}/${filename}`
try {
return await this.instance.getFileContents(remoteFilePath, options)
@@ -121,7 +120,7 @@ export default class WebDav {
throw new Error('WebDAV client not initialized')
}
const remoteFilePath = path.posix.join(this.webdavPath, filename)
const remoteFilePath = `${this.webdavPath}/${filename}`
try {
return await this.instance.deleteFile(remoteFilePath)

View File

@@ -116,6 +116,12 @@ export class WindowService {
app.exit(1)
}
})
mainWindow.webContents.on('unresponsive', () => {
// 在升级到electron 34后可以获取具体js stack trace,目前只打个日志监控下
// https://www.electronjs.org/blog/electron-34-0#unresponsive-renderer-javascript-call-stacks
Logger.error('Renderer process unresponsive')
})
}
private setupMaximize(mainWindow: BrowserWindow, isMaximized: boolean) {
@@ -538,25 +544,6 @@ export class WindowService {
public setPinMiniWindow(isPinned) {
this.isPinnedMiniWindow = isPinned
}
/**
* 引用文本到主窗口
* @param text 原始文本(未格式化)
*/
public quoteToMainWindow(text: string): void {
try {
this.showMainWindow()
const mainWindow = this.getMainWindow()
if (mainWindow && !mainWindow.isDestroyed()) {
setTimeout(() => {
mainWindow.webContents.send(IpcChannel.App_QuoteToMain, text)
}, 100)
}
} catch (error) {
Logger.error('Failed to quote to main window:', error as Error)
}
}
}
export const windowService = WindowService.getInstance()

View File

@@ -0,0 +1,7 @@
import os from 'os'
export function isWindows7() {
if (process.platform !== 'win32') return false
const version = os.release()
return version.startsWith('6.1') // Windows 7 的版本号为 6.1
}

Binary file not shown.

View File

@@ -1,9 +1,8 @@
import type { ExtractChunkData } from '@cherrystudio/embedjs-interfaces'
import { electronAPI } from '@electron-toolkit/preload'
import { FeedUrl } from '@shared/config/constant'
import { IpcChannel } from '@shared/IpcChannel'
import { FileType, KnowledgeBaseParams, KnowledgeItem, MCPServer, Shortcut, ThemeMode, WebDavConfig } from '@types'
import { contextBridge, ipcRenderer, OpenDialogOptions, shell, webUtils } from 'electron'
import { contextBridge, ipcRenderer, OpenDialogOptions, shell } from 'electron'
import { Notification } from 'src/renderer/src/types/notification'
import { CreateDirectoryOptions } from 'webdav'
@@ -21,7 +20,6 @@ const api = {
setLaunchToTray: (isActive: boolean) => ipcRenderer.invoke(IpcChannel.App_SetLaunchToTray, isActive),
setTray: (isActive: boolean) => ipcRenderer.invoke(IpcChannel.App_SetTray, isActive),
setTrayOnClose: (isActive: boolean) => ipcRenderer.invoke(IpcChannel.App_SetTrayOnClose, isActive),
setFeedUrl: (feedUrl: FeedUrl) => ipcRenderer.invoke(IpcChannel.App_SetFeedUrl, feedUrl),
setTheme: (theme: ThemeMode) => ipcRenderer.invoke(IpcChannel.App_SetTheme, theme),
handleZoomFactor: (delta: number, reset: boolean = false) =>
ipcRenderer.invoke(IpcChannel.App_HandleZoomFactor, delta, reset),
@@ -83,10 +81,14 @@ const api = {
copy: (fileId: string, destPath: string) => ipcRenderer.invoke(IpcChannel.File_Copy, fileId, destPath),
binaryImage: (fileId: string) => ipcRenderer.invoke(IpcChannel.File_BinaryImage, fileId),
base64File: (fileId: string) => ipcRenderer.invoke(IpcChannel.File_Base64File, fileId),
getPathForFile: (file: File) => webUtils.getPathForFile(file)
getPathForFile: (file: File) => {
const electronFile = file as File & { path?: string }
return electronFile.path || null
}
// getPathForFile: (file: File) => webUtils.getPathForFile(file)
},
fs: {
read: (pathOrUrl: string, encoding?: BufferEncoding) => ipcRenderer.invoke(IpcChannel.Fs_Read, pathOrUrl, encoding)
read: (path: string) => ipcRenderer.invoke(IpcChannel.Fs_Read, path)
},
export: {
toWord: (markdown: string, fileName: string) => ipcRenderer.invoke(IpcChannel.Export_Word, markdown, fileName)
@@ -228,8 +230,7 @@ const api = {
closeActionWindow: () => ipcRenderer.invoke(IpcChannel.Selection_ActionWindowClose),
minimizeActionWindow: () => ipcRenderer.invoke(IpcChannel.Selection_ActionWindowMinimize),
pinActionWindow: (isPinned: boolean) => ipcRenderer.invoke(IpcChannel.Selection_ActionWindowPin, isPinned)
},
quoteToMainWindow: (text: string) => ipcRenderer.invoke(IpcChannel.App_QuoteToMain, text)
}
}
// Use `contextBridge` APIs to expose Electron APIs to

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 550 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

View File

@@ -4,3 +4,13 @@
border-top-left-radius: 10px;
border-left: 0.5px solid var(--color-border);
}
.group-container {
.context-menu-container {
width: 100%;
}
}
.context-menu-container {
max-width: 100%;
}

View File

@@ -129,29 +129,22 @@ ul {
.message-content-container {
margin: 5px 0;
border-radius: 8px;
padding: 0.5rem 1rem;
padding: 10px 15px 0 15px;
}
.block-wrapper {
display: flow-root;
}
.message-content-container > *:last-child {
margin-bottom: 0;
}
.message-thought-container {
margin-top: 8px;
}
.message-user {
color: var(--chat-text-user);
.message-content-container-user .anticon {
.markdown,
.anticon,
.iconfont,
.lucide,
.message-tokens {
color: var(--chat-text-user) !important;
}
.markdown {
color: var(--chat-text-user);
.message-action-button:hover {
background-color: var(--color-white-soft);
}
}
.group-grid-container.horizontal,
@@ -172,12 +165,6 @@ ul {
code {
color: var(--color-text);
}
.markdown {
display: flow-root;
*:last-child {
margin-bottom: 0;
}
}
}
.lucide {

View File

@@ -295,16 +295,13 @@ emoji-picker {
--border-size: 0;
}
.katex,
mjx-container {
display: inline-block;
.katex-display {
overflow-x: auto;
overflow-y: hidden;
overflow-wrap: break-word;
vertical-align: middle;
max-width: 100%;
padding: 1px 2px;
margin-top: -2px;
}
mjx-container {
overflow-x: auto;
}
/* CodeMirror 相关样式 */

View File

@@ -134,31 +134,26 @@ const CodePreview = ({ children, language, setTools }: CodePreviewProps) => {
return () => cleanupTokenizers(callerId)
}, [callerId, cleanupTokenizers])
// 触发代码高亮
// - 进入视口后触发第一次高亮
// - 内容变化后触发之后的高亮
// 处理第二次开始的代码高亮
useEffect(() => {
let isMounted = true
if (prevCodeLengthRef.current > 0) {
setTimeout(highlightCode, 0)
return
}
}, [highlightCode])
// 视口检测逻辑,只处理第一次代码高亮
useEffect(() => {
const codeElement = codeContentRef.current
if (!codeElement) return
if (!codeElement || prevCodeLengthRef.current > 0) return
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].intersectionRatio > 0 && isMounted) {
setTimeout(highlightCode, 0)
observer.disconnect()
}
},
{
rootMargin: '50px 0px 50px 0px'
let isMounted = true
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && isMounted) {
setTimeout(highlightCode, 0)
observer.disconnect()
}
)
})
observer.observe(codeElement)

View File

@@ -26,7 +26,6 @@ interface Props {
onSave?: (newContent: string) => void
onChange?: (newContent: string) => void
setTools?: (value: React.SetStateAction<CodeTool[]>) => void
height?: string
minHeight?: string
maxHeight?: string
/** 用于覆写编辑器的某些设置 */
@@ -55,7 +54,6 @@ const CodeEditor = ({
onSave,
onChange,
setTools,
height,
minHeight,
maxHeight,
options,
@@ -195,7 +193,6 @@ const CodeEditor = ({
value={initialContent.current}
placeholder={placeholder}
width="100%"
height={height}
minHeight={minHeight}
maxHeight={collapsible && !isExpanded ? (maxHeight ?? '350px') : 'none'}
editable={true}

View File

@@ -1,3 +1,4 @@
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
import { Dropdown } from 'antd'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -6,12 +7,12 @@ import styled from 'styled-components'
interface ContextMenuProps {
children: React.ReactNode
onContextMenu?: (e: React.MouseEvent) => void
style?: React.CSSProperties
}
const ContextMenu: React.FC<ContextMenuProps> = ({ children, onContextMenu, style }) => {
const ContextMenu: React.FC<ContextMenuProps> = ({ children, onContextMenu }) => {
const { t } = useTranslation()
const [contextMenuPosition, setContextMenuPosition] = useState<{ x: number; y: number } | null>(null)
const [selectedQuoteText, setSelectedQuoteText] = useState<string>('')
const [selectedText, setSelectedText] = useState<string>('')
const handleContextMenu = useCallback(
@@ -19,6 +20,12 @@ const ContextMenu: React.FC<ContextMenuProps> = ({ children, onContextMenu, styl
e.preventDefault()
const _selectedText = window.getSelection()?.toString()
if (_selectedText) {
const quotedText =
_selectedText
.split('\n')
.map((line) => `> ${line}`)
.join('\n') + '\n-------------'
setSelectedQuoteText(quotedText)
setContextMenuPosition({ x: e.clientX, y: e.clientY })
setSelectedText(_selectedText)
}
@@ -38,7 +45,7 @@ const ContextMenu: React.FC<ContextMenuProps> = ({ children, onContextMenu, styl
}, [])
// 获取右键菜单项
const getContextMenuItems = (t: (key: string) => string, selectedText: string) => [
const getContextMenuItems = (t: (key: string) => string, selectedQuoteText: string, selectedText: string) => [
{
key: 'copy',
label: t('common.copy'),
@@ -59,19 +66,19 @@ const ContextMenu: React.FC<ContextMenuProps> = ({ children, onContextMenu, styl
key: 'quote',
label: t('chat.message.quote'),
onClick: () => {
if (selectedText) {
window.api?.quoteToMainWindow(selectedText)
if (selectedQuoteText) {
EventEmitter.emit(EVENT_NAMES.QUOTE_TEXT, selectedQuoteText)
}
}
}
]
return (
<ContextContainer onContextMenu={handleContextMenu} className="context-menu-container" style={style}>
<ContextContainer onContextMenu={handleContextMenu} className="context-menu-container">
{contextMenuPosition && (
<Dropdown
overlayStyle={{ position: 'fixed', left: contextMenuPosition.x, top: contextMenuPosition.y, zIndex: 1000 }}
menu={{ items: getContextMenuItems(t, selectedText) }}
menu={{ items: getContextMenuItems(t, selectedQuoteText, selectedText) }}
open={true}
trigger={['contextMenu']}>
<div />

View File

@@ -1,141 +0,0 @@
import {
CopyOutlined,
DownloadOutlined,
FileImageOutlined,
RotateLeftOutlined,
RotateRightOutlined,
SwapOutlined,
UndoOutlined,
ZoomInOutlined,
ZoomOutOutlined
} from '@ant-design/icons'
import { download } from '@renderer/utils/download'
import { Dropdown, Image as AntImage, ImageProps as AntImageProps, Space } from 'antd'
import { Base64 } from 'js-base64'
import mime from 'mime'
import React from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
interface ImageViewerProps extends AntImageProps {
src: string
}
const ImageViewer: React.FC<ImageViewerProps> = ({ src, style, ...props }) => {
const { t } = useTranslation()
// 复制图片到剪贴板
const handleCopyImage = async (src: string) => {
try {
if (src.startsWith('data:')) {
// 处理 base64 格式的图片
const match = src.match(/^data:(image\/\w+);base64,(.+)$/)
if (!match) throw new Error('无效的 base64 图片格式')
const mimeType = match[1]
const byteArray = Base64.toUint8Array(match[2])
const blob = new Blob([byteArray], { type: mimeType })
await navigator.clipboard.write([new ClipboardItem({ [mimeType]: blob })])
} else if (src.startsWith('file://')) {
// 处理本地文件路径
const bytes = await window.api.fs.read(src)
const mimeType = mime.getType(src) || 'application/octet-stream'
const blob = new Blob([bytes], { type: mimeType })
await navigator.clipboard.write([
new ClipboardItem({
[mimeType]: blob
})
])
} else {
// 处理 URL 格式的图片
const response = await fetch(src)
const blob = await response.blob()
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
])
}
window.message.success(t('message.copy.success'))
} catch (error) {
console.error('复制图片失败:', error)
window.message.error(t('message.copy.failed'))
}
}
const getContextMenuItems = (src: string) => {
return [
{
key: 'copy-url',
label: t('common.copy'),
icon: <CopyOutlined />,
onClick: () => {
navigator.clipboard.writeText(src)
window.message.success(t('message.copy.success'))
}
},
{
key: 'download',
label: t('common.download'),
icon: <DownloadOutlined />,
onClick: () => download(src)
},
{
key: 'copy-image',
label: t('code_block.preview.copy.image'),
icon: <FileImageOutlined />,
onClick: () => handleCopyImage(src)
}
]
}
return (
<Dropdown menu={{ items: getContextMenuItems(src) }} trigger={['contextMenu']}>
<AntImage
src={src}
style={style}
{...props}
preview={{
mask: typeof props.preview === 'object' ? props.preview.mask : false,
toolbarRender: (
_,
{
transform: { scale },
actions: { onFlipY, onFlipX, onRotateLeft, onRotateRight, onZoomOut, onZoomIn, onReset }
}
) => (
<ToolbarWrapper size={12} className="toolbar-wrapper">
<SwapOutlined rotate={90} onClick={onFlipY} />
<SwapOutlined onClick={onFlipX} />
<RotateLeftOutlined onClick={onRotateLeft} />
<RotateRightOutlined onClick={onRotateRight} />
<ZoomOutOutlined disabled={scale === 1} onClick={onZoomOut} />
<ZoomInOutlined disabled={scale === 50} onClick={onZoomIn} />
<UndoOutlined onClick={onReset} />
<CopyOutlined onClick={() => handleCopyImage(src)} />
<DownloadOutlined onClick={() => download(src)} />
</ToolbarWrapper>
)
}}
/>
</Dropdown>
)
}
const ToolbarWrapper = styled(Space)`
padding: 0px 24px;
color: #fff;
font-size: 20px;
background-color: rgba(0, 0, 0, 0.1);
border-radius: 100px;
.anticon {
padding: 12px;
cursor: pointer;
}
.anticon:hover {
opacity: 0.3;
}
`
export default ImageViewer

View File

@@ -23,7 +23,8 @@ import { setMinappsOpenLinkExternal } from '@renderer/store/settings'
import { MinAppType } from '@renderer/types'
import { delay } from '@renderer/utils'
import { Avatar, Drawer, Tooltip } from 'antd'
import { WebviewTag } from 'electron'
// import { WebviewTag } from 'electron'
declare type WebviewTag = any
import { useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import BeatLoader from 'react-spinners/BeatLoader'

View File

@@ -1,4 +1,5 @@
import { WebviewTag } from 'electron'
// import { WebviewTag } from 'electron'
declare type WebviewTag = any
import { memo, useEffect, useRef } from 'react'
/**

View File

@@ -20,16 +20,10 @@ interface FileInfo {
name: string
}
const ObsidianProcessingMethod = {
APPEND: '1',
PREPEND: '2',
NEW_OR_OVERWRITE: '3'
} as const
interface PopupContainerProps {
title: string
obsidianTags: string | null
processingMethod: (typeof ObsidianProcessingMethod)[keyof typeof ObsidianProcessingMethod]
processingMethod: string | '3'
open: boolean
resolve: (success: boolean) => void
message?: Message
@@ -236,10 +230,10 @@ const PopupContainer: React.FC<PopupContainerProps> = ({
markdown = ''
}
let content = ''
if (state.processingMethod !== ObsidianProcessingMethod.NEW_OR_OVERWRITE) {
if (state.processingMethod !== '3') {
content = `\n---\n${markdown}`
} else {
content = `---\ntitle: ${state.title}\ncreated: ${state.createdAt}\nsource: ${state.source}\ntags: ${state.tags}\n---\n${markdown}`
content = `---\n\ntitle: ${state.title}\ncreated: ${state.createdAt}\nsource: ${state.source}\ntags: ${state.tags}\n---\n${markdown}`
}
if (content === '') {
window.message.error(i18n.t('chat.topics.export.obsidian_export_failed'))
@@ -286,9 +280,9 @@ const PopupContainer: React.FC<PopupContainerProps> = ({
const titleWithoutExt = fileName.endsWith('.md') ? fileName.substring(0, fileName.length - 3) : fileName
handleChange('title', titleWithoutExt)
setHasTitleBeenManuallyEdited(false)
handleChange('processingMethod', ObsidianProcessingMethod.APPEND)
handleChange('processingMethod', '1')
} else {
handleChange('processingMethod', ObsidianProcessingMethod.NEW_OR_OVERWRITE)
handleChange('processingMethod', '3')
if (!hasTitleBeenManuallyEdited) {
handleChange('title', title)
}
@@ -396,15 +390,9 @@ const PopupContainer: React.FC<PopupContainerProps> = ({
onChange={(value) => handleChange('processingMethod', value)}
placeholder={i18n.t('chat.topics.export.obsidian_operate_placeholder')}
allowClear>
<Option value={ObsidianProcessingMethod.APPEND}>
{i18n.t('chat.topics.export.obsidian_operate_append')}
</Option>
<Option value={ObsidianProcessingMethod.PREPEND}>
{i18n.t('chat.topics.export.obsidian_operate_prepend')}
</Option>
<Option value={ObsidianProcessingMethod.NEW_OR_OVERWRITE}>
{i18n.t('chat.topics.export.obsidian_operate_new_or_overwrite')}
</Option>
<Option value="1">{i18n.t('chat.topics.export.obsidian_operate_append')}</Option>
<Option value="2">{i18n.t('chat.topics.export.obsidian_operate_prepend')}</Option>
<Option value="3">{i18n.t('chat.topics.export.obsidian_operate_new_or_overwrite')}</Option>
</Select>
</Form.Item>
<Form.Item label={i18n.t('chat.topics.export.obsidian_reasoning')}>
@@ -415,4 +403,4 @@ const PopupContainer: React.FC<PopupContainerProps> = ({
)
}
export { ObsidianProcessingMethod, PopupContainer }
export { PopupContainer }

View File

@@ -1,11 +1,11 @@
import { ObsidianProcessingMethod, PopupContainer } from '@renderer/components/ObsidianExportDialog'
import { PopupContainer } from '@renderer/components/ObsidianExportDialog'
import { TopView } from '@renderer/components/TopView'
import type { Topic } from '@renderer/types'
import type { Message } from '@renderer/types/newMessage'
interface ObsidianExportOptions {
title: string
processingMethod: (typeof ObsidianProcessingMethod)[keyof typeof ObsidianProcessingMethod]
processingMethod: string | '3'
topic?: Topic
message?: Message
messages?: Message[]

View File

@@ -65,7 +65,7 @@ const TopViewContainer: React.FC<Props> = ({ children }) => {
const FullScreenContainer: React.FC<PropsWithChildren> = useCallback(({ children }) => {
return (
<Box flex={1} position="absolute" w="100%" h="100%" className="topview-fullscreen-container">
<Box flex={1} position="absolute" w="100%" h="100%">
<Box position="absolute" w="100%" h="100%" onClick={onPop} />
{children}
</Box>

View File

@@ -14,9 +14,9 @@ interface BackupFile {
interface WebdavConfig {
webdavHost: string
webdavUser?: string
webdavPass?: string
webdavPath?: string
webdavUser: string
webdavPass: string
webdavPath: string
}
interface WebdavBackupManagerProps {
@@ -47,7 +47,7 @@ export function WebdavBackupManager({ visible, onClose, webdavConfig, restoreMet
const { webdavHost, webdavUser, webdavPass, webdavPath } = webdavConfig
const fetchBackupFiles = useCallback(async () => {
if (!webdavHost) {
if (!webdavHost || !webdavUser || !webdavPass || !webdavPath) {
message.error(t('message.error.invalid.webdav'))
return
}
@@ -93,7 +93,7 @@ export function WebdavBackupManager({ visible, onClose, webdavConfig, restoreMet
return
}
if (!webdavHost) {
if (!webdavHost || !webdavUser || !webdavPass || !webdavPath) {
message.error(t('message.error.invalid.webdav'))
return
}
@@ -132,7 +132,7 @@ export function WebdavBackupManager({ visible, onClose, webdavConfig, restoreMet
}
const handleDeleteSingle = async (fileName: string) => {
if (!webdavHost) {
if (!webdavHost || !webdavUser || !webdavPass || !webdavPath) {
message.error(t('message.error.invalid.webdav'))
return
}
@@ -165,7 +165,7 @@ export function WebdavBackupManager({ visible, onClose, webdavConfig, restoreMet
}
const handleRestore = async (fileName: string) => {
if (!webdavHost) {
if (!webdavHost || !webdavUser || !webdavPass || !webdavPath) {
message.error(t('message.error.invalid.webdav'))
return
}

View File

@@ -123,7 +123,7 @@ export function useWebdavRestoreModal({
const [backupFiles, setBackupFiles] = useState<BackupFile[]>([])
const showRestoreModal = useCallback(async () => {
if (!webdavHost) {
if (!webdavHost || !webdavUser || !webdavPass || !webdavPath) {
window.message.error({ content: t('message.error.invalid.webdav'), key: 'webdav-error' })
return
}
@@ -146,7 +146,7 @@ export function useWebdavRestoreModal({
}, [webdavHost, webdavUser, webdavPass, webdavPath, t])
const handleRestore = useCallback(async () => {
if (!selectedFile || !webdavHost) {
if (!selectedFile || !webdavHost || !webdavUser || !webdavPass || !webdavPath) {
window.message.error({
content: !selectedFile ? t('message.error.no.file.selected') : t('message.error.invalid.webdav'),
key: 'restore-error'
@@ -170,7 +170,7 @@ export function useWebdavRestoreModal({
}
}
})
}, [selectedFile, webdavHost, t, restoreMethod])
}, [selectedFile, webdavHost, webdavUser, webdavPass, webdavPath, t, restoreMethod])
const handleCancel = () => {
setIsRestoreModalVisible(false)

View File

@@ -34,15 +34,6 @@ export const NavbarRight: FC<Props> = ({ children, ...props }) => {
)
}
export const NavbarMain: FC<Props> = ({ children, ...props }) => {
const isFullscreen = useFullscreen()
return (
<NavbarMainContainer {...props} $isFullscreen={isFullscreen}>
{children}
</NavbarMainContainer>
)
}
const NavbarContainer = styled.div`
min-width: 100%;
display: flex;
@@ -81,15 +72,3 @@ const NavbarRightContainer = styled.div<{ $isFullscreen: boolean }>`
padding-right: ${({ $isFullscreen }) => ($isFullscreen ? '12px' : isWindows ? '140px' : isLinux ? '120px' : '12px')};
justify-content: flex-end;
`
const NavbarMainContainer = styled.div<{ $isFullscreen: boolean }>`
flex: 1;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 0 ${isMac ? '20px' : 0};
font-weight: bold;
color: var(--color-text-1);
padding-right: ${({ $isFullscreen }) => ($isFullscreen ? '12px' : isWindows ? '140px' : isLinux ? '120px' : '12px')};
`

View File

@@ -1,5 +1,8 @@
import * as AppMeta from '../../../shared/app-meta'
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 APP_NAME = AppMeta.APP_NAME
export const APP_IS_CUSTOM_PRODUCT = AppMeta.APP_IS_CUSTOM_PRODUCT
export const isLocalAi = false

View File

@@ -140,8 +140,6 @@ import XirangModelLogo from '@renderer/assets/images/models/xirang.png'
import XirangModelLogoDark from '@renderer/assets/images/models/xirang_dark.png'
import YiModelLogo from '@renderer/assets/images/models/yi.png'
import YiModelLogoDark from '@renderer/assets/images/models/yi_dark.png'
import YoudaoLogo from '@renderer/assets/images/providers/netease-youdao.svg'
import NomicLogo from '@renderer/assets/images/providers/nomic.png'
import { getProviderByModel } from '@renderer/services/AssistantService'
import { Assistant, Model } from '@renderer/types'
import OpenAI from 'openai'
@@ -299,7 +297,7 @@ export function getModelLogo(modelId: string) {
'davinci-': isLight ? ChatGptModelLogo : ChatGptModelLogoDakr,
glm: isLight ? ChatGLMModelLogo : ChatGLMModelLogoDark,
deepseek: isLight ? DeepSeekModelLogo : DeepSeekModelLogoDark,
'(qwen|qwq|qwq-|qvq-)': isLight ? QwenModelLogo : QwenModelLogoDark,
'(qwen|qwq-|qvq-)': isLight ? QwenModelLogo : QwenModelLogoDark,
gemma: isLight ? GemmaModelLogo : GemmaModelLogoDark,
'yi-': isLight ? YiModelLogo : YiModelLogoDark,
llama: isLight ? LlamaModelLogo : LlamaModelLogoDark,
@@ -378,14 +376,12 @@ export function getModelLogo(modelId: string) {
'google/': isLight ? GoogleModelLogo : GoogleModelLogoDark,
xirang: isLight ? XirangModelLogo : XirangModelLogoDark,
hugging: isLight ? HuggingfaceModelLogo : HuggingfaceModelLogoDark,
youdao: YoudaoLogo,
embedding: isLight ? EmbeddingModelLogo : EmbeddingModelLogoDark,
perplexity: isLight ? PerplexityModelLogo : PerplexityModelLogoDark,
sonar: isLight ? PerplexityModelLogo : PerplexityModelLogoDark,
'bge-': BgeModelLogo,
'voyage-': VoyageModelLogo,
tokenflux: isLight ? TokenFluxModelLogo : TokenFluxModelLogoDark,
'nomic-': NomicLogo
tokenflux: isLight ? TokenFluxModelLogo : TokenFluxModelLogoDark
}
for (const key in logoMap) {
@@ -399,116 +395,6 @@ export function getModelLogo(modelId: string) {
}
export const SYSTEM_MODELS: Record<string, Model[]> = {
defaultModel: [
{
// 默认助手模型
id: 'deepseek-ai/DeepSeek-V3',
name: 'deepseek-ai/DeepSeek-V3',
provider: 'silicon',
group: 'deepseek-ai'
},
{
// 默认话题命名模型
id: 'Qwen/Qwen3-8B',
name: 'Qwen/Qwen3-8B',
provider: 'silicon',
group: 'Qwen'
},
{
// 默认翻译模型
id: 'deepseek-ai/DeepSeek-V3',
name: 'deepseek-ai/DeepSeek-V3',
provider: 'silicon',
group: 'deepseek-ai'
},
{
// 默认快捷助手模型
id: 'deepseek-ai/DeepSeek-V3',
name: 'deepseek-ai/DeepSeek-V3',
provider: 'silicon',
group: 'deepseek-ai'
}
],
'302ai': [
{
id: 'deepseek-chat',
name: 'deepseek-chat',
provider: '302ai',
group: 'DeepSeek'
},
{
id: 'deepseek-reasoner',
name: 'deepseek-reasoner',
provider: '302ai',
group: 'DeepSeek'
},
{
id: 'chatgpt-4o-latest',
name: 'chatgpt-4o-latest',
provider: '302ai',
group: 'OpenAI'
},
{
id: 'gpt-4.1',
name: 'gpt-4.1',
provider: '302ai',
group: 'OpenAI'
},
{
id: 'o3',
name: 'o3',
provider: '302ai',
group: 'OpenAI'
},
{
id: 'o4-mini',
name: 'o4-mini',
provider: '302ai',
group: 'OpenAI'
},
{
id: 'qwen3-235b-a22b',
name: 'qwen3-235b-a22b',
provider: '302ai',
group: 'Qwen'
},
{
id: 'gemini-2.5-flash-preview-05-20',
name: 'gemini-2.5-flash-preview-05-20',
provider: '302ai',
group: 'Gemini'
},
{
id: 'gemini-2.5-pro-preview-06-05',
name: 'gemini-2.5-pro-preview-06-05',
provider: '302ai',
group: 'Gemini'
},
{
id: 'claude-sonnet-4-20250514',
provider: '302ai',
name: 'claude-sonnet-4-20250514',
group: 'Anthropic'
},
{
id: 'claude-opus-4-20250514',
provider: '302ai',
name: 'claude-opus-4-20250514',
group: 'Anthropic'
},
{
id: 'jina-clip-v2',
name: 'jina-clip-v2',
provider: '302ai',
group: 'Jina AI'
},
{
id: 'jina-reranker-m0',
name: 'jina-reranker-m0',
provider: '302ai',
group: 'Jina AI'
}
],
aihubmix: [
{
id: 'gpt-4o',
@@ -714,17 +600,17 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
name: 'Qwen2.5-7B-Instruct',
group: 'Qwen'
},
{
id: 'meta-llama/Llama-3.3-70B-Instruct',
name: 'meta-llama/Llama-3.3-70B-Instruct',
provider: 'silicon',
group: 'meta-llama'
},
{
id: 'BAAI/bge-m3',
name: 'BAAI/bge-m3',
provider: 'silicon',
group: 'BAAI'
},
{
id: 'Qwen/Qwen3-8B',
name: 'Qwen/Qwen3-8B',
provider: 'silicon',
group: 'Qwen'
}
],
ppio: [
@@ -1823,6 +1709,24 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
name: 'ERNIE-Speed-128K',
group: '免费模型'
},
{
id: 'THUDM/glm-4-9b-chat',
provider: 'dmxapi',
name: 'THUDM/glm-4-9b-chat',
group: '免费模型'
},
{
id: 'glm-4-flash',
provider: 'dmxapi',
name: 'glm-4-flash',
group: '免费模型'
},
{
id: 'hunyuan-lite',
provider: 'dmxapi',
name: 'hunyuan-lite',
group: '免费模型'
},
{
id: 'gpt-4o',
provider: 'dmxapi',
@@ -2161,14 +2065,6 @@ export const SYSTEM_MODELS: Record<string, Model[]> = {
name: 'Qwen Plus',
group: 'Qwen'
}
],
cephalon: [
{
id: 'DeepSeek-R1',
provider: 'cephalon',
name: 'DeepSeek-R1满血版',
group: 'DeepSeek'
}
]
}
@@ -2735,8 +2631,7 @@ export function groupQwenModels(models: Model[]): Record<string, Model[]> {
export const THINKING_TOKEN_MAP: Record<string, { min: number; max: number }> = {
// Gemini models
'gemini-.*-flash.*$': { min: 0, max: 24576 },
'gemini-.*-pro.*$': { min: 128, max: 32768 },
'gemini-.*$': { min: 0, max: 24576 },
// Qwen models
'qwen-plus-.*$': { min: 0, max: 38912 },

View File

@@ -1,7 +1,6 @@
import ZhinaoProviderLogo from '@renderer/assets/images/models/360.png'
import HunyuanProviderLogo from '@renderer/assets/images/models/hunyuan.png'
import AzureProviderLogo from '@renderer/assets/images/models/microsoft.png'
import Ai302ProviderLogo from '@renderer/assets/images/providers/302ai.webp'
import AiHubMixProviderLogo from '@renderer/assets/images/providers/aihubmix.webp'
import AlayaNewProviderLogo from '@renderer/assets/images/providers/alayanew.webp'
import AnthropicProviderLogo from '@renderer/assets/images/providers/anthropic.png'
@@ -9,7 +8,6 @@ import BaichuanProviderLogo from '@renderer/assets/images/providers/baichuan.png
import BaiduCloudProviderLogo from '@renderer/assets/images/providers/baidu-cloud.svg'
import BailianProviderLogo from '@renderer/assets/images/providers/bailian.png'
import BurnCloudProviderLogo from '@renderer/assets/images/providers/burncloud.png'
import CephalonProviderLogo from '@renderer/assets/images/providers/cephalon.jpeg'
import DeepSeekProviderLogo from '@renderer/assets/images/providers/deepseek.png'
import DmxapiProviderLogo from '@renderer/assets/images/providers/DMXAPI.png'
import FireworksProviderLogo from '@renderer/assets/images/providers/fireworks.png'
@@ -50,7 +48,6 @@ import ZhipuProviderLogo from '@renderer/assets/images/providers/zhipu.png'
import { TOKENFLUX_HOST } from './constant'
const PROVIDER_LOGO_MAP = {
'302ai': Ai302ProviderLogo,
openai: OpenAiProviderLogo,
silicon: SiliconFlowProviderLogo,
deepseek: DeepSeekProviderLogo,
@@ -97,8 +94,7 @@ const PROVIDER_LOGO_MAP = {
alayanew: AlayaNewProviderLogo,
voyageai: VoyageAIProviderLogo,
qiniu: QiniuProviderLogo,
tokenflux: TokenFluxProviderLogo,
cephalon: CephalonProviderLogo
tokenflux: TokenFluxProviderLogo
} as const
export function getProviderLogo(providerId: string) {
@@ -110,17 +106,6 @@ export const NOT_SUPPORTED_REANK_PROVIDERS = ['ollama']
export const ONLY_SUPPORTED_DIMENSION_PROVIDERS = ['ollama', 'infini']
export const PROVIDER_CONFIG = {
'302ai': {
api: {
url: 'https://api.302.ai'
},
websites: {
official: 'https://302.ai',
apiKey: 'https://dash.302.ai/apis/list',
docs: 'https://302ai.apifox.cn/api-147522039',
models: 'https://302.ai/pricing/'
}
},
openai: {
api: {
url: 'https://api.openai.com'
@@ -184,7 +169,7 @@ export const PROVIDER_CONFIG = {
official: 'https://www.siliconflow.cn',
apiKey: 'https://cloud.siliconflow.cn/i/d1nTBKXU',
docs: 'https://docs.siliconflow.cn/',
models: 'https://cloud.siliconflow.cn/models'
models: 'https://docs.siliconflow.cn/docs/model-names'
}
},
'gitee-ai': {
@@ -627,16 +612,5 @@ export const PROVIDER_CONFIG = {
docs: `${TOKENFLUX_HOST}/docs`,
models: `${TOKENFLUX_HOST}/models`
}
},
cephalon: {
api: {
url: 'https://cephalon.cloud/user-center/v1/model'
},
websites: {
official: 'https://cephalon.cloud/share/register-landing?invite_id=jSdOYA',
apiKey: 'https://cephalon.cloud/api',
docs: 'https://cephalon.cloud/apitoken/1864244127731589124',
models: 'https://cephalon.cloud/model'
}
}
}

View File

@@ -281,6 +281,7 @@ export async function upgradeToV7(tx: Transaction): Promise<void> {
modelId: oldMessage.modelId,
model: oldMessage.model,
type: oldMessage.type === 'clear' ? 'clear' : undefined,
isPreset: oldMessage.isPreset,
useful: oldMessage.useful,
askId: oldMessage.askId,
mentions: oldMessage.mentions,

View File

@@ -4,7 +4,6 @@ import {
SendMessageShortcut,
setAssistantIconType,
setAutoCheckUpdate as _setAutoCheckUpdate,
setEarlyAccess as _setEarlyAccess,
setLaunchOnBoot,
setLaunchToTray,
setPinTopicsToTop,
@@ -20,7 +19,6 @@ import {
setWindowStyle
} from '@renderer/store/settings'
import { SidebarIcon, ThemeMode, TranslateLanguageVarious } from '@renderer/types'
import { FeedUrl } from '@shared/config/constant'
export function useSettings() {
const settings = useAppSelector((state) => state.settings)
@@ -60,11 +58,6 @@ export function useSettings() {
window.api.setAutoUpdate(isAutoUpdate)
},
setEarlyAccess(isEarlyAccess: boolean) {
dispatch(_setEarlyAccess(isEarlyAccess))
window.api.setFeedUrl(isEarlyAccess ? FeedUrl.EARLY_ACCESS : FeedUrl.PRODUCTION)
},
setTheme(theme: ThemeMode) {
dispatch(setTheme(theme))
},

View File

@@ -1,65 +1,27 @@
import { createSelector } from '@reduxjs/toolkit'
import { RootState, useAppDispatch, useAppSelector } from '@renderer/store'
import { setTagsOrder, updateAssistants } from '@renderer/store/assistants'
import { flatMap, groupBy, uniq } from 'lodash'
import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useAssistants } from './useAssistant'
// 基础选择器
const selectAssistantsState = (state: RootState) => state.assistants
// 记忆化 tagsOrder 选择器(自动处理默认值)--- 这是一个选择器,用于从 store 中获取 tagsOrder 的值。因为之前的tagsOrder是后面新加的不这样做会报错所以这里需要处理一下默认值
const selectTagsOrder = createSelector([selectAssistantsState], (assistants) => assistants.tagsOrder ?? [])
// 定义useTags的返回类型包含所有标签和获取特定标签的助手函数
// 为了不增加新的概念,标签直接作为助手的属性,所以这里的标签是指助手的标签属性
// 但是为了方便管理,增加了一个获取特定标签的助手函数
export const useTags = () => {
const { assistants } = useAssistants()
const { t } = useTranslation()
const dispatch = useAppDispatch()
const savedTagsOrder = useAppSelector(selectTagsOrder)
// 计算所有标签
const allTags = useMemo(() => {
const tags = uniq(flatMap(assistants, (assistant) => assistant.tags || []))
if (savedTagsOrder.length > 0) {
return [
...savedTagsOrder.filter((tag) => tags.includes(tag)),
...tags.filter((tag) => !savedTagsOrder.includes(tag))
]
}
return tags
}, [assistants, savedTagsOrder])
return uniq(flatMap(assistants, (assistant) => assistant.tags || []))
}, [assistants])
const getAssistantsByTag = useCallback(
(tag: string) => assistants.filter((assistant) => assistant.tags?.includes(tag)),
[assistants]
)
const updateTagsOrder = useCallback(
(newOrder: string[]) => {
dispatch(setTagsOrder(newOrder))
updateAssistants(
assistants.map((assistant) => {
if (!assistant.tags || assistant.tags.length === 0) {
return assistant
}
const newTags = [...assistant.tags]
newTags.sort((a, b) => {
return newOrder.indexOf(a) - newOrder.indexOf(b)
})
return {
...assistant,
tags: newTags
}
})
)
},
[assistants, dispatch]
)
const getGroupedAssistants = useMemo(() => {
// 按标签分组,处理多标签的情况
const assistantsByTags = flatMap(assistants, (assistant) => {
@@ -80,30 +42,12 @@ export const useTags = () => {
grouped.unshift(untagged)
}
// 根据savedTagsOrder对标签组进行排序
if (savedTagsOrder.length > 0) {
const untagged = grouped.length > 0 && grouped[0].tag === t('assistants.tags.untagged') ? grouped.shift() : null
grouped.sort((a, b) => {
const indexA = savedTagsOrder.indexOf(a.tag)
const indexB = savedTagsOrder.indexOf(b.tag)
if (indexA === -1 && indexB === -1) return 0
if (indexA === -1) return 1
if (indexB === -1) return -1
return indexA - indexB
})
if (untagged) {
grouped.unshift(untagged)
}
}
return grouped
}, [assistants, t, savedTagsOrder])
}, [assistants, t])
return {
allTags,
getAssistantsByTag,
getGroupedAssistants,
updateTagsOrder
getGroupedAssistants
}
}

View File

@@ -99,6 +99,8 @@ export const autoRenameTopic = async (assistant: Assistant, topicId: string) =>
const data = { ...topic, name: summaryText }
_setActiveTopic(data)
store.dispatch(updateTopic({ assistantId: assistant.id, topic: data }))
} else {
window.message?.error(i18n.t('message.error.fetchTopicName'))
}
}
} finally {

View File

@@ -8,10 +8,7 @@
"add.name.placeholder": "Enter name",
"add.prompt": "Prompt",
"add.prompt.placeholder": "Enter prompt",
"add.prompt.variables.tip": {
"title": "Available variables",
"content": "{{date}}:\tDate\n{{time}}:\tTime\n{{datetime}}:\tDate and time\n{{system}}:\tOperating system\n{{arch}}:\tCPU architecture\n{{language}}:\tLanguage\n{{model_name}}:\tModel name"
},
"add.prompt.variables.tip": "Available variables: {{date}}, {{time}}, {{datetime}}, {{system}}, {{arch}}, {{language}}, {{model_name}}",
"add.title": "Create Agent",
"import": {
"title": "Import from External",
@@ -33,7 +30,16 @@
"agent": "Export Agent"
},
"delete.popup.content": "Are you sure you want to delete this agent?",
"edit.message.add.title": "Add",
"edit.message.assistant.placeholder": "Enter assistant message",
"edit.message.assistant.title": "Assistant",
"edit.message.empty.content": "Conversation input content cannot be empty",
"edit.message.group.title": "Message Group",
"edit.message.title": "Preset messages",
"edit.message.user.placeholder": "Enter user message",
"edit.message.user.title": "User",
"edit.model.select.title": "Select Model",
"edit.settings.hide_preset_messages": "Hide Preset Message",
"edit.title": "Edit Agent",
"manage.title": "Manage Agents",
"my_agents": "My Agents",
@@ -70,6 +76,7 @@
"settings.mcp.noServersAvailable": "No MCP servers available. Add servers in settings",
"settings.mcp.description": "Default enabled MCP servers",
"settings.model": "Model Settings",
"settings.preset_messages": "Preset Messages",
"settings.prompt": "Prompt Settings",
"settings.reasoning_effort": "Reasoning effort",
"settings.reasoning_effort.off": "Off",
@@ -261,7 +268,6 @@
"topics.clear.title": "Clear Messages",
"topics.copy.image": "Copy as image",
"topics.copy.md": "Copy as markdown",
"topics.copy.plain_text": "Copy as plain text (remove Markdown)",
"topics.copy.title": "Copy",
"topics.delete.shortcut": "Hold {{key}} to delete directly",
"topics.edit.placeholder": "Enter new name",
@@ -566,12 +572,8 @@
"urls": "URLs",
"dimensions": "Embedding dimension",
"dimensions_size_tooltip": "The size of the embedding dimension; the larger the value, the larger the embedding dimension, but it also consumes more tokens.",
"dimensions_size_placeholder": " Embedding dimension size, e.g. 1024",
"dimensions_auto_set": "Auto-set embedding dimensions",
"dimensions_error_invalid": "Please enter embedding dimension size",
"dimensions_size_too_large": "The embedding dimension cannot exceed the model's context limit ({{max_context}}).",
"dimensions_set_right": "⚠️ Please ensure the model supports the set embedding dimension size",
"dimensions_default": "The model will use default embedding dimensions"
"dimensions_size_placeholder": "Default value (modification not recommended)",
"dimensions_size_too_large": "The embedding dimension cannot exceed the model's context limit ({{max_context}})."
},
"languages": {
"arabic": "Arabic",
@@ -948,10 +950,7 @@
"magic_prompt_option_tip": "Intelligently enhances upscaling prompts"
},
"text_desc_required": "Please enter image description first",
"image_handle_required": "Please upload an image first.",
"req_error_text": "Operation failed. Please try again. Avoid using 'copyrighted' or 'sensitive' words in your prompt.",
"req_error_token": "Please check the validity of the token",
"req_error_no_balance": "Please check the validity of the token",
"auto_create_paint": "Auto-create image",
"auto_create_paint_tip": "After the image is generated, a new image will be created automatically.",
"select_model": "Select Model",
@@ -978,7 +977,6 @@
"azure-openai": "Azure OpenAI",
"baichuan": "Baichuan",
"baidu-cloud": "Baidu Cloud",
"cephalon": "Cephalon",
"copilot": "GitHub Copilot",
"dashscope": "Alibaba Cloud",
"deepseek": "DeepSeek",
@@ -1019,8 +1017,7 @@
"zhipu": "ZHIPU AI",
"voyageai": "Voyage AI",
"qiniu": "Qiniu AI",
"tokenflux": "TokenFlux",
"302ai": "302.AI"
"tokenflux": "TokenFlux"
},
"restore": {
"confirm": "Are you sure you want to restore data?",
@@ -1348,8 +1345,6 @@
"general.emoji_picker": "Emoji Picker",
"general.image_upload": "Image Upload",
"general.auto_check_update.title": "Auto Update",
"general.early_access.title": "Early Access",
"general.early_access.tooltip": "Enable to use the latest version from GitHub, which may be slower. Please backup your data in advance.",
"general.reset.button": "Reset",
"general.reset.title": "Data Reset",
"general.restore.button": "Restore",
@@ -1519,7 +1514,6 @@
"messages.prompt": "Show prompt",
"messages.tokens": "Show token usage",
"messages.divider": "Show divider between messages",
"messages.divider.tooltip": "Not applicable to bubble-style message",
"messages.grid_columns": "Message grid display columns",
"messages.grid_popover_trigger": "Grid detail trigger",
"messages.grid_popover_trigger.click": "Click to display",
@@ -1552,7 +1546,6 @@
"models.add.model_id.select.placeholder": "Select Model",
"models.add.model_id.tooltip": "Example: gpt-3.5-turbo",
"models.add.model_name": "Model Name",
"models.add.model_name.tooltip": "Optional e.g. GPT-4",
"models.add.model_name.placeholder": "Optional e.g. GPT-4",
"models.check.all": "All",
"models.check.all_models_passed": "All models check passed",
@@ -1704,8 +1697,6 @@
"exit_fullscreen": "Exit Fullscreen",
"key": "Key",
"mini_window": "Quick Assistant",
"selection_assistant_toggle": "Toggle Selection Assistant",
"selection_assistant_select_text": "Selection Assistant: Select Text",
"new_topic": "New Topic",
"press_shortcut": "Press Shortcut",
"reset_defaults": "Reset Defaults",
@@ -1831,7 +1822,7 @@
"close": "Close",
"closed": "Translation closed",
"copied": "Translation content copied",
"detected.language": "Auto Detect",
"detected.language": "Detected Language",
"empty": "Translation content is empty",
"not.found": "Translation content not found",
"confirm": {
@@ -1893,8 +1884,7 @@
"summary": "Summarize",
"search": "Search",
"refine": "Refine",
"copy": "Copy",
"quote": "Quote"
"copy": "Copy"
},
"window": {
"pin": "Pin",
@@ -1922,15 +1912,10 @@
"title": "Toolbar",
"trigger_mode": {
"title": "Trigger Mode",
"description": "The way to trigger the selection assistant and show the toolbar",
"description_note": "Some applications do not support selecting text with the Ctrl key. If you have remapped the Ctrl key using tools like AHK, it may cause some applications to fail to select text.",
"description": "Show toolbar immediately when text is selected, or show only when Ctrl key is held after selection.",
"description_note": "The Ctrl key may not work in some apps. If you use AHK or other tools to remap the Ctrl key, it may not work.",
"selected": "Selection",
"selected_note": "Show toolbar immediately when text is selected",
"ctrlkey": "Ctrl Key",
"ctrlkey_note": "After selection, hold down the Ctrl key to show the toolbar",
"shortcut": "Shortcut",
"shortcut_note": "After selection, use shortcut to show the toolbar. Please set the shortcut in the shortcut settings page and enable it. ",
"shortcut_link": "Go to Shortcut Settings"
"ctrlkey": "Ctrl Key"
},
"compact_mode": {
"title": "Compact Mode",

View File

@@ -8,10 +8,7 @@
"add.name.placeholder": "名前を入力",
"add.prompt": "プロンプト",
"add.prompt.placeholder": "プロンプトを入力",
"add.prompt.variables.tip": {
"title": "利用可能な変数",
"content": "{{date}}:\t日付\n{{time}}:\t時間\n{{datetime}}:\t日付と時間\n{{system}}:\tオペレーティングシステム\n{{arch}}:\tCPUアーキテクチャ\n{{language}}:\t言語\n{{model_name}}:\tモデル名"
},
"add.prompt.variables.tip": "利用可能な変数:{{date}}, {{time}}, {{datetime}}, {{system}}, {{arch}}, {{language}}, {{model_name}}",
"add.title": "エージェントを作成",
"import": {
"title": "外部からインポート",
@@ -33,7 +30,16 @@
"agent": "エージェントをエクスポート"
},
"delete.popup.content": "このエージェントを削除してもよろしいですか?",
"edit.message.add.title": "追加",
"edit.message.assistant.placeholder": "アシスタントのメッセージを入力",
"edit.message.assistant.title": "アシスタント",
"edit.message.empty.content": "会話の入力内容が空です",
"edit.message.group.title": "メッセージグループ",
"edit.message.title": "プリセットメッセージ",
"edit.message.user.placeholder": "ユーザーメッセージを入力",
"edit.message.user.title": "ユーザー",
"edit.model.select.title": "モデルを選択",
"edit.settings.hide_preset_messages": "プリセットメッセージを非表示",
"edit.title": "エージェントを編集",
"manage.title": "エージェントを管理",
"my_agents": "マイエージェント",
@@ -70,6 +76,7 @@
"settings.default_model": "デフォルトモデル",
"settings.knowledge_base": "ナレッジベース設定",
"settings.model": "モデル設定",
"settings.preset_messages": "プリセットメッセージ",
"settings.prompt": "プロンプト設定",
"settings.reasoning_effort": "思考連鎖の長さ",
"settings.reasoning_effort.off": "オフ",
@@ -261,7 +268,6 @@
"topics.clear.title": "メッセージをクリア",
"topics.copy.image": "画像としてコピー",
"topics.copy.md": "Markdownとしてコピー",
"topics.copy.plain_text": "プレーンテキストとしてコピーMarkdownを除去",
"topics.copy.title": "コピー",
"topics.delete.shortcut": "{{key}}キーを押しながらで直接削除",
"topics.edit.placeholder": "新しい名前を入力",
@@ -566,12 +572,8 @@
"urls": "URL",
"dimensions": "埋め込み次元",
"dimensions_size_tooltip": "埋め込み次元のサイズは、数値が大きいほど埋め込み次元も大きくなりますが、消費するトークンも増えます。",
"dimensions_size_placeholder": " 埋め込み次元のサイズ1024",
"dimensions_auto_set": "埋め込み次元を自動設定",
"dimensions_error_invalid": "埋め込み次元のサイズを入力してください",
"dimensions_size_too_large": "埋め込み次元はモデルのコンテキスト制限({{max_context}})を超えてはなりません。",
"dimensions_set_right": "⚠️ モデルが設定した埋め込み次元のサイズをサポートしていることを確認してください",
"dimensions_default": "モデルはデフォルトの埋め込み次元を使用します"
"dimensions_size_placeholder": "デフォルト値(変更はお勧めしません",
"dimensions_size_too_large": "埋め込み次元はモデルのコンテキスト制限({{max_context}})を超えてはなりません。"
},
"languages": {
"arabic": "アラビア語",
@@ -633,6 +635,7 @@
"error.enter.api.key": "APIキーを入力してください",
"error.enter.model": "モデルを選択してください",
"error.enter.name": "ナレッジベース名を入力してください",
"error.fetchTopicName": "トピックの命名に失敗しました",
"error.get_embedding_dimensions": "埋込み次元を取得できませんでした",
"error.invalid.api.host": "無効なAPIアドレスです",
"error.invalid.api.key": "無効なAPIキーです",
@@ -703,8 +706,7 @@
"warn.siyuan.exporting": "思源ノートにエクスポート中です。重複してエクスポートしないでください!",
"error.yuque.no_config": "語雀のAPIアドレスまたはトークンが設定されていません",
"download.success": "ダウンロードに成功しました",
"download.failed": "ダウンロードに失敗しました",
"error.fetchTopicName": "トピック名の取得に失敗しました"
"download.failed": "ダウンロードに失敗しました"
},
"minapp": {
"popup": {
@@ -948,10 +950,7 @@
"rendering_speed": "レンダリング速度",
"translating": "翻訳中...",
"text_desc_required": "画像の説明を先に入力してください",
"image_handle_required": "最初に画像をアップロードしてください。",
"req_error_text": "実行に失敗しました。もう一度お試しください。プロンプトに「著作権用語」や「センシティブな用語」を含めないでください。",
"req_error_token": "トークンの有効性を確認してください",
"req_error_no_balance": "トークンの有効性を確認してください",
"auto_create_paint": "画像を自動作成",
"auto_create_paint_tip": "画像が生成された後、自動的に新しい画像が作成されます。",
"select_model": "モデルを選択",
@@ -1018,9 +1017,7 @@
"zhipu": "智譜AI",
"voyageai": "Voyage AI",
"qiniu": "七牛云 AI 推理",
"tokenflux": "TokenFlux",
"302ai": "302.AI",
"cephalon": "Cephalon"
"tokenflux": "TokenFlux"
},
"restore": {
"confirm": "データを復元しますか?",
@@ -1513,7 +1510,6 @@
"messages.prompt": "プロンプト表示",
"messages.tokens": "トークン使用量を表示",
"messages.divider": "メッセージ間に区切り線を表示",
"messages.divider.tooltip": "バブルスタイルのメッセージには適用されません",
"messages.grid_columns": "メッセージグリッドの表示列数",
"messages.grid_popover_trigger": "グリッド詳細トリガー",
"messages.grid_popover_trigger.click": "クリックで表示",
@@ -1546,8 +1542,7 @@
"models.add.model_id.select.placeholder": "モデルを選択",
"models.add.model_id.tooltip": "例gpt-3.5-turbo",
"models.add.model_name": "モデル名",
"models.add.model_name.tooltip": "例GPT-4",
"models.add.model_name.placeholder": "例GPT-4",
"models.add.model_name.placeholder": "例GPT-3.5",
"models.check.all": "すべて",
"models.check.all_models_passed": "すべてのモデルチェックが成功しました",
"models.check.button_caption": "健康チェック",
@@ -1692,8 +1687,6 @@
"exit_fullscreen": "フルスクリーンを終了",
"key": "キー",
"mini_window": "クイックアシスタント",
"selection_assistant_toggle": "選択アシスタントを切り替え",
"selection_assistant_select_text": "選択アシスタント:テキストを選択",
"new_topic": "新しいトピック",
"press_shortcut": "ショートカットを押す",
"reset_defaults": "デフォルトのショートカットをリセット",
@@ -1765,8 +1758,6 @@
"content_limit_tooltip": "検索結果の内容長を制限し、制限を超える内容は切り捨てられます。"
},
"general.auto_check_update.title": "自動更新",
"general.early_access.title": "早期アクセス",
"general.early_access.tooltip": "有効にすると、GitHub の最新バージョンを使用します。ダウンロード速度が遅く、不安定な場合があります。データを事前にバックアップしてください。",
"quickPhrase": {
"title": "クイックフレーズ",
"add": "フレーズを追加",
@@ -1864,7 +1855,7 @@
"menu": {
"description": "對當前輸入框內容進行翻譯"
},
"detected.language": "自動検出"
"detected.language": "検出された言語"
},
"tray": {
"quit": "終了",
@@ -1893,8 +1884,7 @@
"summary": "要約",
"search": "検索",
"refine": "最適化",
"copy": "コピー",
"quote": "引用"
"copy": "コピー"
},
"window": {
"pin": "最前面に固定",
@@ -1921,16 +1911,11 @@
"toolbar": {
"title": "ツールバー",
"trigger_mode": {
"title": "単語の取り出し方",
"description": "テキスト選択後、取詞ツールバーを表示する方法",
"description_note": "一部のアプリケーションでは、Ctrl キーでテキスト選択できません。AHK などのツールを使用して Ctrl キーをマップした場合、一部のアプリケーションでテキスト選択が失敗する可能性があります。",
"title": "表示方法",
"description": "テキスト選択時に即時表示、またはCtrlキー押下時のみ表示",
"description_note": "一部のアプリCtrlキーでテキスト選択に対応していません。AHKなどCtrlキーをマップすると、選択できなくなる場合があります。",
"selected": "選択時",
"selected_note": "テキスト選択時に即時表示",
"ctrlkey": "Ctrlキー",
"ctrlkey_note": "テキスト選択後、Ctrlキーを押下して表示",
"shortcut": "ショートカットキー",
"shortcut_note": "テキスト選択後、ショートカットキーを押下して表示。ショートカットキーを設定するには、ショートカット設定ページで有効にしてください。",
"shortcut_link": "ショートカット設定ページに移動"
"ctrlkey": "Ctrlキー"
},
"compact_mode": {
"title": "コンパクトモード",

View File

@@ -8,13 +8,19 @@
"add.name.placeholder": "Введите имя",
"add.prompt": "Промпт",
"add.prompt.placeholder": "Введите промпт",
"add.prompt.variables.tip": {
"title": "Доступные переменные",
"content": "{{date}}:\tДата\n{{time}}:\tВремя\n{{datetime}}:\tДата и время\n{{system}}:\tОперационная система\n{{arch}}:\tАрхитектура процессора\n{{language}}:\tЯзык\n{{model_name}}:\tНазвание модели"
},
"add.prompt.variables.tip": "Доступные переменные: {{date}}, {{time}}, {{datetime}}, {{system}}, {{arch}}, {{language}}, {{model_name}}",
"add.title": "Создать агента",
"delete.popup.content": "Вы уверены, что хотите удалить этого агента?",
"edit.message.add.title": "Добавить",
"edit.message.assistant.placeholder": "Введите сообщение ассистента",
"edit.message.assistant.title": "Ассистент",
"edit.message.empty.content": "Содержание вводимого сообщения не может быть пустым",
"edit.message.group.title": "Группа сообщений",
"edit.message.title": "Предустановленные сообщения",
"edit.message.user.placeholder": "Введите сообщение пользователя",
"edit.message.user.title": "Пользователь",
"edit.model.select.title": "Выбрать модель",
"edit.settings.hide_preset_messages": "Скрыть предустановленные сообщения",
"edit.title": "Редактировать агента",
"manage.title": "Редактировать агентов",
"my_agents": "Мои агенты",
@@ -70,6 +76,7 @@
"settings.default_model": "Модель по умолчанию",
"settings.knowledge_base": "Настройки базы знаний",
"settings.model": "Настройки модели",
"settings.preset_messages": "Предустановленные сообщения",
"settings.prompt": "Настройки промптов",
"settings.reasoning_effort.off": "Выключить",
"settings.reasoning_effort.high": "Стараюсь думать",
@@ -261,7 +268,6 @@
"topics.clear.title": "Очистить сообщения",
"topics.copy.image": "Скопировать как изображение",
"topics.copy.md": "Скопировать как Markdown",
"topics.copy.plain_text": "Копировать как обычный текст (удалить Markdown)",
"topics.copy.title": "Скопировать",
"topics.delete.shortcut": "Удерживайте {{key}} для мгновенного удаления",
"topics.edit.placeholder": "Введите новый заголовок",
@@ -566,12 +572,8 @@
"urls": "URL-адреса",
"dimensions": "векторное пространство",
"dimensions_size_tooltip": "Размерность вложения, чем больше значение, тем больше размерность вложения, но и потребляемых токенов также становится больше.",
"dimensions_size_placeholder": " Размерность эмбеддинга, например 1024",
"dimensions_auto_set": "Автоматическая установка размерности эмбеддинга",
"dimensions_error_invalid": "Пожалуйста, введите размерность эмбеддинга",
"dimensions_size_too_large": "Размерность вложения не может превышать ограничение контекста модели ({{max_context}})",
"dimensions_set_right": "⚠️ Убедитесь, что модель поддерживает заданный размер эмбеддинга",
"dimensions_default": "Модель будет использовать размер эмбеддинга по умолчанию"
"dimensions_size_placeholder": "Значение по умолчанию (не рекомендуется изменять)",
"dimensions_size_too_large": "Размерность вложения не может превышать ограничение контекста модели ({{max_context}})"
},
"languages": {
"arabic": "Арабский",
@@ -633,6 +635,7 @@
"error.enter.api.key": "Пожалуйста, введите ваш API ключ",
"error.enter.model": "Пожалуйста, выберите модель",
"error.enter.name": "Пожалуйста, введите название базы знаний",
"error.fetchTopicName": "Не удалось назвать тему",
"error.get_embedding_dimensions": "Не удалось получить размерность встраивания",
"error.invalid.api.host": "Неверный API адрес",
"error.invalid.api.key": "Неверный API ключ",
@@ -703,8 +706,7 @@
"warn.yuque.exporting": "Экспортируется в Yuque, пожалуйста, не отправляйте повторные запросы!",
"warn.siyuan.exporting": "Экспортируется в Siyuan, пожалуйста, не отправляйте повторные запросы!",
"download.success": "Скачано успешно",
"download.failed": "Скачивание не удалось",
"error.fetchTopicName": "Не удалось назвать топик"
"download.failed": "Скачивание не удалось"
},
"minapp": {
"popup": {
@@ -948,10 +950,7 @@
"magic_prompt_option_tip": "Улучшает увеличение изображений с помощью интеллектуального оптимизирования промптов"
},
"text_desc_required": "Пожалуйста, сначала введите описание изображения",
"image_handle_required": "Пожалуйста, сначала загрузите изображение.",
"req_error_text": "Операция не удалась, повторите попытку. Пожалуйста, избегайте защищенных авторским правом терминов и конфиденциальных слов в запросах.",
"req_error_token": "Пожалуйста, проверьте действительность токена",
"req_error_no_balance": "Пожалуйста, проверьте действительность токена",
"auto_create_paint": "Автоматическое создание изображения",
"auto_create_paint_tip": "После генерации изображения будет автоматически создано новое.",
"select_model": "Выбрать модель",
@@ -978,7 +977,6 @@
"azure-openai": "Azure OpenAI",
"baichuan": "Baichuan",
"baidu-cloud": "Baidu Cloud",
"cephalon": "Cephalon",
"copilot": "GitHub Copilot",
"dashscope": "Alibaba Cloud",
"deepseek": "DeepSeek",
@@ -1019,8 +1017,7 @@
"zhipu": "ZHIPU AI",
"voyageai": "Voyage AI",
"qiniu": "Qiniu AI",
"tokenflux": "TokenFlux",
"302ai": "302.AI"
"tokenflux": "TokenFlux"
},
"restore": {
"confirm": "Вы уверены, что хотите восстановить данные?",
@@ -1513,7 +1510,6 @@
"messages.prompt": "Показывать подсказки",
"messages.tokens": "Показать использование токенов",
"messages.divider": "Показывать разделитель между сообщениями",
"messages.divider.tooltip": "Не применимо к сообщениям в стиле пузырей",
"messages.grid_columns": "Количество столбцов сетки сообщений",
"messages.grid_popover_trigger": "Триггер для отображения подробной информации в сетке",
"messages.grid_popover_trigger.click": "Нажатие для отображения",
@@ -1546,7 +1542,6 @@
"models.add.model_id.select.placeholder": "Выберите модель",
"models.add.model_id.tooltip": "Пример: gpt-3.5-turbo",
"models.add.model_name": "Имя модели",
"models.add.model_name.tooltip": "Необязательно, например, GPT-4",
"models.add.model_name.placeholder": "Необязательно, например, GPT-4",
"models.check.all": "Все",
"models.check.all_models_passed": "Все модели прошли проверку",
@@ -1692,8 +1687,6 @@
"exit_fullscreen": "Выйти из полноэкранного режима",
"key": "Клавиша",
"mini_window": "Быстрый помощник",
"selection_assistant_toggle": "Переключить помощник выделения",
"selection_assistant_select_text": "Помощник выделения: выделить текст",
"new_topic": "Новый топик",
"press_shortcut": "Нажмите сочетание клавиш",
"reset_defaults": "Сбросить настройки по умолчанию",
@@ -1764,9 +1757,7 @@
"content_limit": "Ограничение длины текста",
"content_limit_tooltip": "Ограничьте длину содержимого результатов поиска, контент, превышающий ограничение, будет обрезан."
},
"general.auto_check_update.title": "Автоматическое обновление",
"general.early_access.title": "Ранний доступ",
"general.early_access.tooltip": "Включить для использования последней версии из GitHub, что может быть медленнее и нестабильно. Пожалуйста, сделайте резервную копию данных заранее.",
"general.auto_check_update.title": "Включить автообновление",
"quickPhrase": {
"title": "Быстрые фразы",
"add": "Добавить фразу",
@@ -1864,7 +1855,7 @@
"menu": {
"description": "Перевести содержимое текущего ввода"
},
"detected.language": "Автоматическое обнаружение"
"detected.language": "Обнаруженный язык"
},
"tray": {
"quit": "Выйти",
@@ -1893,8 +1884,7 @@
"summary": "Суммаризировать",
"search": "Поиск",
"refine": "Уточнить",
"copy": "Копировать",
"quote": "Цитировать"
"copy": "Копировать"
},
"window": {
"pin": "Закрепить",
@@ -1922,15 +1912,10 @@
"title": "Панель инструментов",
"trigger_mode": {
"title": "Режим активации",
"description": "Показывать панель сразу при выделении, или только при удержании Ctrl, или только при нажатии на сочетание клавиш",
"description": "Показывать панель сразу при выделении или только при удержании Ctrl.",
"description_note": "В некоторых приложениях Ctrl может не работать. Если вы используете AHK или другие инструменты для переназначения Ctrl, это может привести к тому, что некоторые приложения не смогут выделить текст.",
"selected": "При выделении",
"selected_note": "После выделения",
"ctrlkey": "По Ctrl",
"ctrlkey_note": "После выделения, удерживайте Ctrl для показа панели. Пожалуйста, установите Ctrl в настройках клавиатуры и активируйте его.",
"shortcut": "По сочетанию клавиш",
"shortcut_note": "После выделения, используйте сочетание клавиш для показа панели. Пожалуйста, установите сочетание клавиш в настройках клавиатуры и активируйте его.",
"shortcut_link": "Перейти к настройкам клавиатуры"
"ctrlkey": "По Ctrl"
},
"compact_mode": {
"title": "Компактный режим",

View File

@@ -8,10 +8,7 @@
"add.name.placeholder": "输入名称",
"add.prompt": "提示词",
"add.prompt.placeholder": "输入提示词",
"add.prompt.variables.tip": {
"title": "可用的变量",
"content": "{{date}}:\t日期\n{{time}}:\t时间\n{{datetime}}:\t日期和时间\n{{system}}:\t操作系统\n{{arch}}:\tCPU架构\n{{language}}:\t语言\n{{model_name}}:\t模型名称"
},
"add.prompt.variables.tip": "可用的变量:{{date}}, {{time}}, {{datetime}}, {{system}}, {{arch}}, {{language}}, {{model_name}}",
"add.title": "创建智能体",
"import": {
"title": "从外部导入",
@@ -33,7 +30,16 @@
"agent": "导出智能体"
},
"delete.popup.content": "确定要删除此智能体吗?",
"edit.message.add.title": "添加",
"edit.message.assistant.placeholder": "输入助手消息",
"edit.message.assistant.title": "助手",
"edit.message.empty.content": "会话输入内容不能为空",
"edit.message.group.title": "消息组",
"edit.message.title": "预设消息",
"edit.message.user.placeholder": "输入用户消息",
"edit.message.user.title": "用户",
"edit.model.select.title": "选择模型",
"edit.settings.hide_preset_messages": "隐藏预设消息",
"edit.title": "编辑智能体",
"manage.title": "管理智能体",
"my_agents": "我的智能体",
@@ -77,6 +83,7 @@
"settings.tool_use_mode.function": "函数",
"settings.tool_use_mode.prompt": "提示词",
"settings.model": "模型设置",
"settings.preset_messages": "预设消息",
"settings.prompt": "提示词设置",
"settings.reasoning_effort": "思维链长度",
"settings.reasoning_effort.off": "关闭",
@@ -279,7 +286,6 @@
"topics.clear.title": "清空消息",
"topics.copy.image": "复制为图片",
"topics.copy.md": "复制为 Markdown",
"topics.copy.plain_text": "复制为纯文本(去除 Markdown",
"topics.copy.title": "复制",
"topics.delete.shortcut": "按住 {{key}} 可直接删除",
"topics.edit.placeholder": "输入新名称",
@@ -519,11 +525,7 @@
"delete_confirm": "确定要删除此知识库吗?",
"dimensions": "嵌入维度",
"dimensions_size_tooltip": "嵌入维度大小,数值越大,嵌入维度越大,但消耗的 Token 也越多",
"dimensions_set_right": "⚠️ 请确保模型支持所设置的嵌入维度大小",
"dimensions_default": "模型将使用默认嵌入维度",
"dimensions_size_placeholder": " 嵌入维度大小,如 1024",
"dimensions_auto_set": "自动设置嵌入维度",
"dimensions_error_invalid": "请输入嵌入维度大小",
"dimensions_size_placeholder": " 默认值(不建议修改)",
"dimensions_size_too_large": "嵌入维度不能超过模型上下文限制({{max_context}}",
"directories": "目录",
"directory_placeholder": "请输入目录路径",
@@ -949,9 +951,6 @@
},
"text_desc_required": "请先输入图片描述",
"req_error_text": "运行失败,请重试。提示词避免“版权词”和”敏感词”哦。",
"req_error_token": "请检查令牌有效性",
"req_error_no_balance": "请检查令牌有效性",
"image_handle_required": "请先上传图片",
"auto_create_paint": "自动新建图片",
"auto_create_paint_tip": "在图片生成后,会自动新建图片",
"select_model": "选择模型",
@@ -978,7 +977,6 @@
"azure-openai": "Azure OpenAI",
"baichuan": "百川",
"baidu-cloud": "百度云千帆",
"cephalon": "Cephalon",
"copilot": "GitHub Copilot",
"dashscope": "阿里云百炼",
"deepseek": "深度求索",
@@ -1019,8 +1017,7 @@
"zhipu": "智谱AI",
"voyageai": "Voyage AI",
"qiniu": "七牛云 AI 推理",
"tokenflux": "TokenFlux",
"302ai": "302.AI"
"tokenflux": "TokenFlux"
},
"restore": {
"confirm": "确定要恢复数据吗?",
@@ -1348,8 +1345,6 @@
"general.emoji_picker": "表情选择器",
"general.image_upload": "图片上传",
"general.auto_check_update.title": "自动更新",
"general.early_access.title": "抢先体验",
"general.early_access.tooltip": "开启后,将使用 GitHub 的最新版本,下载速度可能较慢,请务必提前备份数据",
"general.reset.button": "重置",
"general.reset.title": "重置数据",
"general.restore.button": "恢复",
@@ -1519,7 +1514,6 @@
"messages.prompt": "显示提示词",
"messages.tokens": "显示Token用量",
"messages.divider": "消息分割线",
"messages.divider.tooltip": "不适用于气泡样式消息",
"messages.grid_columns": "消息网格展示列数",
"messages.grid_popover_trigger": "网格详情触发",
"messages.grid_popover_trigger.click": "点击显示",
@@ -1552,8 +1546,7 @@
"models.add.model_id.select.placeholder": "选择模型",
"models.add.model_id.tooltip": "例如 gpt-3.5-turbo",
"models.add.model_name": "模型名称",
"models.add.model_name.placeholder": "例如 GPT-4",
"models.add.model_name.tooltip": "例如 GPT-4",
"models.add.model_name.placeholder": "例如 GPT-3.5",
"models.check.all": "所有",
"models.check.all_models_passed": "所有模型检测通过",
"models.check.button_caption": "健康检测",
@@ -1704,8 +1697,6 @@
"exit_fullscreen": "退出全屏",
"key": "按键",
"mini_window": "快捷助手",
"selection_assistant_toggle": "开关划词助手",
"selection_assistant_select_text": "划词助手:取词",
"new_topic": "新建话题",
"press_shortcut": "按下快捷键",
"reset_defaults": "重置默认快捷键",
@@ -1715,7 +1706,7 @@
"search_message_in_chat": "在当前对话中搜索消息",
"show_app": "显示/隐藏应用",
"show_settings": "打开设置",
"title": "快捷",
"title": "快捷方式",
"toggle_new_context": "清除上下文",
"toggle_show_assistants": "切换助手显示",
"toggle_show_topics": "切换话题显示",
@@ -1864,7 +1855,7 @@
},
"title": "翻译",
"tooltip.newline": "换行",
"detected.language": "自动检测"
"detected.language": "检测到的语言"
},
"tray": {
"quit": "退出",
@@ -1893,8 +1884,7 @@
"summary": "总结",
"search": "搜索",
"refine": "优化",
"copy": "复制",
"quote": "引用"
"copy": "复制"
},
"window": {
"pin": "置顶",
@@ -1921,16 +1911,11 @@
"toolbar": {
"title": "工具栏",
"trigger_mode": {
"title": "取词方式",
"description": "划词后,触发取词并显示工具栏的方式",
"title": "触发方式",
"description": "划词立即显示工具栏,或者划词后按住 Ctrl 键才显示工具栏",
"description_note": "少数应用不支持通过 Ctrl 键划词。若使用了AHK等工具对 Ctrl 键进行了重映射,可能导致部分应用无法划词。",
"selected": "划词",
"selected_note": "划词后立即显示工具栏",
"ctrlkey": "Ctrl 键",
"ctrlkey_note": "划词后,再 按住 Ctrl键才显示工具栏",
"shortcut": "快捷键",
"shortcut_note": "划词后,使用快捷键显示工具栏。请在快捷键设置页面中设置取词快捷键并启用。",
"shortcut_link": "前往快捷键设置"
"ctrlkey": "Ctrl 键"
},
"compact_mode": {
"title": "紧凑模式",

View File

@@ -8,10 +8,7 @@
"add.name.placeholder": "輸入名稱",
"add.prompt": "提示詞",
"add.prompt.placeholder": "輸入提示詞",
"add.prompt.variables.tip": {
"title": "可用的變數",
"content": "{{date}}:\t日期\n{{time}}:\t時間\n{{datetime}}:\t日期和時間\n{{system}}:\t作業系統\n{{arch}}:\tCPU架構\n{{language}}:\t語言\n{{model_name}}:\t模型名稱"
},
"add.prompt.variables.tip": "可用的變數:{{date}}, {{time}}, {{datetime}}, {{system}}, {{arch}}, {{language}}, {{model_name}}",
"add.title": "建立智慧代理人",
"import": {
"title": "從外部導入",
@@ -33,7 +30,16 @@
"agent": "匯出智慧代理人"
},
"delete.popup.content": "確定要刪除此智慧代理人嗎?",
"edit.message.add.title": "新增",
"edit.message.assistant.placeholder": "輸入助手訊息",
"edit.message.assistant.title": "助手",
"edit.message.empty.content": "會話輸入內容不能為空",
"edit.message.group.title": "訊息分組",
"edit.message.title": "預設訊息",
"edit.message.user.placeholder": "輸入使用者訊息",
"edit.message.user.title": "使用者",
"edit.model.select.title": "選擇模型",
"edit.settings.hide_preset_messages": "隱藏預設訊息",
"edit.title": "編輯智慧代理人",
"manage.title": "管理智慧代理人",
"my_agents": "我的智慧代理人",
@@ -70,6 +76,7 @@
"settings.default_model": "預設模型",
"settings.knowledge_base": "知識庫設定",
"settings.model": "模型設定",
"settings.preset_messages": "預設訊息",
"settings.prompt": "提示詞設定",
"settings.reasoning_effort": "思維鏈長度",
"settings.reasoning_effort.off": "關閉",
@@ -261,7 +268,6 @@
"topics.clear.title": "清空訊息",
"topics.copy.image": "複製為圖片",
"topics.copy.md": "複製為 Markdown",
"topics.copy.plain_text": "複製為純文字(移除 Markdown",
"topics.copy.title": "複製",
"topics.delete.shortcut": "按住 {{key}} 可直接刪除",
"topics.edit.placeholder": "輸入新名稱",
@@ -566,12 +572,8 @@
"urls": "網址",
"dimensions": "嵌入維度",
"dimensions_size_tooltip": "嵌入維度大小,數值越大,嵌入維度越大,但消耗的 Token 也越多",
"dimensions_size_placeholder": " 嵌入維度大小,例如 1024",
"dimensions_auto_set": "自動設定嵌入維度",
"dimensions_error_invalid": "請輸入嵌入維度大小",
"dimensions_size_too_large": "嵌入維度不能超過模型上下文限制({{max_context}}",
"dimensions_set_right": "⚠️ 請確保模型支援所設置的嵌入維度大小",
"dimensions_default": "模型將使用預設嵌入維度"
"dimensions_size_placeholder": "預設值(不建議修改)",
"dimensions_size_too_large": "嵌入維度不能超過模型上下文限制({{max_context}}"
},
"languages": {
"arabic": "阿拉伯文",
@@ -948,10 +950,7 @@
},
"rendering_speed": "渲染速度",
"text_desc_required": "請先輸入圖片描述",
"image_handle_required": "請先上傳圖片。",
"req_error_text": "运行失败,请重试。提示词避免“版权词”和”敏感词”哦。",
"req_error_token": "請檢查令牌的有效性",
"req_error_no_balance": "請檢查令牌的有效性",
"auto_create_paint": "自動新增圖片",
"auto_create_paint_tip": "圖片生成後,會自動新增圖片",
"select_model": "選擇模型",
@@ -978,7 +977,6 @@
"azure-openai": "Azure OpenAI",
"baichuan": "百川",
"baidu-cloud": "百度雲千帆",
"cephalon": "Cephalon",
"copilot": "GitHub Copilot",
"dashscope": "阿里雲百鍊",
"deepseek": "深度求索",
@@ -1019,8 +1017,7 @@
"zhipu": "智譜 AI",
"voyageai": "Voyage AI",
"qiniu": "七牛雲 AI 推理",
"tokenflux": "TokenFlux",
"302ai": "302.AI"
"tokenflux": "TokenFlux"
},
"restore": {
"confirm": "確定要復原資料嗎?",
@@ -1516,7 +1513,6 @@
"messages.prompt": "提示詞顯示",
"messages.tokens": "Token用量顯示",
"messages.divider": "訊息間顯示分隔線",
"messages.divider.tooltip": "不適用於氣泡樣式消息",
"messages.grid_columns": "訊息網格展示列數",
"messages.grid_popover_trigger": "網格詳細資訊觸發",
"messages.grid_popover_trigger.click": "點選顯示",
@@ -1550,7 +1546,6 @@
"models.add.model_id.tooltip": "例如 gpt-3.5-turbo",
"models.add.model_name": "模型名稱",
"models.add.model_name.placeholder": "選填,例如 GPT-4",
"models.add.model_name.tooltip": "例如 GPT-4",
"models.check.all": "所有",
"models.check.all_models_passed": "所有模型檢查通過",
"models.check.button_caption": "健康檢查",
@@ -1694,8 +1689,6 @@
"copy_last_message": "複製上一則訊息",
"key": "按鍵",
"mini_window": "快捷助手",
"selection_assistant_toggle": "開關劃詞助手",
"selection_assistant_select_text": "劃詞助手:取词",
"new_topic": "新增話題",
"press_shortcut": "按下快捷鍵",
"reset_defaults": "重設預設快捷鍵",
@@ -1705,7 +1698,7 @@
"search_message_in_chat": "在當前對話中搜尋訊息",
"show_app": "顯示/隱藏應用程式",
"show_settings": "開啟設定",
"title": "快捷鍵",
"title": "快速方式",
"toggle_new_context": "清除上下文",
"toggle_show_assistants": "切換助手顯示",
"toggle_show_topics": "切換話題顯示",
@@ -1767,9 +1760,7 @@
"content_limit": "內容長度限制",
"content_limit_tooltip": "限制搜尋結果的內容長度,超過限制的內容將被截斷"
},
"general.auto_check_update.title": "自動更新",
"general.early_access.title": "搶先體驗",
"general.early_access.tooltip": "開啟後,將使用 GitHub 的最新版本,下載速度可能較慢,請務必提前備份數據",
"general.auto_check_update.title": "啟用自動更新",
"quickPhrase": {
"title": "快捷短語",
"add": "新增短語",
@@ -1864,7 +1855,7 @@
"menu": {
"description": "對當前輸入框內容進行翻譯"
},
"detected.language": "自動檢測"
"detected.language": "檢測到的語言"
},
"tray": {
"quit": "結束",
@@ -1893,8 +1884,7 @@
"summary": "總結",
"search": "搜尋",
"refine": "優化",
"copy": "複製",
"quote": "引用"
"copy": "複製"
},
"window": {
"pin": "置頂",
@@ -1921,16 +1911,11 @@
"toolbar": {
"title": "工具列",
"trigger_mode": {
"title": "取詞方式",
"description": "劃詞後,觸發取詞並顯示工具列的方式",
"title": "觸發方式",
"description": "劃詞立即顯示工具列,或者劃詞後按住 Ctrl 鍵才顯示工具列",
"description_note": "在某些應用中可能無法透過 Ctrl 鍵劃詞。若使用了AHK等工具對Ctrl鍵進行了重新對應可能導致部分應用程式無法劃詞。",
"selected": "劃詞",
"selected_note": "劃詞後,立即顯示工具列",
"ctrlkey": "Ctrl 鍵",
"ctrlkey_note": "劃詞後,再 按住 Ctrl鍵才顯示工具列",
"shortcut": "快捷鍵",
"shortcut_note": "劃詞後,使用快捷鍵顯示工具列。請在快捷鍵設定頁面中設置取詞快捷鍵並啟用。",
"shortcut_link": "前往快捷鍵設定"
"ctrlkey": "Ctrl 鍵"
},
"compact_mode": {
"title": "緊湊模式",

View File

@@ -8,13 +8,18 @@
"add.name.placeholder": "Εισαγάγετε όνομα",
"add.prompt": "Φράση προκαλέσεως",
"add.prompt.placeholder": "Εισαγάγετε φράση προκαλέσεως",
"add.prompt.variables.tip": {
"title": "Διαθέσιμες μεταβλητές",
"content": "{{date}}:\tΗμερομηνία\n{{time}}:\tΏρα\n{{datetime}}:\tΗμερομηνία και ώρα\n{{system}}:\tΛειτουργικό σύστημα\n{{arch}}:\tΑρχιτεκτονική CPU\n{{language}}:\tΓλώσσα\n{{model_name}}:\tΌνομα μοντέλου"
},
"add.title": "Δημιουργία νέου ειδικού",
"delete.popup.content": "Είστε σίγουροι ότι θέλετε να διαγράψετε αυτόν τον ειδικό;",
"edit.message.add.title": "Προσθήκη",
"edit.message.assistant.placeholder": "Εισαγάγετε μήνυμα βοηθού",
"edit.message.assistant.title": "Βοηθός",
"edit.message.empty.content": "Το περιεχόμενο του συνομιλητή δεν μπορεί να είναι κενό.",
"edit.message.group.title": "Ομάδα μηνυμάτων",
"edit.message.title": "Προεπιλογές μηνυμάτων",
"edit.message.user.placeholder": "Εισαγάγετε μήνυμα χρήστη",
"edit.message.user.title": "Χρήστης",
"edit.model.select.title": "Επιλογή μοντέλου",
"edit.settings.hide_preset_messages": "Απόκρυψη προεπιλογών μηνυμάτων",
"edit.title": "Επεξεργασία ειδικού",
"manage.title": "Διαχείριση ειδικών",
"my_agents": "Οι ειδικοί μου",
@@ -59,6 +64,7 @@
"settings.default_model": "Προεπιλεγμένο μοντέλο",
"settings.knowledge_base": "Ρυθμίσεις βάσης γνώσεων",
"settings.model": "Ρυθμίσεις μοντέλου",
"settings.preset_messages": "Προεπιλεγμένα μηνύματα",
"settings.prompt": "Ρυθμίσεις προκαλύμματος",
"settings.reasoning_effort": "Μήκος λογισμικού αλυσίδας",
"settings.reasoning_effort.high": "Μεγάλο",
@@ -198,7 +204,6 @@
"topics.clear.title": "Καθαρισμός μηνυμάτων",
"topics.copy.image": "Αντιγραφή ως εικόνα",
"topics.copy.md": "Αντιγραφή ως Markdown",
"topics.copy.plain_text": "Αντιγραφή ως απλό κείμενο (αφαίρεση Markdown)",
"topics.copy.title": "Αντιγραφή",
"topics.delete.shortcut": "Πατήστε {{key}} για να διαγράψετε αμέσως",
"topics.edit.placeholder": "Εισαγάγετε το νέο όνομα",
@@ -491,12 +496,8 @@
"urls": "Διευθύνσεις",
"dimensions": "Διαστάσεις ενσωμάτωσης",
"dimensions_size_tooltip": "Το μέγεθος των διαστάσεων ενσωμάτωσης. Όσο μεγαλύτερη η τιμή, τόσο περισσότερες οι διαστάσεις ενσωμάτωσης, αλλά και οι απαιτούμενες μονάδες (Tokens).",
"dimensions_size_placeholder": " Μέγεθος διαστάσεων ενσωμάτωσης, π.χ. 1024",
"dimensions_auto_set": "Αυτόματη ρύθμιση διαστάσεων ενσωμάτωσης",
"dimensions_error_invalid": "Παρακαλώ εισάγετε μέγεθος διαστάσεων ενσωμάτωσης",
"dimensions_size_too_large": "Οι διαστάσεις ενσωμάτωσης δεν μπορούν να υπερβούν το όριο περιεχομένου του μοντέλου ({{max_context}})",
"dimensions_set_right": "⚠️ Βεβαιωθείτε ότι το μοντέλο υποστηρίζει το καθορισμένο μέγεθος διαστάσεων ενσωμάτωσης",
"dimensions_default": "Το μοντέλο θα χρησιμοποιήσει τις προεπιλεγμένες διαστάσεις ενσωμάτωσης"
"dimensions_size_placeholder": "Προεπιλεγμένη τιμή (δεν συνιστάται να τροποποιηθεί)",
"dimensions_size_too_large": "Οι διαστάσεις ενσωμάτωσης δεν μπορούν να υπερβούν το όριο περιεχομένου του μοντέλου ({{max_context}})"
},
"languages": {
"arabic": "Αραβικά",
@@ -556,6 +557,7 @@
"error.enter.api.key": "Παρακαλώ εισάγετε το κλειδί API σας",
"error.enter.model": "Παρακαλώ επιλέξτε ένα μοντέλο",
"error.enter.name": "Παρακαλώ εισάγετε ένα όνομα για τη βάση γνώσεων",
"error.fetchTopicName": "Αποτυχία ονοματοδοσίας θέματος",
"error.get_embedding_dimensions": "Απέτυχε η πρόσληψη διαστάσεων ενσωμάτωσης",
"error.invalid.api.host": "Μη έγκυρη διεύθυνση API",
"error.invalid.api.key": "Μη έγκυρο κλειδί API",
@@ -840,7 +842,6 @@
"azure-openai": "Azure OpenAI",
"baichuan": "Παράκειμαι",
"baidu-cloud": "Baidu Cloud Qianfan",
"cephalon": "Cephalon",
"copilot": "GitHub Copilot",
"dashscope": "AliCloud Bailian",
"deepseek": "Βαθιά Αναζήτηση",
@@ -1305,7 +1306,6 @@
"advancedSettings": "Προχωρημένες Ρυθμίσεις"
},
"messages.divider": "Διαχωριστική γραμμή μηνυμάτων",
"messages.divider.tooltip": "Δεν ισχύει για μηνύματα με στυλ φυσαλίδας",
"messages.grid_columns": "Αριθμός στήλων γριλ μηνυμάτων",
"messages.grid_popover_trigger": "Καταγραφή στοιχείων στο grid",
"messages.grid_popover_trigger.click": "Εμφάνιση κλικ",

View File

@@ -8,13 +8,18 @@
"add.name.placeholder": "Ingrese el nombre",
"add.prompt": "Palabra clave",
"add.prompt.placeholder": "Ingrese la palabra clave",
"add.prompt.variables.tip": {
"title": "Variables disponibles",
"content": "{{date}}:\tFecha\n{{time}}:\tHora\n{{datetime}}:\tFecha y hora\n{{system}}:\tSistema operativo\n{{arch}}:\tArquitectura de CPU\n{{language}}:\tIdioma\n{{model_name}}:\tNombre del modelo"
},
"add.title": "Crear agente inteligente",
"delete.popup.content": "¿Está seguro de que desea eliminar este agente inteligente?",
"edit.message.add.title": "Agregar",
"edit.message.assistant.placeholder": "Ingrese el mensaje del asistente",
"edit.message.assistant.title": "Asistente",
"edit.message.empty.content": "El contenido de la sesión de chat no puede estar vacío",
"edit.message.group.title": "Grupo de mensajes",
"edit.message.title": "Mensaje predeterminado",
"edit.message.user.placeholder": "Ingrese el mensaje del usuario",
"edit.message.user.title": "Usuario",
"edit.model.select.title": "Seleccionar modelo",
"edit.settings.hide_preset_messages": "Ocultar mensajes predeterminados",
"edit.title": "Editar agente inteligente",
"manage.title": "Administrar agentes inteligentes",
"my_agents": "Mis agentes inteligentes",
@@ -59,6 +64,7 @@
"settings.default_model": "Modelo Predeterminado",
"settings.knowledge_base": "Configuración de Base de Conocimientos",
"settings.model": "Configuración de Modelo",
"settings.preset_messages": "Mensajes Preestablecidos",
"settings.prompt": "Configuración de Palabras Clave",
"settings.reasoning_effort": "Longitud de Cadena de Razonamiento",
"settings.reasoning_effort.high": "Largo",
@@ -199,7 +205,6 @@
"topics.clear.title": "Limpiar mensajes",
"topics.copy.image": "Copiar como imagen",
"topics.copy.md": "Copiar como Markdown",
"topics.copy.plain_text": "Copiar como texto sin formato (eliminar Markdown)",
"topics.copy.title": "Copiar",
"topics.delete.shortcut": "Mantén presionada {{key}} para eliminar directamente",
"topics.edit.placeholder": "Introduce nuevo nombre",
@@ -492,12 +497,8 @@
"urls": "URLs",
"dimensions": "Dimensión de incrustación",
"dimensions_size_tooltip": "Tamaño de la dimensión de incrustación, cuanto mayor sea el valor, mayor será la dimensión de incrustación, pero también consumirá más Tokens",
"dimensions_size_placeholder": " Tamaño de dimensión de incrustación, ej. 1024",
"dimensions_auto_set": "Configuración automática de dimensiones de incrustación",
"dimensions_error_invalid": "Por favor ingrese el tamaño de dimensión de incrustación",
"dimensions_size_too_large": "La dimensión de incrustación no puede exceder el límite del contexto del modelo ({{max_context}})",
"dimensions_set_right": "⚠️ Asegúrese de que el modelo admita el tamaño de dimensión de incrustación establecido",
"dimensions_default": "El modelo utilizará las dimensiones de incrustación predeterminadas"
"dimensions_size_placeholder": "Valor predeterminado (no recomendado modificar)",
"dimensions_size_too_large": "La dimensión de incrustación no puede exceder el límite del contexto del modelo ({{max_context}})"
},
"languages": {
"arabic": "Árabe",
@@ -557,6 +558,7 @@
"error.enter.api.key": "Ingrese su clave API",
"error.enter.model": "Seleccione un modelo",
"error.enter.name": "Ingrese el nombre de la base de conocimiento",
"error.fetchTopicName": "Error al nombrar el tema",
"error.get_embedding_dimensions": "Fallo al obtener las dimensiones de incrustación",
"error.invalid.api.host": "Dirección API inválida",
"error.invalid.api.key": "Clave API inválida",
@@ -841,7 +843,6 @@
"azure-openai": "Azure OpenAI",
"baichuan": "BaiChuan",
"baidu-cloud": "Baidu Nube Qiánfān",
"cephalon": "Cephalon",
"copilot": "GitHub Copiloto",
"dashscope": "Álibaba Nube BaiLiàn",
"deepseek": "Profundo Buscar",
@@ -1304,7 +1305,6 @@
"advancedSettings": "Configuración avanzada"
},
"messages.divider": "Separador de mensajes",
"messages.divider.tooltip": "No aplicable para mensajes de estilo burbuja",
"messages.grid_columns": "Número de columnas en la cuadrícula de mensajes",
"messages.grid_popover_trigger": "Desencadenante de detalles de cuadrícula",
"messages.grid_popover_trigger.click": "Mostrar al hacer clic",

View File

@@ -8,13 +8,18 @@
"add.name.placeholder": "Entrer le nom",
"add.prompt": "Mot-clé",
"add.prompt.placeholder": "Entrer le mot-clé",
"add.prompt.variables.tip": {
"title": "Variables disponibles",
"content": "{{date}}:\tDate\n{{time}}:\tHeure\n{{datetime}}:\tDate et heure\n{{system}}:\tSystème d'exploitation\n{{arch}}:\tArchitecture du processeur\n{{language}}:\tLangue\n{{model_name}}:\tNom du modèle"
},
"add.title": "Créer un agent intelligent",
"delete.popup.content": "Êtes-vous sûr de vouloir supprimer cet agent intelligent ?",
"edit.message.add.title": "Ajouter",
"edit.message.assistant.placeholder": "Entrer le message de l'assistant",
"edit.message.assistant.title": "Assistant",
"edit.message.empty.content": "Le contenu de la session ne peut pas être vide",
"edit.message.group.title": "Groupe de messages",
"edit.message.title": "Messages prédéfinis",
"edit.message.user.placeholder": "Entrer le message de l'utilisateur",
"edit.message.user.title": "Utilisateur",
"edit.model.select.title": "Sélectionner un modèle",
"edit.settings.hide_preset_messages": "Masquer les messages prédéfinis",
"edit.title": "Modifier l'agent intelligent",
"manage.title": "Gérer les agents intelligents",
"my_agents": "Mes agents intelligents",
@@ -59,6 +64,7 @@
"settings.default_model": "Modèle par défaut",
"settings.knowledge_base": "Paramètres de la base de connaissances",
"settings.model": "Paramètres du modèle",
"settings.preset_messages": "Messages prédéfinis",
"settings.prompt": "Paramètres de l'invite",
"settings.reasoning_effort": "Longueur de la chaîne de raisonnement",
"settings.reasoning_effort.high": "Long",
@@ -198,7 +204,6 @@
"topics.clear.title": "Effacer le message",
"topics.copy.image": "Copier sous forme d'image",
"topics.copy.md": "Copier sous forme de Markdown",
"topics.copy.plain_text": "Copier en tant que texte brut (supprimer Markdown)",
"topics.copy.title": "Copier",
"topics.delete.shortcut": "Maintenez {{key}} pour supprimer directement",
"topics.edit.placeholder": "Entrez un nouveau nom",
@@ -491,12 +496,8 @@
"urls": "URLs",
"dimensions": "Размерность встраивания",
"dimensions_size_tooltip": "Размерность встраивания. Чем больше значение, тем выше размерность, но тем больше токенов требуется",
"dimensions_size_placeholder": " Taille de dimension d'incorporation, ex. 1024",
"dimensions_auto_set": "Réglage automatique des dimensions d'incorporation",
"dimensions_error_invalid": "Veuillez saisir la taille de dimension d'incorporation",
"dimensions_size_too_large": "Размерность встраивания не может превышать ограничение контекста модели ({{max_context}})",
"dimensions_set_right": "⚠️ Assurez-vous que le modèle prend en charge la taille de dimension d'incorporation définie",
"dimensions_default": "Le modèle utilisera les dimensions d'incorporation par défaut"
"dimensions_size_placeholder": "Значение по умолчанию (не рекомендуется изменять)",
"dimensions_size_too_large": "Размерность встраивания не может превышать ограничение контекста модели ({{max_context}})"
},
"languages": {
"arabic": "Arabe",
@@ -556,6 +557,7 @@
"error.enter.api.key": "Veuillez entrer votre clé API",
"error.enter.model": "Veuillez sélectionner un modèle",
"error.enter.name": "Veuillez entrer le nom de la base de connaissances",
"error.fetchTopicName": "Échec de la dénomination du sujet",
"error.get_embedding_dimensions": "Impossible d'obtenir les dimensions d'encodage",
"error.invalid.api.host": "Adresse API invalide",
"error.invalid.api.key": "Clé API invalide",
@@ -840,7 +842,6 @@
"azure-openai": "Azure OpenAI",
"baichuan": "BaiChuan",
"baidu-cloud": "Baidu Cloud Qianfan",
"cephalon": "Cephalon",
"copilot": "GitHub Copilote",
"dashscope": "AliCloud BaiLian",
"deepseek": "DeepSeek",
@@ -1305,7 +1306,6 @@
"advancedSettings": "Расширенные настройки"
},
"messages.divider": "Séparateur de messages",
"messages.divider.tooltip": "Non applicable aux messages de style bulle",
"messages.grid_columns": "Nombre de colonnes de la grille de messages",
"messages.grid_popover_trigger": "Déclencheur de popover de la grille",
"messages.grid_popover_trigger.click": "Afficher au clic",

View File

@@ -8,13 +8,18 @@
"add.name.placeholder": "Digite o Nome",
"add.prompt": "Prompt",
"add.prompt.placeholder": "Digite o Prompt",
"add.prompt.variables.tip": {
"title": "Variáveis disponíveis",
"content": "{{date}}:\tData\n{{time}}:\tHora\n{{datetime}}:\tData e hora\n{{system}}:\tSistema operativo\n{{arch}}:\tArquitetura da CPU\n{{language}}:\tIdioma\n{{model_name}}:\tNome do modelo"
},
"add.title": "Criar Agente Inteligente",
"delete.popup.content": "Tem certeza de que deseja excluir este agente inteligente?",
"edit.message.add.title": "Adicionar",
"edit.message.assistant.placeholder": "Digite a Mensagem do Assistente",
"edit.message.assistant.title": "Assistente",
"edit.message.empty.content": "O conteúdo da sessão não pode estar vazio",
"edit.message.group.title": "Grupo de Mensagens",
"edit.message.title": "Mensagens Padrão",
"edit.message.user.placeholder": "Digite a Mensagem do Usuário",
"edit.message.user.title": "Usuário",
"edit.model.select.title": "Selecionar Modelo",
"edit.settings.hide_preset_messages": "Ocultar Mensagens Padrão",
"edit.title": "Editar Agente Inteligente",
"manage.title": "Gerenciar Agentes Inteligentes",
"my_agents": "Meus Agentes Inteligentes",
@@ -59,6 +64,7 @@
"settings.default_model": "Modelo Padrão",
"settings.knowledge_base": "Configurações da Base de Conhecimento",
"settings.model": "Configurações do Modelo",
"settings.preset_messages": "Mensagens Pré-definidas",
"settings.prompt": "Configurações de Prompt",
"settings.reasoning_effort": "Comprimento da Cadeia de Raciocínio",
"settings.reasoning_effort.high": "Longo",
@@ -199,7 +205,6 @@
"topics.clear.title": "Limpar mensagens",
"topics.copy.image": "Copiar como imagem",
"topics.copy.md": "Copiar como Markdown",
"topics.copy.plain_text": "Copiar como texto simples (remover Markdown)",
"topics.copy.title": "Copiar",
"topics.delete.shortcut": "Pressione {{key}} para deletar diretamente",
"topics.edit.placeholder": "Digite novo nome",
@@ -493,12 +498,8 @@
"urls": "URLs",
"dimensions": "Dimensão de incorporação",
"dimensions_size_tooltip": "Tamanho da dimensão de incorporação, quanto maior o valor, maior a dimensão de incorporação, mas também maior o consumo de tokens",
"dimensions_size_placeholder": " Tamanho da dimensão de incorporação, ex. 1024",
"dimensions_auto_set": "Definição automática de dimensões de incorporação",
"dimensions_error_invalid": "Por favor insira o tamanho da dimensão de incorporação",
"dimensions_size_too_large": "A dimensão de incorporação não pode exceder o limite do contexto do modelo ({{max_context}})",
"dimensions_set_right": "⚠️ Certifique-se de que o modelo suporta o tamanho da dimensão de incorporação definido",
"dimensions_default": "O modelo utilizará as dimensões de incorporação padrão"
"dimensions_size_placeholder": "Valor padrão (não recomendado alterar)",
"dimensions_size_too_large": "A dimensão de incorporação não pode exceder o limite do contexto do modelo ({{max_context}})"
},
"languages": {
"arabic": "Árabe",
@@ -558,6 +559,7 @@
"error.enter.api.key": "Insira sua chave API",
"error.enter.model": "Selecione um modelo",
"error.enter.name": "Insira o nome da base de conhecimento",
"error.fetchTopicName": "Falha ao nomear o tópico",
"error.get_embedding_dimensions": "Falha ao obter dimensões de incorporação",
"error.invalid.api.host": "Endereço API inválido",
"error.invalid.api.key": "Chave API inválida",
@@ -1306,7 +1308,6 @@
"advancedSettings": "Configurações Avançadas"
},
"messages.divider": "Divisor de mensagens",
"messages.divider.tooltip": "Não aplicável a mensagens de estilo bolha",
"messages.grid_columns": "Número de colunas da grade de mensagens",
"messages.grid_popover_trigger": "Disparador de detalhes da grade",
"messages.grid_popover_trigger.click": "Clique para mostrar",

View File

@@ -1,5 +1,6 @@
import KeyvStorage from '@kangfenmao/keyv-storage'
import { APP_IS_CUSTOM_PRODUCT, APP_NAME } from './config/env'
import { startAutoSync } from './services/BackupService'
import { startNutstoreAutoSync } from './services/NutstoreService'
import storeSyncService from './services/StoreSyncService'
@@ -30,3 +31,7 @@ function initStoreSync() {
initKeyv()
initAutoSync()
initStoreSync()
if (APP_IS_CUSTOM_PRODUCT) {
document.title = APP_NAME
}

View File

@@ -45,7 +45,7 @@ export function useSystemAgents() {
// 如果没有远程配置或获取失败,加载本地代理
if (resourcesPath && _agents.length === 0) {
const localAgentsData = await window.api.fs.read(resourcesPath + '/data/agents.json', 'utf-8')
const localAgentsData = await window.api.fs.read(resourcesPath + '/data/agents.json')
_agents = JSON.parse(localAgentsData) as Agent[]
}

View File

@@ -1,22 +1,18 @@
import { Navbar, NavbarMain } from '@renderer/components/app/Navbar'
import { Navbar, NavbarCenter } from '@renderer/components/app/Navbar'
import { useMinapps } from '@renderer/hooks/useMinapps'
import { Button, Input } from 'antd'
import { Search, SettingsIcon, X } from 'lucide-react'
import React, { FC, useEffect, useState } from 'react'
import { Input } from 'antd'
import { Search } from 'lucide-react'
import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocation } from 'react-router'
import styled from 'styled-components'
import App from './App'
import MiniAppSettings from './MiniappSettings/MiniAppSettings'
import NewAppButton from './NewAppButton'
const AppsPage: FC = () => {
const { t } = useTranslation()
const [search, setSearch] = useState('')
const { minapps } = useMinapps()
const [isSettingsOpen, setIsSettingsOpen] = useState(false)
const location = useLocation()
const filteredApps = search
? minapps.filter(
@@ -35,51 +31,31 @@ const AppsPage: FC = () => {
e.preventDefault()
}
useEffect(() => {
setIsSettingsOpen(false)
}, [location.key])
return (
<Container onContextMenu={handleContextMenu}>
<Navbar>
<NavbarMain>
<NavbarCenter style={{ borderRight: 'none', justifyContent: 'space-between' }}>
{t('minapp.title')}
<Input
placeholder={t('common.search')}
className="nodrag"
style={{
width: '30%',
height: 28,
borderRadius: 15,
position: 'absolute',
left: '50vw',
transform: 'translateX(-50%)'
}}
style={{ width: '30%', height: 28, borderRadius: 15 }}
size="small"
variant="filled"
suffix={<Search size={18} />}
value={search}
onChange={(e) => setSearch(e.target.value)}
disabled={isSettingsOpen}
/>
<Button
type="text"
className="nodrag"
icon={isSettingsOpen ? <X size={18} /> : <SettingsIcon size={18} color="var(--color-text-2)" />}
onClick={() => setIsSettingsOpen(!isSettingsOpen)}
/>
</NavbarMain>
<div style={{ width: 80 }} />
</NavbarCenter>
</Navbar>
<ContentContainer id="content-container">
{isSettingsOpen && <MiniAppSettings />}
{!isSettingsOpen && (
<AppsContainer style={{ height: containerHeight }}>
{filteredApps.map((app) => (
<App key={app.id} app={app} />
))}
<NewAppButton />
</AppsContainer>
)}
<AppsContainer style={{ height: containerHeight }}>
{filteredApps.map((app) => (
<App key={app.id} app={app} />
))}
<NewAppButton />
</AppsContainer>
</ContentContainer>
</Container>
)

View File

@@ -18,7 +18,7 @@ import { modelGenerating, useRuntime } from '@renderer/hooks/useRuntime'
import { useMessageStyle, useSettings } from '@renderer/hooks/useSettings'
import { useShortcut, useShortcutDisplay } from '@renderer/hooks/useShortcuts'
import { useSidebarIconShow } from '@renderer/hooks/useSidebarIcon'
import { getDefaultTopic } from '@renderer/services/AssistantService'
import { addAssistantMessagesToTopic, getDefaultTopic } from '@renderer/services/AssistantService'
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
import FileManager from '@renderer/services/FileManager'
import { checkRateLimit, getUserMessage } from '@renderer/services/MessagesService'
@@ -33,10 +33,8 @@ import { sendMessage as _sendMessage } from '@renderer/store/thunk/messageThunk'
import { Assistant, FileType, KnowledgeBase, KnowledgeItem, Model, Topic } from '@renderer/types'
import type { MessageInputBaseParams } from '@renderer/types/newMessage'
import { classNames, delay, formatFileSize, getFileExtension } from '@renderer/utils'
import { formatQuotedText } from '@renderer/utils/formats'
import { getFilesFromDropEvent } from '@renderer/utils/input'
import { documentExts, imageExts, textExts } from '@shared/config/constant'
import { IpcChannel } from '@shared/IpcChannel'
import { Button, Tooltip } from 'antd'
import TextArea, { TextAreaRef } from 'antd/es/input/TextArea'
import dayjs from 'dayjs'
@@ -410,6 +408,7 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic, topic }) =
const topic = getDefaultTopic(assistant.id)
await db.topics.add({ id: topic.id, messages: [] })
await addAssistantMessagesToTopic({ assistant, topic })
// Clear previous state
// Reset to assistant default model
@@ -421,19 +420,6 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic, topic }) =
setTimeout(() => EventEmitter.emit(EVENT_NAMES.SHOW_TOPIC_SIDEBAR), 0)
}, [addTopic, assistant, setActiveTopic, setModel])
const onQuote = useCallback(
(text: string) => {
const quotedText = formatQuotedText(text)
setText((prevText) => {
const newText = prevText ? `${prevText}\n${quotedText}\n` : `${quotedText}\n`
setTimeout(() => resizeTextArea(), 0)
return newText
})
textareaRef.current?.focus()
},
[resizeTextArea]
)
const onPause = async () => {
await pauseMessages()
}
@@ -638,25 +624,21 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic, topic }) =
_setEstimateTokenCount(tokensCount)
setContextCount({ current: contextCount.current, max: contextCount.max }) // 现在contextCount是一个对象而不是单个数值
}),
EventEmitter.on(EVENT_NAMES.ADD_NEW_TOPIC, addNewTopic)
EventEmitter.on(EVENT_NAMES.ADD_NEW_TOPIC, addNewTopic),
EventEmitter.on(EVENT_NAMES.QUOTE_TEXT, (quotedText: string) => {
setText((prevText) => {
const newText = prevText ? `${prevText}\n${quotedText}\n` : `${quotedText}\n`
setTimeout(() => resizeTextArea(), 0)
return newText
})
textareaRef.current?.focus()
})
]
// 监听引用事件
const quoteFromAnywhereRemover = window.electron?.ipcRenderer.on(
IpcChannel.App_QuoteToMain,
(_, selectedText: string) => onQuote(selectedText)
)
return () => {
unsubscribes.forEach((unsub) => unsub())
quoteFromAnywhereRemover?.()
}
}, [addNewTopic, onQuote])
return () => unsubscribes.forEach((unsub) => unsub())
}, [addNewTopic, resizeTextArea])
useEffect(() => {
if (!document.querySelector('.topview-fullscreen-container')) {
textareaRef.current?.focus()
}
textareaRef.current?.focus()
}, [assistant, topic])
useEffect(() => {
@@ -741,28 +723,50 @@ const Inputbar: FC<Props> = ({ assistant: _assistant, setActiveTopic, topic }) =
}, [])
const onToggleExpended = () => {
const currentlyExpanded = expended || !!textareaHeight
const shouldExpand = !currentlyExpanded
setExpend(shouldExpand)
if (textareaHeight) {
const textArea = textareaRef.current?.resizableTextArea?.textArea
if (textArea) {
textArea.style.height = 'auto'
setTextareaHeight(undefined)
setTimeout(() => {
textArea.style.height = `${textArea.scrollHeight}px`
}, 200)
return
}
}
const isExpended = !expended
setExpend(isExpended)
const textArea = textareaRef.current?.resizableTextArea?.textArea
if (!textArea) return
if (shouldExpand) {
textArea.style.height = '70vh'
setTextareaHeight(window.innerHeight * 0.7)
} else {
textArea.style.height = 'auto'
setTextareaHeight(undefined)
requestAnimationFrame(() => {
if (textArea) {
const contentHeight = textArea.scrollHeight
textArea.style.height = contentHeight > 400 ? '400px' : `${contentHeight}px`
}
})
if (textArea) {
if (isExpended) {
textArea.style.height = '70vh'
} else {
resetHeight()
}
}
textareaRef.current?.focus()
}
const resetHeight = () => {
if (expended) {
setExpend(false)
}
setTextareaHeight(undefined)
requestAnimationFrame(() => {
const textArea = textareaRef.current?.resizableTextArea?.textArea
if (textArea) {
textArea.style.height = 'auto'
const contentHeight = textArea.scrollHeight
textArea.style.height = contentHeight > 400 ? '400px' : `${contentHeight}px`
}
})
}
const isExpended = expended || !!textareaHeight
const showThinkingButton = isSupportedThinkingTokenModel(model) || isSupportedReasoningEffortModel(model)
@@ -945,11 +949,11 @@ const Textarea = styled(TextArea)`
padding: 0;
border-radius: 0;
display: flex;
flex: 1;
resize: none !important;
overflow: auto;
width: 100%;
box-sizing: border-box;
transition: height 0.2s ease;
&.ant-input {
line-height: 1.4;
}
@@ -964,9 +968,6 @@ const Toolbar = styled.div`
margin-bottom: 4px;
height: 30px;
gap: 16px;
position: relative;
z-index: 2;
flex-shrink: 0;
`
const ToolbarMenu = styled.div`

View File

@@ -2,7 +2,6 @@ import 'katex/dist/katex.min.css'
import 'katex/dist/contrib/copy-tex'
import 'katex/dist/contrib/mhchem'
import ImageViewer from '@renderer/components/ImageViewer'
import MarkdownShadowDOMRenderer from '@renderer/components/MarkdownShadowDOMRenderer'
import { useSettings } from '@renderer/hooks/useSettings'
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
@@ -13,7 +12,7 @@ import { findCitationInChildren, getCodeBlockId } from '@renderer/utils/markdown
import { isEmpty } from 'lodash'
import { type FC, memo, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import ReactMarkdown, { type Components, defaultUrlTransform } from 'react-markdown'
import ReactMarkdown, { type Components } from 'react-markdown'
import rehypeKatex from 'rehype-katex'
// @ts-ignore rehype-mathjax is not typed
import rehypeMathjax from 'rehype-mathjax'
@@ -23,6 +22,7 @@ import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import CodeBlock from './CodeBlock'
import ImagePreview from './ImagePreview'
import Link from './Link'
const ALLOWED_ELEMENTS =
@@ -83,25 +83,19 @@ const Markdown: FC<Props> = ({ block }) => {
code: (props: any) => (
<CodeBlock {...props} id={getCodeBlockId(props?.node?.position?.start)} onSave={onSaveCodeBlock} />
),
img: (props: any) => <ImageViewer style={{ maxWidth: 500, maxHeight: 500 }} {...props} />,
pre: (props: any) => <pre style={{ overflow: 'visible' }} {...props} />,
p: (props) => {
const hasImage = props?.node?.children?.some((child: any) => child.tagName === 'img')
if (hasImage) return <div {...props} />
return <p {...props} />
}
img: ImagePreview,
pre: (props: any) => <pre style={{ overflow: 'visible' }} {...props} />
} as Partial<Components>
}, [onSaveCodeBlock])
// if (role === 'user' && !renderInputMessageAsMarkdown) {
// return <p style={{ marginBottom: 5, whiteSpace: 'pre-wrap' }}>{messageContent}</p>
// }
if (messageContent.includes('<style>')) {
components.style = MarkdownShadowDOMRenderer as any
}
const urlTransform = useCallback((value: string) => {
if (value.startsWith('data:image/png') || value.startsWith('data:image/jpeg')) return value
return defaultUrlTransform(value)
}, [])
return (
<ReactMarkdown
rehypePlugins={rehypePlugins}
@@ -109,7 +103,6 @@ const Markdown: FC<Props> = ({ block }) => {
className="markdown"
components={components}
disallowedElements={DISALLOWED_ELEMENTS}
urlTransform={urlTransform}
remarkRehypeOptions={{
footnoteLabel: t('common.footnotes'),
footnoteLabelTagName: 'h4',

View File

@@ -31,7 +31,7 @@ const MessageErrorInfo: React.FC<{ block: ErrorMessageBlock }> = ({ block }) =>
}
const Alert = styled(AntdAlert)`
margin: 0.5rem 0;
margin: 15px 0 8px;
padding: 10px;
font-size: 12px;
`

View File

@@ -1,37 +1,15 @@
import SvgSpinners180Ring from '@renderer/components/Icons/SvgSpinners180Ring'
import ImageViewer from '@renderer/components/ImageViewer'
import type { ImageMessageBlock } from '@renderer/types/newMessage'
import React from 'react'
import styled from 'styled-components'
import MessageImage from '../MessageImage'
interface Props {
block: ImageMessageBlock
}
const ImageBlock: React.FC<Props> = ({ block }) => {
if (block.status !== 'success') return <SvgSpinners180Ring />
const images = block.metadata?.generateImageResponse?.images?.length
? block.metadata?.generateImageResponse?.images
: block?.file?.path
? [`file://${block?.file?.path}`]
: []
return (
<Container style={{ marginBottom: 8 }}>
{images.map((src, index) => (
<ImageViewer
src={src}
key={`image-${index}`}
style={{ maxWidth: 500, maxHeight: 500, padding: 5, borderRadius: 8 }}
/>
))}
</Container>
)
return block.status === 'success' ? <MessageImage block={block} /> : <SvgSpinners180Ring />
}
const Container = styled.div`
display: flex;
flex-direction: row;
gap: 10px;
margin-top: 8px;
`
export default React.memo(ImageBlock)

View File

@@ -151,7 +151,7 @@ const MainTextBlock: React.FC<Props> = ({ block, citationBlockId, role, mentions
</Flex>
)}
{role === 'user' && !renderInputMessageAsMarkdown ? (
<p className="markdown" style={{ whiteSpace: 'pre-wrap' }}>
<p className="markdown" style={{ marginBottom: 5, whiteSpace: 'pre-wrap' }}>
{block.content}
</p>
) : (

View File

@@ -42,7 +42,6 @@ const blockWrapperVariants = {
const AnimatedBlockWrapper: React.FC<AnimatedBlockWrapperProps> = ({ children, enableAnimation }) => {
return (
<motion.div
className="block-wrapper"
variants={blockWrapperVariants}
initial={enableAnimation ? 'hidden' : 'static'}
animate={enableAnimation ? 'visible' : 'static'}>

View File

@@ -139,7 +139,6 @@ const WebSearchCitation: React.FC<{ citation: Citation }> = ({ citation }) => {
<WebSearchCard>
<ContextMenu>
<WebSearchCardHeader>
<CitationIndex>{citation.number}</CitationIndex>
{citation.showFavicon && citation.url && (
<Favicon hostname={new URL(citation.url).hostname} alt={citation.title || citation.hostname || ''} />
)}
@@ -163,7 +162,6 @@ const KnowledgeCitation: React.FC<{ citation: Citation }> = ({ citation }) => {
<WebSearchCard>
<ContextMenu>
<WebSearchCardHeader>
<CitationIndex>{citation.number}</CitationIndex>
{citation.showFavicon && <FileSearch width={16} />}
<CitationLink className="text-nowrap" href={citation.url} onClick={(e) => handleLinkClick(citation.url, e)}>
{citation.title}
@@ -212,13 +210,6 @@ const PreviewIcon = styled.div`
}
`
const CitationIndex = styled.div`
font-size: 14px;
line-height: 1.6;
color: var(--color-text-2);
margin-right: 8px;
`
const CitationLink = styled.a`
font-size: 14px;
line-height: 1.6;

View File

@@ -21,6 +21,7 @@ import MessageEditor from './MessageEditor'
import MessageErrorBoundary from './MessageErrorBoundary'
import MessageHeader from './MessageHeader'
import MessageMenubar from './MessageMenubar'
import MessageTokens from './MessageTokens'
interface Props {
message: Message
@@ -28,6 +29,7 @@ interface Props {
assistant?: Assistant
index?: number
total?: number
hidePresetMessages?: boolean
hideMenuBar?: boolean
style?: React.CSSProperties
isGrouped?: boolean
@@ -40,6 +42,7 @@ const MessageItem: FC<Props> = ({
topic,
// assistant,
index,
hidePresetMessages,
hideMenuBar = false,
isGrouped,
isStreaming = false,
@@ -98,7 +101,7 @@ const MessageItem: FC<Props> = ({
const isAssistantMessage = message.role === 'assistant'
const showMenubar = !hideMenuBar && !isStreaming && !message.status.includes('ing') && !isEditing
const messageBorder = !isBubbleStyle && showMessageDivider ? '1px dotted var(--color-border)' : 'none'
const messageBorder = showMessageDivider ? undefined : 'none'
const messageBackground = getMessageBackground(isBubbleStyle, isAssistantMessage)
const messageHighlightHandler = useCallback((highlight: boolean = true) => {
@@ -119,6 +122,10 @@ const MessageItem: FC<Props> = ({
return () => unsubscribes.forEach((unsub) => unsub())
}, [message.id, messageHighlightHandler])
if (hidePresetMessages && message.isPreset) {
return null
}
if (message.type === 'clear') {
return (
<NewContextMessage className="clear-context-divider" onClick={() => EventEmitter.emit(EVENT_NAMES.NEW_CONTEXT)}>
@@ -129,6 +136,22 @@ const MessageItem: FC<Props> = ({
)
}
if (isEditing) {
return (
<MessageContainer style={{ paddingTop: 15 }}>
<MessageHeader message={message} assistant={assistant} model={model} key={getModelUniqId(model)} />
<div style={{ paddingLeft: messageStyle === 'plain' ? 46 : undefined }}>
<MessageEditor
message={message}
onSave={handleEditSave}
onResend={handleEditResend}
onCancel={handleEditCancel}
/>
</div>
</MessageContainer>
)
}
return (
<MessageContainer
key={message.id}
@@ -138,100 +161,35 @@ const MessageItem: FC<Props> = ({
'message-user': !isAssistantMessage
})}
ref={messageContainerRef}
style={{
...style,
justifyContent: isBubbleStyle ? (isAssistantMessage ? 'flex-start' : 'flex-end') : undefined,
flex: isBubbleStyle ? undefined : 1
}}>
{isEditing && (
<ContextMenu
style={{ ...style, alignItems: isBubbleStyle ? (isAssistantMessage ? 'start' : 'end') : undefined }}>
<ContextMenu>
<MessageHeader message={message} assistant={assistant} model={model} key={getModelUniqId(model)} />
<MessageContentContainer
className={
message.role === 'user'
? 'message-content-container message-content-container-user'
: message.role === 'assistant'
? 'message-content-container message-content-container-assistant'
: 'message-content-container'
}
style={{
display: 'flex',
flexDirection: 'column',
alignSelf: isAssistantMessage ? 'flex-start' : 'flex-end',
width: isBubbleStyle ? '70%' : '100%'
fontFamily: messageFont === 'serif' ? 'var(--font-family-serif)' : 'var(--font-family)',
fontSize,
background: messageBackground,
overflowY: 'visible',
maxWidth: narrowMode ? 760 : undefined
}}>
<MessageHeader
message={message}
assistant={assistant}
model={model}
key={getModelUniqId(model)}
index={index}
/>
<div style={{ paddingLeft: messageStyle === 'plain' ? 46 : undefined }}>
<MessageEditor
message={message}
onSave={handleEditSave}
onResend={handleEditResend}
onCancel={handleEditCancel}
/>
</div>
</ContextMenu>
)}
{!isEditing && (
<ContextMenu
style={{
display: 'flex',
flexDirection: 'column',
alignSelf: isAssistantMessage ? 'flex-start' : 'flex-end',
flex: 1,
maxWidth: '100%'
}}>
<MessageHeader
message={message}
assistant={assistant}
model={model}
key={getModelUniqId(model)}
index={index}
/>
<MessageContentContainer
className={
message.role === 'user'
? 'message-content-container message-content-container-user'
: message.role === 'assistant'
? 'message-content-container message-content-container-assistant'
: 'message-content-container'
}
style={{
fontFamily: messageFont === 'serif' ? 'var(--font-family-serif)' : 'var(--font-family)',
fontSize,
background: messageBackground,
overflowY: 'visible',
maxWidth: narrowMode ? 760 : undefined,
alignSelf: isBubbleStyle ? (isAssistantMessage ? 'start' : 'end') : undefined
}}>
<MessageErrorBoundary>
<MessageContent message={message} />
</MessageErrorBoundary>
{showMenubar && !isBubbleStyle && (
<MessageFooter
className="MessageFooter"
style={{
borderTop: messageBorder,
flexDirection: !isLastMessage ? 'row-reverse' : undefined
}}>
<MessageMenubar
message={message}
assistant={assistant}
model={model}
index={index}
topic={topic}
isLastMessage={isLastMessage}
isAssistantMessage={isAssistantMessage}
isGrouped={isGrouped}
messageContainerRef={messageContainerRef as React.RefObject<HTMLDivElement>}
setModel={setModel}
/>
</MessageFooter>
)}
</MessageContentContainer>
{showMenubar && isBubbleStyle && (
<MessageErrorBoundary>
<MessageContent message={message} />
</MessageErrorBoundary>
{showMenubar && (
<MessageFooter
className="MessageFooter"
style={{
borderTop: messageBorder,
flexDirection: !isAssistantMessage ? 'row-reverse' : undefined
border: messageBorder,
flexDirection: isLastMessage || isBubbleStyle ? 'row-reverse' : undefined
}}>
<MessageTokens message={message} isLastMessage={isLastMessage} />
<MessageMenubar
message={message}
assistant={assistant}
@@ -246,8 +204,8 @@ const MessageItem: FC<Props> = ({
/>
</MessageFooter>
)}
</ContextMenu>
)}
</MessageContentContainer>
</ContextMenu>
</MessageContainer>
)
}
@@ -262,7 +220,7 @@ const getMessageBackground = (isBubbleStyle: boolean, isAssistantMessage: boolea
const MessageContainer = styled.div`
display: flex;
width: 100%;
flex-direction: column;
position: relative;
transition: background-color 0.3s ease;
padding: 0 20px;
@@ -305,12 +263,12 @@ const MessageFooter = styled.div`
align-items: center;
padding: 2px 0;
margin-top: 2px;
border-top: 1px dotted var(--color-border);
gap: 20px;
`
const NewContextMessage = styled.div`
cursor: pointer;
flex: 1;
`
export default memo(MessageItem)

View File

@@ -14,7 +14,7 @@ const MessageContent: React.FC<Props> = ({ message }) => {
return (
<>
{!isEmpty(message.mentions) && (
<Flex gap="8px" wrap>
<Flex gap="8px" wrap style={{ marginBottom: 10 }}>
{message.mentions?.map((model) => <MentionTag key={getModelUniqId(model)}>{'@' + model.name}</MentionTag>)}
</Flex>
)}

View File

@@ -45,14 +45,6 @@ const MessageBlockEditor: FC<Props> = ({ message, onSave, onResend, onCancel })
const textareaRef = useRef<TextAreaRef>(null)
const attachmentButtonRef = useRef<AttachmentButtonRef>(null)
const resizeTextArea = useCallback(() => {
const textArea = textareaRef.current?.resizableTextArea?.textArea
if (textArea) {
textArea.style.height = 'auto'
textArea.style.height = textArea?.scrollHeight > 400 ? '400px' : `${textArea?.scrollHeight}px`
}
}, [])
useEffect(() => {
setTimeout(() => {
resizeTextArea()
@@ -60,7 +52,16 @@ const MessageBlockEditor: FC<Props> = ({ message, onSave, onResend, onCancel })
textareaRef.current.focus({ cursor: 'end' })
}
}, 0)
}, [resizeTextArea])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const resizeTextArea = useCallback(() => {
const textArea = textareaRef.current?.resizableTextArea?.textArea
if (textArea) {
textArea.style.height = 'auto'
textArea.style.height = textArea?.scrollHeight > 400 ? '400px' : `${textArea?.scrollHeight}px`
}
}, [])
const onPaste = useCallback(
async (event: ClipboardEvent) => {
@@ -83,9 +84,13 @@ const MessageBlockEditor: FC<Props> = ({ message, onSave, onResend, onCancel })
// 添加全局粘贴事件处理
useEffect(() => {
// 注册当前组件的粘贴处理函数
PasteService.registerHandler('messageEditor', onPaste)
// 在组件加载时将焦点设置为当前组件
PasteService.setLastFocusedComponent('messageEditor')
// 卸载时取消注册
return () => {
PasteService.unregisterHandler('messageEditor')
}
@@ -160,6 +165,12 @@ const MessageBlockEditor: FC<Props> = ({ message, onSave, onResend, onCancel })
}
}
const autoResizeTextArea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const textarea = e.target
textarea.style.height = 'auto'
textarea.style.height = `${textarea.scrollHeight}px`
}
return (
<EditorContainer className="message-editor" onDragOver={(e) => e.preventDefault()} onDrop={handleDrop}>
{editedBlocks
@@ -173,7 +184,7 @@ const MessageBlockEditor: FC<Props> = ({ message, onSave, onResend, onCancel })
value={block.content}
onChange={(e) => {
handleTextChange(block.id, e.target.value)
resizeTextArea()
autoResizeTextArea(e)
}}
autoFocus
contextMenu="true"

View File

@@ -19,10 +19,11 @@ import SelectableMessage from './MessageSelect'
interface Props {
messages: (Message & { index: number })[]
topic: Topic
hidePresetMessages?: boolean
registerMessageElement?: (id: string, element: HTMLElement | null) => void
}
const MessageGroup = ({ messages, topic, registerMessageElement }: Props) => {
const MessageGroup = ({ messages, topic, hidePresetMessages, registerMessageElement }: Props) => {
const { editMessage } = useMessageOperations(topic)
const { multiModelMessageStyle: multiModelMessageStyleSetting, gridColumns, gridPopoverTrigger } = useSettings()
const { isMultiSelectMode } = useChatContext(topic)
@@ -167,6 +168,7 @@ const MessageGroup = ({ messages, topic, registerMessageElement }: Props) => {
message,
topic,
index: message.index,
hidePresetMessages,
style: {
paddingTop: isGrouped && ['horizontal', 'grid'].includes(multiModelMessageStyle) ? 0 : 15
}
@@ -180,8 +182,7 @@ const MessageGroup = ({ messages, topic, registerMessageElement }: Props) => {
$isGrouped={isGrouped}
key={message.id}
className={classNames({
// 加个卡片布局
'group-message-wrapper': message.role === 'assistant' && (isHorizontal || isGrid) && isGrouped,
'group-message-wrapper': message.role === 'assistant' && isHorizontal && isGrouped,
[multiModelMessageStyle]: isGrouped,
selected: message.id === selectedMessageId
})}>
@@ -219,7 +220,16 @@ const MessageGroup = ({ messages, topic, registerMessageElement }: Props) => {
</SelectableMessage>
)
},
[isGrid, isGrouped, topic, multiModelMessageStyle, isHorizontal, selectedMessageId, gridPopoverTrigger]
[
isGrid,
isGrouped,
topic,
hidePresetMessages,
multiModelMessageStyle,
isHorizontal,
selectedMessageId,
gridPopoverTrigger
]
)
return (
@@ -316,7 +326,6 @@ interface MessageWrapperProps {
const MessageWrapper = styled(Scrollbar)<MessageWrapperProps>`
width: 100%;
display: flex;
&.horizontal {
display: inline-block;

View File

@@ -17,13 +17,10 @@ import { CSSProperties, FC, memo, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
import MessageTokens from './MessageTokens'
interface Props {
message: Message
assistant: Assistant
model?: Model
index: number | undefined
}
const getAvatarSource = (isLocalAi: boolean, modelId: string | undefined) => {
@@ -31,7 +28,7 @@ const getAvatarSource = (isLocalAi: boolean, modelId: string | undefined) => {
return modelId ? getModelLogo(modelId) : undefined
}
const MessageHeader: FC<Props> = memo(({ assistant, model, message, index }) => {
const MessageHeader: FC<Props> = memo(({ assistant, model, message }) => {
const avatar = useAvatar()
const { theme } = useTheme()
const { userName, sidebarIcons } = useSettings()
@@ -55,11 +52,9 @@ const MessageHeader: FC<Props> = memo(({ assistant, model, message, index }) =>
const isAssistantMessage = message.role === 'assistant'
const showMinappIcon = sidebarIcons.visible.includes('minapp')
const { showTokens } = useSettings()
const avatarName = useMemo(() => firstLetter(assistant?.name).toUpperCase(), [assistant?.name])
const username = useMemo(() => removeLeadingEmoji(getUserName()), [getUserName])
const isLastMessage = index === 0
const showMiniApp = useCallback(() => {
showMinappIcon && model?.provider && openMinappById(model.provider)
@@ -116,14 +111,7 @@ const MessageHeader: FC<Props> = memo(({ assistant, model, message, index }) =>
<UserName isBubbleStyle={isBubbleStyle} theme={theme}>
{username}
</UserName>
<InfoWrap
style={{
flexDirection: !isAssistantMessage && isBubbleStyle ? 'row-reverse' : undefined
}}>
<MessageTime>{dayjs(message?.updatedAt ?? message.createdAt).format('MM/DD HH:mm')}</MessageTime>
{showTokens && <DividerContainer style={{ color: 'var(--color-text-3)' }}> | </DividerContainer>}
<MessageTokens message={message} isLastMessage={isLastMessage} />
</InfoWrap>
<MessageTime>{dayjs(message?.updatedAt ?? message.createdAt).format('MM/DD HH:mm')}</MessageTime>
</UserWrap>
</AvatarWrapper>
</Container>
@@ -152,19 +140,6 @@ const UserWrap = styled.div`
justify-content: space-between;
`
const InfoWrap = styled.div`
display: flex;
flex-direction: row;
align-items: center;
gap: 4px;
`
const DividerContainer = styled.div`
font-size: 10px;
color: var(--color-text-3);
margin: 0 2px;
`
const UserName = styled.div<{ isBubbleStyle?: boolean; theme?: string }>`
font-size: 14px;
font-weight: 600;

View File

@@ -5,7 +5,6 @@ import { TranslateLanguageOptions } from '@renderer/config/translate'
import { useMessageEditing } from '@renderer/context/MessageEditingContext'
import { useChatContext } from '@renderer/hooks/useChatContext'
import { useMessageOperations, useTopicLoading } from '@renderer/hooks/useMessageOperations'
import { useMessageStyle } from '@renderer/hooks/useSettings'
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
import { getMessageTitle } from '@renderer/services/MessagesService'
import { translateText } from '@renderer/services/TranslateService'
@@ -23,7 +22,6 @@ import {
exportMessageToNotion,
messageToMarkdown
} from '@renderer/utils/export'
import { copyMessageAsPlainText } from '@renderer/utils/copy'
// import { withMessageThought } from '@renderer/utils/formats'
import { removeTrailingDoubleSpaces } from '@renderer/utils/markdown'
import { findMainTextBlocks, findTranslationBlocks, getMainTextContent } from '@renderer/utils/messageUtils/find'
@@ -68,9 +66,6 @@ const MessageMenubar: FC<Props> = (props) => {
appendAssistantResponse,
removeMessageBlock
} = useMessageOperations(topic)
const { isBubbleStyle } = useMessageStyle()
const loading = useTopicLoading(topic)
const isUserMessage = message.role === 'user'
@@ -202,11 +197,6 @@ const MessageMenubar: FC<Props> = (props) => {
key: 'export',
icon: <Share size={16} color="var(--color-icon)" style={{ marginTop: 3 }} />,
children: [
{
label: t('chat.topics.copy.plain_text'),
key: 'copy_message_plain_text',
onClick: () => copyMessageAsPlainText(message)
},
exportMenuOptions.image && {
label: t('chat.topics.copy.image'),
key: 'img',
@@ -342,29 +332,24 @@ const MessageMenubar: FC<Props> = (props) => {
return translationBlocks.length > 0
}, [message])
const softHoverBg = isBubbleStyle && !isLastMessage
return (
<MenusBar className={`menubar ${isLastMessage && 'show'}`}>
{message.role === 'user' && (
<Tooltip title={t('common.regenerate')} mouseEnterDelay={0.8}>
<ActionButton
className="message-action-button"
onClick={() => handleResendUserMessage()}
$softHoverBg={isBubbleStyle}>
<ActionButton className="message-action-button" onClick={() => handleResendUserMessage()}>
<SyncOutlined />
</ActionButton>
</Tooltip>
)}
{message.role === 'user' && (
<Tooltip title={t('common.edit')} mouseEnterDelay={0.8}>
<ActionButton className="message-action-button" onClick={onEdit} $softHoverBg={softHoverBg}>
<ActionButton className="message-action-button" onClick={onEdit}>
<EditOutlined />
</ActionButton>
</Tooltip>
)}
<Tooltip title={t('common.copy')} mouseEnterDelay={0.8}>
<ActionButton className="message-action-button" onClick={onCopy} $softHoverBg={softHoverBg}>
<ActionButton className="message-action-button" onClick={onCopy}>
{!copied && <Copy size={16} />}
{copied && <CheckOutlined style={{ color: 'var(--color-primary)' }} />}
</ActionButton>
@@ -381,7 +366,7 @@ const MessageMenubar: FC<Props> = (props) => {
mouseEnterDelay={0.8}
open={showRegenerateTooltip}
onOpenChange={setShowRegenerateTooltip}>
<ActionButton className="message-action-button" $softHoverBg={softHoverBg}>
<ActionButton className="message-action-button">
<RefreshCw size={16} />
</ActionButton>
</Tooltip>
@@ -389,7 +374,7 @@ const MessageMenubar: FC<Props> = (props) => {
)}
{isAssistantMessage && (
<Tooltip title={t('message.mention.title')} mouseEnterDelay={0.8}>
<ActionButton className="message-action-button" onClick={onMentionModel} $softHoverBg={softHoverBg}>
<ActionButton className="message-action-button" onClick={onMentionModel}>
<AtSign size={16} />
</ActionButton>
</Tooltip>
@@ -397,10 +382,6 @@ const MessageMenubar: FC<Props> = (props) => {
{!isUserMessage && (
<Dropdown
menu={{
style: {
maxHeight: 250,
overflowY: 'auto'
},
items: [
...TranslateLanguageOptions.map((item) => ({
label: item.emoji + ' ' + item.label,
@@ -456,13 +437,10 @@ const MessageMenubar: FC<Props> = (props) => {
onClick: (e) => e.domEvent.stopPropagation()
}}
trigger={['click']}
placement="top"
placement="topRight"
arrow>
<Tooltip title={t('chat.translate')} mouseEnterDelay={1.2}>
<ActionButton
className="message-action-button"
onClick={(e) => e.stopPropagation()}
$softHoverBg={softHoverBg}>
<ActionButton className="message-action-button" onClick={(e) => e.stopPropagation()}>
<Languages size={16} />
</ActionButton>
</Tooltip>
@@ -470,7 +448,7 @@ const MessageMenubar: FC<Props> = (props) => {
)}
{isAssistantMessage && isGrouped && (
<Tooltip title={t('chat.message.useful')} mouseEnterDelay={0.8}>
<ActionButton className="message-action-button" onClick={onUseful} $softHoverBg={softHoverBg}>
<ActionButton className="message-action-button" onClick={onUseful}>
{message.useful ? (
<ThumbsUp size={17.5} fill="var(--color-primary)" strokeWidth={0} />
) : (
@@ -485,7 +463,7 @@ const MessageMenubar: FC<Props> = (props) => {
icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
onOpenChange={(open) => open && setShowDeleteTooltip(false)}
onConfirm={() => deleteMessage(message.id)}>
<ActionButton className="message-action-button" onClick={(e) => e.stopPropagation()} $softHoverBg={softHoverBg}>
<ActionButton className="message-action-button" onClick={(e) => e.stopPropagation()}>
<Tooltip
title={t('common.delete')}
mouseEnterDelay={1}
@@ -501,10 +479,7 @@ const MessageMenubar: FC<Props> = (props) => {
trigger={['click']}
placement="topRight"
arrow>
<ActionButton
className="message-action-button"
onClick={(e) => e.stopPropagation()}
$softHoverBg={softHoverBg}>
<ActionButton className="message-action-button" onClick={(e) => e.stopPropagation()}>
<Menu size={19} />
</ActionButton>
</Dropdown>
@@ -521,7 +496,7 @@ const MenusBar = styled.div`
gap: 6px;
`
const ActionButton = styled.div<{ $softHoverBg?: boolean }>`
const ActionButton = styled.div`
cursor: pointer;
border-radius: 8px;
display: flex;
@@ -532,11 +507,8 @@ const ActionButton = styled.div<{ $softHoverBg?: boolean }>`
height: 30px;
transition: all 0.2s ease;
&:hover {
background-color: ${(props) =>
props.$softHoverBg ? 'var(--color-background-soft)' : 'var(--color-background-mute)'};
color: var(--color-text-1);
.anticon,
.lucide {
background-color: var(--color-background-mute);
.anticon {
color: var(--color-text-1);
}
}
@@ -546,6 +518,9 @@ const ActionButton = styled.div<{ $softHoverBg?: boolean }>`
font-size: 14px;
color: var(--color-icon);
}
&:hover {
color: var(--color-text-1);
}
.icon-at {
font-size: 16px;
}

View File

@@ -69,14 +69,19 @@ const MessgeTokens: React.FC<MessageTokensProps> = ({ message }) => {
}
const MessageMetadata = styled.div`
font-size: 10px;
color: var(--color-text-3);
font-size: 11px;
color: var(--color-text-2);
user-select: text;
margin: 2px 0;
cursor: pointer;
text-align: right;
.tokens span {
padding: 0 2px;
.tokens {
display: block;
span {
padding: 0 2px;
}
}
`

View File

@@ -289,6 +289,7 @@ const Messages: React.FC<MessagesProps> = ({ assistant, topic, setActiveTopic, o
key={key}
messages={groupMessages}
topic={topic}
hidePresetMessages={assistant.settings?.hideMessages}
registerMessageElement={registerMessageElement}
/>
))}

View File

@@ -1,4 +1,4 @@
import { DownOutlined, PlusOutlined, RightOutlined } from '@ant-design/icons'
import { PlusOutlined } from '@ant-design/icons'
import DragableList from '@renderer/components/DragableList'
import Scrollbar from '@renderer/components/Scrollbar'
import { useAgents } from '@renderer/hooks/useAgents'
@@ -27,7 +27,6 @@ const Assistants: FC<AssistantsTabProps> = ({
}) => {
const { assistants, removeAssistant, addAssistant, updateAssistants } = useAssistants()
const [dragging, setDragging] = useState(false)
const [collapsedTags, setCollapsedTags] = useState<Record<string, boolean>>({})
const { addAgent } = useAgents()
const { t } = useTranslation()
const { getGroupedAssistants } = useTags()
@@ -46,13 +45,6 @@ const Assistants: FC<AssistantsTabProps> = ({
[activeAssistant, assistants, removeAssistant, setActiveAssistant, onCreateDefaultAssistant]
)
const toggleTagCollapse = useCallback((tag: string) => {
setCollapsedTags((prev) => ({
...prev,
[tag]: !prev[tag]
}))
}, [])
const handleSortByChange = useCallback(
(sortType: AssistantsSortType) => {
setAssistantsTabSortType(sortType)
@@ -60,23 +52,6 @@ const Assistants: FC<AssistantsTabProps> = ({
[setAssistantsTabSortType]
)
const handleGroupReorder = useCallback(
(tag: string, newGroupList: Assistant[]) => {
let insertIndex = 0
const newGlobal = assistants.map((a) => {
const tags = a.tags?.length ? a.tags : [t('assistants.tags.untagged')]
if (tags.includes(tag)) {
const replaced = newGroupList[insertIndex]
insertIndex += 1
return replaced
}
return a
})
updateAssistants(newGlobal)
},
[assistants, t, updateAssistants]
)
if (assistantsTabSortType === 'tags') {
return (
<Container className="assistants-tab" ref={containerRef}>
@@ -84,45 +59,27 @@ const Assistants: FC<AssistantsTabProps> = ({
{getGroupedAssistants.map((group) => (
<TagsContainer key={group.tag}>
{group.tag !== t('assistants.tags.untagged') && (
<GroupTitle onClick={() => toggleTagCollapse(group.tag)}>
<GroupTitle>
<Tooltip title={group.tag}>
<GroupTitleName>
{collapsedTags[group.tag] ? (
<RightOutlined style={{ fontSize: '10px', marginRight: '5px' }} />
) : (
<DownOutlined style={{ fontSize: '10px', marginRight: '5px' }} />
)}
{group.tag}
</GroupTitleName>
<GroupTitleName>{group.tag}</GroupTitleName>
</Tooltip>
<Divider style={{ margin: '12px 0' }}></Divider>
</GroupTitle>
)}
{!collapsedTags[group.tag] && (
<div>
<DragableList
list={group.assistants}
onUpdate={(newList) => handleGroupReorder(group.tag, newList)}
style={{ paddingBottom: dragging ? '34px' : 0 }}
onDragStart={() => setDragging(true)}
onDragEnd={() => setDragging(false)}>
{(assistant) => (
<AssistantItem
key={assistant.id}
assistant={assistant}
isActive={assistant.id === activeAssistant.id}
sortBy={assistantsTabSortType}
onSwitch={setActiveAssistant}
onDelete={onDelete}
addAgent={addAgent}
addAssistant={addAssistant}
onCreateDefaultAssistant={onCreateDefaultAssistant}
handleSortByChange={handleSortByChange}
/>
)}
</DragableList>
</div>
)}
{group.assistants.map((assistant) => (
<AssistantItem
key={assistant.id}
assistant={assistant}
isActive={assistant.id === activeAssistant.id}
sortBy={assistantsTabSortType}
onSwitch={setActiveAssistant}
onDelete={onDelete}
addAgent={addAgent}
addAssistant={addAssistant}
onCreateDefaultAssistant={onCreateDefaultAssistant}
handleSortByChange={handleSortByChange}
/>
))}
</TagsContainer>
))}
</div>
@@ -207,13 +164,12 @@ const AssistantAddItem = styled.div`
`
const GroupTitle = styled.div`
padding: 8px 0;
padding: 8px 0px;
position: relative;
color: var(--color-text-2);
font-size: 12px;
font-weight: 500;
margin-bottom: -8px;
cursor: pointer;
`
const GroupTitleName = styled.div`

View File

@@ -318,12 +318,7 @@ const SettingsTab: FC<Props> = (props) => {
</SettingRow>
<SettingDivider />
<SettingRow>
<SettingRowTitleSmall>
{t('settings.messages.divider')}
<Tooltip title={t('settings.messages.divider.tooltip')}>
<CircleHelp size={14} style={{ marginLeft: 4 }} color="var(--color-text-2)" />
</Tooltip>
</SettingRowTitleSmall>
<SettingRowTitleSmall>{t('settings.messages.divider')}</SettingRowTitleSmall>
<Switch
size="small"
checked={showMessageDivider}

View File

@@ -26,7 +26,7 @@ import { RootState } from '@renderer/store'
import { setGenerating } from '@renderer/store/runtime'
import { Assistant, Topic } from '@renderer/types'
import { removeSpecialCharactersForFileName } from '@renderer/utils'
import { copyTopicAsMarkdown, copyTopicAsPlainText } from '@renderer/utils/copy'
import { copyTopicAsMarkdown } from '@renderer/utils/copy'
import {
exportMarkdownToJoplin,
exportMarkdownToSiyuan,
@@ -280,11 +280,6 @@ const Topics: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic
label: t('chat.topics.copy.md'),
key: 'md',
onClick: () => copyTopicAsMarkdown(topic)
},
{
label: t('chat.topics.copy.plain_text'),
key: 'plain_text',
onClick: () => copyTopicAsPlainText(topic)
}
]
},

View File

@@ -185,10 +185,10 @@ const handleTagOperation = (
assistants: Assistant[],
updateAssistants: (assistants: Assistant[]) => void
) => {
const removeTag = () => updateAssistants(assistants.map((a) => (a.id === assistant.id ? { ...a, tags: [] } : a)))
const addTag = () => updateAssistants(assistants.map((a) => (a.id === assistant.id ? { ...a, tags: [tag] } : a)))
const hasTag = assistant.tags?.includes(tag)
hasTag ? removeTag() : addTag()
if (assistant.tags?.includes(tag)) {
return
}
updateAssistants(assistants.map((a) => (a.id === assistant.id ? { ...a, tags: [tag] } : a)))
}
// 提取创建菜单项的函数

View File

@@ -1,4 +1,3 @@
import { DragDropContext, Draggable, Droppable } from '@hello-pangea/dnd'
import { Box } from '@renderer/components/Layout'
import { TopView } from '@renderer/components/TopView'
import { useAssistants } from '@renderer/hooks/useAssistant'
@@ -20,10 +19,9 @@ interface Props extends ShowParams {
const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
const [open, setOpen] = useState(true)
const { allTags, getAssistantsByTag, updateTagsOrder } = useTags()
const { allTags, getAssistantsByTag } = useTags()
const { assistants, updateAssistants } = useAssistants()
const { t } = useTranslation()
const [tags, setTags] = useState(allTags)
const onOk = () => {
setOpen(false)
@@ -51,24 +49,10 @@ const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
})
)
}
const newTags = tags.filter((tag) => tag !== removedTag)
setTags(newTags)
updateTagsOrder(newTags)
}
})
}
const handleDragEnd = (result) => {
if (!result.destination) return
const items = Array.from(tags)
const [reorderedItem] = items.splice(result.source.index, 1)
items.splice(result.destination.index, 0, reorderedItem)
setTags(items)
updateTagsOrder(items)
}
AssistantTagsPopup.hide = onCancel
return (
@@ -82,37 +66,13 @@ const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
transitionName="animation-move-down"
centered>
<Container>
{tags.length > 0 ? (
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="tags">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{tags.map((tag, index) => (
<Draggable key={tag} draggableId={tag} index={index}>
{(provided) => (
<TagItem ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
<Box mr={8}>{tag}</Box>
<Button
type="text"
icon={<Trash size={16} />}
danger
onClick={(e) => {
e.stopPropagation()
onDelete(tag)
}}
/>
</TagItem>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
) : (
<Empty description="" />
)}
{allTags.map((tag) => (
<TagItem key={tag}>
<Box mr={8}>{tag}</Box>
<Button type="text" icon={<Trash size={16} />} danger onClick={() => onDelete(tag)} />
</TagItem>
))}
{allTags.length === 0 && <Empty description="" />}
</Container>
</Modal>
)

View File

@@ -93,7 +93,7 @@ const KnowledgeContent: FC<KnowledgeContentProps> = ({ selectedBase }) => {
.map((file) => ({
id: file.name,
name: file.name,
path: window.api.file.getPathForFile(file),
path: window.api.file.getPathForFile(file) || '',
size: file.size,
ext: `.${file.name.split('.').pop()}`.toLowerCase(),
count: 1,

View File

@@ -9,9 +9,9 @@ import { SettingHelpText } from '@renderer/pages/settings'
import AiProvider from '@renderer/providers/AiProvider'
import { getKnowledgeBaseParams } from '@renderer/services/KnowledgeService'
import { getModelUniqId } from '@renderer/services/ModelService'
import { KnowledgeBase, Model } from '@renderer/types'
import { Model } from '@renderer/types'
import { getErrorMessage } from '@renderer/utils/error'
import { Flex, Form, Input, InputNumber, Modal, Select, Slider, Switch } from 'antd'
import { Form, Input, Modal, Select, Slider } from 'antd'
import { find, sortBy } from 'lodash'
import { nanoid } from 'nanoid'
import { useMemo, useRef, useState } from 'react'
@@ -24,8 +24,6 @@ interface ShowParams {
interface FormData {
name: string
model: string
autoDims: boolean | undefined
dimensions: number | undefined
rerankModel: string | undefined
documentCount: number | undefined
}
@@ -37,7 +35,6 @@ interface Props extends ShowParams {
const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
const [open, setOpen] = useState(true)
const [loading, setLoading] = useState(false)
const [autoDims, setAutoDims] = useState(true)
const [form] = Form.useForm<FormData>()
const { t } = useTranslation()
const { providers } = useProviders()
@@ -70,8 +67,7 @@ const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
.map((m) => ({
label: m.name,
value: getModelUniqId(m),
providerId: p.id,
modelId: m.id
key: `${p.id}-${m.id}`
}))
}))
.filter((group) => group.options.length > 0)
@@ -111,27 +107,24 @@ const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
return
}
if (autoDims || typeof values.dimensions === 'undefined') {
try {
const aiProvider = new AiProvider(provider)
values.dimensions = await aiProvider.getEmbeddingDimensions(selectedEmbeddingModel)
} catch (error) {
console.error('Error getting embedding dimensions:', error)
window.message.error(t('message.error.get_embedding_dimensions') + '\n' + getErrorMessage(error))
setLoading(false)
return
}
} else if (typeof values.dimensions === 'string') {
// 按理来说不应该是string的但是确实是string
values.dimensions = parseInt(values.dimensions)
const aiProvider = new AiProvider(provider)
let dimensions = 0
try {
dimensions = await aiProvider.getEmbeddingDimensions(selectedEmbeddingModel)
} catch (error) {
console.error('Error getting embedding dimensions:', error)
window.message.error(t('message.error.get_embedding_dimensions') + '\n' + getErrorMessage(error))
setLoading(false)
return
}
const newBase: KnowledgeBase = {
const newBase = {
id: nanoid(),
name: values.name,
model: selectedEmbeddingModel,
rerankModel: selectedRerankModel,
dimensions: values.dimensions,
dimensions,
documentCount: values.documentCount || DEFAULT_KNOWLEDGE_DOCUMENT_COUNT,
items: [],
created_at: Date.now(),
@@ -141,7 +134,7 @@ const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
await window.api.knowledgeBase.create(getKnowledgeBaseParams(newBase))
addKnowledgeBase(newBase)
addKnowledgeBase(newBase as any)
setOpen(false)
resolve(newBase)
}
@@ -210,59 +203,11 @@ const PopupContainer: React.FC<Props> = ({ title, resolve }) => {
marks={{ 1: '1', 6: t('knowledge.document_count_default'), 30: '30' }}
/>
</Form.Item>
<Form.Item
name="autoDims"
colon={false}
initialValue={true}
layout="horizontal"
label={t('knowledge.dimensions_auto_set')}
tooltip={t('knowledge.dimensions_default')}
style={{ marginBottom: 0, justifyContent: 'space-between' }}>
<Flex justify="flex-end" style={{ marginBottom: '1rem' }}>
<Switch
checked={autoDims}
onClick={() => {
form.setFieldValue('autoDims', !autoDims)
if (!autoDims) {
form.validateFields(['dimensions'])
}
setAutoDims(!autoDims)
}}></Switch>
</Flex>
</Form.Item>
<Form.Item
name="dimensions"
colon={false}
layout="horizontal"
initialValue={undefined}
label={t('knowledge.dimensions')}
tooltip={{ title: t('knowledge.dimensions_size_tooltip') }}
dependencies={['model']}
style={{ display: autoDims ? 'none' : 'block' }}
rules={[
({ getFieldValue }) => ({
validator(_, value) {
if (getFieldValue('autoDims') || value > 0) {
return Promise.resolve()
} else {
return Promise.reject(t('knowledge.dimensions_error_invalid'))
}
}
})
]}>
<InputNumber min={1} style={{ width: '100%' }} placeholder={t('knowledge.dimensions_size_placeholder')} />
</Form.Item>
{!autoDims && (
<SettingHelpText style={{ marginTop: -15, marginBottom: 20 }}>
{t('knowledge.dimensions_set_right')}
</SettingHelpText>
)}
</Form>
</Modal>
)
}
export default class AddKnowledgePopup {
static hide() {
TopView.hide('AddKnowledgePopup')

View File

@@ -187,6 +187,32 @@ const PopupContainer: React.FC<Props> = ({ base: _base, resolve }) => {
</AdvancedSettingsButton>
<div style={{ display: showAdvanced ? 'block' : 'none' }}>
<Form.Item
name="dimensions"
label={t('knowledge.dimensions')}
layout="horizontal"
initialValue={base.dimensions}
tooltip={{ title: t('knowledge.dimensions_size_tooltip') }}
rules={[
{
validator(_, value) {
const maxContext = getEmbeddingMaxContext(base.model.id)
if (value && maxContext && value > maxContext) {
return Promise.reject(
new Error(t('knowledge.dimensions_size_too_large', { max_context: maxContext }))
)
}
return Promise.resolve()
}
}
]}>
<InputNumber
style={{ width: '100%' }}
defaultValue={base.dimensions}
placeholder={t('knowledge.dimensions_size_placeholder')}
disabled={base.model.id !== 'voyage-3-large'}
/>
</Form.Item>
<Form.Item
name="chunkSize"
label={t('knowledge.chunk_size')}

View File

@@ -15,8 +15,8 @@ import { useAppDispatch } from '@renderer/store'
import { setGenerating } from '@renderer/store/runtime'
import type { FileType, PaintingsState } from '@renderer/types'
import { uuid } from '@renderer/utils'
import { DmxapiPainting } from '@types'
import { Avatar, Button, Input, Radio, Segmented, Select, Switch, Tooltip } from 'antd'
import { DmxapiPainting, PaintingAction } from '@types'
import { Avatar, Button, Input, Radio, Select, Switch, Tooltip } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { Info } from 'lucide-react'
import React, { FC } from 'react'
@@ -25,19 +25,14 @@ import { useTranslation } from 'react-i18next'
import { useLocation, useNavigate } from 'react-router-dom'
import styled from 'styled-components'
import { generationModeType } from '../../types'
import SendMessageButton from '../home/Inputbar/SendMessageButton'
import { SettingHelpLink, SettingTitle } from '../settings'
import Artboard from './components/Artboard'
import ImageUploader from './components/ImageUploader'
import PaintingsList from './components/PaintingsList'
import {
COURSE_URL,
DEFAULT_PAINTING,
IMAGE_EDIT_MODELS,
IMAGE_MERGE_MODELS,
IMAGE_SIZES,
MODEOPTIONS,
STYLE_TYPE_OPTIONS,
TEXT_TO_IMAGES_MODELS
} from './config/DmxapiConfig'
@@ -69,71 +64,11 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
const navigate = useNavigate()
const location = useLocation()
interface FileMapType {
imageFiles?: FileType[]
paths?: string[]
}
const [fileMap, setFileMap] = useState<FileMapType>({
imageFiles: [],
paths: []
})
const modeOptions = MODEOPTIONS.map((ele) => {
return {
label: t(ele.label),
value: ele.value
}
})
const getModelOptions = (mode: generationModeType) => {
if (mode === generationModeType.EDIT) {
return IMAGE_EDIT_MODELS.map((model) => ({
label: model.name,
value: model.id
}))
}
if (mode === generationModeType.MERGE) {
return IMAGE_MERGE_MODELS.map((model) => ({
label: model.name,
value: model.id
}))
}
// 默认情况或其它模式下的选项
return TEXT_TO_IMAGES_MODELS.map((model) => ({
label: model.name,
value: model.id
}))
}
const [modelOptions, setModelOptions] = useState(() => {
// 根据当前painting的generationMode初始化modelOptions
const currentMode = painting?.generationMode || (MODEOPTIONS[0].value as generationModeType)
return getModelOptions(currentMode)
})
const textareaRef = useRef<any>(null)
// 更新painting状态的辅助函数
const updatePaintingState = (updates: Partial<DmxapiPainting>) => {
const updatedPainting = { ...painting, ...updates }
setPainting(updatedPainting)
updatePainting('DMXAPIPaintings', updatedPainting)
}
const getNewPainting = (params?: Partial<DmxapiPainting>) => {
clearImages()
const generationMode = params?.generationMode || painting?.generationMode || MODEOPTIONS[0].value
const modelOptionsList = getModelOptions(generationMode as generationModeType)
const getNewPainting = () => {
return {
...DEFAULT_PAINTING,
id: uuid(),
seed: generateRandomSeed(),
generationMode,
model: modelOptionsList[0]?.value,
...params
seed: generateRandomSeed()
}
}
@@ -147,6 +82,19 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
setPainting(addPainting('DMXAPIPaintings', copyPainting))
}
const modelOptions = TEXT_TO_IMAGES_MODELS.map((model) => ({
label: model.name,
value: model.id
}))
const textareaRef = useRef<any>(null)
const updatePaintingState = (updates: Partial<DmxapiPainting>) => {
const updatedPainting = { ...painting, ...updates }
setPainting(updatedPainting)
updatePainting('DMXAPIPaintings', updatedPainting)
}
const onSelectModel = (modelId: string) => {
const model = TEXT_TO_IMAGES_MODELS.find((m) => m.id === modelId)
if (model) {
@@ -187,62 +135,6 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
}
}
const onbeforeunload = (file, index?: number) => {
const path = URL.createObjectURL(file)
// 更新 fileMap
setFileMap((prevFileMap) => {
const currentFiles = prevFileMap.imageFiles || []
const currentPaths = prevFileMap.paths || []
let newFiles: FileType[]
let newPaths: string[]
if (index !== undefined) {
// 替换指定索引的图片
newFiles = [...currentFiles]
newFiles[index] = file as FileType
newPaths = [...currentPaths]
newPaths[index] = path
} else {
// 添加新图片到最后
newFiles = [...currentFiles, file as FileType]
newPaths = [...currentPaths, path]
}
return {
imageFiles: newFiles,
paths: newPaths
}
})
return false // 阻止默认上传行为
}
const onGenerationModeChange = (v: generationModeType) => {
clearImages()
const newModelOptions = getModelOptions(v)
setModelOptions(newModelOptions)
const firstModel = newModelOptions[0]?.value
// 如果有urls创建新的painting
if (Array.isArray(painting.urls) && painting.urls.length > 0) {
const newPainting = getNewPainting({
generationMode: v,
model: firstModel // 使用新模式下的第一个模型
})
const addedPainting = addPainting('DMXAPIPaintings', newPainting)
setPainting(addedPainting)
} else {
// 否则更新当前painting
updatePaintingState({
generationMode: v,
model: firstModel // 使用新模式下的第一个模型
})
}
}
// 检查提供者状态函数
const checkProviderStatus = () => {
if (!dmxapiProvider.enabled) {
@@ -260,14 +152,6 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
if (!painting.prompt) {
throw new Error('paintings.text_desc_required')
}
if (
painting.generationMode &&
[generationModeType.EDIT, generationModeType.MERGE].includes(painting.generationMode) &&
(!fileMap.imageFiles || fileMap.imageFiles.length === 0)
) {
throw new Error('paintings.image_handle_required')
}
}
// 准备V1生成请求函数
@@ -278,10 +162,6 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
n: painting.n
}
const headerExpand = {
'Content-Type': 'application/json'
}
if (painting.aspect_ratio) {
params['aspect_ratio'] = painting.aspect_ratio
}
@@ -304,57 +184,21 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
return {
body: JSON.stringify(params),
headerExpand: headerExpand,
endpoint: `${dmxapiProvider.apiHost}/v1/images/generations`
}
}
// 准备V2生成请求函数
const prepareV2GenerateRequest = (prompt: string, painting: DmxapiPainting) => {
const params = {
prompt,
n: painting.n,
model: painting.model
}
if (painting.image_size) {
params['size'] = '1024x1024'
}
if (painting.style_type) {
params.prompt = prompt + ',风格:' + painting.style_type
}
const formData = new FormData()
for (const key in params) {
formData.append(key, params[key])
}
if (Array.isArray(fileMap.imageFiles)) {
fileMap.imageFiles.forEach((file) => {
formData.append(`image`, file as unknown as Blob)
})
}
return {
body: formData,
endpoint: `${dmxapiProvider.apiHost}/v1/images/edits`
}
}
// API请求函数
const callApi = async (
requestConfig: { endpoint: string; body: any; headerExpand?: any },
controller: AbortController
) => {
const { endpoint, body, headerExpand } = requestConfig
const callApi = async (requestConfig: { endpoint: string; body: any }, controller: AbortController) => {
const { endpoint, body } = requestConfig
const headers = {}
const headers = {
Accept: 'application/json',
Authorization: `Bearer ${dmxapiProvider.apiKey}`,
'User-Agent': 'DMXAPI/1.0.0 (https://www.dmxapi.com)',
...headerExpand
// 如果是JSON数据添加Content-Type头
if (typeof body === 'string') {
headers['Content-Type'] = 'application/json'
headers['Authorization'] = `Bearer ${dmxapiProvider.apiKey}`
headers['User-Agent'] = 'DMXAPI/1.0.0 (https://www.dmxapi.com)'
headers['Accept'] = 'application/json'
}
const response = await fetch(endpoint, {
@@ -365,23 +209,10 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
})
if (!response.ok) {
if (response.status === 401) {
throw new Error('paintings.req_error_token')
} else if (response.status === 403) {
throw new Error('paintings.req_error_no_balance')
}
throw new Error('操作失败,请稍后重试')
}
const data = await response.json()
if (
painting.generationMode &&
[generationModeType.EDIT, generationModeType.MERGE].includes(painting.generationMode)
) {
return data.data.map((item: { b64_json: string }) => 'data:image/png;base64,' + item.b64_json)
}
return data.data.map((item: { url: string }) => item.url)
}
@@ -415,16 +246,9 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
}
// 准备请求配置函数
const prepareRequestConfig = (prompt: string, painting: DmxapiPainting) => {
const prepareRequestConfig = (prompt: string, painting: PaintingAction) => {
// 根据模式和模型版本返回不同的请求配置
if (
painting.generationMode !== undefined &&
[generationModeType.MERGE, generationModeType.EDIT].includes(painting.generationMode)
) {
return prepareV2GenerateRequest(prompt, painting)
} else {
return prepareV1GenerateRequest(prompt, painting)
}
return prepareV1GenerateRequest(prompt, painting)
}
const onGenerate = async () => {
@@ -514,7 +338,7 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
setCurrentImageIndex((prev) => (prev - 1 + painting.files.length) % painting.files.length)
}
const onDeletePainting = async (paintingToDelete: DmxapiPainting) => {
const onDeletePainting = (paintingToDelete: DmxapiPainting) => {
if (paintingToDelete.id === painting.id) {
const currentIndex = DMXAPIPaintings.findIndex((p) => p.id === paintingToDelete.id)
@@ -525,25 +349,17 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
}
}
// 删除绘画
await removePainting(mode, paintingToDelete)
// 检查是否删除空了
if (!DMXAPIPaintings || DMXAPIPaintings.length === 1) {
// 如果删除后没有绘画了,创建一个新的
const newPainting = getNewPainting()
const addedPainting = addPainting('DMXAPIPaintings', newPainting)
setPainting(addedPainting)
}
removePainting(mode, paintingToDelete).then(() => {})
}
const onSelectPainting = (newPainting: DmxapiPainting) => {
if (generating) return
clearImages()
setPainting(newPainting)
setCurrentImageIndex(0)
}
const spaceClickTimer = useRef<NodeJS.Timeout>(null)
const handleProviderChange = (providerId: string) => {
const routeName = location.pathname.split('/').pop()
if (providerId !== routeName) {
@@ -551,97 +367,20 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
}
}
// 清除图片函数
const clearImages = () => {
setFileMap(() => ({ paths: [], imageFiles: [] }))
}
const handleDeleteImage = (index: number) => {
setFileMap((prevFileMap) => {
const newPaths = [...(prevFileMap.paths || [])]
const newImageFiles = [...(prevFileMap.imageFiles || [])]
// 删除指定索引的图片
newPaths.splice(index, 1)
newImageFiles.splice(index, 1)
return {
paths: newPaths,
imageFiles: newImageFiles
}
})
}
// 定义大图的默认图片
const defaultCoverImage = () => {
if (painting.generationMode === generationModeType.EDIT) {
if (painting?.urls.length === 0 && fileMap.paths && fileMap.paths?.length > 0 && fileMap.paths[0]) {
return (
<EmptyImgBox>
<EmptyImg bgUrl={fileMap.paths[0]}></EmptyImg>
</EmptyImgBox>
)
}
}
if (painting?.urls?.length > 0 || DMXAPIPaintings?.length > 1) {
return null
} else {
return (
<EmptyImgBox>
<EmptyImg></EmptyImg>
</EmptyImgBox>
)
}
}
const defaultLoadText = () => {
if (
painting.generationMode &&
[generationModeType.EDIT, generationModeType.MERGE].includes(painting.generationMode)
) {
return (
<LoadTextWrap>
<div>
OpenAI gpt-image-1
<br />
2~5
<br />
DMIAPI后台日志查看
</div>
</LoadTextWrap>
)
}
return null
}
useEffect(() => {
if (!DMXAPIPaintings || DMXAPIPaintings.length === 0) {
const newPainting = getNewPainting()
addPainting('DMXAPIPaintings', newPainting)
setPainting(newPainting)
} else if (painting && !painting.generationMode) {
// 如果当前painting没有generationMode添加默认值
const updatedPainting = { ...painting, generationMode: MODEOPTIONS[0].value }
setPainting(updatedPainting)
updatePainting('DMXAPIPaintings', updatedPainting)
}
// 确保所有paintings都有generationMode属性
DMXAPIPaintings.forEach((p) => {
if (!p.generationMode) {
const updatedPainting = { ...p, generationMode: MODEOPTIONS[0].value }
updatePainting('DMXAPIPaintings', updatedPainting)
return () => {
if (spaceClickTimer.current) {
// eslint-disable-next-line react-hooks/exhaustive-deps
clearTimeout(spaceClickTimer.current)
}
})
// 确保modelOptions与当前painting的generationMode保持一致
if (painting?.generationMode) {
setModelOptions(getModelOptions(painting.generationMode as generationModeType))
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []) // 空依赖数组,只在组件挂载时执行一次
}, [DMXAPIPaintings, DMXAPIPaintings.length, addPainting, mode])
return (
<Container>
@@ -683,60 +422,40 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
</Select.Option>
))}
</Select>
{painting.generationMode &&
[generationModeType.EDIT, generationModeType.MERGE].includes(painting.generationMode) && (
<>
<SettingTitle style={{ marginBottom: 5, marginTop: 15 }}></SettingTitle>
<ImageUploader
fileMap={fileMap}
maxImages={painting.generationMode === generationModeType.EDIT ? 1 : 3}
onClearImages={clearImages}
onDeleteImage={handleDeleteImage}
onAddImage={onbeforeunload}
mode={painting.generationMode}
/>
</>
)}
<SettingTitle style={{ marginBottom: 5, marginTop: 15 }}>{t('common.model')}</SettingTitle>
<Select value={painting.model} options={modelOptions} onChange={onSelectModel} />
<SettingTitle style={{ marginBottom: 5, marginTop: 15 }}>{t('paintings.image.size')}</SettingTitle>
<Radio.Group
value={painting.image_size}
onChange={(e) => onSelectImageSize(e.target.value)}
style={{ display: 'flex' }}>
{IMAGE_SIZES.map((size) => (
<RadioButton value={size.value} key={size.value}>
<VStack alignItems="center">
<ImageSizeImage src={size.icon} theme={theme} />
<span>{size.label}</span>
</VStack>
</RadioButton>
))}
</Radio.Group>
{painting.generationMode === generationModeType.GENERATION && (
<>
<SettingTitle style={{ marginBottom: 5, marginTop: 15 }}>{t('paintings.image.size')}</SettingTitle>
<Radio.Group
value={painting.image_size}
onChange={(e) => onSelectImageSize(e.target.value)}
style={{ display: 'flex' }}>
{IMAGE_SIZES.map((size) => (
<RadioButton value={size.value} key={size.value}>
<VStack alignItems="center">
<ImageSizeImage src={size.icon} theme={theme} />
<span>{size.label}</span>
</VStack>
</RadioButton>
))}
</Radio.Group>
<SettingTitle style={{ marginBottom: 5, marginTop: 15 }}>
{t('paintings.seed')}
<Tooltip title={t('paintings.seed_desc_tip')}>
<InfoIcon />
</Tooltip>
</SettingTitle>
<Input
value={painting.seed}
pattern="[0-9]*"
onChange={(e) => onInputSeed(e)}
suffix={
<RedoOutlined
onClick={() => updatePaintingState({ seed: Math.floor(Math.random() * 1000000).toString() })}
style={{ cursor: 'pointer', color: 'var(--color-text-2)' }}
/>
}
<SettingTitle style={{ marginBottom: 5, marginTop: 15 }}>
{t('paintings.seed')}
<Tooltip title={t('paintings.seed_desc_tip')}>
<InfoIcon />
</Tooltip>
</SettingTitle>
<Input
value={painting.seed}
pattern="[0-9]*"
onChange={(e) => onInputSeed(e)}
suffix={
<RedoOutlined
onClick={() => updatePaintingState({ seed: Math.floor(Math.random() * 1000000).toString() })}
style={{ cursor: 'pointer', color: 'var(--color-text-2)' }}
/>
</>
)}
}
/>
<SettingTitle style={{ marginBottom: 5, marginTop: 15 }}>{t('paintings.style_type')}</SettingTitle>
<SliderContainer>
@@ -763,14 +482,6 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
</HStack>
</LeftContainer>
<MainContainer>
<ModeSegmentedContainer>
<Segmented
shape="round"
value={painting.generationMode}
onChange={onGenerationModeChange}
options={modeOptions}
/>
</ModeSegmentedContainer>
<Artboard
painting={painting}
isLoading={isLoading}
@@ -778,8 +489,13 @@ const DmxapiPage: FC<{ Options: string[] }> = ({ Options }) => {
onPrevImage={prevImage}
onNextImage={nextImage}
onCancel={onCancel}
imageCover={defaultCoverImage()}
loadText={defaultLoadText()}
imageCover={
painting?.urls?.length > 0 || DMXAPIPaintings?.length > 1 ? null : (
<EmptyImgBox>
<EmptyImg></EmptyImg>
</EmptyImgBox>
)
}
/>
<InputContainer>
<Textarea
@@ -968,13 +684,6 @@ const RadioTextItem = styled.div`
}
`
// 添加新的样式组件
const ModeSegmentedContainer = styled.div`
display: flex;
justify-content: center;
padding-top: 24px;
`
const EmptyImgBox = styled.div`
display: flex;
flex: 1;
@@ -983,25 +692,11 @@ const EmptyImgBox = styled.div`
align-items: center;
`
const EmptyImg = styled.div<{ bgUrl?: string }>`
const EmptyImg = styled.div`
width: 70vh;
height: 70vh;
background-size: cover;
background-image: ${(props) => (props.bgUrl ? `url(${props.bgUrl})` : `url(${DMXAPIToImg})`)};
`
const LoadTextWrap = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
color: black;
text-shadow:
-1px -1px 0 #ffffff,
1px -1px 0 #ffffff,
-1px 1px 0 #ffffff,
1px 1px 0 #ffffff;
background-size: 100% 100%;
background-image: url(${DMXAPIToImg});
`
export default DmxapiPage

View File

@@ -1,11 +1,14 @@
import ImageViewer from '@renderer/components/ImageViewer'
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons'
import FileManager from '@renderer/services/FileManager'
import { Painting } from '@renderer/types'
import { Button, Spin } from 'antd'
import { download } from '@renderer/utils/download'
import { Button, Dropdown, Spin } from 'antd'
import React, { FC } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
import ImagePreview from '../../home/Markdown/ImagePreview'
interface ArtboardProps {
painting: Painting
isLoading: boolean
@@ -15,7 +18,6 @@ interface ArtboardProps {
onCancel: () => void
retry?: (painting: Painting) => void
imageCover?: React.ReactNode
loadText?: React.ReactNode
}
const Artboard: FC<ArtboardProps> = ({
@@ -26,8 +28,7 @@ const Artboard: FC<ArtboardProps> = ({
onNextImage,
onCancel,
retry,
imageCover,
loadText
imageCover
}) => {
const { t } = useTranslation()
@@ -36,6 +37,29 @@ const Artboard: FC<ArtboardProps> = ({
return currentFile ? FileManager.getFileUrl(currentFile) : ''
}
const handleContextMenu = (e: React.MouseEvent) => {
e.preventDefault()
}
const getContextMenuItems = () => {
return [
{
key: 'copy',
label: t('common.copy'),
icon: <CopyOutlined />,
onClick: () => {
navigator.clipboard.writeText(painting.urls[currentImageIndex])
}
},
{
key: 'download',
label: t('common.download'),
icon: <DownloadOutlined />,
onClick: () => download(getCurrentImageUrl())
}
]
}
return (
<Container>
<LoadingContainer spinning={isLoading}>
@@ -46,17 +70,20 @@ const Artboard: FC<ArtboardProps> = ({
</NavigationButton>
)}
<ImageViewer
src={getCurrentImageUrl()}
preview={{ mask: false }}
style={{
maxWidth: '70vh',
maxHeight: '70vh',
objectFit: 'contain',
backgroundColor: 'var(--color-background-soft)',
cursor: 'pointer'
}}
/>
<Dropdown menu={{ items: getContextMenuItems() }} trigger={['contextMenu']}>
<ImagePreview
src={getCurrentImageUrl()}
preview={{ mask: false }}
onContextMenu={handleContextMenu}
style={{
maxWidth: '70vh',
maxHeight: '70vh',
objectFit: 'contain',
backgroundColor: 'var(--color-background-soft)',
cursor: 'pointer'
}}
/>
</Dropdown>
{painting.files.length > 1 && (
<NavigationButton onClick={onNextImage} style={{ right: 10 }}>
@@ -84,8 +111,6 @@ const Artboard: FC<ArtboardProps> = ({
</div>
) : imageCover ? (
imageCover
) : loadText && isLoading ? (
''
) : (
<div>{t('paintings.image_placeholder')}</div>
)}
@@ -94,7 +119,6 @@ const Artboard: FC<ArtboardProps> = ({
{isLoading && (
<LoadingOverlay>
<Spin size="large" />
{loadText ? loadText : ''}
<CancelButton onClick={onCancel}>{t('common.cancel')}</CancelButton>
</LoadingOverlay>
)}

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