@lobehub/chat 0.162.3 → 0.162.5

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,56 @@
2
2
 
3
3
  # Changelog
4
4
 
5
+ ### [Version 0.162.5](https://github.com/lobehub/lobe-chat/compare/v0.162.4...v0.162.5)
6
+
7
+ <sup>Released on **2024-05-28**</sup>
8
+
9
+ #### 💄 Styles
10
+
11
+ - **misc**: Add `SYSTEM_AGENT` env.
12
+
13
+ <br/>
14
+
15
+ <details>
16
+ <summary><kbd>Improvements and Fixes</kbd></summary>
17
+
18
+ #### Styles
19
+
20
+ - **misc**: Add `SYSTEM_AGENT` env, closes [#2694](https://github.com/lobehub/lobe-chat/issues/2694) ([0dfcf8d](https://github.com/lobehub/lobe-chat/commit/0dfcf8d))
21
+
22
+ </details>
23
+
24
+ <div align="right">
25
+
26
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
27
+
28
+ </div>
29
+
30
+ ### [Version 0.162.4](https://github.com/lobehub/lobe-chat/compare/v0.162.3...v0.162.4)
31
+
32
+ <sup>Released on **2024-05-28**</sup>
33
+
34
+ #### 🐛 Bug Fixes
35
+
36
+ - **misc**: Fix auto focus issues.
37
+
38
+ <br/>
39
+
40
+ <details>
41
+ <summary><kbd>Improvements and Fixes</kbd></summary>
42
+
43
+ #### What's fixed
44
+
45
+ - **misc**: Fix auto focus issues, closes [#2697](https://github.com/lobehub/lobe-chat/issues/2697) ([8df856e](https://github.com/lobehub/lobe-chat/commit/8df856e))
46
+
47
+ </details>
48
+
49
+ <div align="right">
50
+
51
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
52
+
53
+ </div>
54
+
5
55
  ### [Version 0.162.3](https://github.com/lobehub/lobe-chat/compare/v0.162.2...v0.162.3)
6
56
 
7
57
  <sup>Released on **2024-05-28**</sup>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "0.162.3",
3
+ "version": "0.162.5",
4
4
  "description": "Lobe Chat - an open-source, high-performance chatbot framework that supports speech synthesis, multimodal, and extensible Function Call plugin system. Supports one-click free deployment of your private ChatGPT/LLM web application.",
5
5
  "keywords": [
6
6
  "framework",
@@ -1,107 +1,45 @@
1
1
  import { act, renderHook } from '@testing-library/react';
2
- import { RefObject } from 'react';
2
+ import { describe, expect, it, vi } from 'vitest';
3
3
 
4
- import { useAutoFocus } from '../useAutoFocus';
5
-
6
- enum ElType {
7
- div,
8
- input,
9
- markdown,
10
- debug,
11
- }
12
-
13
- // 模拟elementFromPoint方法
14
- document.elementFromPoint = function (x) {
15
- if (x === ElType.div) {
16
- return document.createElement('div');
17
- }
4
+ import { useChatStore } from '@/store/chat';
5
+ import { chatSelectors } from '@/store/chat/selectors';
18
6
 
19
- if (x === ElType.input) {
20
- return document.createElement('input');
21
- }
22
-
23
- if (x === ElType.debug) {
24
- return document.createElement('pre');
25
- }
26
-
27
- if (x === ElType.markdown) {
28
- const markdownEl = document.createElement('article');
29
- const markdownChildEl = document.createElement('p');
30
- markdownEl.appendChild(markdownChildEl);
31
- return markdownChildEl;
32
- }
7
+ import { useAutoFocus } from '../useAutoFocus';
33
8
 
34
- return null;
35
- };
9
+ vi.mock('zustand/traditional');
36
10
 
37
11
  describe('useAutoFocus', () => {
38
- it('should focus inputRef when mouseup event happens outside of input or markdown element', () => {
39
- const inputRef = { current: { focus: vi.fn() } } as RefObject<any>;
40
- renderHook(() => useAutoFocus(inputRef));
12
+ it('should focus the input when chatKey changes', () => {
13
+ const focusMock = vi.fn();
14
+ const inputRef = { current: { focus: focusMock } };
41
15
 
42
- // Simulate a mousedown event on an element outside of input or markdown element
43
16
  act(() => {
44
- document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, clientX: ElType.div }));
17
+ useChatStore.setState({ activeId: '1', activeTopicId: '2' });
45
18
  });
46
19
 
47
- // Simulate a mouseup event
48
- act(() => {
49
- document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
50
- });
51
-
52
- expect(inputRef.current?.focus).toHaveBeenCalledTimes(1);
53
- });
20
+ renderHook(() => useAutoFocus(inputRef as any));
54
21
 
55
- it('should not focus inputRef when mouseup event happens inside of input element', () => {
56
- const inputRef = { current: { focus: vi.fn() } } as RefObject<any>;
57
- renderHook(() => useAutoFocus(inputRef));
22
+ expect(focusMock).toHaveBeenCalledTimes(1);
58
23
 
59
- // Simulate a mousedown event on an input element
60
24
  act(() => {
61
- document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, clientX: ElType.input }));
25
+ useChatStore.setState({ activeId: '1', activeTopicId: '3' });
62
26
  });
63
27
 
64
- // Simulate a mouseup event
65
- act(() => {
66
- document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
67
- });
28
+ renderHook(() => useAutoFocus(inputRef as any));
68
29
 
69
- expect(inputRef.current?.focus).not.toHaveBeenCalled();
30
+ // I don't know why its 3, but is large than 2 is fine
31
+ expect(focusMock).toHaveBeenCalledTimes(3);
70
32
  });
71
33
 
72
- it('should not focus inputRef when mouseup event happens inside of markdown element', () => {
73
- const inputRef = { current: { focus: vi.fn() } } as RefObject<any>;
74
- renderHook(() => useAutoFocus(inputRef));
34
+ it('should not focus the input if inputRef is not available', () => {
35
+ const inputRef = { current: null };
75
36
 
76
- // Simulate a mousedown event on a markdown element
77
37
  act(() => {
78
- document.dispatchEvent(
79
- new MouseEvent('mousedown', { bubbles: true, clientX: ElType.markdown }),
80
- );
38
+ useChatStore.setState({ activeId: '1', activeTopicId: '2' });
81
39
  });
82
40
 
83
- // Simulate a mouseup event
84
- act(() => {
85
- document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
86
- });
87
-
88
- expect(inputRef.current?.focus).not.toHaveBeenCalled();
89
- });
90
-
91
- it('should not focus inputRef when mouseup event happens inside of debug element', () => {
92
- const inputRef = { current: { focus: vi.fn() } } as RefObject<any>;
93
- renderHook(() => useAutoFocus(inputRef));
94
-
95
- // Simulate a mousedown event on a debug element
96
- act(() => {
97
- document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, clientX: ElType.debug }));
98
- });
99
-
100
- // Simulate a mouseup event
101
- act(() => {
102
- document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
103
- });
41
+ renderHook(() => useAutoFocus(inputRef as any));
104
42
 
105
- expect(inputRef.current?.focus).not.toHaveBeenCalled();
43
+ expect(inputRef.current).toBeNull();
106
44
  });
