Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ refactor: refactor keyVaults and rename endpoint to baseURL #2673

Merged
merged 5 commits into from
May 27, 2024

Conversation

arvinxx
Copy link
Contributor

@arvinxx arvinxx commented May 26, 2024

💻 变更类型 | Change Type

  • ✨ feat
  • 🐛 fix
  • ♻️ refactor
  • 💄 style
  • 🔨 chore
  • ⚡️ perf
  • 📝 docs

🔀 变更说明 | Description of Change

为增强用户输入的秘钥安全性,计划将 apikey 和 endpoint 作为关键私密数据从 languageModel 中抽取出来,后续将采用加密算法进行加密存储。借由此次变更,顺带可以实现 endpoint -> baseURL 的字段重构操作。

几个关键变更:

  1. 所有 apiKey 的位置从 languageModel -> keyVaults ,涉及到 url 分享的兼容性问题, @cy948 看下是 Breaking ,还是兼容下;
  2. endpoint 改名为 baseURL,与 agent-runtime 对齐,这样就可以直接透传 keyVaults 而不需要再解构了,后续 agent-runtime 的赋值初始化可以简化实现。 cc @cy948

📝 补充信息 | Additional Information

Summary by CodeRabbit

  • New Features

    • Introduced themeMode in settings, allowing users to toggle between different themes.
    • Added new configurations for key vaults, enhancing security and management of API keys.
  • Bug Fixes

    • Improved language retrieval logic in user settings.
  • Refactor

    • Renamed various selectors and updated import statements for better code clarity and maintainability.
  • Tests

    • Added new test cases for user settings selectors, ensuring correct retrieval of language and theme mode.

Copy link

vercel bot commented May 26, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
lobe-chat-community ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 26, 2024 5:48pm

@lobehubbot
Copy link
Member

👍 @arvinxx

Thank you for raising your pull request and contributing to our Community
Please make sure you have followed our contributing guidelines. We will review it as soon as possible.
If you encounter any problems, please feel free to connect with us.
非常感谢您提出拉取请求并为我们的社区做出贡献,请确保您已经遵循了我们的贡献指南,我们会尽快审查它。
如果您遇到任何问题,请随时与我们联系。

Copy link

coderabbitai bot commented May 26, 2024

Walkthrough

This update primarily focuses on refactoring and renaming selectors related to user settings, particularly shifting from settingsSelectors to userGeneralSettingsSelectors. It also includes updates to configuration keys, migrations for database schema, and enhancements in testing. The changes aim to improve code clarity, maintainability, and alignment with new configuration structures.

Changes

Files/Paths Change Summary
src/app/(main)/.../SubmitAgentModal.tsx Updated import statement for settingsSelectors to userGeneralSettingsSelectors.
src/app/(main)/.../Common.tsx Changed name property from string to array.
src/app/(main)/.../ThemeSwatches/ThemeSwatches...tsx Renamed settingsSelectors to userGeneralSettingsSelectors and updated related logic.
src/app/(main)/.../Theme/index.tsx Added userGeneralSettingsSelectors to imports, introduced themeMode in state.
src/app/(main)/.../Azure/index.tsx Updated imports and key references in AzureOpenAIProvider component.
src/app/(main)/.../Bedrock/index.tsx Renamed constant LLMProviderConfigKey to KeyVaultsConfigKey.
src/app/(main)/.../ProviderConfig/index.tsx Renamed selectors from modelConfigSelectors to keyVaultsConfigSelectors.
src/app/(main)/.../const.ts Updated exported constants related to configuration keys.
src/app/(main)/.../Checker.tsx Added .catch() method to handle promise rejection in checkConnection function.
src/const/settings/... Renamed UserGeneralSettings to UserGeneralConfig and updated related types.
src/database/client/... Added migration method upgradeToV11 in BrowserDB class.
src/features/... Various updates to import statements and selector usage.
src/hooks/... Updated import statements and selectors in hooks.
src/layout/GlobalProvider/AppTheme.tsx Updated import statement for selectors.
src/libs/agent-runtime/types/type.ts Removed ChatGLM and Tongyi enum values, added ModelProviderKey type definition.
src/migrations/... Introduced migration class MigrationV6ToV7 and updated version control.
src/services/__tests__/... Updated tests to reflect changes in selectors and configuration keys.
src/services/... Updated import and usage of selectors in various services.
src/store/user/... Updated import statements, function calls, and object structures in store slices and selectors.
src/store/user/slices/settings/selectors/general.test.ts Added test cases for selectors related to user general settings.

In code's vast realm, changes flow,
Selectors renamed, settings grow.
Keys and vaults, a new array,
Migration paths, we pave the way.
With tests to guide, and themes to light,
Our code evolves, a wondrous sight.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to full the review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@arvinxx arvinxx force-pushed the refactor/language-model-settings branch from e27a596 to e309db2 Compare May 26, 2024 15:44
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 17

Outside diff range and nitpick comments (17)
src/const/settings/index.ts (1)

Line range hint 1-1: Consider using TypeScript's import type for imports that are only used as types to clarify their usage and potentially optimize bundling.

- import { UserSettings } from '@/types/user/settings';
+ import type { UserSettings } from '@/types/user/settings';
src/libs/agent-runtime/types/type.ts (1)

Line range hint 12-12: Avoid using any type for better type safety and clarity.

- [key: string]: any;
+ [key: string]: string | number;
src/const/settings/llm.ts (1)

Line range hint 19-20: Consider using import type for imports only used as types to clarify that they are not used at runtime.

