@lobehub/chat 0.106.0 → 0.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/locales/en_US/common.json +19 -0
  3. package/locales/en_US/migration.json +45 -0
  4. package/locales/en_US/setting.json +7 -7
  5. package/locales/ja_JP/common.json +19 -0
  6. package/locales/ja_JP/migration.json +45 -0
  7. package/locales/ja_JP/setting.json +2 -2
  8. package/locales/ko_KR/common.json +19 -0
  9. package/locales/ko_KR/migration.json +45 -0
  10. package/locales/ko_KR/setting.json +2 -2
  11. package/locales/ru_RU/common.json +19 -0
  12. package/locales/ru_RU/migration.json +45 -0
  13. package/locales/ru_RU/setting.json +2 -2
  14. package/locales/zh_CN/common.json +19 -0
  15. package/locales/zh_CN/migration.json +45 -0
  16. package/locales/zh_CN/setting.json +1 -1
  17. package/locales/zh_TW/common.json +19 -0
  18. package/locales/zh_TW/migration.json +45 -0
  19. package/locales/zh_TW/setting.json +2 -2
  20. package/package.json +2 -1
  21. package/src/app/api/openai/chat/createChatCompletion.test.ts +4 -4
  22. package/src/app/api/openai/chat/createChatCompletion.ts +4 -10
  23. package/src/app/api/openai/createBizOpenAI/index.ts +1 -1
  24. package/src/app/api/openai/errorResponse.test.ts +1 -1
  25. package/src/app/chat/(desktop)/features/ChatInput/Footer/index.tsx +2 -1
  26. package/src/app/chat/(mobile)/features/ChatInput/SendButton.tsx +2 -2
  27. package/src/app/chat/features/ChatHeader/ShareButton/Inner.tsx +2 -5
  28. package/src/app/chat/features/ChatHeader/ShareButton/index.tsx +2 -2
  29. package/src/app/chat/features/ChatInput/ActionBar/Clear.tsx +2 -2
  30. package/src/app/chat/features/ChatInput/ActionBar/Token/TokenTag.tsx +8 -2
  31. package/src/app/chat/features/ChatInput/InputAreaInner/index.tsx +2 -2
  32. package/src/app/chat/features/ChatInput/STT/index.tsx +2 -2
  33. package/src/app/chat/features/ChatInput/Topic/index.tsx +2 -2
  34. package/src/app/chat/features/ChatInput/useSend.ts +3 -3
  35. package/src/app/chat/features/Conversation/ChatList/Actions/index.ts +2 -2
  36. package/src/app/chat/features/Conversation/ChatList/Error/ApiKeyForm.tsx +2 -2
  37. package/src/app/chat/features/Conversation/ChatList/Error/InvalidAccess.tsx +2 -2
  38. package/src/app/chat/features/Conversation/ChatList/Error/Plugin/PluginSettings.tsx +2 -2
  39. package/src/app/chat/features/Conversation/ChatList/Extras/Assistant.test.tsx +4 -4
  40. package/src/app/chat/features/Conversation/ChatList/Extras/Assistant.tsx +30 -31
  41. package/src/app/chat/features/Conversation/ChatList/Extras/TTS.tsx +2 -2
  42. package/src/app/chat/features/Conversation/ChatList/Extras/Translate.tsx +2 -2
  43. package/src/app/chat/features/Conversation/ChatList/Extras/User.tsx +8 -5
  44. package/src/app/chat/features/Conversation/ChatList/Extras/index.ts +3 -3
  45. package/src/app/chat/features/Conversation/ChatList/Extras/type.ts +5 -0
  46. package/src/app/chat/features/Conversation/ChatList/Messages/Assistant.tsx +10 -6
  47. package/src/app/chat/features/Conversation/ChatList/Messages/Default.tsx +7 -3
  48. package/src/app/chat/features/Conversation/ChatList/Messages/Function.tsx +7 -6
  49. package/src/app/chat/features/Conversation/ChatList/Messages/index.ts +7 -7
  50. package/src/app/chat/features/Conversation/ChatList/Plugins/Render/StandaloneType/Iframe.tsx +6 -6
  51. package/src/app/chat/features/Conversation/ChatList/index.tsx +16 -24
  52. package/src/app/chat/features/Conversation/ScrollAnchor/index.tsx +2 -2
  53. package/src/app/chat/features/Conversation/index.tsx +3 -3
  54. package/src/app/chat/features/Conversation/useInitConversation.ts +43 -0
  55. package/src/app/chat/features/Migration/ExportConfigButton.tsx +33 -0
  56. package/src/app/chat/features/Migration/Failed.tsx +115 -0
  57. package/src/app/chat/features/Migration/Modal.tsx +80 -0
  58. package/src/app/chat/features/Migration/Start.tsx +106 -0
  59. package/src/app/chat/features/Migration/UpgradeButton.tsx +74 -0
  60. package/src/app/chat/features/Migration/const.ts +15 -0
  61. package/src/app/chat/features/Migration/index.tsx +44 -0
  62. package/src/app/chat/features/SessionListContent/DefaultMode.tsx +54 -0
  63. package/src/app/chat/features/SessionListContent/List/Item/Actions.tsx +5 -4
  64. package/src/app/chat/features/SessionListContent/List/Item/index.tsx +22 -28
  65. package/src/app/chat/features/SessionListContent/SearchMode.tsx +15 -0
  66. package/src/app/chat/features/SessionListContent/index.tsx +4 -44
  67. package/src/app/chat/features/SessionSearchBar/index.tsx +11 -3
  68. package/src/app/chat/features/TopicListContent/Header.tsx +4 -4
  69. package/src/app/chat/features/TopicListContent/Topic/TopicContent.tsx +11 -9
  70. package/src/app/chat/features/TopicListContent/Topic/TopicItem.tsx +15 -13
  71. package/src/app/chat/features/TopicListContent/Topic/index.tsx +9 -16
  72. package/src/app/chat/features/TopicListContent/TopicSearchBar/index.tsx +13 -4
  73. package/src/app/chat/features/TopicListContent/index.tsx +1 -2
  74. package/src/app/chat/page.tsx +6 -1
  75. package/src/app/chat/settings/features/HeaderContent.tsx +3 -3
  76. package/src/app/home/Redirect.tsx +13 -7
  77. package/src/app/settings/(mobile)/features/ExtraList.tsx +12 -4
  78. package/src/app/settings/common/Common.tsx +16 -4
  79. package/src/app/welcome/features/Banner/index.tsx +9 -10
  80. package/src/chains/summaryTitle.ts +5 -2
  81. package/src/components/DataStyleModal/index.tsx +64 -0
  82. package/src/config/client.ts +5 -0
  83. package/src/const/session.ts +21 -0
  84. package/src/const/settings.ts +1 -1
  85. package/src/database/core/__tests__/db.test.ts +8 -5
  86. package/src/database/core/__tests__/model.test.ts +3 -3
  87. package/src/database/core/db.ts +38 -10
  88. package/src/database/core/index.ts +1 -0
  89. package/src/database/core/model.ts +121 -10
  90. package/src/database/core/schemas.ts +22 -0
  91. package/src/database/core/types/db.ts +13 -0
  92. package/src/database/models/__DEBUG.ts +119 -0
  93. package/src/database/models/{file.test.ts → __tests__/file.test.ts} +19 -6
  94. package/src/database/models/__tests__/message.test.ts +314 -0
  95. package/src/database/models/__tests__/session.test.ts +117 -0
  96. package/src/database/models/__tests__/topic.test.ts +250 -0
  97. package/src/database/models/file.ts +9 -5
  98. package/src/database/models/message.ts +186 -0
  99. package/src/database/models/session.ts +160 -0
  100. package/src/database/models/topic.ts +196 -0
  101. package/src/{types/database → database/schemas}/files.ts +2 -2
  102. package/src/database/schemas/message.ts +37 -0
  103. package/src/database/schemas/session.ts +56 -0
  104. package/src/database/schemas/topic.ts +12 -0
  105. package/src/features/AgentSetting/AgentTTS/SelectWithTTSPreview.tsx +1 -1
  106. package/src/features/AgentSetting/store/action.ts +1 -1
  107. package/src/features/AgentSetting/store/initialState.ts +1 -1
  108. package/src/features/AgentSetting/store/reducers/config.ts +1 -1
  109. package/src/features/DataImporter/index.tsx +240 -0
  110. package/src/features/DebugUI/index.tsx +34 -0
  111. package/src/features/SideBar/BottomActions.tsx +8 -14
  112. package/src/hooks/useImportConfig.ts +13 -30
  113. package/src/hooks/useTTS.ts +1 -1
  114. package/src/layout/GlobalLayout/index.tsx +16 -1
  115. package/src/locales/default/common.ts +19 -0
  116. package/src/locales/default/migration.ts +47 -0
  117. package/src/locales/default/setting.ts +1 -1
  118. package/src/locales/resources/en_US.ts +2 -0
  119. package/src/locales/resources/ja_JP.ts +2 -0
  120. package/src/locales/resources/ko_KR.ts +2 -0
  121. package/src/locales/resources/ru_RU.ts +2 -0
  122. package/src/locales/resources/zh_CN.ts +2 -0
  123. package/src/locales/resources/zh_TW.ts +2 -0
  124. package/src/migrations/FromV0ToV1.ts +2 -4
  125. package/src/migrations/FromV1ToV2/fixtures/input-v1-session.json +191 -0
  126. package/src/migrations/FromV1ToV2/fixtures/output-v2.json +202 -0
  127. package/src/migrations/FromV1ToV2/index.ts +82 -0
  128. package/src/migrations/FromV1ToV2/migrations.test.ts +224 -0
  129. package/src/migrations/FromV1ToV2/types/v1.ts +78 -0
  130. package/src/migrations/FromV1ToV2/types/v2.ts +52 -0
  131. package/src/{utils → migrations}/VersionController.test.ts +1 -3
  132. package/src/{utils → migrations}/VersionController.ts +5 -2
  133. package/src/migrations/index.ts +17 -3
  134. package/src/services/__tests__/file.test.ts +3 -3
  135. package/src/services/chat.ts +66 -5
  136. package/src/services/config.ts +184 -0
  137. package/src/services/debug.ts +13 -0
  138. package/src/services/file.ts +6 -2
  139. package/src/services/github.ts +25 -0
  140. package/src/services/message.ts +79 -0
  141. package/src/services/session.ts +63 -0
  142. package/src/services/topic.ts +56 -0
  143. package/src/store/chat/actions/enhance.ts +95 -0
  144. package/src/store/{session/slices/chat → chat}/actions/message.ts +225 -247
  145. package/src/store/{session/slices/chat → chat}/actions/plugin.ts +29 -34
  146. package/src/store/{session/slices/chat → chat}/actions/share.ts +9 -13
  147. package/src/store/chat/actions/topic.ts +197 -0
  148. package/src/store/chat/helpers.ts +23 -0
  149. package/src/store/chat/index.ts +3 -0
  150. package/src/store/chat/initialState.ts +48 -0
  151. package/src/store/chat/reducers/message.test.ts +83 -0
  152. package/src/store/chat/reducers/message.ts +83 -0
  153. package/src/store/chat/selectors/__tests__/topic.test.ts +43 -0
  154. package/src/store/chat/selectors/chat.ts +119 -0
  155. package/src/store/chat/selectors/index.ts +2 -0
  156. package/src/store/chat/selectors/topic.ts +28 -0
  157. package/src/store/chat/store.ts +63 -0
  158. package/src/store/files/slices/images/action.ts +6 -4
  159. package/src/store/global/store.ts +1 -1
  160. package/src/store/middleware/createHyperStorage/index.ts +40 -24
  161. package/src/store/middleware/createHyperStorage/keyMapper.ts +8 -2
  162. package/src/store/middleware/createHyperStorage/type.ts +10 -8
  163. package/src/store/plugin/slices/plugin/action.ts +1 -1
  164. package/src/store/plugin/store.ts +2 -4
  165. package/src/store/session/helpers.ts +1 -1
  166. package/src/store/session/hooks/useSessionHydrated.ts +6 -10
  167. package/src/store/session/initialState.ts +26 -7
  168. package/src/store/session/selectors.ts +1 -2
  169. package/src/store/session/slices/agent/action.ts +26 -35
  170. package/src/store/session/slices/agent/selectors.ts +32 -37
  171. package/src/store/session/slices/session/action.ts +81 -88
  172. package/src/store/session/slices/session/helpers.ts +19 -0
  173. package/src/store/session/slices/session/initialState.ts +7 -10
  174. package/src/store/session/slices/session/selectors/export.ts +12 -9
  175. package/src/store/session/slices/session/selectors/index.ts +2 -35
  176. package/src/store/session/slices/session/selectors/list.test.ts +25 -203
  177. package/src/store/session/slices/session/selectors/list.ts +40 -78
  178. package/src/store/session/store.ts +11 -17
  179. package/src/types/agent/index.ts +61 -0
  180. package/src/types/chatMessage.ts +11 -20
  181. package/src/types/exportConfig.ts +7 -2
  182. package/src/types/files.ts +2 -2
  183. package/src/types/llm.ts +1 -1
  184. package/src/types/meta.ts +24 -12
  185. package/src/types/openai/chat.ts +9 -1
  186. package/src/types/openai/functionCall.ts +4 -0
  187. package/src/types/session.ts +10 -94
  188. package/src/types/translate.ts +2 -1
  189. package/src/utils/config.ts +5 -11
  190. package/src/utils/fetch.ts +8 -2
  191. package/src/app/chat/features/Conversation/usePluginsInit.ts +0 -14
  192. package/src/database/core/schema.ts +0 -9
  193. package/src/helpers/export.ts +0 -69
  194. package/src/hooks/useExportConfig.ts +0 -6
  195. package/src/store/session/slices/chat/actions/index.ts +0 -32
  196. package/src/store/session/slices/chat/actions/topic.ts +0 -171
  197. package/src/store/session/slices/chat/actions/translate.ts +0 -113
  198. package/src/store/session/slices/chat/helpers.ts +0 -9
  199. package/src/store/session/slices/chat/initialState.ts +0 -13
  200. package/src/store/session/slices/chat/reducers/message.test.ts +0 -319
  201. package/src/store/session/slices/chat/reducers/message.ts +0 -156
  202. package/src/store/session/slices/chat/reducers/topic.test.ts +0 -179
  203. package/src/store/session/slices/chat/reducers/topic.ts +0 -81
  204. package/src/store/session/slices/chat/selectors/chat.ts +0 -111
  205. package/src/store/session/slices/chat/selectors/index.ts +0 -26
  206. package/src/store/session/slices/chat/selectors/topic.ts +0 -30
  207. package/src/store/session/slices/chat/selectors/utils.test.ts +0 -385
  208. package/src/store/session/slices/chat/selectors/utils.ts +0 -91
  209. package/src/store/session/slices/chat/utils.ts +0 -13
  210. package/src/store/session/slices/session/reducers/session.test.ts +0 -577
  211. package/src/store/session/slices/session/reducers/session.ts +0 -182
  212. package/src/types/database/db.ts +0 -4
  213. /package/src/store/{session/slices/chat → chat}/reducers/files.test.ts +0 -0
  214. /package/src/store/{session/slices/chat → chat}/reducers/files.ts +0 -0