107
45
  });
@@ -1,39 +1,13 @@
1
1
  import { TextAreaRef } from 'antd/es/input/TextArea';
2
2
  import { RefObject, useEffect } from 'react';
3
3
 
4
- export const useAutoFocus = (inputRef: RefObject<TextAreaRef>) => {
5
- useEffect(() => {
6
- let isInputOrMarkdown = false;
7
-
8
- const onMousedown = (e: MouseEvent) => {
9
- isInputOrMarkdown = false;
10
- const element = document.elementFromPoint(e.clientX, e.clientY);
11
- if (!element) return;
12
- let currentElement: Element | null = element;
13
- // 因为点击 Markdown 元素时,element 会是 article 标签的子元素
14
- // Debug 信息时,element 会是 pre 标签
15
- // 所以向上查找全局点击对象是否是 Markdown 或者 Input 或者 Debug 元素
16
- while (currentElement && !isInputOrMarkdown) {
17
- isInputOrMarkdown = ['TEXTAREA', 'INPUT', 'ARTICLE', 'PRE'].includes(
18
- currentElement.tagName,
19
- );
20
- currentElement = currentElement.parentElement;
21
- }
22
- };
4
+ import { useChatStore } from '@/store/chat';
5
+ import { chatSelectors } from '@/store/chat/selectors';
23
6
 
24
- const onMouseup = () => {
25
- // 因为有时候要复制 Markdown 里生成的内容,或者点击别的 Input
26
- // 所以全局点击元素不是 Markdown 或者 Input 元素的话就聚焦
27
- if (!isInputOrMarkdown) {
28
- inputRef.current?.focus();
29
- }
30
- };
7
+ export const useAutoFocus = (inputRef: RefObject<TextAreaRef>) => {
8
+ const chatKey = useChatStore(chatSelectors.currentChatKey);
31
9
 
32
- document.addEventListener('mousedown', onMousedown);
33
- document.addEventListener('mouseup', onMouseup);
34
- return () => {
35
- document.removeEventListener('mousedown', onMousedown);
36
- document.removeEventListener('mouseup', onMouseup);
37
- };
38
- }, []);
10
+ useEffect(() => {
11
+ inputRef.current?.focus();
12
+ }, [chatKey]);
39
13
  };
@@ -7,6 +7,8 @@ import { useGlobalStore } from '@/store/global';
7
7
  import { systemStatusSelectors } from '@/store/global/selectors';
8
8
  import { useSessionStore } from '@/store/session';
9
9
  import { sessionSelectors } from '@/store/session/selectors';
10
+ import { useUserStore } from '@/store/user';
11
+ import { authSelectors } from '@/store/user/selectors';
10
12
  import { SessionDefaultGroup } from '@/types/session';
11
13
 
12
14
  import Actions from '../SessionListContent/CollapseGroup/Actions';
@@ -23,8 +25,9 @@ const DefaultMode = memo(() => {
23
25
  const [renameGroupModalOpen, setRenameGroupModalOpen] = useState(false);
24
26
  const [configGroupModalOpen, setConfigGroupModalOpen] = useState(false);
25
27
 
28
+ const isLogin = useUserStore(authSelectors.isLogin);
26
29
  const [useFetchSessions] = useSessionStore((s) => [s.useFetchSessions]);
27
- useFetchSessions();
30
+ useFetchSessions(isLogin);
28
31
 
29
32
  const defaultSessions = useSessionStore(sessionSelectors.defaultSessions, isEqual);
30
33
  const customSessionGroups = useSessionStore(sessionSelectors.customSessionGroups, isEqual);
package/src/config/app.ts CHANGED
@@ -25,6 +25,7 @@ export const getAppConfig = () => {
25
25
  AGENTS_INDEX_URL: z.string().url(),
26
26
 
27
27
  DEFAULT_AGENT_CONFIG: z.string(),
28
+ SYSTEM_AGENT: z.string().optional(),
28
29
 
29
30
  PLUGINS_INDEX_URL: z.string().url(),
30
31
  PLUGIN_SETTINGS: z.string().optional(),
@@ -44,6 +45,7 @@ export const getAppConfig = () => {
44
45
  : 'https://chat-agents.lobehub.com',
45
46
 
46
47
  DEFAULT_AGENT_CONFIG: process.env.DEFAULT_AGENT_CONFIG || '',
48
+ SYSTEM_AGENT: process.env.SYSTEM_AGENT,
47
49
 
48
50
  PLUGINS_INDEX_URL: !!process.env.PLUGINS_INDEX_URL
49
51
  ? process.env.PLUGINS_INDEX_URL
@@ -1,4 +1,4 @@
1
- import { getAppConfig } from '@/config/app';
1
+ import { appEnv, getAppConfig } from '@/config/app';
2
2
  import { fileEnv } from '@/config/file';
3
3
  import { langfuseEnv } from '@/config/langfuse';
4
4
  import { getLLMConfig } from '@/config/llm';
@@ -9,6 +9,7 @@ import {
9
9
  TogetherAIProviderCard,
10
10
  } from '@/config/modelProviders';
11
11
  import { enableNextAuth } from '@/const/auth';
12
+ import { parseSystemAgent } from '@/server/globalConfig/parseSystemAgent';
12
13
  import { GlobalServerConfig } from '@/types/serverConfig';
13
14
  import { extractEnabledModels, transformToChatModelCards } from '@/utils/parseModels';
14
15
 
@@ -51,7 +52,6 @@ export const getServerGlobalConfig = () => {
51
52
  defaultAgent: {
52
53
  config: parseAgentConfig(DEFAULT_AGENT_CONFIG),
53
54
  },
54
-
55
55
  enableUploadFileToServer: !!fileEnv.S3_SECRET_ACCESS_KEY,
56
56
  enabledAccessCode: ACCESS_CODES?.length > 0,
57
57
  enabledOAuthSSO: enableNextAuth,
@@ -114,6 +114,7 @@ export const getServerGlobalConfig = () => {
114
114
  zeroone: { enabled: ENABLED_ZEROONE },
115
115
  zhipu: { enabled: ENABLED_ZHIPU },
116
116
  },
117
+ systemAgent: parseSystemAgent(appEnv.SYSTEM_AGENT),
117
118
  telemetry: {
118
119
  langfuse: langfuseEnv.ENABLE_LANGFUSE,
119
120
  },
@@ -0,0 +1,95 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { parseSystemAgent } from './parseSystemAgent';
4
+
5
+ describe('parseSystemAgent', () => {
6
+ it('should parse a valid environment variable string correctly', () => {
7
+ const envValue = 'topic=openai/gpt-3.5-turbo,translation=anthropic/claude-1';
8
+ const expected = {
9
+ topic: { provider: 'openai', model: 'gpt-3.5-turbo' },
10
+ translation: { provider: 'anthropic', model: 'claude-1' },
11
+ };
12
+
13
+ expect(parseSystemAgent(envValue)).toEqual(expected);
14
+ });
15
+
16
+ it('should handle empty environment variable string', () => {
17
+ const envValue = '';
18
+ const expected = {};
19
+
20
+ expect(parseSystemAgent(envValue)).toEqual(expected);
21
+ });
22
+
23
+ it('should ignore unknown keys in environment variable string', () => {
24
+ const envValue = 'topic=openai/gpt-3.5-turbo,unknown=test/model';
25
+ const expected = {
26
+ topic: { provider: 'openai', model: 'gpt-3.5-turbo' },
27
+ };
28
+
29
+ expect(parseSystemAgent(envValue)).toEqual(expected);
30
+ });
31
+
32
+ it('should throw an error for missing model or provider values', () => {
33
+ const envValue1 = 'topic=openai,translation=/claude-1';
34
+ const envValue2 = 'topic=/gpt-3.5-turbo,translation=anthropic/';
35
+
36
+ expect(() => parseSystemAgent(envValue1)).toThrowError(/Missing model or provider/);
37
+ expect(() => parseSystemAgent(envValue2)).toThrowError(/Missing model or provider/);
38
+ });
39
+
40
+ it('should throw an error for invalid environment variable format', () => {
41
+ const envValue = 'topic-openai/gpt-3.5-turbo';
42
+
43
+ expect(() => parseSystemAgent(envValue)).toThrowError(/Invalid environment variable format/);
44
+ });
45
+
46
+ it('should handle provider or model names with special characters', () => {
47
+ const envValue = 'topic=openrouter/mistralai/mistral-7b-instruct:free';
48
+ const expected = {
49
+ topic: { provider: 'openrouter', model: 'mistralai/mistral-7b-instruct:free' },
50
+ };
51
+
52
+ expect(parseSystemAgent(envValue)).toEqual(expected);
53
+ });
54
+
55
+ it('should handle extra whitespace in environment variable string', () => {
56
+ const envValue = ' topic = openai/gpt-3.5-turbo , translation = anthropic/claude-1 ';
57
+ const expected = {
58
+ topic: { provider: 'openai', model: 'gpt-3.5-turbo' },
59
+ translation: { provider: 'anthropic', model: 'claude-1' },
60
+ };
61
+
62
+ expect(parseSystemAgent(envValue)).toEqual(expected);
63
+ });
64
+
65
+ it('should handle full-width comma in environment variable string', () => {
66
+ const envValue = 'topic=openai/gpt-3.5-turbo,translation=anthropic/claude-1';
67
+ const expected = {
68
+ topic: { provider: 'openai', model: 'gpt-3.5-turbo' },
69
+ translation: { provider: 'anthropic', model: 'claude-1' },
70
+ };
71
+
72
+ expect(parseSystemAgent(envValue)).toEqual(expected);
73
+ });
74
+
75
+ it('should handle extra whitespace around provider and model names', () => {
76
+ const envValue = 'topic= openai / gpt-3.5-turbo ,translation= anthropic / claude-1 ';
77
+ const expected = {
78
+ topic: { provider: 'openai', model: 'gpt-3.5-turbo' },
79
+ translation: { provider: 'anthropic', model: 'claude-1' },
80
+ };
81
+
82
+ expect(parseSystemAgent(envValue)).toEqual(expected);
83
+ });
84
+
85
+ it('should handle an excessively long environment variable string', () => {
86
+ const longProviderName = 'a'.repeat(100);
87
+ const longModelName = 'b'.repeat(100);
88
+ const envValue = `topic=${longProviderName}/${longModelName}`;
89
+ const expected = {
90
+ topic: { provider: longProviderName, model: longModelName },
91
+ };
92
+
93
+ expect(parseSystemAgent(envValue)).toEqual(expected);
94
+ });
95
+ });
@@ -0,0 +1,39 @@
1
+ import { DEFAULT_SYSTEM_AGENT_CONFIG } from '@/const/settings';
2
+ import { UserSystemAgentConfig } from '@/types/user/settings';
3
+
4
+ const protectedKeys = Object.keys(DEFAULT_SYSTEM_AGENT_CONFIG);
5
+
6
+ export const parseSystemAgent = (envString: string = ''): Partial<UserSystemAgentConfig> => {
7
+ if (!envString) return {};
8
+
9
+ const config: Partial<UserSystemAgentConfig> = {};
10
+
11
+ // 处理全角逗号和多余空格
12
+ let envValue = envString.replaceAll(',', ',').trim();
13
+
14
+ const pairs = envValue.split(',');
15
+
16
+ for (const pair of pairs) {
17
+ const [key, value] = pair.split('=').map((s) => s.trim());
18
+
19
+ if (key && value) {
20
+ const [provider, ...modelParts] = value.split('/');
21
+ const model = modelParts.join('/');
22
+
23
+ if (!provider || !model) {
24
+ throw new Error('Missing model or provider value');
25
+ }
26
+
27
+ if (protectedKeys.includes(key)) {
28
+ config[key as keyof UserSystemAgentConfig] = {
29
+ model: model.trim(),
30
+ provider: provider.trim(),
31
+ };
32
+ }
33
+ } else {
34
+ throw new Error('Invalid environment variable format');
35
+ }
36
+ }
37
+
38
+ return config;
39
+ };
@@ -72,7 +72,7 @@ export interface SessionAction {
72
72
 
73
73
  updateSearchKeywords: (keywords: string) => void;
74
74
 
75
- useFetchSessions: () => SWRResponse<ChatSessionList>;
75
+ useFetchSessions: (isLogin: boolean | undefined) => SWRResponse<ChatSessionList>;
76
76
  useSearchSessions: (keyword?: string) => SWRResponse<any>;
77
77
 
78
78
  internal_dispatchSessions: (payload: SessionDispatch) => void;
@@ -192,29 +192,33 @@ export const createSessionSlice: StateCreator<
192
192
  await refreshSessions();
193
193
  },
194
194
 
195
- useFetchSessions: () =>
196
- useClientDataSWR<ChatSessionList>(FETCH_SESSIONS_KEY, sessionService.getGroupedSessions, {
197
- fallbackData: {
198
- sessionGroups: [],
199
- sessions: [],
200
- },
201
- onSuccess: (data) => {
202
- if (
203
- get().isSessionsFirstFetchFinished &&
204
- isEqual(get().sessions, data.sessions) &&
205
- isEqual(get().sessionGroups, data.sessionGroups)
206
- )
207
- return;
208
-
209
- get().internal_processSessions(
210
- data.sessions,
211
- data.sessionGroups,
212
- n('useFetchSessions/updateData') as any,
213
- );
214
- set({ isSessionsFirstFetchFinished: true }, false, n('useFetchSessions/onSuccess', data));
195
+ useFetchSessions: (isLogin) =>
196
+ useClientDataSWR<ChatSessionList>(
197
+ [FETCH_SESSIONS_KEY, isLogin],
198
+ () => sessionService.getGroupedSessions(),
199
+ {
200
+ fallbackData: {
201
+ sessionGroups: [],
202
+ sessions: [],
203
+ },
204
+ onSuccess: (data) => {
205
+ if (
206
+ get().isSessionsFirstFetchFinished &&
207
+ isEqual(get().sessions, data.sessions) &&
208
+ isEqual(get().sessionGroups, data.sessionGroups)
209
+ )
210
+ return;
211
+
212
+ get().internal_processSessions(
213
+ data.sessions,
214
+ data.sessionGroups,
215
+ n('useFetchSessions/updateData') as any,
216
+ );
217
+ set({ isSessionsFirstFetchFinished: true }, false, n('useFetchSessions/onSuccess', data));
218
+ },
219
+ suspense: true,
215
220
  },
216
- suspense: true,
217
- }),
221
+ ),
218
222
  useSearchSessions: (keyword) =>
219
223
  useSWR<LobeSessions>(
220
224
  [SEARCH_SESSIONS_KEY, keyword],
@@ -81,7 +81,9 @@ export const createCommonSlice: StateCreator<
81
81
  const serverSettings: DeepPartial<UserSettings> = {
82
82
  defaultAgent: serverConfig.defaultAgent,
83
83
  languageModel: serverConfig.languageModel,
84
+ systemAgent: serverConfig.systemAgent,
84
85
  };
86
+
85
87
  const defaultSettings = merge(get().defaultSettings, serverSettings);
86
88
 
87
89
  // merge preference
@@ -1,7 +1,11 @@
1
1
  import { DeepPartial } from 'utility-types';
2
2
 
3
3
  import { ChatModelCard } from '@/types/llm';
4
- import { UserDefaultAgent, GlobalLLMProviderKey } from '@/types/user/settings';
4
+ import {
5
+ GlobalLLMProviderKey,
6
+ UserDefaultAgent,
7
+ UserSystemAgentConfig,
8
+ } from '@/types/user/settings';
5
9
 
6
10
  export interface ServerModelProviderConfig {
7
11
  enabled?: boolean;
@@ -21,6 +25,7 @@ export interface GlobalServerConfig {
21
25
  enabledAccessCode?: boolean;
22
26
  enabledOAuthSSO?: boolean;
23
27
  languageModel?: ServerLanguageModel;
28
+ systemAgent?: DeepPartial<UserSystemAgentConfig>;
24
29
  telemetry: {
25
30
  langfuse?: boolean;
26
31
  };