- import {
+ import type {
  AnthropicProviderCard,
  BedrockProviderCard,
  DeepSeekProviderCard,
  GoogleProviderCard,
  GroqProviderCard,
  MinimaxProviderCard,
  MistralProviderCard,
  MoonshotProviderCard,
  OllamaProviderCard,
  OpenAIProviderCard,
  OpenRouterProviderCard,
  PerplexityProviderCard,
  TogetherAIProviderCard,
  ZeroOneProviderCard,
  ZhiPuProviderCard,
  filterEnabledModels,
} from '@/config/modelProviders';
src/features/Conversation/Error/APIKeyForm/ProviderApiKeyForm.tsx (2)

Line range hint 35-36: Replace any type with more specific types to ensure type safety.

-  description={t(`${provider}.unlock.description` as any)}
+  description={t(`${provider}.unlock.description` as string)}

-  title={t(`${provider}.unlock.title` as any)}
+  title={t(`${provider}.unlock.title` as string)}

Line range hint 3-4: Consider using import type for imports only used as types to clarify that they are not used at runtime.

- import { Icon } from '@lobehub/ui';
- import { Button, Input } from 'antd';
- import { Network } from 'lucide-react';
- import { ReactNode, memo, useState } from 'react';
- import { useTranslation } from 'react-i18next';
+ import type { Icon } from '@lobehub/ui';
+ import type { Button, Input } from 'antd';
+ import type { Network } from 'lucide-react';
+ import type { ReactNode, memo, useState } from 'react';
+ import type { useTranslation } from 'react-i18next';

- import { keyVaultsConfigSelectors } from '@/store/user/selectors';
- import { GlobalLLMProviderKey } from '@/types/user/settings';
+ import type { keyVaultsConfigSelectors } from '@/store/user/selectors';
+ import type { GlobalLLMProviderKey } from '@/types/user/settings';

Also applies to: 8-9

src/hooks/useTTS.ts (1)

Line range hint 1-9: Consider using import type for imports only used as types to clarify that they are not used at runtime.

- import {
+ import type {
  EdgeSpeechOptions,
  MicrosoftSpeechOptions,
  OpenAITTSOptions,
  TTSOptions,
  useEdgeSpeech,
  useMicrosoftSpeech,
  useOpenAITTS,
} from '@lobehub/tts/react';
- import { settingsSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';
+ import type { settingsSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';

Also applies to: 17-18

src/app/(main)/settings/llm/Azure/index.tsx (1)

Line range hint 101-103: JSX elements without children should be self-closing to improve readability.

- <Azure.Combine size={22} type={'color'}></Azure.Combine>
+ <Azure.Combine size={22} type={'color'} />
- <OpenAI.Combine size={24}></OpenAI.Combine>
+ <OpenAI.Combine size={24} />
src/layout/GlobalProvider/AppTheme.tsx (1)

Line range hint 2-3: Consider marking imports that are only used as types with type to clarify their usage and potentially optimize bundling.

- import { ConfigProvider, NeutralColors, PrimaryColors, ThemeProvider } from '@lobehub/ui';
+ import type { ConfigProvider, NeutralColors, PrimaryColors, ThemeProvider } from '@lobehub/ui';

Also applies to: 3-4, 7-8

src/features/ChatInput/STT/openai.tsx (1)

Line range hint 60-60: Avoid using any as a type for error handling. Specify a more precise type for better type safety.

- const setDefaultError = useCallback((err?: any) => {
+ const setDefaultError = useCallback((err?: Error) => {
src/features/PluginDevModal/LocalForm.tsx (1)

Line range hint 1-1: Consider marking imports that are only used as types with type to clarify their usage and potentially optimize bundling.

- import { Form, FormItemProps, Input, TextArea } from '@lobehub/ui';
+ import type { Form, FormItemProps, Input, TextArea } from '@lobehub/ui';

Also applies to: 1-2

src/features/AgentSetting/AgentTTS/index.tsx (1)

Line range hint 38-38: Ensure all dependencies are specified in the useMemo hook to avoid potential bugs due to missing re-evaluations.

- const { edgeVoiceOptions, microsoftVoiceOptions } = useMemo(() => voiceList(showAllLocaleVoice), [showAllLocaleVoice]);
+ const { edgeVoiceOptions, microsoftVoiceOptions } = useMemo(() => voiceList(showAllLocaleVoice), [showAllLocaleVoice, voiceList]);
src/features/Conversation/components/ChatItem/index.tsx (3)

Line range hint 74-74: Consider simplifying the expression by removing unnecessary string literal.

- return { message: errorT(`response.${messageError.type}` as any), ...alertConfig };
+ return { message: errorT(`response.${messageError.type}`), ...alertConfig };

Line range hint 86-86: The use of any type should be avoided to maintain type safety. Specify explicit types for better maintainability and error checking.

Also applies to: 102-102


Line range hint 96-96: The useMemo hook is missing a dependency on errorT. This can lead to stale or incorrect data being used in the component.

- }, [item?.error]);
+ }, [item?.error, errorT]);
src/store/user/slices/modelList/action.test.ts (1)

Line range hint 189-189: Avoid using non-null assertions as they can lead to runtime errors if assumptions about non-nullability prove incorrect.

- expect(result.current.setModelProviderConfig).not.toHaveBeenCalled();
+ expect(result.current.setModelProviderConfig).not.toHaveBeenCalled();
src/services/__tests__/chat.test.ts (2)

Line range hint 50-50: Specify a more precise type instead of 'any' to improve type safety and code clarity.

- return { ...(module as any), getMessageError: vi.fn() };
+ return { ...(module as unknown as SomeSpecificType), getMessageError: vi.fn() }; // Replace 'SomeSpecificType' with the actual type

Line range hint 551-552: Avoid using non-null assertions in test cases as they can lead to false positives if the assumptions about non-nullability are incorrect.

- expect(calls![0]).toMatchSnapshot();
- expect(calls![1]).toBeUndefined();
+ expect(calls?.[0]).toMatchSnapshot();
+ expect(calls?.[1]).toBeUndefined();

Also applies to: 554-555

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 6650daf and e309db2.
Files selected for processing (52)
  • src/app/(main)/chat/settings/features/SubmitAgentButton/SubmitAgentModal.tsx (2 hunks)
  • src/app/(main)/settings/common/features/Common.tsx (1 hunks)
  • src/app/(main)/settings/common/features/Theme/ThemeSwatches/ThemeSwatchesNeutral.tsx (1 hunks)
  • src/app/(main)/settings/common/features/Theme/ThemeSwatches/ThemeSwatchesPrimary.tsx (1 hunks)
  • src/app/(main)/settings/common/features/Theme/index.tsx (5 hunks)
  • src/app/(main)/settings/llm/Azure/index.tsx (3 hunks)
  • src/app/(main)/settings/llm/components/ProviderConfig/index.tsx (4 hunks)
  • src/app/(main)/settings/llm/const.ts (2 hunks)
  • src/const/settings/common.ts (1 hunks)
  • src/const/settings/index.ts (1 hunks)
  • src/const/settings/llm.ts (1 hunks)
  • src/database/client/models/user.ts (2 hunks)
  • src/features/AgentSetting/AgentMeta/index.tsx (3 hunks)
  • src/features/AgentSetting/AgentTTS/index.tsx (2 hunks)
  • src/features/ChatInput/STT/browser.tsx (2 hunks)
  • src/features/ChatInput/STT/openai.tsx (2 hunks)
  • src/features/Conversation/Error/APIKeyForm/Bedrock.tsx (2 hunks)
  • src/features/Conversation/Error/APIKeyForm/ProviderApiKeyForm.tsx (2 hunks)
  • src/features/Conversation/Error/AccessCodeForm.tsx (2 hunks)
  • src/features/Conversation/Extras/TTS/index.tsx (1 hunks)
  • src/features/Conversation/Plugins/Render/MarkdownType/index.tsx (2 hunks)
  • src/features/Conversation/components/ChatItem/index.tsx (2 hunks)
  • src/features/PluginDevModal/LocalForm.tsx (1 hunks)
  • src/features/User/UserPanel/LangButton.tsx (1 hunks)
  • src/features/User/UserPanel/ThemeButton.tsx (2 hunks)
  • src/hooks/_header.ts (1 hunks)
  • src/hooks/useTTS.ts (2 hunks)
  • src/layout/GlobalProvider/AppTheme.tsx (2 hunks)
  • src/libs/agent-runtime/types/type.ts (2 hunks)
  • src/migrations/FromV6ToV7/fixtures/output-v7-from-v1.json (1 hunks)
  • src/migrations/FromV6ToV7/fixtures/provider-input-v6.json (1 hunks)
  • src/migrations/FromV6ToV7/fixtures/provider-output-v7.json (1 hunks)
  • src/migrations/FromV6ToV7/index.ts (1 hunks)
  • src/migrations/FromV6ToV7/migrations.test.ts (1 hunks)
  • src/migrations/FromV6ToV7/types/v6.ts (1 hunks)
  • src/migrations/FromV6ToV7/types/v7.ts (1 hunks)
  • src/services/tests/chat.test.ts (16 hunks)
  • src/services/tests/share.test.ts (1 hunks)
  • src/services/_auth.test.ts (3 hunks)
  • src/services/_auth.ts (3 hunks)
  • src/services/_header.ts (1 hunks)
  • src/services/ollama.ts (2 hunks)
  • src/services/user/client.test.ts (1 hunks)
  • src/store/user/helpers.ts (1 hunks)
  • src/store/user/selectors.ts (1 hunks)
  • src/store/user/slices/common/action.test.ts (3 hunks)
  • src/store/user/slices/common/action.ts (2 hunks)
  • src/store/user/slices/modelList/action.test.ts (2 hunks)
  • src/store/user/slices/modelList/action.ts (5 hunks)
  • src/store/user/slices/modelList/selectors/index.ts (1 hunks)
  • src/store/user/slices/modelList/selectors/keyVaults.ts (1 hunks)
  • src/store/user/slices/modelList/selectors/modelConfig.test.ts (1 hunks)
Files not processed due to max files limit (12)
  • src/store/user/slices/modelList/selectors/modelConfig.ts
  • src/store/user/slices/settings/action.test.ts
  • src/store/user/slices/settings/action.ts
  • src/store/user/slices/settings/selectors/general.test.ts
  • src/store/user/slices/settings/selectors/general.ts
  • src/store/user/slices/settings/selectors/index.ts
  • src/store/user/slices/settings/selectors/settings.test.ts
  • src/store/user/slices/settings/selectors/settings.ts
  • src/types/user/settings/general.ts
  • src/types/user/settings/index.ts
  • src/types/user/settings/keyVaults.ts
  • src/types/user/settings/modelProvider.ts
Files skipped from review due to trivial changes (2)
  • src/store/user/selectors.ts
  • src/store/user/slices/modelList/selectors/index.ts
Additional Context Used
Biome (158)
src/app/(main)/chat/settings/features/SubmitAgentButton/SubmitAgentModal.tsx (1)

31-31: Change to an optional chain.

src/app/(main)/settings/common/features/Common.tsx (19)

52-52: This hook does not specify all of its dependencies: message.success


52-52: This hook does not specify all of its dependencies: signOut


52-52: This hook does not specify all of its dependencies: modal.confirm


52-52: This hook does not specify all of its dependencies: t


64-64: This hook does not specify all of its dependencies: signIn


68-68: This hook does not specify all of its dependencies: form.setFieldsValue


68-68: This hook does not specify all of its dependencies: modal.confirm


68-68: This hook does not specify all of its dependencies: t


68-68: This hook does not specify all of its dependencies: message.success


68-68: This hook does not specify all of its dependencies: resetSettings


81-81: This hook does not specify all of its dependencies: clearAllMessages


81-81: This hook does not specify all of its dependencies: clearSessions


81-81: This hook does not specify all of its dependencies: removeAllFiles


81-81: This hook does not specify all of its dependencies: t


81-81: This hook does not specify all of its dependencies: modal.confirm


81-81: This hook does not specify all of its dependencies: removeAllPlugins


81-81: This hook does not specify all of its dependencies: message.success


81-81: This hook does not specify all of its dependencies: clearSessionGroups


81-81: This hook does not specify all of its dependencies: clearTopics

src/app/(main)/settings/common/features/Theme/ThemeSwatches/ThemeSwatchesNeutral.tsx (2)

19-19: Unexpected any. Specify a different type.


1-7: Some named imports are only used as types.

src/app/(main)/settings/common/features/Theme/ThemeSwatches/ThemeSwatchesPrimary.tsx (2)

19-19: Unexpected any. Specify a different type.


1-7: Some named imports are only used as types.

src/app/(main)/settings/llm/Azure/index.tsx (2)

101-101: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.


103-103: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

src/app/(main)/settings/llm/components/ProviderConfig/index.tsx (6)

116-116: Unexpected any. Specify a different type.


119-119: Unexpected any. Specify a different type.


120-120: Unexpected any. Specify a different type.


162-162: Forbidden non-null assertion.


6-7: Some named imports are only used as types.


21-22: All these imports are only used as types.

src/const/settings/common.ts (1)

1-1: All these imports are only used as types.

src/const/settings/index.ts (1)

1-1: All these imports are only used as types.

src/const/settings/llm.ts (1)

19-20: All these imports are only used as types.

src/database/client/models/user.ts (4)

47-47: Unexpected any. Specify a different type.


1-1: All these imports are only used as types.


3-4: All these imports are only used as types.


6-7: Some named imports are only used as types.

src/features/AgentSetting/AgentMeta/index.tsx (5)

42-42: Unexpected any. Specify a different type.


49-49: Unexpected any. Specify a different type.


56-56: Unexpected any. Specify a different type.


118-118: Unexpected any. Specify a different type.


16-17: All these imports are only used as types.

src/features/AgentSetting/AgentTTS/index.tsx (2)

3-4: Some named imports are only used as types.


38-38: This hook does not specify all of its dependencies: voiceList

src/features/ChatInput/STT/browser.tsx (4)

49-49: Unexpected any. Specify a different type.


1-1: Some named imports are only used as types.


4-5: All these imports are only used as types.


12-13: All these imports are only used as types.

src/features/ChatInput/STT/openai.tsx (4)

60-60: Unexpected any. Specify a different type.


1-2: Some named imports are only used as types.


5-6: All these imports are only used as types.


15-16: All these imports are only used as types.

src/features/Conversation/Error/APIKeyForm/ProviderApiKeyForm.tsx (4)

35-35: Unexpected any. Specify a different type.


36-36: Unexpected any. Specify a different type.


3-4: Some named imports are only used as types.


8-9: All these imports are only used as types.

src/features/Conversation/Extras/TTS/index.tsx (1)

9-10: Some named imports are only used as types.

src/features/Conversation/components/ChatItem/index.tsx (7)

74-74: The computed expression can be simplified without the use of a string literal.


86-86: This variable implicitly has the any type.


102-102: Unexpected any. Specify a different type.


1-1: Some named imports are only used as types.


3-4: Some named imports are only used as types.


14-15: All these imports are only used as types.


96-96: This hook does not specify all of its dependencies: errorT

src/features/PluginDevModal/LocalForm.tsx (2)

1-1: Some named imports are only used as types.


1-2: All these imports are only used as types.

src/features/User/UserPanel/LangButton.tsx (1)

22-22: This hook does not specify all of its dependencies: switchLocale

src/features/User/UserPanel/ThemeButton.tsx (1)

27-27: This hook does not specify all of its dependencies: switchThemeMode

src/hooks/useTTS.ts (4)

31-31: This variable implicitly has the any type.


32-32: Unexpected any. Specify a different type.


1-9: Some named imports are only used as types.


17-18: All these imports are only used as types.

src/layout/GlobalProvider/AppTheme.tsx (3)

2-3: Some named imports are only used as types.


3-4: Some named imports are only used as types.


7-8: Some named imports are only used as types.

src/libs/agent-runtime/types/type.ts (4)

12-12: Unexpected any. Specify a different type.


1-1: All these imports are only used as types.


2-3: All these imports are only used as types.


3-4: All these imports are only used as types.

src/migrations/FromV6ToV7/index.ts (2)

2-3: All these imports are only used as types.


3-4: All these imports are only used as types.

src/migrations/FromV6ToV7/migrations.test.ts (3)

17-17: This variable implicitly has the any type.


18-18: Unexpected any. Specify a different type.


7-8: Some named imports are only used as types.

src/migrations/FromV6ToV7/types/v6.ts (6)

4-4: Unexpected any. Specify a different type.


10-10: Unexpected any. Specify a different type.


44-44: Unexpected any. Specify a different type.


51-51: Unexpected any. Specify a different type.


53-53: Unexpected any. Specify a different type.


54-54: Unexpected any. Specify a different type.

src/migrations/FromV6ToV7/types/v7.ts (6)

41-41: Unexpected any. Specify a different type.


46-46: Unexpected any. Specify a different type.


60-60: Unexpected any. Specify a different type.


64-64: Unexpected any. Specify a different type.


65-65: Unexpected any. Specify a different type.


66-66: Unexpected any. Specify a different type.

src/services/__tests__/chat.test.ts (20)

50-50: Unexpected any. Specify a different type.


551-552: Forbidden non-null assertion.


554-555: Forbidden non-null assertion.


693-694: The computed expression can be simplified without the use of a string literal.


696-696: The computed expression can be simplified without the use of a string literal.


714-714: The computed expression can be simplified without the use of a string literal.


729-729: The computed expression can be simplified without the use of a string literal.


742-743: The computed expression can be simplified without the use of a string literal.


761-761: The computed expression can be simplified without the use of a string literal.


776-776: The computed expression can be simplified without the use of a string literal.


790-791: The computed expression can be simplified without the use of a string literal.


806-806: The computed expression can be simplified without the use of a string literal.


821-821: The computed expression can be simplified without the use of a string literal.


835-836: The computed expression can be simplified without the use of a string literal.


851-851: The computed expression can be simplified without the use of a string literal.


866-866: The computed expression can be simplified without the use of a string literal.


881-881: The computed expression can be simplified without the use of a string literal.


896-896: The computed expression can be simplified without the use of a string literal.


909-909: Unexpected any. Specify a different type.


917-917: The computed expression can be simplified without the use of a string literal.

src/services/__tests__/share.test.ts (4)

1-1: All these imports are only used as types.


1-2: Some named imports are only used as types.


4-5: All these imports are only used as types.


5-6: All these imports are only used as types.

src/services/_auth.test.ts (1)

5-10: Some named imports are only used as types.

src/services/_auth.ts (3)

58-58: Unexpected any. Specify a different type.


1-1: Some named imports are only used as types.


4-5: All these imports are only used as types.

src/services/ollama.ts (1)

1-1: Some named imports are only used as types.

src/services/user/client.test.ts (6)

41-41: The computed expression can be simplified without the use of a string literal.


94-94: The computed expression can be simplified without the use of a string literal.


1-1: All these imports are only used as types.


1-2: Some named imports are only used as types.


4-5: All these imports are only used as types.


5-6: All these imports are only used as types.

src/store/user/slices/common/action.test.ts (7)

24-24: Unexpected any. Specify a different type.


59-59: Unexpected any. Specify a different type.


198-198: Unexpected any. Specify a different type.


198-198: Unexpected any. Specify a different type.


225-225: Unexpected any. Specify a different type.


10-11: All these imports are only used as types.


11-12: All these imports are only used as types.

src/store/user/slices/common/action.ts (4)

73-73: Avoid redundant double-negation.


1-1: Some named imports are only used as types.


1-2: All these imports are only used as types.


9-10: All these imports are only used as types.

src/store/user/slices/modelList/action.test.ts (3)

189-189: Forbidden non-null assertion.


6-7: All these imports are only used as types.


9-10: All these imports are only used as types.

src/store/user/slices/modelList/action.ts (6)

127-127: Unexpected any. Specify a different type.


1-2: Some named imports are only used as types.


6-7: All these imports are only used as types.


7-8: All these imports are only used as types.


8-13: All these imports are only used as types.


15-16: Some named imports are only used as types.

src/store/user/slices/modelList/selectors/keyVaults.ts (2)

1-1: All these imports are only used as types.


1-2: All these imports are only used as types.

src/store/user/slices/modelList/selectors/modelConfig.test.ts (3)

2-3: All these imports are only used as types.


5-6: All these imports are only used as types.


6-7: Some named imports are only used as types.

Additional comments not posted (50)
src/const/settings/common.ts (2)

1-1: The import is correctly used as a type, promoting better tree-shaking and compile-time checks.


3-3: The definition of DEFAULT_COMMON_SETTINGS is clear and aligns well with the UserGeneralConfig type structure.

src/store/user/helpers.ts (2)

1-1: The imports are correctly used and necessary for the functionality of the helper functions.


4-5: The function getCurrentLanguage correctly utilizes the userGeneralSettingsSelectors to fetch the current language setting.

src/app/(main)/settings/llm/const.ts (1)

14-14: The renaming of LLMProviderBaseUrlKey from endpoint to baseURL aligns with the PR's objective to refactor endpoint usage to baseURL.

src/features/Conversation/Plugins/Render/MarkdownType/index.tsx (1)

15-15: The usage of userGeneralSettingsSelectors.fontSize in PluginMarkdownType is appropriate and aligns with the new selector structure.

src/services/_header.ts (2)

3-6: The imports in this file are correctly used to support the functionality of createHeaderWithOpenAI.


14-21: The function createHeaderWithOpenAI effectively uses the keyVaultsConfigSelectors to construct headers, aligning with the updated configuration structure.

src/hooks/_header.ts (2)

3-6: The imports in this file are correctly used to support the functionality of createHeaderWithOpenAI.


11-14: The function createHeaderWithOpenAI effectively uses the keyVaultsConfigSelectors to construct headers, aligning with the updated configuration structure.

src/const/settings/index.ts (1)

21-22: The addition of general and keyVaults fields to DEFAULT_SETTINGS aligns well with the refactoring objectives.

src/app/(main)/settings/common/features/Theme/ThemeSwatches/ThemeSwatchesNeutral.tsx (1)

11-11: The update to use userGeneralSettingsSelectors is consistent with the broader refactoring effort.

src/app/(main)/settings/common/features/Theme/ThemeSwatches/ThemeSwatchesPrimary.tsx (1)

11-11: The update to use userGeneralSettingsSelectors is consistent with the broader refactoring effort.

src/libs/agent-runtime/types/type.ts (1)

39-44: The changes to the ModelProvider enum and the introduction of ModelProviderKey are well-implemented.

src/store/user/slices/modelList/selectors/keyVaults.ts (1)

6-25: The introduction of new selectors for key vault configurations is well-implemented and aligns with the refactoring objectives.

src/features/Conversation/Extras/TTS/index.tsx (1)

7-7: The update to use userGeneralSettingsSelectors is consistent with the broader refactoring effort.

src/services/ollama.ts (2)

6-6: Use TypeScript's type import for imports used only as types to clarify their usage and potentially optimize bundling.

- import { ListResponse, Ollama as OllamaBrowser, ProgressResponse } from 'ollama/browser';
+ import type { ListResponse, Ollama as OllamaBrowser, ProgressResponse } from 'ollama/browser';

28-30: The refactoring of the getHost method to use keyVaultsConfigSelectors is correctly implemented and aligns with the PR's objectives.

src/migrations/FromV6ToV7/migrations.test.ts (1)

25-39: The test cases are well-structured and effectively validate the migration logic from previous versions to version 7.

Also applies to: 42-63

src/app/(main)/chat/settings/features/SubmitAgentButton/SubmitAgentModal.tsx (1)

20-20: The update to use userGeneralSettingsSelectors is correctly implemented. Consider using optional chaining when accessing properties to enhance code robustness.

- const language = useUserStore((s) => userGeneralSettingsSelectors.currentLanguage(s));
+ const language = useUserStore((s) => userGeneralSettingsSelectors.currentLanguage(s)?.value);

Also applies to: 28-28

src/services/user/client.test.ts (1)

61-61: The refactoring of the settings patch to include a nested general property is correctly implemented and aligns with the PR's objectives.

src/features/ChatInput/STT/browser.tsx (1)

12-12: The usage of both settingsSelectors and userGeneralSettingsSelectors is noted. Ensure that this is intentional and part of a transitional refactoring phase.

Also applies to: 25-25

src/app/(main)/settings/llm/Azure/index.tsx (1)

60-60: The update to use new constants for form field names is correctly implemented and aligns with the PR's objectives.

Also applies to: 66-66, 88-88

src/migrations/FromV6ToV7/fixtures/provider-input-v6.json (1)

1-98: The JSON structure appears correctly formatted and consistent with the expected version 6 settings.

src/layout/GlobalProvider/AppTheme.tsx (1)

17-17: The refactoring from settingsSelectors to userGeneralSettingsSelectors aligns with the PR's objectives and is correctly implemented in the theme settings component.

Also applies to: 89-93

src/features/ChatInput/STT/openai.tsx (1)

15-15: The refactoring from settingsSelectors to userGeneralSettingsSelectors is correctly implemented in the OpenAI STT feature.

Also applies to: 28-28

src/features/PluginDevModal/LocalForm.tsx (1)

10-10: The refactoring to use userGeneralSettingsSelectors for locale settings in the plugin development form is correctly implemented.

Also applies to: 16-16

src/features/AgentSetting/AgentTTS/index.tsx (1)

13-13: The refactoring from settingsSelectors to userGeneralSettingsSelectors is correctly implemented in the TTS settings component.

Also applies to: 27-27

src/migrations/FromV6ToV7/fixtures/provider-output-v7.json (1)

1-116: The JSON structure appears correctly formatted and consistent with the expected version 7 settings.

src/services/__tests__/share.test.ts (1)

95-95: Ensure the URL encoding is correct for the new settings structure.

Verification successful

Ensure the URL encoding is correct for the new settings structure.


Ensure the URL encoding is correct for the new settings structure.


Ensure the URL encoding is correct for the new settings structure.


Ensure the URL encoding is correct for the new settings structure.


Ensure the URL encoding is correct for the new settings structure.


The createShareSettingsUrl function in src/services/share.ts uses encodeURI to encode the settings object, which includes the new keyVaults structure. This ensures that the URL encoding should handle the new structure correctly.

  • src/services/share.ts:
    public createShareSettingsUrl(settings: DeepPartial<UserSettings>) {
      return withBasePath(`/?${LOBE_URL_IMPORT_NAME}=${encodeURI(JSON.stringify(settings))}`);
    }

The function appears to correctly encode the settings object, including the new keyVaults property.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the URL encoding for the new settings structure.

# Test: Check the URL encoding. Expect: Correct encoding for the new structure.
rg --type python $'createShareSettingsUrl'

Length of output: 72



Script:

#!/bin/bash
# Description: Verify the URL encoding for the new settings structure.

# Test: Check the URL encoding. Expect: Correct encoding for the new structure.
rg --type typescript 'createShareSettingsUrl'

Length of output: 80



Script:

#!/bin/bash
# Description: Verify the URL encoding for the new settings structure.

# Test: Check the URL encoding. Expect: Correct encoding for the new structure.
rg 'createShareSettingsUrl' --glob '*.ts'

Length of output: 318



Script:

#!/bin/bash
# Description: Review the implementation of createShareSettingsUrl to ensure it handles the new keyVaults structure.

# Extract the implementation of createShareSettingsUrl from src/services/share.ts
ast-grep --lang typescript --pattern $'class $_ {
  $$$
  createShareSettingsUrl($_) {
    $$$
  }
  $$$  
}' src/services/share.ts

Length of output: 132



Script:

#!/bin/bash
# Description: Review the implementation of createShareSettingsUrl to ensure it handles the new keyVaults structure.

# Extract the implementation of createShareSettingsUrl from src/services/share.ts
ast-grep --lang typescript --pattern $'class $_ {
  createShareSettingsUrl($_) {
    $$$
  }
}' src/services/share.ts

Length of output: 118



Script:

#!/bin/bash
# Description: Review the implementation of createShareSettingsUrl to ensure it handles the new keyVaults structure.

# Extract the implementation of createShareSettingsUrl from src/services/share.ts
rg 'createShareSettingsUrl' -A 20 src/services/share.ts

Length of output: 574

src/store/user/slices/common/action.ts (1)

118-118: Ensure the userGeneralSettingsSelectors.config method correctly retrieves the user's language setting.

Verification successful

The userGeneralSettingsSelectors.config method is correctly implemented in src/store/user/slices/settings/selectors/general.ts as generalConfig. This method retrieves the general settings, including the user's language setting, ensuring the functionality is as expected.

  • src/store/user/slices/settings/selectors/general.ts
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the functionality of `userGeneralSettingsSelectors.config`.

# Test: Check the method's functionality. Expect: Correct retrieval of the user's language setting.
rg --type python $'userGeneralSettingsSelectors.config'

Length of output: 85



Script:

#!/bin/bash
# Description: Verify the functionality of `userGeneralSettingsSelectors.config`.

# Test: Check the method's functionality. Expect: Correct retrieval of the user's language setting.
rg --type ts 'userGeneralSettingsSelectors.config'

Length of output: 171



Script:

#!/bin/bash
# Description: Locate the definition of `userGeneralSettingsSelectors` and inspect its `config` method.

# Find the definition of `userGeneralSettingsSelectors`.
rg --type ts 'userGeneralSettingsSelectors' | grep -v 'import'

# Inspect the `config` method within the definition.
ast-grep --lang typescript --pattern $'const userGeneralSettingsSelectors = {
  $$$
  config($_) {
    $$$
  }
  $$$
}'

Length of output: 3183



Script:

#!/bin/bash
# Description: Display the contents of `general.ts` to inspect the `config` method.

# Display the contents of `general.ts`.
cat src/store/user/slices/settings/selectors/general.ts

Length of output: 1155

src/features/AgentSetting/AgentMeta/index.tsx (1)

33-33: Ensure the userGeneralSettingsSelectors.currentLanguage method correctly retrieves the user's current language setting.

Verification successful

The implementation of userGeneralSettingsSelectors.currentLanguage in src/store/user/slices/settings/selectors/general.ts correctly retrieves the user's current language setting. It checks the user's language preference and defaults to the browser's language or a default language if set to 'auto'.

  • src/store/user/slices/settings/selectors/general.ts:
    const currentLanguage = (s: UserStore) => {
      const locale = generalConfig(s).language;
    
      if (locale === 'auto') {
        if (isOnServerSide) return DEFAULT_LANG;
    
        return navigator.language as Locales;
      }
    
      return locale;
    };

This confirms that the selector is functioning as intended.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the functionality of `userGeneralSettingsSelectors.currentLanguage`.

# Test: Check the method's functionality. Expect: Correct retrieval of the user's current language setting.
rg --type python $'userGeneralSettingsSelectors.currentLanguage'

Length of output: 94



Script:

#!/bin/bash
# Description: Verify the functionality of `userGeneralSettingsSelectors.currentLanguage`.

# Test: Check the method's functionality. Expect: Correct retrieval of the user's current language setting.
rg --type typescript 'userGeneralSettingsSelectors.currentLanguage'

Length of output: 102



Script:

#!/bin/bash
# Description: Verify the functionality of `userGeneralSettingsSelectors.currentLanguage`.

# Test: Check the method's functionality. Expect: Correct retrieval of the user's current language setting.
rg 'userGeneralSettingsSelectors.currentLanguage'

Length of output: 1246



Script:

#!/bin/bash
# Description: Locate the implementation of `userGeneralSettingsSelectors.currentLanguage`.

# Test: Find the definition of `currentLanguage` within `userGeneralSettingsSelectors`.
rg 'currentLanguage' --type ts

Length of output: 2938



Script:

#!/bin/bash
# Description: Extract the implementation of `currentLanguage` from `general.ts`.

# Test: Display the code for `currentLanguage` to verify its functionality.
rg 'const currentLanguage' -A 10 src/store/user/slices/settings/selectors/general.ts

Length of output: 315

src/app/(main)/settings/common/features/Theme/index.tsx (2)

28-28: Ensure the userGeneralSettingsSelectors.currentThemeMode method correctly retrieves the user's current theme mode.


82-82: Ensure the form field names general.language and general.fontSize are correctly used in the form.

Also applies to: 117-117

src/store/user/slices/modelList/selectors/modelConfig.test.ts (1)

41-41: Ensure the modelConfigSelectors.isProviderFetchOnClient method correctly checks if the provider fetch is on the client.

Verification successful

The isProviderFetchOnClient function is correctly implemented in modelConfig.ts to check if the provider fetch is on the client. It retrieves the provider configuration and checks the fetchOnClient property, defaulting to false if not defined.

  • src/store/user/slices/modelList/selectors/modelConfig.ts:9-14
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the functionality of `modelConfigSelectors.isProviderFetchOnClient`.

# Test: Check the method's functionality. Expect: Correct check if the provider fetch is on the client.
rg --type python $'modelConfigSelectors.isProviderFetchOnClient'

Length of output: 94



Script:

#!/bin/bash
# Description: Verify the functionality of `modelConfigSelectors.isProviderFetchOnClient`.

# Test: Check the method's functionality. Expect: Correct check if the provider fetch is on the client.
rg --type typescript 'isProviderFetchOnClient'

Length of output: 81



Script:

#!/bin/bash
# Description: Verify the functionality of `modelConfigSelectors.isProviderFetchOnClient`.

# Test: Check the method's functionality. Expect: Correct check if the provider fetch is on the client.
rg --type ts 'isProviderFetchOnClient'

Length of output: 1026



Script:

#!/bin/bash
# Description: Extract the implementation of `isProviderFetchOnClient` from `modelConfig.ts`.

# Extract the function implementation.
ast-grep --lang typescript --pattern $'const isProviderFetchOnClient = (provider: $_) => (s: $_) => {
  $$$
}' src/store/user/slices/modelList/selectors/modelConfig.ts