@@ -2,10 +2,10 @@ import { PluginRequestPayload } from '@lobehub/chat-plugin-sdk';
2
2
  import { Skeleton } from 'antd';
3
3
  import { memo, useRef, useState } from 'react';
4
4
 
5
+ import { useChatStore } from '@/store/chat';
6
+ import { chatSelectors } from '@/store/chat/selectors';
5
7
  import { usePluginStore } from '@/store/plugin';
6
8
  import { pluginSelectors } from '@/store/plugin/selectors';
7
- import { useSessionStore } from '@/store/session';
8
- import { chatSelectors } from '@/store/session/selectors';
9
9
 
10
10
  import { useOnPluginReadyForInteraction } from '../utils/iframeOnReady';
11
11
  import {
@@ -26,7 +26,7 @@ import {
26
26
  // just to simplify code a little, don't use this pattern everywhere
27
27
  const getSettings = (identifier: string) =>
28
28
  pluginSelectors.getPluginSettingsById(identifier)(usePluginStore.getState());
29
- const getMessage = (id: string) => chatSelectors.getMessageById(id)(useSessionStore.getState());
29
+ const getMessage = (id: string) => chatSelectors.getMessageById(id)(useChatStore.getState());
30
30
 
31
31
  interface IFrameRenderProps {
32
32
  height?: number;
@@ -59,7 +59,7 @@ const IFrameRender = memo<IFrameRenderProps>(({ url, id, payload, width = 600, h
59
59
  const iframeWin = iframeRef.current?.contentWindow;
60
60
 
61
61
  if (iframeWin) {
62
- const message = chatSelectors.getMessageById(id)(useSessionStore.getState());
62
+ const message = chatSelectors.getMessageById(id)(useChatStore.getState());
63
63
  if (!message) return;
64
64
  const props = { content: '' };
65
65
 
@@ -74,7 +74,7 @@ const IFrameRender = memo<IFrameRenderProps>(({ url, id, payload, width = 600, h
74
74
  }, []);
75
75
 
76
76
  // when plugin try to send back message, we should fill it to the message content
77
- const fillPluginContent = useSessionStore((s) => s.fillPluginMessageContent);
77
+ const fillPluginContent = useChatStore((s) => s.fillPluginMessageContent);
78
78
  useOnPluginFillContent((content) => {
79
79
  fillPluginContent(id, content);
80
80
  });
@@ -92,7 +92,7 @@ const IFrameRender = memo<IFrameRenderProps>(({ url, id, payload, width = 600, h
92
92
  });
93
93
 
94
94
  // when plugin update state, we should update it to the message pluginState key
95
- const updatePluginState = useSessionStore((s) => s.updatePluginState);
95
+ const updatePluginState = useChatStore((s) => s.updatePluginState);
96
96
  useOnPluginStateUpdate((key, value) => {
97
97
  updatePluginState(id, key, value);
98
98
  });
@@ -5,8 +5,10 @@ import { useHotkeys } from 'react-hotkeys-hook';
5
5
  import { useTranslation } from 'react-i18next';
6
6
 
7
7
  import { PREFIX_KEY, REGENERATE_KEY } from '@/const/hotkeys';
8
- import { useSessionChatInit, useSessionStore } from '@/store/session';
9
- import { agentSelectors, chatSelectors } from '@/store/session/selectors';
8
+ import { useChatStore } from '@/store/chat';
9
+ import { chatSelectors } from '@/store/chat/selectors';
10
+ import { useSessionStore } from '@/store/session';
11
+ import { agentSelectors } from '@/store/session/selectors';
10
12
 
11
13
  import { renderActions, useActionsClick } from './Actions';
12
14
  import { renderErrorMessages } from './Error';
@@ -15,28 +17,20 @@ import { renderMessages, useAvatarsClick } from './Messages';
15
17
  import SkeletonList from './SkeletonList';
16
18
 
17
19
  const List = memo(() => {
18
- const init = useSessionChatInit();
19
20
  const { t } = useTranslation('common');
20
21
 
21
- const data = useSessionStore(chatSelectors.currentChatsWithGuideMessage, isEqual);
22
+ const data = useChatStore(chatSelectors.currentChatsWithGuideMessage, isEqual);
22
23
 
23
- const [
24
- displayMode,
25
- enableHistoryCount,
26
- historyCount,
27
- chatLoadingId,
28
- resendMessage,
29
- dispatchMessage,
30
- ] = useSessionStore((s) => {
24
+ const [init, chatLoadingId, resendMessage, updateMessageContent] = useChatStore((s) => [
25
+ s.messagesInit,
26
+ s.chatLoadingId,
27
+ s.resendMessage,
28
+ s.updateMessageContent,
29
+ ]);
30
+
31
+ const [displayMode, enableHistoryCount, historyCount] = useSessionStore((s) => {
31
32
  const config = agentSelectors.currentAgentConfig(s);
32
- return [
33
- config.displayMode,
34
- config.enableHistoryCount,
35
- config.historyCount,
36
- s.chatLoadingId,
37
- s.resendMessage,
38
- s.dispatchMessage,
39
- ];
33
+ return [config.displayMode, config.enableHistoryCount, config.historyCount];
40
34
  });
41
35
  const onActionsClick = useActionsClick();
42
36
  const onAvatarsClick = useAvatarsClick();
@@ -59,15 +53,13 @@ const List = memo(() => {
59
53
 
60
54
  return (
61
55
  <ChatList
62
- data={data}
56
+ data={data as any}
63
57
  enableHistoryCount={enableHistoryCount}
64
58
  historyCount={historyCount}
65
59
  loadingId={chatLoadingId}
66
60
  onActionsClick={onActionsClick}
67
61
  onAvatarsClick={onAvatarsClick}
68
- onMessageChange={(id, content) =>
69
- dispatchMessage({ id, key: 'content', type: 'updateMessage', value: content })
70
- }
62
+ onMessageChange={(id, content) => updateMessageContent(id, content)}
71
63
  renderActions={renderActions}
72
64
  renderErrorMessages={renderErrorMessages}
73
65
  renderMessages={renderMessages}
@@ -1,12 +1,12 @@
1
1
  import { memo, useEffect } from 'react';
2
2
  import { useInView } from 'react-intersection-observer';
3
3
 
4
- import { useSessionStore } from '@/store/session';
4
+ import { useChatStore } from '@/store/chat';
5
5
 
6
6
  import { useAtBottom } from './useAtBottom';
7
7
 
8
8
  const ChatScrollAnchor = memo(() => {
9
- const trackVisibility = useSessionStore((s) => !!s.chatLoadingId);
9
+ const trackVisibility = useChatStore((s) => !!s.chatLoadingId);
10
10
 
11
11
  const isAtBottom = useAtBottom();
12
12
  const { ref, entry, inView } = useInView({
@@ -8,7 +8,7 @@ import SafeSpacing from '@/components/SafeSpacing';
8
8
 
9
9
  import ChatList from './ChatList';
10
10
  import ChatScrollAnchor from './ScrollAnchor';
11
- import { usePluginsInit } from './usePluginsInit';
11
+ import { useInitConversation } from './useInitConversation';
12
12
 
13
13
  const useStyles = createStyles(
14
14
  ({ css, responsive, stylish }) => css`
@@ -31,8 +31,8 @@ const Conversation = memo<ConversationProps>(({ mobile, chatInput }) => {
31
31
  const { t } = useTranslation('chat');
32
32
  const { styles } = useStyles();
33
33
 
34
- // fetch plugin list and init plugins
35
- usePluginsInit();
34
+ // init conversation
35
+ useInitConversation();
36
36
 
37
37
  return (
38
38
  <Flexbox flex={1} style={{ position: 'relative' }}>
@@ -0,0 +1,43 @@
1
+ import { useEffect } from 'react';
2
+
3
+ import { useChatStore } from '@/store/chat';
4
+ import { usePluginStore } from '@/store/plugin';
5
+ import { useSessionStore } from '@/store/session';
6
+ import { agentSelectors } from '@/store/session/selectors';
7
+
8
+ export const useInitConversation = () => {
9
+ const [sessionId] = useSessionStore((s) => [s.activeId]);
10
+ const plugins = useSessionStore((s) => agentSelectors.currentAgentPlugins(s));
11
+ const [activeTopicId, switchTopic, useFetchMessages, useFetchTopics] = useChatStore((s) => [
12
+ s.activeTopicId,
13
+ s.switchTopic,
14
+ s.useFetchMessages,
15
+ s.useFetchTopics,
16
+ ]);
17
+
18
+ useFetchMessages(sessionId, activeTopicId);
19
+ useFetchTopics(sessionId);
20
+
21
+ const [useFetchPluginStore, checkPluginsIsInstalled] = usePluginStore((s) => [
22
+ s.useFetchPluginStore,
23
+ s.useCheckPluginsIsInstalled,
24
+ ]);
25
+
26
+ useFetchPluginStore();
27
+ checkPluginsIsInstalled(plugins);
28
+
29
+ useEffect(() => {
30
+ useChatStore.persist.rehydrate();
31
+
32
+ // // when activeId changed, switch topic to undefined
33
+ const unsubscribe = useSessionStore.subscribe(
34
+ (s) => s.activeId,
35
+ () => {
36
+ switchTopic();
37
+ },
38
+ );
39
+ return () => {
40
+ unsubscribe();
41
+ };
42
+ }, []);
43
+ };
@@ -0,0 +1,33 @@
1
+ import { Button } from 'antd';
2
+ import { memo } from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+
5
+ const ExportConfigButton = memo<{ primary?: boolean, state: any; }>(({ state, primary }) => {
6
+ const { t } = useTranslation('migration');
7
+
8
+ const exportData = () => {
9
+ const config = { exportType: 'sessions', state, version: 1 };
10
+
11
+ const url = URL.createObjectURL(
12
+ new Blob([JSON.stringify(config)], { type: 'application/json' }),
13
+ );
14
+
15
+ const a = document.createElement('a');
16
+ a.href = url;
17
+ a.download = 'LobeChat-backup-v1.json';
18
+
19
+ document.body.append(a);
20
+ a.click();
21
+
22
+ URL.revokeObjectURL(url);
23
+ a.remove();
24
+ };
25
+
26
+ return (
27
+ <Button onClick={exportData} size={'large'} type={primary ? 'primary' : undefined}>
28
+ {t('dbV1.action.downloadBackup')}
29
+ </Button>
30
+ );
31
+ });
32
+
33
+ export default ExportConfigButton;
@@ -0,0 +1,115 @@
1
+ import { Alert, Highlighter, Icon } from '@lobehub/ui';
2
+ import { Button, Popconfirm, Result } from 'antd';
3
+ import { useTheme } from 'antd-style';
4
+ import { createStore, del, get, set } from 'idb-keyval';
5
+ import { ShieldAlert } from 'lucide-react';
6
+ import Link from 'next/link';
7
+ import { lighten } from 'polished';
8
+ import { memo } from 'react';
9
+ import { Trans, useTranslation } from 'react-i18next';
10
+ import { Flexbox } from 'react-layout-kit';
11
+ import Balancer from 'react-wrap-balancer';
12
+
13
+ import { githubService } from '@/services/github';
14
+
15
+ import ExportConfigButton from './ExportConfigButton';
16
+ import UpgradeButton from './UpgradeButton';
17
+ import { MigrationError, UpgradeStatus, V1DB_NAME, V1DB_TABLE_NAME } from './const';
18
+
19
+ const clearLocal = async () => {
20
+ const store = createStore(V1DB_NAME, V1DB_TABLE_NAME);
21
+ // delete the state key and back it up to state_backup for reproduce
22
+ const state = await get('state', store);
23
+ await del('state');
24
+ await set('state_backup', state, store);
25
+ location.reload();
26
+ };
27
+
28
+ interface FailedProps {
29
+ error?: MigrationError;
30
+ setError: (error: MigrationError) => void;
31
+ setUpgradeStatus: (status: UpgradeStatus) => void;
32
+ state: any;
33
+ upgradeStatus: UpgradeStatus;
34
+ }
35
+ const Failed = memo<FailedProps>(({ error, state, setUpgradeStatus, setError, upgradeStatus }) => {
36
+ const { t } = useTranslation('migration');
37
+ const theme = useTheme();
38
+
39
+ return (
40
+ <Result
41
+ extra={
42
+ <Flexbox gap={24}>
43
+ {!!error && (
44
+ <Alert
45
+ extra={
46
+ <Highlighter copyButtonSize={'small'} language={'json'}>
47
+ {JSON.stringify(error)}
48
+ </Highlighter>
49
+ }
50
+ message={error.message}
51
+ style={{ flex: 1 }}
52
+ type={'error'}
53
+ />
54
+ )}
55
+ <Flexbox
56
+ gap={16}
57
+ horizontal
58
+ justify={'center'}
59
+ style={{
60
+ alignSelf: 'center',
61
+ flexWrap: 'wrap',
62
+ }}
63
+ >
64
+ <ExportConfigButton primary state={state} />
65
+ <Popconfirm
66
+ okButtonProps={{
67
+ danger: true,
68
+ }}
69
+ onConfirm={clearLocal}
70
+ overlayInnerStyle={{ background: lighten(0.03, theme.colorBgElevated) }}
71
+ overlayStyle={{ width: 340 }}
72
+ title={t('dbV1.clear.confirm')}
73
+ >
74
+ <Button size={'large'}>{t('dbV1.action.clearDB')}</Button>
75
+ </Popconfirm>
76
+ <UpgradeButton
77
+ primary={false}
78
+ setError={setError}
79
+ setUpgradeStatus={setUpgradeStatus}
80
+ state={state}
81
+ upgradeStatus={upgradeStatus}
82
+ >
83
+ {t('dbV1.action.reUpgrade')}
84
+ </UpgradeButton>
85
+ </Flexbox>
86
+ </Flexbox>
87
+ }
88
+ icon={<Icon icon={ShieldAlert} />}
89
+ status={'error'}
90
+ style={{ paddingBlock: 24, width: 450 }}
91
+ subTitle={
92
+ <Balancer>
93
+ <Trans i18nKey="dbV1.upgrade.error.subTitle" ns={'migration'}>
94
+ 非常抱歉,数据库升级过程发生异常。请重试升级,或
95
+ <Link
96
+ aria-label={'issue'}
97
+ href="https://github.com/lobehub/lobe-chat/issues"
98
+ onClick={(e) => {
99
+ e.preventDefault();
100
+ githubService.submitDBV1UpgradeError(1, error!);
101
+ }}
102
+ target="_blank"
103
+ >
104
+ 提交问题
105
+ </Link>
106
+ 我们将会第一时间帮你排查问题。
107
+ </Trans>
108
+ </Balancer>
109
+ }
110
+ title={t('dbV1.upgrade.error.title')}
111
+ />
112
+ );
113
+ });
114
+
115
+ export default Failed;
@@ -0,0 +1,80 @@
1
+ import { Icon } from '@lobehub/ui';
2
+ import { Button, Result } from 'antd';
3
+ import { BadgeCheck, CpuIcon } from 'lucide-react';
4
+ import { memo, useState } from 'react';
5
+ import { useTranslation } from 'react-i18next';
6
+ import { Center } from 'react-layout-kit';
7
+
8
+ import DataStyleModal from '@/components/DataStyleModal';
9
+
10
+ import Failed from './Failed';
11
+ import MigrationStart from './Start';
12
+ import { MigrationError, UpgradeStatus } from './const';
13
+
14
+ interface MigrationModalProps {
15
+ open: boolean;
16
+ setOpen: (open: boolean) => void;
17
+ state: any;
18
+ }
19
+
20
+ const MigrationModal = memo<MigrationModalProps>(({ setOpen, open, state: dbState }) => {
21
+ const { t } = useTranslation('migration');
22
+ const [upgradeStatus, setUpgradeStatus] = useState<UpgradeStatus>(UpgradeStatus.START);
23
+
24
+ const [error, setError] = useState<MigrationError>();
25
+
26
+ const close = () => {
27
+ setOpen(false);
28
+ };
29
+
30
+ const renderContent = () => {
31
+ switch (upgradeStatus) {
32
+ case UpgradeStatus.START:
33
+ case UpgradeStatus.UPGRADING: {
34
+ return (
35
+ <MigrationStart
36
+ setError={setError}
37
+ setUpgradeStatus={setUpgradeStatus}
38
+ state={dbState}
39
+ upgradeStatus={upgradeStatus}
40
+ />
41
+ );
42
+ }
43
+ case UpgradeStatus.UPGRADED: {
44
+ return (
45
+ <Result
46
+ extra={
47
+ <Button onClick={close} size={'large'} type={'primary'}>
48
+ {t('dbV1.action.start')}
49
+ </Button>
50
+ }
51
+ icon={<Icon icon={BadgeCheck} />}
52
+ status={'success'}
53
+ style={{ paddingBlock: 24 }}
54
+ subTitle={t('dbV1.upgrade.success.subTitle')}
55
+ title={t('dbV1.upgrade.success.title')}
56
+ />
57
+ );
58
+ }
59
+ case UpgradeStatus.UPGRADE_FAILED: {
60
+ return (
61
+ <Failed
62
+ error={error}
63
+ setError={setError}
64
+ setUpgradeStatus={setUpgradeStatus}
65
+ state={dbState}
66
+ upgradeStatus={upgradeStatus}
67
+ />
68
+ );
69
+ }
70
+ }
71
+ };
72
+
73
+ return (
74
+ <DataStyleModal icon={CpuIcon} open={open} title={t('dbV1.title')}>
75
+ <Center gap={48}>{renderContent()}</Center>
76
+ </DataStyleModal>
77
+ );
78
+ });
79
+
80
+ export default MigrationModal;
@@ -0,0 +1,106 @@
1
+ import { Icon } from '@lobehub/ui';
2
+ import { createStyles } from 'antd-style';
3
+ import { Database, SearchCheck, Zap } from 'lucide-react';
4
+ import { memo } from 'react';
5
+ import { useTranslation } from 'react-i18next';
6
+ import { Center, Flexbox } from 'react-layout-kit';
7
+ import Balancer from 'react-wrap-balancer';
8
+
9
+ import ExportConfigButton from './ExportConfigButton';
10
+ import UpgradeButton, { UpgradeButtonProps } from './UpgradeButton';
11
+
12
+ const useStyles = createStyles(({ css, token, isDarkMode, responsive }) => ({
13
+ desc: css`
14
+ width: 280px;
15
+ color: ${token.colorTextSecondary};
16
+
17
+ ${responsive.mobile} {
18
+ line-height: ${token.lineHeight};
19
+ }
20
+ `,
21
+ hint: css`
22
+ font-size: ${token.fontSizeSM}px;
23
+ color: ${token.colorTextTertiary};
24
+ text-align: center;
25
+ `,
26
+ icon: css`
27
+ color: ${isDarkMode ? token.blue : token.geekblue};
28
+ `,
29
+ iconCtn: css`
30
+ width: 72px;
31
+ height: 72px;
32
+ background: ${isDarkMode ? token.blue1 : token.geekblue1};
33
+ border-radius: 50%;
34
+ `,
35
+ intro: css`
36
+ ${responsive.mobile} {
37
+ width: 350px;
38
+ margin-top: 24px;
39
+ line-height: ${token.lineHeight};
40
+ }
41
+ `,
42
+
43
+ title: css`
44
+ font-size: ${token.fontSizeLG}px;
45
+ font-weight: bold;
46
+ `,
47
+ }));
48
+
49
+ const MigrationStart = memo<UpgradeButtonProps>((props) => {
50
+ const { t } = useTranslation('migration');
51
+ const { styles } = useStyles();
52
+
53
+ const features = [
54
+ {
55
+ avatar: Database,
56
+ desc: t('dbV1.features.capability.desc'),
57
+ title: t('dbV1.features.capability.title'),
58
+ },
59
+ {
60
+ avatar: Zap,
61
+ desc: t('dbV1.features.performance.desc'),
62
+ title: t('dbV1.features.performance.title'),
63
+ },
64
+ {
65
+ avatar: SearchCheck,
66
+ desc: t('dbV1.features.use.desc'),
67
+ title: t('dbV1.features.use.title'),
68
+ },
69
+ ];
70
+
71
+ return (
72
+ <>
73
+ <Flexbox>
74
+ <Flexbox className={styles.intro} style={{ textAlign: 'center' }} width={460}>
75
+ {t('dbV1.description')}
76
+ </Flexbox>
77
+ </Flexbox>
78
+ <Flexbox gap={32}>
79
+ {features.map((item) => {
80
+ return (
81
+ <Flexbox align={'flex-start'} gap={24} horizontal key={item.title}>
82
+ <Center className={styles.iconCtn}>
83
+ <Icon className={styles.icon} icon={item.avatar} size={{ fontSize: 36 }} />
84
+ </Center>
85
+ <Flexbox gap={8}>
86
+ <p className={styles.title}>{item.title}</p>
87
+ <p className={styles.desc}>{item.desc}</p>
88
+ </Flexbox>
89
+ </Flexbox>
90
+ );
91
+ })}
92
+ </Flexbox>
93
+ <Flexbox align={'center'} gap={16} style={{ paddingBottom: 16 }}>
94
+ <Flexbox gap={16} horizontal justify={'center'} style={{ flexWrap: 'wrap' }}>
95
+ <ExportConfigButton state={props.state} />
96
+ <UpgradeButton {...props} />
97
+ </Flexbox>
98
+ <Flexbox align={'center'} className={styles.hint}>
99
+ <Balancer>{t('dbV1.upgradeTip')}</Balancer>
100
+ </Flexbox>
101
+ </Flexbox>
102
+ </>
103
+ );
104
+ });
105
+
106
+ export default MigrationStart;
@@ -0,0 +1,74 @@
1
+ import { Button } from 'antd';
2
+ import { createStore, set } from 'idb-keyval';
3
+ import { ReactNode, memo } from 'react';
4
+ import { useTranslation } from 'react-i18next';
5
+
6
+ import { Migration } from '@/migrations';
7
+ import { configService } from '@/services/config';
8
+ import { useChatStore } from '@/store/chat';
9
+ import { useSessionStore } from '@/store/session';
10
+
11
+ import { MIGRATE_KEY, MigrationError, UpgradeStatus, V1DB_NAME, V1DB_TABLE_NAME } from './const';
12
+
13
+ export interface UpgradeButtonProps {
14
+ children?: ReactNode;
15
+ primary?: boolean;
16
+ setError: (error: MigrationError) => void;
17
+ setUpgradeStatus: (status: UpgradeStatus) => void;
18
+ state: any;
19
+ upgradeStatus: UpgradeStatus;
20
+ }
21
+
22
+ const UpgradeButton = memo<UpgradeButtonProps>(
23
+ ({ setUpgradeStatus, upgradeStatus, state, setError, primary = true, children }) => {
24
+ const { t } = useTranslation('migration');
25
+
26
+ const refreshSession = useSessionStore((s) => s.refreshSessions);
27
+ const [refreshMessages, refreshTopic] = useChatStore((s) => [
28
+ s.refreshMessages,
29
+ s.refreshTopic,
30
+ ]);
31
+
32
+ const upgrade = async () => {
33
+ try {
34
+ const data = Migration.migrate({ state, version: 1 });
35
+
36
+ setUpgradeStatus(UpgradeStatus.UPGRADING);
37
+
38
+ await configService.importConfigState({
39
+ exportType: 'sessions',
40
+ state: data.state,
41
+ version: 2,
42
+ });
43
+
44
+ await refreshSession();
45
+ await refreshMessages();
46
+ await refreshTopic();
47
+
48
+ await set(MIGRATE_KEY, true, createStore(V1DB_NAME, V1DB_TABLE_NAME));
49
+
50
+ setUpgradeStatus(UpgradeStatus.UPGRADED);
51
+
52
+ return { success: true };
53
+ } catch (error) {
54
+ setUpgradeStatus(UpgradeStatus.UPGRADE_FAILED);
55
+ const err = error as { message: string; stack: string };
56
+
57
+ setError({ message: err.message, stack: err.stack });
58
+ }
59
+ };
60
+
61
+ return (
62
+ <Button
63
+ loading={upgradeStatus === UpgradeStatus.UPGRADING}
64
+ onClick={upgrade}
65
+ size={'large'}
66
+ type={primary ? 'primary' : undefined}
67
+ >
68
+ {children ?? t('dbV1.action.upgrade')}
69
+ </Button>
70
+ );
71
+ },
72
+ );
73
+
74
+ export default UpgradeButton;
@@ -0,0 +1,15 @@
1
+ export const MIGRATE_KEY = 'migrated';
2
+ export enum UpgradeStatus {
3
+ START,
4
+ UPGRADING,
5
+ UPGRADED,
6
+ UPGRADE_FAILED,
7
+ }
8
+
9
+ export const V1DB_NAME = 'LobeHub';
10
+ export const V1DB_TABLE_NAME = 'LOBE_CHAT';
11
+
12
+ export interface MigrationError {
13
+ message: string;
14
+ stack: string;
15
+ }
@@ -0,0 +1,44 @@
1
+ 'use client';
2
+
3
+ import { Spin } from 'antd';
4
+ import { createStore, getMany } from 'idb-keyval';
5
+ import dynamic from 'next/dynamic';
6
+ import { PropsWithChildren, memo, useEffect, useState } from 'react';
7
+
8
+ import { MIGRATE_KEY, V1DB_NAME, V1DB_TABLE_NAME } from './const';
9
+
10
+ const Modal = dynamic(() => import('./Modal'), { loading: () => <Spin fullscreen />, ssr: false });
11
+
12
+ const Migration = memo<PropsWithChildren>(({ children }) => {
13
+ const [dbState, setDbState] = useState(null);
14
+ const [open, setOpen] = useState(false);
15
+
16
+ const checkMigration = async () => {
17
+ const [state, migrated] = await getMany(
18
+ ['state', MIGRATE_KEY],
19
+ createStore(V1DB_NAME, V1DB_TABLE_NAME),
20
+ );
21
+
22
+ // if db have migrated already, don't show modal
23
+ if (migrated) return;
24
+
25
+ // if db doesn't exist state key,it means a new user
26
+ if (!state) return;
27
+
28
+ setDbState(state);
29
+ setOpen(true);
30
+ };
31
+
32
+ useEffect(() => {
33
+ checkMigration();
34
+ }, []);
35
+
36
+ return (
37
+ <>
38
+ {open && <Modal open={open} setOpen={setOpen} state={dbState} />}
39
+ {children}
40
+ </>
41
+ );
42
+ });
43
+
44
+ export default Migration;