Skip to content

Commit 4757583

Browse files
MyPrototypeWhatlizhixuanalephpieceousugokangfenmao
authored
refactor: message block structure (#4660)
* feat(message-blocks): introduce new message block types and middleware for handling message updates - Added new types for message blocks including MainText, Thinking, Translation, Code, Image, ToolCall, ToolResult, KnowledgeCitation, WebSearch, File, and Error blocks. - Implemented middleware to manage message block mapping and updates in Redux, enhancing the handling of message states and blocks. - Introduced LRU caching for efficient message block retrieval and management. * feat(messages): implement message management slice and utility functions - Introduced a new Redux slice for managing messages, including actions for setting the current topic, loading state, error handling, and message updates. - Added utility functions for creating various message block types, enhancing the structure and management of message content. - Updated message type definitions to include timestamped block references, improving the tracking of message block states. * feat(store): add messageBlocks reducer and integrate into rootReducer - Introduced a new messageBlocks reducer to manage message block state. - Updated rootReducer to include messageBlocks alongside existing reducers. - Refactored newMessage slice to accommodate changes in message structure and block handling. - Removed obsolete messageBlockMap utility file to streamline codebase. * feat(database): implement version 7 migration and enhance message structure - Added new message_blocks table to the database schema for improved message handling. - Introduced upgradeToV7 function to migrate existing topics and messages to the new structure. - Refactored message creation utilities to support new message block types and improved error handling. - Implemented various message filtering utilities to streamline message processing. - Updated Redux store to accommodate new message structure and loading states. * feat(message): refactor message handling and introduce messageStreamProcessor - Updated database schema to correct types for topics and message blocks. - Introduced messageStreamProcessor to handle API responses and transform them into application-specific data structures. - Refactored messageThunk to streamline message creation and updates, ensuring consistency with the new message structure. - Enhanced error handling and state management during message processing. * refactor(message): update message handling with new types and utility functions - Refactored message operations to utilize new message types and improved utility functions for content retrieval. - Introduced helper functions for finding message blocks, enhancing the structure and readability of message processing. - Updated various providers to align with the new message structure, ensuring consistent handling of message content and blocks. - Enhanced error handling and state management during message processing, improving overall reliability. * refactor(message): wip create XxxBlock components - Refactored message handling to utilize new message types, enhancing the overall structure and readability. - Introduced new message blocks including CitationBlock, CodeBlock, ErrorBlock, FileBlock, ImageBlock, ThinkingBlock, ToolBlock, and TranslationBlock. - Updated existing components to align with the new message structure, ensuring consistent handling of message content and blocks. - Improved utility functions for finding and processing message blocks, enhancing the reliability of message operations. * refactor(message): enhance message operations with new selectors and blocks - Updated useMessageOperations to integrate new message block types and selectors for improved state management. - Introduced new selectors for fetching topic messages and loading states, enhancing the efficiency of message retrieval. - Refactored message handling in Inputbar and MessageContent components to align with the new message structure. - Added CitationBlock and improved rendering logic for message blocks, ensuring consistent display of message content. - Enhanced error handling and logging for message operations, improving overall reliability. * refactor(message): enhance message update logic with block instructions - Updated the updateMessage reducer to handle block instructions, allowing for more flexible message updates. - Improved the fetchAndProcessAssistantResponseImpl function to track the last added block, ensuring proper handling of streaming content. - Refactored stream processing to accommodate new callback signatures and improve error handling. - Removed unused console logs and cleaned up code for better readability and maintainability. * merge origin/main * refactor(message): update message handling and block structure - Replaced `prepareTopicMessages` with `loadTopicMessagesThunk` for improved message loading logic. - Updated `MessageTools` to accept `ToolBlock` instead of `Message`, enhancing type safety. - Introduced `resetMessage` utility to streamline message object creation and reset mutable fields. - Refactored `findCitationBlocks` and related types for consistency in message block handling. - Enhanced error handling in message update logic to ensure robustness during database operations. * refactor(message): update message and block handling for improved clarity and performance - Refactored message handling by removing unnecessary cloning of messages in `MessageContent`. - Updated `Inputbar` to import `Message` from the new message types module. - Simplified block rendering logic in `MessageBlockRenderer` by removing redundant checks. - Adjusted `StreamProcessingService` to use the updated import path for `GroundingMetadata`. - Enhanced message status handling in `newMessage` to include 'streaming' status. - Removed deprecated `createUserMessageThunk` to streamline thunk actions. - Updated type definitions in `newMessageTypes` for better clarity and consistency. * refactor(message): enhance message block structure and type handling - Updated `Markdown` component to utilize `MainTextMessageBlock` for improved type safety. - Refactored `MessageContent` to remove error handling logic and streamline rendering. - Adjusted `MessageError` to accept `ErrorMessageBlock` and simplified error display logic. - Enhanced `MessageTools` to work with `ToolMessageBlock`, improving clarity in tool response handling. - Updated `MainTextBlock` to pass the correct props to `Markdown`, ensuring consistent rendering. - Refactored utility functions to align with new message block types, enhancing overall code clarity and maintainability. * refactor: update message types import paths and enhance message handling logic - Changed import paths for message types from 'newMessageTypes' to 'newMessage' across multiple files. - Refactored message handling functions to utilize the new message structure, ensuring compatibility with the updated types. - Improved logic for finding and processing main text blocks in messages. - Updated related components and hooks to reflect the new message structure, enhancing overall code maintainability. * refactor: improve stream processing and message handling logic - Updated the `createStreamProcessor` function to handle null and undefined chunks more robustly. - Introduced a helper function `handleBlockTransition` to streamline state transitions between message blocks. - Enhanced error handling in the `onComplete` function to specifically manage abort errors and create error blocks when necessary. - Improved final block status updates to ensure accurate tracking of message processing states. * refactor: use rehype-sanitize for html tags # Conflicts: # src/renderer/src/pages/home/Markdown/Markdown.tsx * refactor: merge rehype plugins * refactor(ModelList): extract NameSpan component and adjust styling for better layout * feat: update Z.ai app configuration with additional styling and increment store version to 97 # Conflicts: # src/renderer/src/store/index.ts * feat(FeatureMenus, Footer): replace Ant Design icons with Lucide icons and enhance layout - Updated icons in FeatureMenus from Ant Design to Lucide for improved visual consistency. - Refactored Footer component to use Lucide icons and adjusted layout for better alignment and spacing. - Enhanced styling of Tag components for a more cohesive design. * lint: fix code format * chore(version): 1.2.5 * feat(locales): add locale cleanup functionality to after-pack script - Introduced a new `remove-locales.js` script to handle the removal of unnecessary locale files based on the platform. - Integrated the locale cleanup process into the `after-pack.js` script to ensure locales are managed during packaging. * feat: support escaping the comma character in the API key. (#5088) feat: support escaping the comma character in the API key. * feat(Citations): enhance CitationsList with title and info icon, and update styling * Revert "feat: add chat message translate copy button (#4620)" This reverts commit c452fdf. # Conflicts: # src/renderer/src/hooks/useMessageOperations.ts # src/renderer/src/pages/home/Inputbar/Inputbar.tsx * refactor: update message status handling and improve message creation logic - Introduced `AssistantMessageStatus` to standardize message statuses across the application. - Updated various components and services to utilize the new status enum, replacing string literals for better type safety. - Refactored message creation and processing functions to align with the new status definitions. - Adjusted filtering logic in `useMessageOperations` to reflect changes in message status handling. - Cleaned up unused code and comments for improved readability. * refactor: enhance citation handling and web search integration - Updated CitationBlock and MainTextBlock components to improve citation processing logic. - Refactored citation data handling to accommodate new web search sources and formats. - Introduced new chunk types for better handling of streaming responses, including text and web search results. - Enhanced the integration of web search results into message blocks, ensuring accurate citation references. - Updated related types and interfaces to reflect changes in citation and web search structures. * refactor: improve message handling and citation integration - Added debug logging to various components for better traceability during message processing. - Refactored CitationBlock and MainTextBlock to streamline citation handling and improve integration with web search results. - Updated Inputbar to include debug logs for message sending and dispatching actions. - Enhanced the message block rendering logic to decouple citation references from main text blocks. - Improved the handling of citation data and ensured accurate formatting across different sources. * feat: add regenerate assistant response functionality - Introduced `regenerateAssistantResponseThunk` to allow regeneration of assistant messages. - Updated `useMessageOperations` to include the new `regenerateAssistantMessage` function. - Refactored `MessageMenubar` to utilize the new regeneration feature. - Adjusted `MessageImage` and `ImageBlock` components to align with updated props. - Cleaned up unused code and comments across various files for improved readability. * fix: deepseek-reasoner does not support successive user or assistant messages in MCP scenario (#5112) * fix: deepseek-reasoner does not support successive user or assistant messages in MCP scenario. * fix: @ts-ignore * refactor: remove google analytics * feat: add PostHogProvider for analytics integration - Introduced PostHogProvider to manage data collection based on user settings. - Wrapped the main application in PostHogProvider to enable analytics when data collection is allowed. * refactor(AxiosProxy): improve proxy handling and initialization logic - Changed cacheAxios from undefined to null for better initialization. - Updated proxy handling to use ProxyAgent, ensuring axios instance is recreated when the proxy changes. - Simplified axios instance creation by directly using the current proxy agent. * refactor: remove search enhanceMode * fix: 知识库和网络搜索使用输出语言问题 (#5129) * feat(proxy): use os-proxy-config to get system proxy info instead of resolveProxy (#5123) * feat(proxy): integrate os-proxy-config for system proxy management - Added os-proxy-config dependency to manage system proxy settings. - Refactored setSystemProxy method to utilize getSystemProxy for improved proxy handling. * fix lint error * chore(version): 1.2.6 * fix: zipfile dependencies * chore(release): update default release tag to v1.0.0 and install setuptools for Mac build * disable auto update in portable exe * chore(electron-builder): add StartupWMClass for CherryStudio in liunx desktop configuration (#5158) chore(electron-builder): add StartupWMClass for CherryStudio in desktop configuration * fix(MinApp): integrate dynamic background color for MinappPopupContainer (#5142) * fix(models): 更新OpenRouter模型ID和名称,简化模型组分类 (#5172) * fix: purify minapp user agent tag (#5173) * fix: electron-builder 新增配置导致的无法构建的问题 (#5175) fix: electron-builder 新增配置导致的无法构建的问题 当前 electron-builder 的版本为 "26.0.13",但在 v26 之后,StartupWMClass 等配置标签要在 desktop > entry 下,而不是直接在 desktop 下,否则会导致无法构建打包 * Revert "fix(minapps): remove AI Studio entry from default mini apps list" (#5177) This reverts commit 5834eae. * refactor(Markdown): remove rehype-sanitize and implement custom element filtering - Removed rehype-sanitize dependency and its related configuration. - Introduced ALLOWED_ELEMENTS and DISALLOWED_ELEMENTS for custom HTML element filtering. - Updated rehypePlugins logic to conditionally apply plugins based on message content. - Added encodeHTML utility function for HTML entity encoding. # Conflicts: # src/renderer/src/pages/home/Markdown/Markdown.tsx * refactor: mcp buttons and mcp settings * refactor: add MessageTranslate.tsx & MessageCitations.tsx * refactor: add MessageContent.main.tsx { getModelUniqId } from '@renderer/services/ModelService' import { Message, Model } from '@renderer/types' import { getBriefInfo } from '@renderer/utils' import { formatCitations, withMessageThought } from '@renderer/utils/formats' import { encodeHTML } from '@renderer/utils/markdown' import { Flex } from 'antd' import { clone } from 'lodash' import { Search } from 'lucide-react' import React, { Fragment, useMemo } from 'react' import { useTranslation } from 'react-i18next' import BarLoader from 'react-spinners/BarLoader' import styled, { css } from 'styled-components' * refactor: enhance translation handling by integrating TranslationMessageBlock into Markdown and MessageTranslate components, and streamline TranslationBlock to utilize MessageTranslate for rendering. * refactor: introduce citation processing optimization checklist and enhance citation handling - Added a new refactoring checklist for optimizing citation processing logic. - Implemented a lookup map for citations in MainTextBlock to improve performance. - Updated Citation interface to include optional content field. - Modified chunk types for web and knowledge search responses to improve type safety. - Enhanced citation formatting to include content from web search results. * refactor: update web search handling in GeminiProvider and OpenAIProvider * refactor: update prompt handling and citation processing logic * refactor: standardize chunk type usage across providers and improve image handling in MessageImage component * refactor: update message operations and API service for improved message handling - Translated comment in useMessageOperations.ts for clarity. - Refactored ApiService to utilize findMainTextBlocks for knowledge base checks. - Enhanced messageThunk with multi-model dispatch logic for better assistant response handling. * refactor: optimize knowledge base ID handling in ApiService - Removed unused store import and streamlined knowledge base ID extraction logic. - Enhanced fetchExternalTool function to utilize mainTextBlocks for knowledge base checks, improving clarity and efficiency. * feat: add message lifecycle documentation and enhance citation handling in CitationBlock component * feat: add SearchingSpinner component and enhance message handling with ThinkingMessageBlock - Introduced a new SearchingSpinner component for better user feedback during processing. - Updated Markdown and MessageThought components to support ThinkingMessageBlock. - Enhanced CitationBlock to display the SearchingSpinner when processing citations. - Refactored message handling to include thinking time metrics across various components and services. * refactor: enhance ApiService and message handling for improved search functionality - Streamlined knowledge base ID extraction using flatMap for better performance. - Added early checks for extractResults in search functions to prevent errors and improve logging. - Updated chunk types to include SEARCH_IN_PROGRESS_UNION and SEARCH_COMPLETE_UNION for better state management during searches. - Refactored search execution logic to handle different search scenarios more efficiently. * refactor: streamline message update logic and enhance block handling - Simplified message update dispatching by using the store's dispatch directly. - Improved block transition handling by replacing direct calls with a dedicated function. - Refactored conditional logic for updating blocks to ensure accurate state management. * feat: enhance StreamProcessingService with tool call progress handling - Added onToolCallInProgress callback to StreamProcessorCallbacks for handling tool call progress updates. - Updated createStreamProcessor function to accept an empty object as default for callbacks. - Implemented logic to process MCP_TOOL_IN_PROGRESS and MCP_TOOL_COMPLETE chunks in message handling. - Improved type definitions for MCPToolInProgressChunk to include responses. * refactor: enhance AI providers with abort controller integration for improved request handling - Added abort controller functionality to AnthropicProvider, GeminiProvider, and OpenAIProvider to manage request cancellations effectively. - Updated API calls to include signal for aborting requests, ensuring better control over ongoing operations. - Improved cleanup logic to handle abort scenarios gracefully. * feat: add TODO for pause capability in WebSearchService - Added a TODO comment in WebSearchService to implement pause functionality for network searches, enhancing future service capabilities. * fix(WebdavBackupManager): update modal confirmation to use window.modal and center content * refactor: improve message operations and API service for enhanced functionality - Updated useMessageOperations to dispatch resendMessageThunk with topic ID instead of object for better clarity. - Refactored ApiService to streamline knowledge base ID extraction using flatMap and added early checks for improved error handling. - Enhanced message handling in messageThunk by integrating topic queue management and simplifying error handling logic. - Cleaned up commented-out code for better readability and maintainability. * fix: enhance message resending functionality and integrate abort signal for web searches - Updated resendMessageThunk to reset assistant messages without deleting other messages, improving user experience. - Integrated abort signal handling in WebSearchService and fetch functions to manage request cancellations effectively. - Refactored fetchWebContents and fetchWebContent to accept an optional abort signal for better control over fetch operations. - Added resetAssistantMessage utility to streamline the resetting of assistant messages for regeneration. * fix: enhance chunk handling in AI providers for improved message processing - Added onChunk calls in AnthropicProvider and GeminiProvider to ensure complete text messages are processed correctly. - Updated OpenAIProvider to handle finish reasons more accurately, improving message completion handling. - Removed outdated TODO comment in WebSearchService for better code clarity. * feat: enhance SearchingSpinner component and add processing text localization - Updated SearchingSpinner to accept a text prop for dynamic message rendering. - Added "processing" text localization in English, Japanese, Russian, Chinese (Simplified and Traditional) for improved user experience. - Integrated updated SearchingSpinner in CitationBlock and MainTextBlock components to display appropriate loading messages. * fix(WebdavBackupManager): update modal confirmation to use window.modal and center content fix sse no headers add eventSourceInit refactor: switch from @vitejs/plugin-react to @vitejs/plugin-react-swc for improved performance perf: improve streaming performance (#4986) feat(ProviderSettings): move model provider to the top when toggled When the model provider is toggled (OFF to ON), it is moved to the top of the provider setting for convenience. The change is minimal. fix(settings): handle undefined content limit in BasicSettings component (#5252) feat: update os-proxy-config to 1.1.2 and delete the patch (#5255) updte os-proxy-config to 1.1.2 and delete the patch feat: 添加嵌入维度配置 (#3947) fix(ci): Remove a deleted step which make the nightly build pipeline fail These lines were deleted in `release.yml` in commit 985996f. build: fix nightly build error build: remove sentry integration refactor(GeminiProvider): streamline abort signal handling and improve stream processing #5276 需要处理 GeminiProvider processStream 函数代码 https://github.com/CherryHQ/cherry-studio/pull/5276/files Update @modelcontextprotocol/sdk to v1.10.2 (#5266) - Removed MCPStreamableHttpClient.ts as it is now provided by the SDK. - Adjusted imports in MCPService.ts to use the SDK's implementation. - Updated yarn.lock to reflect the new SDK version. feat: add cherry-text-logo.svg and remove npm.svg; update MCPSettings and NpxSearch components - Introduced a new cherry-text-logo.svg file for branding. - Removed the deprecated npm.svg file. - Refactored MCPSettings and NpxSearch components to enhance functionality and UI, including state management and layout adjustments. - Updated translations in multiple locales to include new types for MCP servers. style(settings): update border-radius to use CSS variable for consistency feat(mcp): mcp setting add service description page chore: update dependencies and clean up code - Reintroduced @mozilla/readability, @shikijs/markdown-it, and @xyflow/react to package.json. - Updated shiki version to 3.2.2 in both package.json and yarn.lock. - Removed trailing whitespace in IpcChannel.ts and index.ts for code cleanliness. - Added outline style to .ant-tabs-tab-btn in ant.scss for improved UI consistency. feat(WindowService): add maximize functionality and disable electron-window-state maxmize (#5292) * feat(WindowService): add maximize functionality and clean up window close logic - Introduced a new `maximize` option in the window state configuration. - Added `setupMaximize` method to handle window maximization based on the launch state. - Removed redundant logic from the window close event handler for clarity. * add code * update code Create pull_request_template.md feat: enhance MinAppIcon component with sidebar prop - Added optional sidebar prop to MinAppIcon for conditional styling. - Updated Sidebar component to pass sidebar prop to MinAppIcon for consistent appearance in sidebar context. refactor(MessageAttachments): move styled component definition inside the component for better encapsulation feat: support portable config dir (#5039) * feat: support portable config dir * fix: remove redundant mkdir feat(image): support grok-2-image image and gpt-4o-image (#4767) * feat(image): support grok image * feat: add gpt-4o-image * feat: 添加 gpt-image-1 到生成图像模型列表 * refactor(GeminiProvider): remove redundant onChunk call in processStream function * refactor(OpenAIProvider): update image generation response format and improve prompt handling * feat(AiProvider): implement thought processing for incremental reasoning and update MessageContent component * refactor(useMessageOperations): update topic handling in resendUserMessageWithEditThunk and improve MessageMenubar component structure * refactor(Messages): streamline message rendering and update type imports for better clarity * refactor(Messages): improve message block rendering logic * refactor(Messages): enhance thinking time calculations * refactor(Messages): enhance message usage estimation logic * refactor(OpenAIProvider): get image generation usage * refactor(Messages): optimize citation handling and improve main text block rendering * refactor(Messages): improve clipboard copy functionality and streamline API response handling * refactor(Messages): update message state management and improve selector usage for topic messages * refactor(upgrades): update citation data structure in upgradeToV7 function and remove unused comments in messageBlock.ts * feat(OpenAIProvider): enhance link conversion for web search results and refactor related logic in ApiService and messageBlock * feat(translation): implement streaming translation updates and refactor translation handling - Added a new `getTranslationUpdater` function to manage streaming translation updates. - Refactored `translate` methods across various providers to support incremental updates. - Updated `fetchTranslate` to accept content directly instead of a message object. - Removed the `MessageContent.main.tsx` file as part of the cleanup. - Enhanced error handling and logging during translation processes. * feat(message-operations): add appendAssistantResponse functionality and enhance message operations - Introduced `appendAssistantResponse` to allow appending new assistant responses using a specified model. - Updated `useMessageOperations` hook to include the new function and improved documentation for existing methods. - Refactored `MessageMenubar` to utilize the new `appendAssistantResponse` function for message handling. - Enhanced error handling and logging in message-related thunks for better debugging and state management. * feat(message): refactor message handling and enhance file block integration - Updated `message_blocks` schema to include `file.id` for better file association. - Refactored `FilesPage` to improve file deletion logic, ensuring related message blocks are updated or deleted accordingly. - Enhanced `Inputbar` and `MessageAttachments` components to utilize new message structure and improve file handling. - Removed deprecated `MessageCitations` component to streamline message management. - Updated various components to use the new `MessageInputBaseParams` type for consistency across message operations. * refactor(tests): clean up and organize formats test suite - Removed commented-out code and unnecessary imports to enhance readability. - Organized test cases for `escapeDollarNumber`, `escapeBrackets`, `extractTitle`, and `removeSvgEmptyLines` for better structure. - Maintained existing test functionality while improving overall code clarity. * refactor(tests): comment out unused tests in formats test suite - Commented out the `withGeminiGrounding` test suite to improve clarity and focus on active tests. - Removed unnecessary imports and organized the test structure for better readability. - Maintained existing functionality while enhancing overall code organization. * refactor(components): remove role prop from Markdown component in MessageThought and MessageTranslate - Removed the `role` prop from the `Markdown` component in both `MessageThought` and `MessageTranslate` for consistency and to simplify the component usage. - Updated import statements in `export.ts` to use type imports for `Message` and `Topic`, enhancing type safety. - Commented out unused mock dependencies in the formats test suite to improve clarity and focus on active tests. * refactor(messages): update message selection and handling for improved consistency - Replaced legacy message selectors with new message handling methods in `ChatFlowHistory`, `ChatNavigation`, and `MessageAnchorLine` components. - Utilized `getMainTextContent` utility for consistent message content retrieval across components. - Updated state management in `messageThunk` to set the current topic ID correctly. - Enhanced markdown export functions to utilize new message structure for better content handling. * fix(databases): correct syntax in message_blocks schema for proper key separation - Updated the `message_blocks` schema to include a comma separator between `messageId` and `file.id` for accurate primary key definition. - Ensured consistency in database schema definitions to prevent potential issues during data retrieval. * refactor(messages): enhance loading state handling and improve message block rendering - Introduced a new `LoadingBlock` component to manage loading states for different message block types using `BeatLoader`. - Updated `MessageContent` to display loading indicators when messages are pending. - Cleaned up commented-out code and improved the structure of message block rendering logic. - Adjusted `throttledBlockUpdate` and `throttledBlockDbUpdate` to prevent unnecessary updates when block statuses are already successful. - Added error handling improvements in `fetchExternalTool` and `fetchAndProcessAssistantResponseImpl` for better robustness. * refactor(messages): improve loading state handling in message block rendering - Integrated `MessageBlockStatus` for better management of message block statuses. - Added `LoadingBlock` component to handle loading states during message processing. - Updated `fetchAndProcessAssistantResponseImpl` to set the status of tool blocks to `PROCESSING` for improved state tracking. - Cleaned up commented-out code to enhance readability and maintainability of the rendering logic. * refactor(messages): streamline message handling for clearing user messages * feat(message-operations): add createTopicBranch functionality to clone messages to a new topic - Implemented `createTopicBranch` in `useMessageOperations` to facilitate cloning messages from a source topic to a new topic. - Introduced `cloneMessagesToNewTopicThunk` for handling the cloning process, including unique ID generation and database updates. - Updated `Messages` component to utilize the new cloning functionality, ensuring proper topic management and error handling. - Cleaned up unused imports and commented-out code in `MessageMenubar` for improved readability. * fix(Messages): remove unused message operations in Messages component - Removed `createNewContext` from the destructured message operations in the `Messages` component to clean up unused functionality. - Added `getUserMessage` import to enhance message handling capabilities. * 优化格式化和测试:重构消息处理和格式化功能 - 在 `formats.ts` 中移除未使用的 `withGeminiGrounding` 函数,并更新相关类型导入。 - 在测试文件中添加了对 `withGenerateImage` 和 `addImageFileToContents` 函数的测试,确保它们正确处理消息块和图像元数据。 - 通过创建辅助函数来简化测试数据的生成,提高测试的可读性和一致性。 - 清理了测试中的注释代码,提升了代码的整洁性。 * 优化消息处理和类型导入:更新消息相关组件以使用新消息类型 - 在多个组件中更新消息导入,确保使用 `newMessage` 类型以提高类型安全性。 - 移除未使用的 `CodeBlock` 组件,简化代码结构。 - 在 `SearchResults` 组件中引入 `getMainTextContent` 函数,以改进消息内容处理。 - 清理 `Suggestions` 组件中的冗余代码,提升可读性。 - 更新 `Message` 组件以支持新的消息处理逻辑,确保与助手消息状态的兼容性。 * feat(PlaceholderBlock): introduce PlaceholderBlock and Spinner component for loading states - Added a new `Spinner` component to provide a visual loading indicator using `BarLoader` and `Search` icon. - Replaced the deprecated `SearchingSpinner` with the new `Spinner` component in `CitationBlock` and `PlaceholderBlock` for improved consistency in loading states. - Removed the unused `LoadingBlock` component to streamline the codebase. - Updated `MessageContent` to enhance rendering logic by removing commented-out code and improving readability. * feat:upgradeToV7 del catch * fix:mini/message lint error * feat(CitationsList): refactor citations rendering with Collapse component - Replaced the direct rendering of citations with a Collapse component for better UI organization. - Utilized useMemo for optimized rendering of citation items. - Updated styling in CitationsContainer for improved layout. - Enhanced PlaceholderBlock to use BeatLoader for loading state indication. * fix(messageThunk): improve logging and cloneMessagesToNewTopicThunk functionality - Updated debug logging to provide clearer information about topic retrieval and cloning process. - Enhanced the cloning logic to correctly map askId for assistant messages, ensuring proper linkage in the new topic. - Added checks to ensure file modifications only occur if the file exists, improving robustness. - Cleaned up comments and improved readability in the cloneMessagesToNewTopicThunk function. * fix(GeminiProvider): enhance image generation logic and response configuration (#5447) * feat(GeminiProvider): enhance image generation logic and response configuration * refactor(GeminiProvider): improve image generation logic readability * feat(Message): enhance message handling and introduce MessageContent component - Updated createAssistantMessage to remove unnecessary 'blocks' property from overrides. - Refactored MessageItem to manage MainTextMessageBlock state and improve message processing logic. - Added new MessageContent component for rendering message content with mentions and Markdown support. --------- Co-authored-by: lizhixuan <[email protected]> Co-authored-by: one <[email protected]> Co-authored-by: ousugo <[email protected]> Co-authored-by: kangfenmao <[email protected]> Co-authored-by: chenxi <[email protected]> Co-authored-by: suyao <[email protected]> Co-authored-by: beyondkmp <[email protected]> Co-authored-by: Chen Tao <[email protected]> Co-authored-by: Asurada <[email protected]> Co-authored-by: Roland <[email protected]> Co-authored-by: fullex <[email protected]> Co-authored-by: tchigher <[email protected]>
1 parent 61a1137 commit 4757583

File tree

99 files changed

+6753
-3211
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

99 files changed

+6753
-3211
lines changed

.yarn/patches/openai-npm-4.87.3-2b30a7685f.patch renamed to .yarn/patches/openai-npm-4.96.0-0665b05cb9.patch

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
diff --git a/core.js b/core.js
2-
index ebb071d31cd5a14792b62814df072c5971e83300..31e1062d4a7f2422ffec79cf96a35dbb69fe89cb 100644
2+
index 862d66101f441fb4f47dfc8cff5e2d39e1f5a11e..6464bebbf696c39d35f0368f061ea4236225c162 100644
33
--- a/core.js
44
+++ b/core.js
5-
@@ -157,7 +157,7 @@ class APIClient {
5+
@@ -159,7 +159,7 @@ class APIClient {
66
Accept: 'application/json',
77
'Content-Type': 'application/json',
88
'User-Agent': this.getUserAgent(),
@@ -12,10 +12,10 @@ index ebb071d31cd5a14792b62814df072c5971e83300..31e1062d4a7f2422ffec79cf96a35dbb
1212
};
1313
}
1414
diff --git a/core.mjs b/core.mjs
15-
index 9c1a0264dcd73a85de1cf81df4efab9ce9ee2ab7..33f9f1f237f2eb2667a05dae1a7e3dc916f6bfff 100644
15+
index 05dbc6cfde51589a2b100d4e4b5b3c1a33b32b89..789fbb4985eb952a0349b779fa83b1a068af6e7e 100644
1616
--- a/core.mjs
1717
+++ b/core.mjs
18-
@@ -150,7 +150,7 @@ export class APIClient {
18+
@@ -152,7 +152,7 @@ export class APIClient {
1919
Accept: 'application/json',
2020
'Content-Type': 'application/json',
2121
'User-Agent': this.getUserAgent(),

docs/technical/Message.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 消息的生命周期
2+
3+
![image](./message-lifecycle.png)

docs/technical/message-lifecycle.png

563 KB
Loading

package.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@
173173
"lucide-react": "^0.487.0",
174174
"mime": "^4.0.4",
175175
"npx-scope-finder": "^1.2.0",
176-
"openai": "patch:openai@npm%3A4.87.3#~/.yarn/patches/openai-npm-4.87.3-2b30a7685f.patch",
176+
"openai": "patch:openai@npm%3A4.96.0#~/.yarn/patches/openai-npm-4.96.0-0665b05cb9.patch",
177177
"p-queue": "^8.1.0",
178178
"prettier": "^3.5.3",
179179
"rc-virtual-list": "^3.18.5",
@@ -214,10 +214,11 @@
214214
"@langchain/openai@npm:>=0.1.0 <0.4.0": "patch:@langchain/openai@npm%3A0.3.16#~/.yarn/patches/@langchain-openai-npm-0.3.16-e525b59526.patch",
215215
"node-gyp": "^9.1.0",
216216
"libsql@npm:^0.4.4": "patch:libsql@npm%3A0.4.7#~/.yarn/patches/libsql-npm-0.4.7-444e260fb1.patch",
217-
"openai@npm:^4.77.0": "patch:openai@npm%3A4.87.3#~/.yarn/patches/openai-npm-4.87.3-2b30a7685f.patch",
217+
"openai@npm:^4.77.0": "patch:openai@npm%3A4.96.0#~/.yarn/patches/openai-npm-4.96.0-0665b05cb9.patch",
218218
"pkce-challenge@npm:^4.1.0": "patch:pkce-challenge@npm%3A4.1.0#~/.yarn/patches/pkce-challenge-npm-4.1.0-fbc51695a3.patch",
219219
"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",
220-
"shiki": "3.2.2"
220+
"shiki": "3.2.2",
221+
"openai@npm:^4.87.3": "patch:openai@npm%3A4.96.0#~/.yarn/patches/openai-npm-4.96.0-0665b05cb9.patch"
221222
},
222223
"packageManager": "[email protected]",
223224
"lint-staged": {
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { Search } from 'lucide-react'
2+
import { useTranslation } from 'react-i18next'
3+
import BarLoader from 'react-spinners/BarLoader'
4+
import styled, { css } from 'styled-components'
5+
6+
interface Props {
7+
text: string
8+
}
9+
10+
export default function Spinner({ text }: Props) {
11+
const { t } = useTranslation()
12+
return (
13+
<Container>
14+
<Search size={24} />
15+
<StatusText>{t(text)}</StatusText>
16+
<BarLoader color="#1677ff" />
17+
</Container>
18+
)
19+
}
20+
21+
const baseContainer = css`
22+
display: flex;
23+
flex-direction: row;
24+
align-items: center;
25+
`
26+
27+
const Container = styled.div`
28+
${baseContainer}
29+
background-color: var(--color-background-mute);
30+
padding: 10px;
31+
border-radius: 10px;
32+
margin-bottom: 10px;
33+
gap: 10px;
34+
`
35+
36+
const StatusText = styled.div`
37+
font-size: 14px;
38+
line-height: 1.6;
39+
text-decoration: none;
40+
color: var(--color-text-1);
41+
`

src/renderer/src/components/TranslateButton.tsx

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@ import { LoadingOutlined } from '@ant-design/icons'
22
import { useDefaultModel } from '@renderer/hooks/useAssistant'
33
import { useSettings } from '@renderer/hooks/useSettings'
44
import { fetchTranslate } from '@renderer/services/ApiService'
5-
import { getDefaultTopic, getDefaultTranslateAssistant } from '@renderer/services/AssistantService'
6-
import { getUserMessage } from '@renderer/services/MessagesService'
5+
import { getDefaultTranslateAssistant } from '@renderer/services/AssistantService'
76
import { Button, Tooltip } from 'antd'
87
import { Languages } from 'lucide-react'
98
import { FC, useEffect, useState } from 'react'
@@ -36,6 +35,7 @@ const TranslateButton: FC<Props> = ({ text, onTranslated, disabled, style, isLoa
3635
}
3736

3837
const handleTranslate = async () => {
38+
console.log('handleTranslate', text)
3939
if (!text?.trim()) return
4040

4141
if (!(await translateConfirm())) {
@@ -56,14 +56,7 @@ const TranslateButton: FC<Props> = ({ text, onTranslated, disabled, style, isLoa
5656
setIsTranslating(true)
5757
try {
5858
const assistant = getDefaultTranslateAssistant(targetLanguage, text)
59-
const message = getUserMessage({
60-
assistant,
61-
topic: getDefaultTopic('default'),
62-
type: 'text',
63-
content: ''
64-
})
65-
66-
const translatedText = await fetchTranslate({ message, assistant })
59+
const translatedText = await fetchTranslate({ content: text, assistant })
6760
onTranslated(translatedText)
6861
} catch (error) {
6962
console.error('Translation failed:', error)

src/renderer/src/databases/index.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
1-
import { FileType, KnowledgeItem, QuickPhrase, Topic, TranslateHistory } from '@renderer/types'
1+
import { FileType, KnowledgeItem, QuickPhrase, TranslateHistory } from '@renderer/types'
2+
// Import necessary types for blocks and new message structure
3+
import type { Message as NewMessage, MessageBlock } from '@renderer/types/newMessage'
24
import { Dexie, type EntityTable } from 'dexie'
35

4-
import { upgradeToV5 } from './upgrades'
6+
import { upgradeToV5, upgradeToV7 } from './upgrades'
57

68
// Database declaration (move this to its own module also)
79
export const db = new Dexie('CherryStudio') as Dexie & {
810
files: EntityTable<FileType, 'id'>
9-
topics: EntityTable<Pick<Topic, 'id' | 'messages'>, 'id'>
11+
topics: EntityTable<{ id: string; messages: NewMessage[] }, 'id'> // Correct type for topics
1012
settings: EntityTable<{ id: string; value: any }, 'id'>
1113
knowledge_notes: EntityTable<KnowledgeItem, 'id'>
1214
translate_history: EntityTable<TranslateHistory, 'id'>
1315
quick_phrases: EntityTable<QuickPhrase, 'id'>
16+
message_blocks: EntityTable<MessageBlock, 'id'> // Correct type for message_blocks
1417
}
1518

1619
db.version(1).stores({
@@ -57,4 +60,18 @@ db.version(6).stores({
5760
quick_phrases: 'id'
5861
})
5962

63+
// --- NEW VERSION 7 ---
64+
db.version(7)
65+
.stores({
66+
// Re-declare all tables for the new version
67+
files: 'id, name, origin_name, path, size, ext, type, created_at, count',
68+
topics: '&id', // Correct index for topics
69+
settings: '&id, value',
70+
knowledge_notes: '&id, baseId, type, content, created_at, updated_at',
71+
translate_history: '&id, sourceText, targetText, sourceLanguage, targetLanguage, createdAt',
72+
quick_phrases: 'id',
73+
message_blocks: 'id, messageId, file.id' // Correct syntax with comma separator
74+
})
75+
.upgrade((tx) => upgradeToV7(tx))
76+
6077
export default db

0 commit comments

Comments
 (0)