Length of output: 779

src/app/(main)/settings/common/features/Common.tsx (1)

113-113: Ensure the form field name keyVaults.password is correctly used in the form.

Verification successful

The form field name keyVaults.password is correctly used in the codebase.

  • Location: src/store/user/slices/settings/selectors/settings.ts
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the correct use of form field name `keyVaults.password`.

# Test: Check the form field name. Expect: Correct use in the form.
rg --type python $'keyVaults.password' -A 5

Length of output: 73



Script:

#!/bin/bash
# Description: Verify the correct use of form field name `keyVaults.password`.

# Test: Check the form field name. Expect: Correct use in the form.
rg --type js --type ts 'keyVaults.password' -A 5

Length of output: 728

src/features/Conversation/components/ChatItem/index.tsx (2)

14-14: Updated import to use userGeneralSettingsSelectors reflects the renaming in the store. This change aligns with the PR's objective to refactor settings selectors.


41-41: The usage of userGeneralSettingsSelectors.fontSize is correct and aligns with the updated import. This ensures that the component correctly accesses the user's font size setting.

src/services/_auth.test.ts (3)

6-10: The imports from @/types/user/settings are correctly updated to reflect the new types related to key vaults and provider configurations. This change is consistent with the PR's theme of updating settings and configurations.


28-31: The function setModelProviderConfig correctly updates the user store with new key vault settings. This is part of the broader refactor to use UserKeyVaults for more granular control over provider configurations.


142-142: The test case correctly uses the new baseURL setting for the Ollama provider, aligning with the PR's objective to refactor endpoint configurations to baseURL.

src/app/(main)/settings/llm/components/ProviderConfig/index.tsx (4)

13-13: The import of constants like LLMProviderBaseUrlKey is correctly updated to reflect the new naming conventions used in the application. This change supports the PR's goal of standardizing naming across the application.


21-21: The updated imports for keyVaultsConfigSelectors and modelConfigSelectors are correctly used in the component to access configuration settings. This aligns with the refactor to enhance the modularity of settings management.


104-104: The selector isProviderEndpointNotEmpty is used correctly to determine the visibility of certain UI elements based on whether the provider endpoint is set. This usage is consistent with the new settings structure.


121-121: The form item names are correctly updated to use arrays, which reflect the nested structure of the new settings configuration. This is a good practice for handling deeply nested form data.

Also applies to: 132-132

src/store/user/slices/modelList/action.ts (2)

9-13: The imports are correctly updated to reflect the new types and keys related to global LLM providers and user key vaults. This change is part of the broader refactor to enhance type safety and clarity in the application's state management.


47-51: The function updateKeyVaultConfig is correctly implemented to update the key vault configuration in the user store. This aligns with the PR's objective to enhance the configurability of key vault settings.

src/store/user/slices/common/action.test.ts (1)

87-87: The tests correctly reflect the updated settings structure, where language settings are nested under general. This change is part of the broader refactor to organize user settings more logically.

Also applies to: 169-169, 219-219

src/migrations/FromV6ToV7/fixtures/output-v7-from-v1.json (1)

1-203: The JSON structure appears well-formed and consistent with typical session, topic, and message configurations. Ensure that all fields and values are correctly migrated and match the expected schema for version 7.

src/services/__tests__/chat.test.ts (1)

679-682: Ensure that the new settings structure for key vaults is correctly implemented across all relevant test cases.

Verification successful

The search results indicate that the term keyVaults is used consistently across multiple TypeScript files. This suggests that the new settings structure for key vaults is implemented throughout the codebase.

  • The term keyVaults appears in various contexts, including imports, exports, function parameters, and settings updates.
  • The consistent usage across different files and functions aligns with the expected implementation of the new settings structure.

Based on this evidence, it appears that the new settings structure for key vaults is correctly implemented across all relevant test cases and other parts of the codebase.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the new settings structure for key vaults is used consistently.

# Test: Search for the key vaults settings usage. Expect: Consistent usage across all test cases.
rg --type python $'keyVaults'

Length of output: 59



Script:

#!/bin/bash
# Description: Verify that the new settings structure for key vaults is used consistently.

# Test: Search for the key vaults settings usage. Expect: Consistent usage across all test cases.
rg --type typescript 'keyVaults'

Length of output: 67



Script:

#!/bin/bash
# Description: Verify that the new settings structure for key vaults is used consistently.

# Find all TypeScript files and search for the term 'keyVaults' within those files.
fd --extension ts --exec rg 'keyVaults' {}

Length of output: 2494

Comment on lines 6 to +7
import { useUserStore } from '@/store/user';
import { OpenAICompatibleProviderConfig } from '@/types/user/settings';
import { ProviderConfig } from '@/types/user/settings';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using TypeScript's import type for imports that are only used for type declarations to clarify that these are not used at runtime.

- import { ProviderConfig } from '@/types/user/settings';
+ import type { ProviderConfig } from '@/types/user/settings';

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
import { useUserStore } from '@/store/user';
import { OpenAICompatibleProviderConfig } from '@/types/user/settings';
import { ProviderConfig } from '@/types/user/settings';
import { useUserStore } from '@/store/user';
import type { ProviderConfig } from '@/types/user/settings';


interface V7ProviderConfig {
autoFetchModelLists?: boolean;
customModelCards?: any[];
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace any type with more specific types to ensure type safety.

-  customModelCards?: any[];
+  customModelCards?: ModelCard[];

-  remoteModelCards?: any[];
+  remoteModelCards?: ModelCard[];

-  defaultAgent: any;
+  defaultAgent: AgentType;

-  languageModel?: V7ModelProviderConfig;
+  languageModel?: V7ModelProviderConfig | null;

-  sync: any;
+  sync: SyncSettings;

-  tts: any;
+  tts: TTSSettings;

Also applies to: 46-46, 60-60, 64-64, 65-65, 66-66


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
customModelCards?: any[];
customModelCards?: ModelCard[];
remoteModelCards?: ModelCard[];
defaultAgent: AgentType;
languageModel?: V7ModelProviderConfig | null;
sync: SyncSettings;
tts: TTSSettings;

Comment on lines +17 to +18
let migrations;
let versionController: VersionController<any>;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Specify explicit types for migrations and versionController to enhance type safety and code clarity.

- let migrations;
- let versionController: VersionController<any>;
+ let migrations: Migration[];
+ let versionController: VersionController<MigrationData>;

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
let migrations;
let versionController: VersionController<any>;
let migrations: Migration[];
let versionController: VersionController<MigrationData>;

@@ -2,7 +2,7 @@ import { Markdown } from '@lobehub/ui';
import { memo } from 'react';

import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import {settingsSelectors, userGeneralSettingsSelectors} from '@/store/user/selectors';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider removing the unused settingsSelectors import if it's no longer needed in this file.

@@ -1,15 +1,17 @@
import { JWTPayload, LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using import type for imports only used as types to clarify that they are not used at runtime.

- import { JWTPayload, LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
- import { ModelProvider } from '@/libs/agent-runtime';
- import { useUserStore } from '@/store/user';
+ import type { JWTPayload, LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
+ import type { ModelProvider } from '@/libs/agent-runtime';
+ import type { useUserStore } from '@/store/user';

- import { keyVaultsConfigSelectors, settingsSelectors } from '@/store/user/selectors';
- import { GlobalLLMProviderKey } from '@/types/user/settings';
+ import type { keyVaultsConfigSelectors, settingsSelectors } from '@/store/user/selectors';
+ import type { GlobalLLMProviderKey } from '@/types/user/settings';

Also applies to: 4-5


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
import { JWTPayload, LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
import type { JWTPayload, LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
import type { ModelProvider } from '@/libs/agent-runtime';
import type { useUserStore } from '@/store/user';
import type { keyVaultsConfigSelectors, settingsSelectors } from '@/store/user/selectors';
import type { GlobalLLMProviderKey } from '@/types/user/settings';

Comment on lines 42 to 48
// @ts-ignore
keyVaults: {
password,
},

// @ts-ignore
languageModel,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider removing @ts-ignore and handling the types explicitly.

- // @ts-ignore
- keyVaults: {
-   password,
- },
+ keyVaults: password ? { password } : undefined,

Also applies to: 47-48


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
// @ts-ignore
keyVaults: {
password,
},
// @ts-ignore
languageModel,
keyVaults: password ? { password } : undefined,
// @ts-ignore
languageModel,


const LangButton = memo(() => {
const theme = useTheme();
const [language, switchLocale] = useUserStore((s) => [
settingsSelectors.currentSettings(s).language,
userGeneralSettingsSelectors.language(s),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add switchLocale to the dependency array of useMemo to ensure it captures the latest function reference.

- [t],
+ [t, switchLocale],

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
userGeneralSettingsSelectors.language(s),
userGeneralSettingsSelectors.language(s),
[t, switchLocale],

Comment on lines +18 to +20
const [password, updateKeyVaults] = useUserStore((s) => [
settingsSelectors.password(s),
s.updateKeyVaults,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update the selector to use keyVaultsConfigSelectors for consistency with the new settings structure.

- settingsSelectors.password(s),
+ keyVaultsConfigSelectors.password(s),

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const [password, updateKeyVaults] = useUserStore((s) => [
settingsSelectors.password(s),
s.updateKeyVaults,
const [password, updateKeyVaults] = useUserStore((s) => [
keyVaultsConfigSelectors.password(s),
s.updateKeyVaults,

@@ -42,7 +41,7 @@ class _UserModel extends BaseModel {

// **************** Update *************** //

async updateSettings(settings: DeepPartial<UserSettings>) {
async updateSettings(settings: DeepPartial<DB_Settings>) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the unsafe type cast to any and ensure type compatibility through proper typing.

- return this.update(user.id, { settings: settings as any });
+ return this.update(user.id, { settings });

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
async updateSettings(settings: DeepPartial<DB_Settings>) {
async updateSettings(settings: DeepPartial<DB_Settings>) {
return this.update(user.id, { settings });
}

@@ -18,7 +18,7 @@ const themeIcons = {
const ThemeButton = memo(() => {
const theme = useTheme();
const [themeMode, switchThemeMode] = useUserStore((s) => [
settingsSelectors.currentSettings(s).themeMode,
userGeneralSettingsSelectors.currentThemeMode(s),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add switchThemeMode to the dependency array of useMemo to ensure it captures the latest function reference.

- [t],
+ [t, switchThemeMode],

Committable suggestion was skipped due low confidence.

Copy link

codecov bot commented May 26, 2024

Codecov Report

Attention: Patch coverage is 97.65625% with 6 lines in your changes missing coverage. Please review.

Project coverage is 93.77%. Comparing base (bef8926) to head (b1744ab).
Report is 1070 commits behind head on main.

Files with missing lines Patch % Lines
src/store/user/slices/settings/action.ts 75.00% 3 Missing ⚠️
src/store/user/slices/modelList/action.ts 86.66% 2 Missing ⚠️
...store/user/slices/modelList/selectors/keyVaults.ts 96.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2673      +/-   ##
==========================================
+ Coverage   93.72%   93.77%   +0.05%     
==========================================
  Files         353      356       +3     
  Lines       20403    20560     +157     
  Branches     2427     1564     -863     
==========================================
+ Hits        19122    19280     +158     
+ Misses       1281     1280       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@arvinxx arvinxx marked this pull request as ready for review May 27, 2024 01:59
@arvinxx arvinxx changed the title ♻️ refactor: refactor endpoint to baseURL ♻️ refactor: refactor eyVaults and rename endpoint to baseURL May 27, 2024
@arvinxx arvinxx changed the title ♻️ refactor: refactor eyVaults and rename endpoint to baseURL ♻️ refactor: refactor keyVaults and rename endpoint to baseURL May 27, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

Outside diff range and nitpick comments (2)
src/database/client/models/__tests__/user.test.ts (1)

Line range hint 6-6: Replace any with a more specific type for userData to enhance type safety in tests.

- let userData: any;
+ let userData: UserData;
src/app/(main)/settings/llm/Ollama/Checker.tsx (1)

Line range hint 63-63: Avoid using any for type assertions. Specify a more precise type for better type safety.

- message={t(`response.${error.type}` as any, { ns: 'error' })}
+ message={t(`response.${error.type}` as ResponseErrorType, { ns: 'error' })}
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between e309db2 and b1744ab.
Files selected for processing (17)
  • src/app/(main)/settings/llm/Bedrock/index.tsx (4 hunks)
  • src/app/(main)/settings/llm/Ollama/Checker.tsx (1 hunks)
  • src/database/client/core/db.ts (3 hunks)
  • src/database/client/core/schemas.ts (1 hunks)
  • src/database/client/models/tests/user.test.ts (2 hunks)
  • src/database/client/schemas/user.ts (1 hunks)
  • src/features/Conversation/Plugins/Render/MarkdownType/index.tsx (2 hunks)
  • src/migrations/FromV6ToV7/fixtures/provider-input-v6.json (1 hunks)
  • src/migrations/FromV6ToV7/fixtures/provider-output-v7.json (1 hunks)
  • src/migrations/FromV6ToV7/index.ts (1 hunks)
  • src/migrations/FromV6ToV7/types/v6.ts (1 hunks)
  • src/migrations/index.ts (1 hunks)
  • src/services/tests/share.test.ts (1 hunks)
  • src/services/_auth.test.ts (5 hunks)
  • src/store/user/slices/settings/action.test.ts (5 hunks)
  • src/store/user/slices/settings/action.ts (4 hunks)
  • src/store/user/slices/settings/selectors/general.test.ts (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • src/features/Conversation/Plugins/Render/MarkdownType/index.tsx
  • src/migrations/FromV6ToV7/fixtures/provider-input-v6.json
  • src/migrations/FromV6ToV7/fixtures/provider-output-v7.json
Additional Context Used
Biome (48)
src/app/(main)/settings/llm/Bedrock/index.tsx (1)

9-10: All these imports are only used as types.

src/app/(main)/settings/llm/Ollama/Checker.tsx (2)

63-63: Unexpected any. Specify a different type.


4-5: All these imports are only used as types.

src/database/client/core/db.ts (14)

121-121: This variable implicitly has the any type.


167-167: Unexpected any. Specify a different type.


197-197: Forbidden non-null assertion.


212-212: Unexpected any. Specify a different type.


225-225: Unexpected any. Specify a different type.


1-1: Some named imports are only used as types.


7-8: All these imports are only used as types.


8-9: All these imports are only used as types.


9-10: All these imports are only used as types.


10-11: All these imports are only used as types.


11-12: All these imports are only used as types.


12-13: All these imports are only used as types.


13-14: All these imports are only used as types.


25-26: Some named imports are only used as types.

src/database/client/models/__tests__/user.test.ts (1)

6-6: Unexpected any. Specify a different type.

src/migrations/FromV6ToV7/index.ts (8)

17-17: Unexpected any. Specify a different type.


22-22: Unexpected any. Specify a different type.


24-34: Prefer for...of instead of forEach.


27-27: The computed expression can be simplified without the use of a string literal.


71-84: Prefer for...of instead of forEach.


81-81: Unexpected any. Specify a different type.


2-3: All these imports are only used as types.


3-4: All these imports are only used as types.

src/migrations/FromV6ToV7/types/v6.ts (6)

4-4: Unexpected any. Specify a different type.


10-10: Unexpected any. Specify a different type.


46-46: Unexpected any. Specify a different type.


53-53: Unexpected any. Specify a different type.


55-55: Unexpected any. Specify a different type.


56-56: Unexpected any. Specify a different type.

src/migrations/index.ts (1)

2-3: All these imports are only used as types.

src/services/__tests__/share.test.ts (4)

1-1: All these imports are only used as types.


1-2: Some named imports are only used as types.


4-5: All these imports are only used as types.


5-6: All these imports are only used as types.

src/services/_auth.test.ts (1)

5-10: Some named imports are only used as types.

src/store/user/slices/settings/action.test.ts (3)

1-2: All these imports are only used as types.


8-9: All these imports are only used as types.


9-10: All these imports are only used as types.

src/store/user/slices/settings/action.ts (5)

1-1: All these imports are only used as types.


2-3: All these imports are only used as types.


7-8: All these imports are only used as types.


8-9: All these imports are only used as types.


9-10: All these imports are only used as types.

src/store/user/slices/settings/selectors/general.test.ts (2)

1-1: All these imports are only used as types.


1-2: Some named imports are only used as types.

GitHub Check Runs (1)
codecov/patch success (4)

src/store/user/slices/settings/action.ts: [warning] 65-65: src/store/user/slices/settings/action.ts#L65
Added line #L65 was not covered by tests


src/store/user/slices/settings/action.ts: [warning] 79-80: src/store/user/slices/settings/action.ts#L79-L80
Added lines #L79 - L80 were not covered by tests

Additional comments not posted (19)
src/migrations/index.ts (1)

13-13: The update of CURRENT_CONFIG_VERSION to 7 is noted. Ensure that all dependent features and modules are compatible with this new version.

src/app/(main)/settings/llm/Bedrock/index.tsx (4)

13-13: Import change aligns with the new key management strategy.


32-32: Change in the name property enhances security by using the new KeyVaultsConfigKey structure.


43-43: Proper use of KeyVaultsConfigKey for secretAccessKey aligns with security enhancements.


58-58: Using KeyVaultsConfigKey for region maintains consistency and security in key management.

src/migrations/FromV6ToV7/index.ts (3)

1-4: Correct use of type imports for migration-related types.


101-101: Export of MigrationV6ToV7 is correctly implemented for use in version control.


39-99: Consider removing @ts-ignore and handling the types explicitly to improve code quality.

- // @ts-ignore
- languageModel[provider] = strippedConfig as any;
+ languageModel[provider] = strippedConfig;
- // @ts-ignore
- keyVaults[provider] = providerVaults;
+ keyVaults[provider] = providerVaults;
src/store/user/slices/settings/action.ts (2)

Line range hint 1-10: Correct use of type imports for user settings management.


23-24: Addition of updateGeneralConfig and updateKeyVaults methods supports the enhanced key management strategy.

src/database/client/core/schemas.ts (1)

83-83: Addition of tool_call_id to the messages table enhances tracking capabilities.

src/services/__tests__/share.test.ts (1)

95-103: Test update correctly reflects the new keyVaults structure for API key management.

src/store/user/slices/settings/action.test.ts (3)

Line range hint 27-45: Test updates correctly reflect the new structure for general settings in user settings management.


72-72: Test update correctly reflects the new structure for partial settings updates.


95-97: Test update correctly reflects the new structure for switching the theme mode in user settings.

src/services/_auth.test.ts (2)

28-31: Ensure the state update reflects the new structure for keyVaults.

This change aligns with the PR's objective to centralize API key management in keyVaults.


142-142: Verify the correct usage of baseURL in place of endpoint.

Also applies to: 155-155, 167-167

Verification successful

The search results indicate multiple instances of endpoint usage across the codebase. To verify the correct usage of baseURL in place of endpoint, we need to focus on the specific context of the changes in src/services/_auth.test.ts.

Observations:

  • The term endpoint is used in various files, including src/services/_auth.ts and src/services/_auth.test.ts.
  • The specific lines in question (142, 155, 167) in src/services/_auth.test.ts need to be checked to ensure baseURL is used correctly.

Next Steps:

  1. Verify the context of endpoint usage in src/services/_auth.test.ts to ensure baseURL is used correctly.
  2. Check if baseURL is defined and used appropriately in the relevant sections of the code.

This script will help us understand the context around the usage of endpoint in src/services/_auth.test.ts and verify if baseURL is used correctly.


The context provided by the script output shows that baseURL is used correctly in place of endpoint for the Ollama provider in src/services/_auth.test.ts. The relevant sections are:

  • For the Ollama provider:

    setModelProviderConfig('ollama', { baseURL: mockOllamaProxyUrl });
    const payload = getProviderAuthPayload(ModelProvider.Ollama);
    expect(payload).toEqual({
      endpoint: mockOllamaProxyUrl,
    });
  • For the Azure provider, endpoint is used correctly:

    const mockAzureConfig = {
      apiKey: 'azure-api-key',
      apiVersion: 'azure-api-version',
      endpoint: 'azure-endpoint',
    };
  • For the OpenAI provider, baseURL is used correctly:

    const mockOpenAIConfig = {
      apiKey: 'openai-api-key',
      baseURL: 'openai-baseURL',
      endpoint: 'openai-endpoint',
      useAzure: true,
      azureApiVersion: 'openai-azure-api-version',
    };

Conclusion:

The usage of baseURL in place of endpoint for the Ollama provider is correct, and the other providers use endpoint appropriately.

  • : The usage of baseURL in place of endpoint is correct in src/services/_auth.test.ts.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `baseURL` is used correctly across the codebase.

# Test: Search for incorrect usage of `endpoint` where `baseURL` should be used.
rg --type typescript $'endpoint' | grep -v 'baseURL'

Length of output: 84



Script:

#!/bin/bash
# Description: Verify that `baseURL` is used correctly across the codebase.

# Test: Search for incorrect usage of `endpoint` where `baseURL` should be used.
rg --type ts 'endpoint' | grep -v 'baseURL'

Length of output: 13922



Script:

#!/bin/bash
# Description: Verify the correct usage of `baseURL` in place of `endpoint` in `src/services/_auth.test.ts`.

# Extract lines around the specific lines in question to understand the context.
rg --context 5 'endpoint' src/services/_auth.test.ts

Length of output: 1643

src/database/client/core/db.ts (2)

5-5: Ensure the import of MigrationKeyValueSettings is used correctly.

This import is necessary for the new migration logic introduced in version 11.


81-84: Review the implementation of upgradeToV11.

The migration logic correctly updates user settings to the new keyVaults structure, aligning with the PR's objectives.

Comment on lines +6 to +10
import {
GlobalLLMProviderKey,
UserKeyVaults,
UserModelProviderConfig,
} from '@/types/user/settings';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor imports to use TypeScript's type-only import syntax.

- import {
-   GlobalLLMProviderKey,
-   UserKeyVaults,
-   UserModelProviderConfig,
- } from '@/types/user/settings';
+ import type {
+   GlobalLLMProviderKey,
+   UserKeyVaults,
+   UserModelProviderConfig,
+ } from '@/types/user/settings';

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
import {
GlobalLLMProviderKey,
UserKeyVaults,
UserModelProviderConfig,
} from '@/types/user/settings';
import type {
GlobalLLMProviderKey,
UserKeyVaults,
UserModelProviderConfig,
} from '@/types/user/settings';

Comment on lines +6 to +12
const generalSechma = z.object({
fontSize: z.number().default(14),
language: z.string(),
neutralColor: z.string().optional(),
password: z.string(),
themeMode: z.string(),
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider renaming generalSechma to generalSchema for correct spelling and consistency.

- const generalSechma = z.object({
+ const generalSchema = z.object({

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const generalSechma = z.object({
fontSize: z.number().default(14),
language: z.string(),
neutralColor: z.string().optional(),
password: z.string(),
themeMode: z.string(),
});
const generalSchema = z.object({
fontSize: z.number().default(14),
language: z.string(),
neutralColor: z.string().optional(),
password: z.string(),
themeMode: z.string(),
});

Comment on lines +19 to +20
general: generalSechma.partial().optional(),
keyVaults: z.any().optional(),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that the keyVaults field in settingsSchema is properly typed instead of using z.any(). Using any can lead to loss of type safety.

- keyVaults: z.any().optional(),
+ keyVaults: z.object({
+   apiKey: z.string(),
+   endpoint: z.string(),
+ }).optional(),

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
general: generalSechma.partial().optional(),
keyVaults: z.any().optional(),
general: generalSechma.partial().optional(),
keyVaults: z.object({
apiKey: z.string(),
endpoint: z.string(),
}).optional(),

@@ -0,0 +1,45 @@
import { UserStore } from '@/store/user';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using TypeScript's import type syntax for imports that are only used as types to clarify their usage and potentially optimize bundling.

- import { UserStore } from '@/store/user';
+ import type { UserStore } from '@/store/user';

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
import { UserStore } from '@/store/user';
import type { UserStore } from '@/store/user';

interface V6OpenAICompatibleConfig {
apiKey?: string;
autoFetchModelLists?: boolean;
customModelCards?: any[];
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace any with more specific types to enhance type safety and maintainability.

- customModelCards?: any[];
+ customModelCards?: ModelCard[];

- remoteModelCards?: any[];
+ remoteModelCards?: ModelCard[];

- defaultAgent: any;
+ defaultAgent: AgentConfig;

- sync: any;
+ sync: SyncConfig;

- tool: any;
+ tool: ToolConfig;

- tts: any;
+ tts: TTSConfig;

Also applies to: 10-10, 46-46, 53-53, 55-55, 56-56

Committable suggestion was skipped due low confidence.

@@ -27,7 +27,7 @@ const OllamaChecker = memo(() => {
);

const checkConnection = () => {
mutate();
mutate().catch();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The catch block in mutate().catch(); is empty. Consider handling potential errors or removing the catch if error handling is not needed.

- mutate().catch();
+ mutate().catch((error) => console.error('Failed to check connection:', error));

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
mutate().catch();
mutate().catch((error) => console.error('Failed to check connection:', error));

Comment on lines +17 to +37
function extractSensitiveInfo<T extends Record<string, any>>(
obj: T,
sensitiveKeys: SensitiveKeys[],
provider: string,
): [T, Record<SensitiveKeys, string>] {
const keyVaults: Record<SensitiveKeys, string> = {} as any;

sensitiveKeys.forEach((key) => {
if (obj[key]) {
if (key === 'endpoint' && provider !== 'azure') {
keyVaults['baseURL'] = obj[key];
} else {
keyVaults[key] = obj[key];
}

delete obj[key];
}
});

return [obj, keyVaults];
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor to use a more specific type than any for keyVaults to enhance type safety.

- const keyVaults: Record<SensitiveKeys, string> = {} as any;
+ const keyVaults: Record<SensitiveKeys, string> = {};

Ensure the renaming logic from endpoint to baseURL is consistent across all non-Azure providers.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
function extractSensitiveInfo<T extends Record<string, any>>(
obj: T,
sensitiveKeys: SensitiveKeys[],
provider: string,
): [T, Record<SensitiveKeys, string>] {
const keyVaults: Record<SensitiveKeys, string> = {} as any;
sensitiveKeys.forEach((key) => {
if (obj[key]) {
if (key === 'endpoint' && provider !== 'azure') {
keyVaults['baseURL'] = obj[key];
} else {
keyVaults[key] = obj[key];
}
delete obj[key];
}
});
return [obj, keyVaults];
}
function extractSensitiveInfo<T extends Record<string, any>>(
obj: T,
sensitiveKeys: SensitiveKeys[],
provider: string,
): [T, Record<SensitiveKeys, string>] {
const keyVaults: Record<SensitiveKeys, string> = {};
sensitiveKeys.forEach((key) => {
if (obj[key]) {
if (key === 'endpoint' && provider !== 'azure') {
keyVaults['baseURL'] = obj[key];
} else {
keyVaults[key] = obj[key];
}
delete obj[key];
}
});
return [obj, keyVaults];
}

Comment on lines +78 to +80
updateKeyVaults: async (keyVaults) => {
await get().setSettings({ keyVaults });
},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Add test coverage for the updateKeyVaults method to ensure its correct functionality. The current search did not find any test cases covering this method.

Analysis chain

Add test coverage for the updateKeyVaults method to ensure its correct functionality.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify test coverage for `updateKeyVaults`.

# Test: Search for tests covering `updateKeyVaults`. Expect: At least one test case.
rg --type typescript $'updateKeyVaults'

Length of output: 73



Script:

#!/bin/bash
# Description: Verify test coverage for `updateKeyVaults`.

# Test: Search for tests covering `updateKeyVaults`. Expect: At least one test case.
rg 'updateKeyVaults' --glob '*.{ts,tsx}' --glob '**/__tests__/**' --glob '**/test/**'

Length of output: 576

Comment on lines +220 to +228
upgradeToV11 = async (trans: Transaction) => {
const users = trans.table('users');

await users.toCollection().modify((user: DB_User) => {
if (user.settings) {
user.settings = MigrationKeyValueSettings.migrateSettings(user.settings as any);
}
});
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The upgradeToV11 method implementation has been successfully extracted. The method contains a type assertion using as any within the migration logic:

upgradeToV11 = async (trans: Transaction) => {
  const users = trans.table('users');

  await users.toCollection().modify((user: DB_User) => {
    if (user.settings) {
      user.settings = MigrationKeyValueSettings.migrateSettings(user.settings as any);
    }
  });
};

This type assertion could potentially lead to runtime errors if user.settings does not conform to the expected type.

  • Location: src/database/client/core/db.ts, lines 220-228
Analysis chain

Confirm the type safety of the migration logic in upgradeToV11.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the type safety of the migration logic.

# Test: Check for any type assertions that could lead to runtime errors.
rg --type typescript $'as any' | grep 'upgradeToV11'

Length of output: 86



Script:

#!/bin/bash
# Description: Verify the type safety of the migration logic.

# Test: Check for any type assertions that could lead to runtime errors.
rg 'as any' src/database/client/core/db.ts | grep 'upgradeToV11'

Length of output: 64



Script:

#!/bin/bash
# Description: Extract the implementation of the `upgradeToV11` method for review.

# Test: Extract the `upgradeToV11` method implementation from the `src/database/client/core/db.ts` file.
ast-grep --lang typescript --pattern $'upgradeToV11 = async (trans: Transaction) => {
  $$$
}' src/database/client/core/db.ts

Length of output: 126



Script:

#!/bin/bash
# Description: Locate the `upgradeToV11` method definition and implementation for review.

# Test: Search for the `upgradeToV11` method definition in the `src/database/client/core/db.ts` file.
rg 'upgradeToV11' src/database/client/core/db.ts

Length of output: 150



Script:

#!/bin/bash
# Description: Extract the full implementation of the `upgradeToV11` method for review.

# Test: Extract the `upgradeToV11` method implementation from the `src/database/client/core/db.ts` file.
ast-grep --lang typescript --pattern $'upgradeToV11 = async (trans: Transaction) => {
  $$$
}' src/database/client/core/db.ts

Length of output: 126



Script:

#!/bin/bash
# Description: Extract the full implementation of the `upgradeToV11` method for review.

# Test: Extract the `upgradeToV11` method implementation from the `src/database/client/core/db.ts` file.
rg 'upgradeToV11 = async (trans: Transaction) => {' -A 10 src/database/client/core/db.ts

Length of output: 246



Script:

#!/bin/bash
# Description: Extract the full implementation of the `upgradeToV11` method for review.

# Test: Extract the `upgradeToV11` method implementation from the `src/database/client/core/db.ts` file.
rg 'upgradeToV11 = async \(trans: Transaction\) => \{' -A 20 src/database/client/core/db.ts

Length of output: 749

Comment on lines +75 to +77
updateGeneralConfig: async (general) => {
await get().setSettings({ general });
},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Ensure to add test coverage for the updateGeneralConfig method to verify its functionality. The current codebase does not contain any test cases for this method.

  • File: src/store/user/slices/settings/action.ts
  • Lines: 75-77
Analysis chain

Ensure to add test coverage for the updateGeneralConfig method to verify its functionality.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify test coverage for `updateGeneralConfig`.

# Test: Search for tests covering `updateGeneralConfig`. Expect: At least one test case.
rg --type typescript $'updateGeneralConfig'

Length of output: 77



Script:

#!/bin/bash
# Description: Verify test coverage for `updateGeneralConfig`.

# Test: Search for tests covering `updateGeneralConfig`. Expect: At least one test case.
rg --type ts 'updateGeneralConfig'

Length of output: 1243



Script:

#!/bin/bash
# Description: Locate test files and search for `updateGeneralConfig`.

# Step 1: Locate test files (assuming common test directories).
test_files=$(fd --type f --extension ts --extension tsx --glob '*test*')

# Step 2: Search for `updateGeneralConfig` within the located test files.
if [ -n "$test_files" ]; then
  rg 'updateGeneralConfig' $test_files
else
  echo "No test files found."
fi

Length of output: 23957

@arvinxx arvinxx merged commit 4049bc7 into main May 27, 2024
10 checks passed
@arvinxx arvinxx deleted the refactor/language-model-settings branch May 27, 2024 02:09
@lobehubbot
Copy link
Member

❤️ Great PR @arvinxx ❤️

The growth of project is inseparable from user feedback and contribution, thanks for your contribution! If you are interesting with the lobehub developer community, please join our discord and then dm @arvinxx or @canisminor1990. They will invite you to our private developer channel. We are talking about the lobe-chat development or sharing ai newsletter around the world.
项目的成长离不开用户反馈和贡献,感谢您的贡献! 如果您对 LobeHub 开发者社区感兴趣,请加入我们的 discord,然后私信 @arvinxx@canisminor1990。他们会邀请您加入我们的私密开发者频道。我们将会讨论关于 Lobe Chat 的开发,分享和讨论全球范围内的 AI 消息。

github-actions bot pushed a commit that referenced this pull request May 27, 2024
### [Version&nbsp;0.161.23](v0.161.22...v0.161.23)
<sup>Released on **2024-05-27**</sup>

#### ♻ Code Refactoring

- **misc**: Refactor `keyVaults` and rename `endpoint` to `baseURL`.

#### 💄 Styles

- **misc**: Fix PluginStore layout.

<br/>

<details>
<summary><kbd>Improvements and Fixes</kbd></summary>

#### Code refactoring

* **misc**: Refactor `keyVaults` and rename `endpoint` to `baseURL`, closes [#2673](#2673) ([4049bc7](4049bc7))

#### Styles

* **misc**: Fix PluginStore layout, closes [#2590](#2590) [#2511](#2511) ([e1ae39b](e1ae39b))

</details>

<div align="right">

[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)

</div>
@lobehubbot
Copy link
Member

🎉 This PR is included in version 0.161.23 🎉

The release is available on:

Your semantic-release bot 📦🚀

github-actions bot pushed a commit to bentwnghk/lobe-chat that referenced this pull request May 27, 2024
### [Version&nbsp;1.41.12](v1.41.11...v1.41.12)
<sup>Released on **2024-05-27**</sup>

#### ♻ Code Refactoring

- **misc**: Refactor `keyVaults` and rename `endpoint` to `baseURL`.

#### 🐛 Bug Fixes

- **misc**: Fix connection checker, fix the batch import error.

#### 💄 Styles

- **misc**: Fix PluginStore layout.

<br/>

<details>
<summary><kbd>Improvements and Fixes</kbd></summary>

#### Code refactoring

* **misc**: Refactor `keyVaults` and rename `endpoint` to `baseURL`, closes [lobehub#2673](https://github.com/bentwnghk/lobe-chat/issues/2673) ([4049bc7](4049bc7))

#### What's fixed

* **misc**: Fix connection checker, closes [lobehub#2672](https://github.com/bentwnghk/lobe-chat/issues/2672) ([bef8926](bef8926))
* **misc**: Fix the batch import error, closes [lobehub#2671](https://github.com/bentwnghk/lobe-chat/issues/2671) ([db8f2c6](db8f2c6))

#### Styles

* **misc**: Fix PluginStore layout, closes [lobehub#2590](https://github.com/bentwnghk/lobe-chat/issues/2590) [lobehub#2511](https://github.com/bentwnghk/lobe-chat/issues/2511) ([e1ae39b](e1ae39b))

</details>

<div align="right">

[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)

</div>
ipoly pushed a commit to ipoly/lobe-chat that referenced this pull request Jul 29, 2024
…obehub#2673)

* ♻️ refactor: refactor endpoint to baseURL

* ✅ test: fix test

* 🚨 ci: fix lint

* ✅ test: fix migration test

* 🗃️ refactor: refactor the user setting client db
ipoly pushed a commit to ipoly/lobe-chat that referenced this pull request Jul 29, 2024
### [Version&nbsp;0.161.23](lobehub/lobe-chat@v0.161.22...v0.161.23)
<sup>Released on **2024-05-27**</sup>

#### ♻ Code Refactoring

- **misc**: Refactor `keyVaults` and rename `endpoint` to `baseURL`.

#### 💄 Styles

- **misc**: Fix PluginStore layout.

<br/>

<details>
<summary><kbd>Improvements and Fixes</kbd></summary>

#### Code refactoring

* **misc**: Refactor `keyVaults` and rename `endpoint` to `baseURL`, closes [lobehub#2673](lobehub#2673) ([4049bc7](lobehub@4049bc7))

#### Styles

* **misc**: Fix PluginStore layout, closes [lobehub#2590](lobehub#2590) [lobehub#2511](lobehub#2511) ([e1ae39b](lobehub@e1ae39b))

</details>

<div align="right">

[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)

</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants