Repository navigation
feat: Unify the 'Add Model Provider' modal - #15768
Conversation
📝 WalkthroughWalkthroughThis PR consolidates 12+ provider-specific modals into a unified, configuration-driven ChangesUnified Provider Modal Architecture
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (15)
web/src/pages/user-setting/setting-model/modal/provider-modal/index.tsx (1)
34-35: ⚡ Quick winUse
useTranslationdirectly for i18n hooks.Line 34 and Line 35 use wrapped translation hooks, but the frontend guideline requests
useTranslationfromreact-i18nextin React components. Please switch these calls to keep i18n usage consistent.As per coding guidelines: "Prefer
useTranslationfromreact-i18nextover project-wrapped utilities likeuseTranslatefor i18n in React components."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/modal/provider-modal/index.tsx` around lines 34 - 35, Replace the project-wrapped hooks useTranslate and useCommonTranslation with the standard useTranslation hook from react-i18next: import useTranslation and call it to obtain the t functions instead of using useTranslate and useCommonTranslation so that the component uses useTranslation('setting') (and the common namespace for the second t if needed) and replace occurrences of t and tc accordingly (look for the const { t } = useTranslate and const { t: tc } = useCommonTranslation declarations and update imports/usages to useTranslation from react-i18next).Source: Coding guidelines
web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-provider-fields.tsx (1)
4-4: ⚡ Quick winSwitch to
useTranslationfor i18n in this React hook.Line 67 uses
useTranslate, but the frontend guideline prefersuseTranslationdirectly.Proposed change
-import { useTranslate } from '`@/hooks/common-hooks`'; +import { useTranslation } from 'react-i18next'; @@ - const { t } = useTranslate('setting'); + const { t } = useTranslation('setting');As per coding guidelines: "Prefer
useTranslationfromreact-i18nextover project-wrapped utilities likeuseTranslatefor i18n in React components."Also applies to: 67-67
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-provider-fields.tsx` at line 4, Replace the project-wrapped useTranslate import and calls with react-i18next's useTranslation in this hook: change the import line (remove useTranslate) and import { useTranslation } from 'react-i18next', then inside the useProviderFields hook (or the function where useTranslate() is called) replace useTranslate() usage with const { t } = useTranslation() and update any t(...) call sites accordingly; also remove the now-unused useTranslate import. Ensure all references that expected useTranslate's return shape are adjusted to the { t } API from useTranslation.Source: Coding guidelines
web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-options.tsx (2)
36-36: ⚡ Quick winPrefer
useTranslationfromreact-i18nextoveruseTranslate.As per coding guidelines, prefer
useTranslationfromreact-i18nextover project-wrapped utilities likeuseTranslatefor i18n in React components.♻️ Recommended fix
-import { useTranslate } from '`@/hooks/common-hooks`'; +import { useTranslation } from 'react-i18next'; import { IProviderModelItem } from '`@/interfaces/request/llm`'; import { useMemo } from 'react'; // ... export const useListModelsOptions = ({ // ... }: UseListModelsOptionsParams) => { - const { t } = useTranslate('setting'); + const { t } = useTranslation('setting');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-options.tsx` at line 36, Replace the project-specific useTranslate hook with react-i18next's useTranslation in use-list-models-options.tsx: update the import to pull useTranslation from 'react-i18next' and change the line const { t } = useTranslate('setting') to use the useTranslation API (e.g., const { t } = useTranslation('setting')), then ensure any usages of t remain unchanged and remove the old useTranslate import.Source: Coding guidelines
39-56: 💤 Low valueRemove unnecessary type cast on sentinel value.
Line 40 casts
nulltostring | null, butToggleListaccepts a genericVforoption.value, so the cast is unnecessary. The cast suggests type confusion or overly narrow type expectations.♻️ Optional cleanup
const allOption = { - value: null as string | null, + value: null, label: (🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-options.tsx` around lines 39 - 56, The allOption object sets value: null as string | null unnecessarily; remove the type cast and let value be plain null so it matches the ToggleList generic V without forcing a string union. Update the allOption declaration (the value field) to just use null, leaving the rest (label JSX, onClick using handleToggleAll, Checkbox handlers) unchanged.web/src/components/ui/input-select.tsx (1)
337-344: ⚡ Quick winGuard against setState during unmount in blur handler.
The 150ms delay is necessary for option clicks to register before closing, but if the component unmounts during this window,
commitInputValue()and the state setters will attempt updates on an unmounted component, triggering React warnings.🛡️ Recommended fix to clear timeout on unmount
const handleInputBlur = () => { - // Delay closing to allow click on options to register - setTimeout(() => { + const timeoutId = setTimeout(() => { commitInputValue(); setOpen(false); setIsFocused(false); }, 150); + return () => clearTimeout(timeoutId); };Alternatively, store the timeout ID in a ref and clear it in a cleanup effect:
+ const blurTimeoutRef = React.useRef<number>(); + + React.useEffect(() => { + return () => { + if (blurTimeoutRef.current) clearTimeout(blurTimeoutRef.current); + }; + }, []); + const handleInputBlur = () => { - setTimeout(() => { + blurTimeoutRef.current = window.setTimeout(() => { commitInputValue(); setOpen(false); setIsFocused(false); }, 150); };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/ui/input-select.tsx` around lines 337 - 344, The blur handler uses a 150ms setTimeout that may call commitInputValue(), setOpen and setIsFocused after the component unmounts; store the timeout ID in a ref (e.g., blurTimeoutRef), use that ref to clearTimeout in a useEffect cleanup, and optionally track a mountedRef to guard calling commitInputValue(), setOpen and setIsFocused inside handleInputBlur so no state updates occur after unmount; update handleInputBlur to set blurTimeoutRef.current = window.setTimeout(...), clear it in the cleanup, and check mountedRef (or ensure timeout cleared) before invoking commitInputValue, setOpen or setIsFocused.web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-picker.ts (1)
151-211: ⚖️ Poor tradeoffCircular dependency between
handleListOpenChangeandmodelInfoList.The dependency array (line 208) includes
modelInfoList, which is derived fromselectedModelItems(line 108). This callback updatesselectedModelItems(line 191), creating a circular dependency cycle. While themodels.length > 0guard (line 154) prevents infinite re-fetching, this pattern is fragile and could break if guards are refactored.The callback uses
modelInfoListonly to pass it throughverifyTransformand into thelistProviderModelsrequest (lines 167, 174). On first open, this will always be an empty array. Consider either:
- Removing
modelInfoListfrom deps and accepting the stale-closure tradeoff (safe because it's only used on first fetch when it's empty), or- Computing the request payload inline without closing over
modelInfoList.♻️ Option 1: Remove from deps with comment
[ hasModelNameField, models.length, listLoading, config, listProviderModels, llmFactory, - modelInfoList, formRef, ], + // modelInfoList intentionally omitted: only used on first fetch when empty );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-picker.ts` around lines 151 - 211, The callback handleListOpenChange closes over modelInfoList which is derived from selectedModelItems, creating a fragile circular dependency; fix by removing modelInfoList from the useCallback dependency array (leave selectedModelItems as-is) and add a concise comment by handleListOpenChange explaining we intentionally accept the stale closure for modelInfoList because it is only used on the initial fetch (always empty) when invoking config.verifyTransform and listProviderModels, or alternatively refactor to compute the verifyArgs inline inside the callback from form values and selectedModelItems so handleListOpenChange no longer needs to close over modelInfoList.web/src/components/ui/toggle-list.tsx (1)
190-198: 💤 Low valueConsider showing chevron for all button content types.
The chevron (expand/collapse indicator) is only rendered when
btnTextis a string (line 190). For ReactNode button content, the chevron is hidden. This creates an inconsistent UX where some toggle buttons show expand/collapse state and others don't.Unless there's a specific design reason (e.g., custom ReactNode content might include its own indicator), consider always rendering the chevron as a consistent affordance.
♻️ Optional fix to always show chevron
> {btnText} - {typeof btnText === 'string' && ( - <ChevronsDown - className={cn( - 'size-4 shrink-0 transition-transform duration-200', - open && 'rotate-180', - )} - aria-hidden="true" - /> - )} + <ChevronsDown + className={cn( + 'size-4 shrink-0 transition-transform duration-200', + open && 'rotate-180', + )} + aria-hidden="true" + /> </button>🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/ui/toggle-list.tsx` around lines 190 - 198, The chevron icon is currently only rendered when btnText is a string which hides the expand/collapse affordance for ReactNode button content; update the ToggleList button render so ChevronsDown is always included (remove the typeof btnText === 'string' guard) and keep the existing className logic using cn with 'size-4 shrink-0 transition-transform duration-200' and the conditional open && 'rotate-180' so the chevron still rotates; ensure aria-hidden remains set and adjust surrounding markup/CSS if needed to preserve spacing when btnText is a custom ReactNode.web/src/pages/user-setting/setting-model/components/used-model.tsx (1)
214-227: ⚡ Quick winAdd error logging in the catch block.
The error handler silently swallows exceptions without logging. While the fallback to list-level data is good, developers should be aware when the details fetch fails:
} catch { + console.warn( + `Failed to fetch instance details for ${providerName}/${instanceName}, using list data`, + ); // Fall back to the list-level instance data if the show request // fails (e.g. network error) — the modal still gets a usable baseline. }This helps diagnose issues during development and debugging.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/components/used-model.tsx` around lines 214 - 227, The catch block inside handleSettingsClick currently swallows errors from fetchInstanceDetails; modify it to catch the error object (e.g., catch (err)) and log the failure before falling back, e.g., use console.error or the app's logger to record the error with context (include providerName and instance id or name) so developers can see why fetchInstanceDetails failed while still calling onEditInstance(providerName, details, models).web/src/pages/user-setting/setting-model/index.tsx (3)
99-141: ⚡ Quick winClarify the comment about model handling.
The comment on lines 120-122 is misleading. It suggests this code handles the
model_infoarray fast-path, but that actually occurs inuseSubmitProviderInstance(hooks.tsx line 38). This code path only executes for legacy split payloads wheresplitProviderPayloadfinds no model fields to create separately.Consider revising the comment to:
- // When model information has been submitted nested in the instance via model_info - // (e.g., VolcEngine / LocalLLM), addInstanceModel is no longer called separately; - // close the modal directly. + // When splitProviderPayload returns no model fields (because the provider + // doesn't use separate model creation), close the modal after instance creation. + // Note: The multi-model fast-path (model_info array) is handled in + // useSubmitProviderInstance before reaching this code. if (!hasModelPayload) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/index.tsx` around lines 99 - 141, The existing comment in handleProviderOk misstates responsibility for the model_info fast-path — that logic lives in useSubmitProviderInstance — so update the comment near the hasModelPayload check in handleProviderOk to say this branch handles legacy split payloads where splitProviderPayload returned no model fields (i.e., when model information is not nested in instance.model_info) and therefore we simply close the modal instead of calling addInstanceModel; mention useSubmitProviderInstance as the place that handles the model_info fast-path to avoid confusion.
280-335: ⚡ Quick winExtract repeated model type normalization into a helper.
The
model_typearray normalization logic is duplicated on lines 289-293 and 310-314:const modelType = Array.isArray(x.model_type) ? x.model_type : x.model_type ? [x.model_type as string] : [];Consider extracting this into a utility function:
♻️ Suggested helper function
// In payload-utils.ts or a new utils file export const normalizeModelType = (modelType: string | string[] | undefined): string[] => { if (Array.isArray(modelType)) return modelType; return modelType ? [modelType] : []; };Then use it in both locations:
- const modelType = Array.isArray(model.model_type) - ? model.model_type - : model.model_type - ? [model.model_type as string] - : []; + const modelType = normalizeModelType(model.model_type);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/index.tsx` around lines 280 - 335, The duplicated model_type normalization in handleViewModeOk should be extracted into a small utility (e.g., normalizeModelType) and used in both places to avoid repetition; create a function like normalizeModelType(modelType: string | string[] | undefined): string[] that returns the input if it's an array, or wraps a string into a single-item array, or returns [] for undefined, then replace the two inline blocks in handleViewModeOk (the ones computing modelType for payload.modelInfos and for fv) with calls to normalizeModelType.
359-370: ⚡ Quick winFix type assertion for
baseUrlOptionsprop.Line 366 uses
as anyto bypass type checking:baseUrlOptions={currentBaseUrlOptions as any}This defeats TypeScript's type safety. The types should be aligned instead:
- Check the expected type of
baseUrlOptionsprop inProviderModal- Ensure
buildBaseUrlOptionsreturn type matches that expectation- Update either the prop type or the helper return type to align
If there's a legitimate structural mismatch (e.g.,
ReactNodelabels), consider using a more specific type assertion or update the prop type to acceptReactNodelabels.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/index.tsx` around lines 359 - 370, The prop baseUrlOptions is being forced to any when rendering ProviderModal; instead align types by checking ProviderModal's prop type for baseUrlOptions and updating buildBaseUrlOptions to return that exact shape (or widen the ProviderModal prop to accept the correct shape). Locate ProviderModal (prop name baseUrlOptions) and the helper/current value currentBaseUrlOptions (and the function buildBaseUrlOptions) and change the return type of buildBaseUrlOptions or the ProviderModal prop type so currentBaseUrlOptions can be passed without using "as any" — if labels are ReactNode adjust the types to ReactNode explicitly or map the helper output to the expected structure before passing to ProviderModal.web/src/pages/user-setting/setting-model/hooks.tsx (2)
35-40: ⚡ Quick winPrefer explicit type guard over
as anycast.The
model_infofield is already declared onIAddProviderInstanceRequestBody, so the cast toanyis unnecessary. Consider checking the property directly:- if (Array.isArray((payload as any).model_info)) { + if (Array.isArray(payload.model_info)) { return addProviderInstance(payload as IAddProviderInstanceRequestBody); }This preserves type safety while achieving the same runtime check.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/hooks.tsx` around lines 35 - 40, Replace the unsafe cast to any when checking payload.model_info: use a proper type-narrowing check against the declared shape (treat payload as IAddProviderInstanceRequestBody or use a type guard) and test Array.isArray(payload.model_info) directly; then call addProviderInstance(payload as IAddProviderInstanceRequestBody) only when the check passes so you preserve type safety for payload, referencing model_info, IAddProviderInstanceRequestBody, addProviderInstance, and payload.
198-216: 💤 Low valueConsider using
unknownor generics instead ofany.The
onVerifysignature usesanyfor both parameters and return type, which bypasses type checking entirely. If the payload shape varies by provider, consider usingunknownto preserve some type safety:onVerify: (postBody: unknown, isVerify?: boolean) => Promise<unknown>;Alternatively, if providers share common fields, a generic constraint or union type would be safer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/hooks.tsx` around lines 198 - 216, The hook useVerifySettings and its callback onApiKeyVerifying currently use any for postBody and return types; replace any with safer types (e.g., unknown or a generic type parameter) by updating the onVerify prop signature and the useVerifySettings declaration to accept onVerify: (postBody: unknown, isVerify?: boolean) => Promise<unknown> or make useVerifySettings generic like <T> (onVerify: (postBody: T, isVerify?: boolean) => Promise<R>) and update onApiKeyVerifying to accept postBody: T and return Promise<R>; adjust the useCallback typing accordingly and propagate the new generic/unknown types wherever onVerify is passed to preserve type safety while keeping runtime behavior unchanged.web/src/interfaces/request/llm.ts (2)
3-4: ⚡ Quick winRemove commented-out code.
The commented-out
model_nameandmodel_typefields should be removed if they are no longer part of the interface contract. Leaving commented code creates confusion about whether these fields are still supported or expected by any consumers.🧹 Remove commented lines
export interface IAddLlmRequestBody { llm_factory: string; // Ollama - // model_name: string; - // model_type: string | string[]; base_url?: string; // chat|embedding|speech2text|image2text🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/interfaces/request/llm.ts` around lines 3 - 4, Remove the two commented-out fields from the LLM request interface by deleting the lines containing // model_name: string; and // model_type: string | string[]; so the interface (llm.ts) no longer contains stale commented code referencing model_name or model_type; ensure no references to these symbols remain in this file and run a quick compile/check to confirm no consumers depend on them.
22-22: ⚡ Quick winConsider constraining the
extrafield type.The
extra?: Record<string, any>field provides no type safety. Since the comment mentions it's intended for backward compatibility and per-model features likeis_tools, consider defining a more specific type (e.g.,{ is_tools?: boolean; [key: string]: any }) to document known fields while preserving extensibility.💡 Suggested type refinement
/** * Per-model extras (e.g. `is_tools` derived from the model descriptor's * `features`). Optional for backward compatibility with legacy * single-model payloads. */ - extra?: Record<string, any>; + extra?: { is_tools?: boolean; [key: string]: any };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/interfaces/request/llm.ts` at line 22, The extra?: Record<string, any> field is too permissive; constrain it to document known keys while preserving extensibility by replacing its type with a narrower shape (for example define a named type/interface like ExtraOptions = { is_tools?: boolean; [key: string]: any } and use extra?: ExtraOptions) so callers get type hints for per-model flags such as is_tools but other keys remain allowed; update the interface declaration that contains extra to reference this new type.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/hooks/use-llm-request.tsx`:
- Around line 154-177: The hook useFetchProviderInstance is using an unsafe
double-cast for initialData; change the query generic to allow undefined (e.g.,
IProviderInstance | undefined), set initialData to undefined (no casts), and
keep enabled: false so callers must handle the possibly-undefined ret.data
(e.g., ret.data ?? {} or optional chaining); update any related references like
LlmKeys.providerInstance and llmService.showProviderInstance usages to expect
the possibly-undefined return.
In `@web/src/locales/en.ts`:
- Around line 1555-1557: The paddleocr text entries are contradictory:
paddleocrAccessTokenMessage currently demands input while
paddleocrAccessTokenPlaceholder marks it optional; update the strings and
corresponding validation so they match (either required or optional). Decide
desired behavior and then: if required, change paddleocrAccessTokenPlaceholder
to remove "(optional)" and ensure the form validator that uses
paddleocrAccessToken / paddleocrAccessTokenMessage enforces presence; if
optional, change paddleocrAccessTokenMessage to a non-mandatory hint (e.g.,
remove "Please input") and ensure the validation rule for paddleocrAccessToken
does not mark it as required. Adjust the three keys paddleocrAccessToken,
paddleocrAccessTokenMessage, and paddleocrAccessTokenPlaceholder and the related
form validation logic to be consistent.
In `@web/src/locales/zh.ts`:
- Around line 1279-1282: The Chinese strings for PaddleOCR token are
inconsistent: paddleocrAccessTokenMessage currently reads as required ("请输入
PaddleOCR 访问令牌!") while paddleocrAccessTokenPlaceholder says optional ("您的
PaddleOCR 访问令牌(可选)"); update the copy to be consistent (either both indicate
required or both indicate optional) and adjust the validation logic accordingly
so message matches actual requirement; change the values for
paddleocrAccessTokenMessage and/or paddleocrAccessTokenPlaceholder and confirm
any form validation that references paddleocrAccessToken uses the same
required/optional semantics as paddleocrAccessTokenMessage.
In `@web/src/pages/user-setting/setting-model/components/used-model.tsx`:
- Around line 243-260: The Settings button is permanently disabled by `{false &&
(...)}` in used-model.tsx so the handler handleSettingsClick and the
Button/Settings JSX are dead code; either remove the unused Button and related
handleSettingsClick export/definition, or replace `false` with the intended
feature flag or state (e.g., isSettingsEnabled) and wire that flag into the
component props or feature-flag hook; ensure any removed handler references are
cleaned up (imports, props, or useCallback) and that enabling uses the same
Button size="icon" variant="ghost" onClick={handleSettingsClick} pattern.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/generic-api-key-config.ts`:
- Around line 64-70: The submitTransform currently sets api_base to an empty
string when base_url is missing (api_base: values.base_url || ''), which may not
match backend expectations; update submitTransform to only include the api_base
property when values.base_url is present (truthy) — construct the payload object
with instance_name, api_key, group_id, max_tokens, and then conditionally add
api_base = values.base_url only if values.base_url is non-empty so the field is
omitted entirely when not provided.
- Around line 34-49: The placeholder chooser uses a case-mismatched check so the
Anthropic branch never matches; replace the faulty condition in the placeholder
function (currently using factory?.toLowerCase() === 'Anthropic') with a direct
LLMFactory enum comparison (factory === LLMFactory.Anthropic) or compare to
'anthropic' to match other branches so the Anthropic placeholder returns
correctly; update the placeholder function in the generic-api-key-config where
LLMFactory is referenced.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/provider-config-map.ts`:
- Around line 141-148: The form field currently named "model_name" (in
provider-config-map.ts) is causing values.endpoint_id to be undefined because
verifyTransform and submitTransform expect endpoint_id; rename the field's name
from "model_name" to "endpoint_id" (and update its label/placeholder/validation
keys if they reference endpointID text) for the occurrence around the block with
name: 'model_name' and repeat the same rename for the second occurrence noted
(lines ~168-181) so that verifyTransform/submitTransform can read
values.endpoint_id correctly.
- Around line 442-455: The submitTransform is dropping the spark_* credentials
sent during verify; update submitTransform (in the provider-config-map where
verifyTransform and submitTransform are defined) to include the Spark credential
fields (same shape used by verifyTransform, e.g., an apiKey or credentials JSON
containing spark_api_password, spark_app_id, spark_api_secret, spark_api_key)
alongside instance_name, llm_factory (LLMFactory.XunFeiSpark) and model_info so
the provider creation/update persists the auth config required for later use.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/utils.ts`:
- Around line 11-24: The function applyChatToImage2Text uses a case-sensitive
check arr.includes('chat') which will miss variants like 'Chat' or 'CHAT';
update the check to perform a case-insensitive comparison by inspecting arr
items lowercased (e.g., using arr.some(item => String(item).toLowerCase() ===
'chat')) while still returning the original arr values (so preserve original
casing in the returned array) and keep the vision guard and returned addition of
'image2text' otherwise unchanged.
In `@web/src/services/llm-service.ts`:
- Around line 49-52: A GET endpoint config named listProviderModels is being
called without the required second argument (native axios config mode) in the
use-list-models-picker hook; update the callsite that currently does
listProviderModels({ ... }) to call listProviderModels({ ... }, true) so the
native axios mode is enabled (note: the other callsite in use-llm-request
already passes true).
---
Nitpick comments:
In `@web/src/components/ui/input-select.tsx`:
- Around line 337-344: The blur handler uses a 150ms setTimeout that may call
commitInputValue(), setOpen and setIsFocused after the component unmounts; store
the timeout ID in a ref (e.g., blurTimeoutRef), use that ref to clearTimeout in
a useEffect cleanup, and optionally track a mountedRef to guard calling
commitInputValue(), setOpen and setIsFocused inside handleInputBlur so no state
updates occur after unmount; update handleInputBlur to set
blurTimeoutRef.current = window.setTimeout(...), clear it in the cleanup, and
check mountedRef (or ensure timeout cleared) before invoking commitInputValue,
setOpen or setIsFocused.
In `@web/src/components/ui/toggle-list.tsx`:
- Around line 190-198: The chevron icon is currently only rendered when btnText
is a string which hides the expand/collapse affordance for ReactNode button
content; update the ToggleList button render so ChevronsDown is always included
(remove the typeof btnText === 'string' guard) and keep the existing className
logic using cn with 'size-4 shrink-0 transition-transform duration-200' and the
conditional open && 'rotate-180' so the chevron still rotates; ensure
aria-hidden remains set and adjust surrounding markup/CSS if needed to preserve
spacing when btnText is a custom ReactNode.
In `@web/src/interfaces/request/llm.ts`:
- Around line 3-4: Remove the two commented-out fields from the LLM request
interface by deleting the lines containing // model_name: string; and //
model_type: string | string[]; so the interface (llm.ts) no longer contains
stale commented code referencing model_name or model_type; ensure no references
to these symbols remain in this file and run a quick compile/check to confirm no
consumers depend on them.
- Line 22: The extra?: Record<string, any> field is too permissive; constrain it
to document known keys while preserving extensibility by replacing its type with
a narrower shape (for example define a named type/interface like ExtraOptions =
{ is_tools?: boolean; [key: string]: any } and use extra?: ExtraOptions) so
callers get type hints for per-model flags such as is_tools but other keys
remain allowed; update the interface declaration that contains extra to
reference this new type.
In `@web/src/pages/user-setting/setting-model/components/used-model.tsx`:
- Around line 214-227: The catch block inside handleSettingsClick currently
swallows errors from fetchInstanceDetails; modify it to catch the error object
(e.g., catch (err)) and log the failure before falling back, e.g., use
console.error or the app's logger to record the error with context (include
providerName and instance id or name) so developers can see why
fetchInstanceDetails failed while still calling onEditInstance(providerName,
details, models).
In `@web/src/pages/user-setting/setting-model/hooks.tsx`:
- Around line 35-40: Replace the unsafe cast to any when checking
payload.model_info: use a proper type-narrowing check against the declared shape
(treat payload as IAddProviderInstanceRequestBody or use a type guard) and test
Array.isArray(payload.model_info) directly; then call
addProviderInstance(payload as IAddProviderInstanceRequestBody) only when the
check passes so you preserve type safety for payload, referencing model_info,
IAddProviderInstanceRequestBody, addProviderInstance, and payload.
- Around line 198-216: The hook useVerifySettings and its callback
onApiKeyVerifying currently use any for postBody and return types; replace any
with safer types (e.g., unknown or a generic type parameter) by updating the
onVerify prop signature and the useVerifySettings declaration to accept
onVerify: (postBody: unknown, isVerify?: boolean) => Promise<unknown> or make
useVerifySettings generic like <T> (onVerify: (postBody: T, isVerify?: boolean)
=> Promise<R>) and update onApiKeyVerifying to accept postBody: T and return
Promise<R>; adjust the useCallback typing accordingly and propagate the new
generic/unknown types wherever onVerify is passed to preserve type safety while
keeping runtime behavior unchanged.
In `@web/src/pages/user-setting/setting-model/index.tsx`:
- Around line 99-141: The existing comment in handleProviderOk misstates
responsibility for the model_info fast-path — that logic lives in
useSubmitProviderInstance — so update the comment near the hasModelPayload check
in handleProviderOk to say this branch handles legacy split payloads where
splitProviderPayload returned no model fields (i.e., when model information is
not nested in instance.model_info) and therefore we simply close the modal
instead of calling addInstanceModel; mention useSubmitProviderInstance as the
place that handles the model_info fast-path to avoid confusion.
- Around line 280-335: The duplicated model_type normalization in
handleViewModeOk should be extracted into a small utility (e.g.,
normalizeModelType) and used in both places to avoid repetition; create a
function like normalizeModelType(modelType: string | string[] | undefined):
string[] that returns the input if it's an array, or wraps a string into a
single-item array, or returns [] for undefined, then replace the two inline
blocks in handleViewModeOk (the ones computing modelType for payload.modelInfos
and for fv) with calls to normalizeModelType.
- Around line 359-370: The prop baseUrlOptions is being forced to any when
rendering ProviderModal; instead align types by checking ProviderModal's prop
type for baseUrlOptions and updating buildBaseUrlOptions to return that exact
shape (or widen the ProviderModal prop to accept the correct shape). Locate
ProviderModal (prop name baseUrlOptions) and the helper/current value
currentBaseUrlOptions (and the function buildBaseUrlOptions) and change the
return type of buildBaseUrlOptions or the ProviderModal prop type so
currentBaseUrlOptions can be passed without using "as any" — if labels are
ReactNode adjust the types to ReactNode explicitly or map the helper output to
the expected structure before passing to ProviderModal.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-options.tsx`:
- Line 36: Replace the project-specific useTranslate hook with react-i18next's
useTranslation in use-list-models-options.tsx: update the import to pull
useTranslation from 'react-i18next' and change the line const { t } =
useTranslate('setting') to use the useTranslation API (e.g., const { t } =
useTranslation('setting')), then ensure any usages of t remain unchanged and
remove the old useTranslate import.
- Around line 39-56: The allOption object sets value: null as string | null
unnecessarily; remove the type cast and let value be plain null so it matches
the ToggleList generic V without forcing a string union. Update the allOption
declaration (the value field) to just use null, leaving the rest (label JSX,
onClick using handleToggleAll, Checkbox handlers) unchanged.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-picker.ts`:
- Around line 151-211: The callback handleListOpenChange closes over
modelInfoList which is derived from selectedModelItems, creating a fragile
circular dependency; fix by removing modelInfoList from the useCallback
dependency array (leave selectedModelItems as-is) and add a concise comment by
handleListOpenChange explaining we intentionally accept the stale closure for
modelInfoList because it is only used on the initial fetch (always empty) when
invoking config.verifyTransform and listProviderModels, or alternatively
refactor to compute the verifyArgs inline inside the callback from form values
and selectedModelItems so handleListOpenChange no longer needs to close over
modelInfoList.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-provider-fields.tsx`:
- Line 4: Replace the project-wrapped useTranslate import and calls with
react-i18next's useTranslation in this hook: change the import line (remove
useTranslate) and import { useTranslation } from 'react-i18next', then inside
the useProviderFields hook (or the function where useTranslate() is called)
replace useTranslate() usage with const { t } = useTranslation() and update any
t(...) call sites accordingly; also remove the now-unused useTranslate import.
Ensure all references that expected useTranslate's return shape are adjusted to
the { t } API from useTranslation.
In `@web/src/pages/user-setting/setting-model/modal/provider-modal/index.tsx`:
- Around line 34-35: Replace the project-wrapped hooks useTranslate and
useCommonTranslation with the standard useTranslation hook from react-i18next:
import useTranslation and call it to obtain the t functions instead of using
useTranslate and useCommonTranslation so that the component uses
useTranslation('setting') (and the common namespace for the second t if needed)
and replace occurrences of t and tc accordingly (look for the const { t } =
useTranslate and const { t: tc } = useCommonTranslation declarations and update
imports/usages to useTranslation from react-i18next).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c3c4f15d-434f-41f2-8fd0-4af74c7943d7
📒 Files selected for processing (40)
web/src/components/ui/input-select.tsxweb/src/components/ui/toggle-list.tsxweb/src/hooks/use-llm-request.tsxweb/src/interfaces/database/llm.tsweb/src/interfaces/request/llm.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/components/used-model.tsxweb/src/pages/user-setting/setting-model/hooks.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/modal/api-key-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/azure-openai-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/fish-audio-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/google-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/mineru-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/next-tencent-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/paddleocr-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/provider-modal/constants.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/field-config/generic-api-key-config.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/field-config/get-provider-config.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/field-config/index.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/field-config/local-llm-configs.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/field-config/provider-config-map.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/field-config/utils.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/hooks/index.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-options.tsxweb/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-picker.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-provider-fields.tsxweb/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-provider-modal-actions.tsweb/src/pages/user-setting/setting-model/modal/provider-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/provider-modal/types.tsweb/src/pages/user-setting/setting-model/modal/spark-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/verify-button/index.tsxweb/src/pages/user-setting/setting-model/modal/volcengine-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/yiyan-modal/index.tsxweb/src/pages/user-setting/setting-model/payload-utils.tsweb/src/services/llm-service.tsweb/src/utils/api.ts
💤 Files with no reviewable changes (12)
- web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/spark-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/yiyan-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/api-key-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/mineru-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/next-tencent-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/paddleocr-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/fish-audio-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/volcengine-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/azure-openai-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsx
- web/src/pages/user-setting/setting-model/modal/google-modal/index.tsx
| /** | ||
| * Fetch full details of a single provider instance (used in viewMode to | ||
| * retrieve fields like `baseUrl` that the list endpoint does not return). | ||
| * Disabled by default; call from an event handler (e.g. onClick) and | ||
| * rely on the returned `refetch` to actually trigger the request. | ||
| */ | ||
| export const useFetchProviderInstance = ( | ||
| providerName: string, | ||
| instanceName: string, | ||
| ) => { | ||
| return useQuery<IProviderInstance>({ | ||
| queryKey: LlmKeys.providerInstance(providerName, instanceName), | ||
| initialData: undefined as unknown as IProviderInstance, | ||
| gcTime: 0, | ||
| enabled: false, | ||
| queryFn: async () => { | ||
| const { data } = await llmService.showProviderInstance( | ||
| { provider_name: providerName, instance_name: instanceName }, | ||
| true, | ||
| ); | ||
| return (data?.data ?? {}) as IProviderInstance; | ||
| }, | ||
| }); | ||
| }; |
There was a problem hiding this comment.
Avoid unsafe type assertion in initialData.
Line 166 uses undefined as unknown as IProviderInstance, which is a double type assertion that bypasses TypeScript's safety checks. When enabled: false, React Query won't call the queryFn until refetch() is invoked, so initialData should be undefined and the return type should reflect that the data may be undefined.
🔧 Proposed fix
export const useFetchProviderInstance = (
providerName: string,
instanceName: string,
) => {
return useQuery<IProviderInstance | undefined>({
queryKey: LlmKeys.providerInstance(providerName, instanceName),
- initialData: undefined as unknown as IProviderInstance,
+ initialData: undefined,
gcTime: 0,
enabled: false,
queryFn: async () => {Callers should handle the undefined case (e.g., ret.data ?? {} or optional chaining).
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** | |
| * Fetch full details of a single provider instance (used in viewMode to | |
| * retrieve fields like `baseUrl` that the list endpoint does not return). | |
| * Disabled by default; call from an event handler (e.g. onClick) and | |
| * rely on the returned `refetch` to actually trigger the request. | |
| */ | |
| export const useFetchProviderInstance = ( | |
| providerName: string, | |
| instanceName: string, | |
| ) => { | |
| return useQuery<IProviderInstance>({ | |
| queryKey: LlmKeys.providerInstance(providerName, instanceName), | |
| initialData: undefined as unknown as IProviderInstance, | |
| gcTime: 0, | |
| enabled: false, | |
| queryFn: async () => { | |
| const { data } = await llmService.showProviderInstance( | |
| { provider_name: providerName, instance_name: instanceName }, | |
| true, | |
| ); | |
| return (data?.data ?? {}) as IProviderInstance; | |
| }, | |
| }); | |
| }; | |
| /** | |
| * Fetch full details of a single provider instance (used in viewMode to | |
| * retrieve fields like `baseUrl` that the list endpoint does not return). | |
| * Disabled by default; call from an event handler (e.g. onClick) and | |
| * rely on the returned `refetch` to actually trigger the request. | |
| */ | |
| export const useFetchProviderInstance = ( | |
| providerName: string, | |
| instanceName: string, | |
| ) => { | |
| return useQuery<IProviderInstance | undefined>({ | |
| queryKey: LlmKeys.providerInstance(providerName, instanceName), | |
| initialData: undefined, | |
| gcTime: 0, | |
| enabled: false, | |
| queryFn: async () => { | |
| const { data } = await llmService.showProviderInstance( | |
| { provider_name: providerName, instance_name: instanceName }, | |
| true, | |
| ); | |
| return (data?.data ?? {}) as IProviderInstance; | |
| }, | |
| }); | |
| }; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/hooks/use-llm-request.tsx` around lines 154 - 177, The hook
useFetchProviderInstance is using an unsafe double-cast for initialData; change
the query generic to allow undefined (e.g., IProviderInstance | undefined), set
initialData to undefined (no casts), and keep enabled: false so callers must
handle the possibly-undefined ret.data (e.g., ret.data ?? {} or optional
chaining); update any related references like LlmKeys.providerInstance and
llmService.showProviderInstance usages to expect the possibly-undefined return.
| paddleocrAccessToken: 'PaddleOCR Access Token', | ||
| paddleocrAccessTokenMessage: 'Please input the PaddleOCR access token!', | ||
| paddleocrAccessTokenPlaceholder: 'Your PaddleOCR access token (optional)', |
There was a problem hiding this comment.
Resolve conflicting optional vs required copy for PaddleOCR access token.
Line 1556 asks users to input the token, while Line 1557 labels it optional. Please align these strings (and corresponding validation behavior) to avoid contradictory UX.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/locales/en.ts` around lines 1555 - 1557, The paddleocr text entries
are contradictory: paddleocrAccessTokenMessage currently demands input while
paddleocrAccessTokenPlaceholder marks it optional; update the strings and
corresponding validation so they match (either required or optional). Decide
desired behavior and then: if required, change paddleocrAccessTokenPlaceholder
to remove "(optional)" and ensure the form validator that uses
paddleocrAccessToken / paddleocrAccessTokenMessage enforces presence; if
optional, change paddleocrAccessTokenMessage to a non-mandatory hint (e.g.,
remove "Please input") and ensure the validation rule for paddleocrAccessToken
does not mark it as required. Adjust the three keys paddleocrAccessToken,
paddleocrAccessTokenMessage, and paddleocrAccessTokenPlaceholder and the related
form validation logic to be consistent.
| paddleocrAccessToken: 'PaddleOCR 访问令牌', | ||
| paddleocrAccessTokenMessage: '请输入 PaddleOCR 访问令牌!', | ||
| paddleocrAccessTokenPlaceholder: '您的 PaddleOCR 访问令牌(可选)', | ||
| paddleocrAlgorithm: 'PaddleOCR 算法', |
There was a problem hiding this comment.
中文文案中“可选”与“必填”语义冲突。
Line 1280 提示“请输入访问令牌”,但 Line 1281 标注“可选”。建议统一文案(并确认校验逻辑一致),避免用户误解。
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/locales/zh.ts` around lines 1279 - 1282, The Chinese strings for
PaddleOCR token are inconsistent: paddleocrAccessTokenMessage currently reads as
required ("请输入 PaddleOCR 访问令牌!") while paddleocrAccessTokenPlaceholder says
optional ("您的 PaddleOCR 访问令牌(可选)"); update the copy to be consistent (either
both indicate required or both indicate optional) and adjust the validation
logic accordingly so message matches actual requirement; change the values for
paddleocrAccessTokenMessage and/or paddleocrAccessTokenPlaceholder and confirm
any form validation that references paddleocrAccessToken uses the same
required/optional semantics as paddleocrAccessTokenMessage.
| <div className="flex justify-between items-center"> | ||
| <div className="flex flex-wrap gap-2 mb-3"> | ||
| {modelTypes.map((type) => ( | ||
| <span | ||
| key={type} | ||
| className="px-2 py-1 text-xs bg-bg-card text-text-secondary rounded-md" | ||
| > | ||
| {mapModelKey[type.trim() as keyof typeof mapModelKey] || type} | ||
| </span> | ||
| ))} | ||
| </div> | ||
| {false && ( | ||
| <Button size="icon" variant="ghost" onClick={handleSettingsClick}> | ||
| <Settings size={12} /> | ||
| </Button> | ||
| )} | ||
| </div> | ||
| )} |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if there are any feature flags or TODO comments related to this settings button
rg -n -C3 -i 'settings.*button|edit.*instance.*model' --type=ts --type=tsx web/src/pages/user-setting/setting-model/Repository: infiniflow/ragflow
Length of output: 90
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="web/src/pages/user-setting/setting-model/components/used-model.tsx"
echo "== File section around 230-280 =="
nl -ba "$FILE" | sed -n '220,290p'
echo
echo "== Search for handler/Settings references in the same directory =="
rg -n -S --hidden --no-ignore-vcs "handleSettingsClick|Settings\\s*\\(|false\\s*&&|settings button|TODO|feature flag|work in progress|wip" web/src/pages/user-setting/setting-model/
echo
echo "== Search for any feature flags mentioning this UI =="
rg -n -S --hidden --no-ignore-vcs "(feature.?flag|enable.*settings|settings.*enabled|flag.*settings)" web/src/pages/user-setting/setting-model/Repository: infiniflow/ragflow
Length of output: 157
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="web/src/pages/user-setting/setting-model/components/used-model.tsx"
DIR="web/src/pages/user-setting/setting-model"
echo "== File section around 230-290 =="
cat -n "$FILE" | sed -n '220,290p'
echo
echo "== Search for handler/Settings references in the same directory =="
rg -n -S --hidden --no-ignore-vcs \
--glob '*.ts' --glob '*.tsx' \
"handleSettingsClick|<Button[^>]*size=\"icon\"[^>]*variant=\"ghost\"|false\\s*&&|TODO|work in progress|feature.?flag|settings" \
"$DIR" || true
echo
echo "== Search for any feature flags mentioning this UI =="
rg -n -S --hidden --no-ignore-vcs \
--glob '*.ts' --glob '*.tsx' \
"(feature.?flag|enable.*settings|settings.*enabled|flag.*settings|wip)" \
"$DIR" || trueRepository: infiniflow/ragflow
Length of output: 3198
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="web/src/pages/user-setting/setting-model/components/used-model.tsx"
DIR="web/src/pages/user-setting/setting-model"
echo "== File section around handleSettingsClick (180-240) =="
cat -n "$FILE" | sed -n '160,240p'
echo
echo "== Find any other occurrences of handleSettingsClick (repo-scoped to this area) =="
rg -n -S --hidden --no-ignore-vcs --glob '*.ts' --glob '*.tsx' "handleSettingsClick" "$DIR" || true
echo
echo "== Search for TODO/WIP around settings dialog in this area =="
rg -n -S --hidden --no-ignore-vcs --glob '*.ts' --glob '*.tsx' \
"(settings dialog|settings.*dialog|handleSettingsClick|TODO|wip|work in progress|feature.?flag|enable.*settings)" \
"$DIR" || trueRepository: infiniflow/ragflow
Length of output: 3907
Remove the permanently disabled Settings button (uses false &&) or gate it properly.
In web/src/pages/user-setting/setting-model/components/used-model.tsx (lines 243-258), the Settings button is wrapped in {false && (...)} while handleSettingsClick and the surrounding comment describe opening the settings dialog. With the button never rendered, this makes the handler effectively dead code unless it’s intentionally controlled by a feature flag (none found here). Either enable it with the intended condition/flag, or remove the unused button/handler until the feature ships.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/user-setting/setting-model/components/used-model.tsx` around
lines 243 - 260, The Settings button is permanently disabled by `{false &&
(...)}` in used-model.tsx so the handler handleSettingsClick and the
Button/Settings JSX are dead code; either remove the unused Button and related
handleSettingsClick export/definition, or replace `false` with the intended
feature flag or state (e.g., isSettingsEnabled) and wire that flag into the
component props or feature-flag hook; ensure any removed handler references are
cleaned up (imports, props, or useCallback) and that enabling uses the same
Button size="icon" variant="ghost" onClick={handleSettingsClick} pattern.
| tooltip: (factory) => { | ||
| if (factory === LLMFactory.MiniMax) return 'minimaxBaseUrlTip'; | ||
| if (factory === LLMFactory.TongYiQianWen) return 'tongyiBaseUrlTip'; | ||
| if (factory === LLMFactory.SILICONFLOW) return 'siliconBaseUrlTip'; | ||
| return 'baseUrlTip'; | ||
| }, | ||
| placeholder: (factory) => { | ||
| if (factory === LLMFactory.MiniMax) return 'minimaxBaseUrlPlaceholder'; | ||
| if (factory === LLMFactory.TongYiQianWen) | ||
| return 'tongyiBaseUrlPlaceholder'; | ||
| if (factory === LLMFactory.SILICONFLOW) | ||
| return 'siliconflowBaseUrlPlaceholder'; | ||
| if (factory?.toLowerCase() === 'Anthropic') | ||
| return 'anthropicBaseUrlPlaceholder'; | ||
| return 'openaiBaseUrlPlaceholder'; | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if Anthropic is defined in the LLMFactory enum
# Find the LLMFactory enum definition
rg -n -A 50 'export\s+(const\s+)?enum\s+LLMFactory' --type ts -g '**/llm.ts'
# Search for other Anthropic references to see the expected casing
rg -n 'LLMFactory\.Anthropic|Anthropic' --type ts -g '**/{constants,llm}*.ts'Repository: infiniflow/ragflow
Length of output: 3053
Fix Anthropic placeholder branch in provider check
In web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/generic-api-key-config.ts (line 46), the code uses factory?.toLowerCase() === 'Anthropic'; since LLMFactory.Anthropic is 'Anthropic', toLowerCase() becomes 'anthropic', so this condition never matches and it falls back to openaiBaseUrlPlaceholder. Use factory === LLMFactory.Anthropic (or compare to 'anthropic') to align with the other LLMFactory.* checks.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/generic-api-key-config.ts`
around lines 34 - 49, The placeholder chooser uses a case-mismatched check so
the Anthropic branch never matches; replace the faulty condition in the
placeholder function (currently using factory?.toLowerCase() === 'Anthropic')
with a direct LLMFactory enum comparison (factory === LLMFactory.Anthropic) or
compare to 'anthropic' to match other branches so the Anthropic placeholder
returns correctly; update the placeholder function in the generic-api-key-config
where LLMFactory is referenced.
| submitTransform: (values) => ({ | ||
| instance_name: values.instance_name, | ||
| api_key: values.api_key, | ||
| api_base: values.base_url || '', | ||
| group_id: values.group_id, | ||
| max_tokens: 0, | ||
| }), |
There was a problem hiding this comment.
Empty string default for api_base may not match backend expectations.
Line 67 uses api_base: values.base_url || '', which sends an empty string when base_url is undefined or empty. Depending on the backend's validation, an empty string may be treated differently than an absent field. Consider omitting the field entirely when it's empty, or verify that the backend accepts empty strings for optional api_base fields.
💡 Suggested fix to omit empty values
submitTransform: (values) => ({
instance_name: values.instance_name,
api_key: values.api_key,
- api_base: values.base_url || '',
+ ...(values.base_url ? { api_base: values.base_url } : {}),
group_id: values.group_id,
max_tokens: 0,
}),📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.
| submitTransform: (values) => ({ | |
| instance_name: values.instance_name, | |
| api_key: values.api_key, | |
| api_base: values.base_url || '', | |
| group_id: values.group_id, | |
| max_tokens: 0, | |
| }), | |
| submitTransform: (values) => ({ | |
| instance_name: values.instance_name, | |
| api_key: values.api_key, | |
| ...(values.base_url ? { api_base: values.base_url } : {}), | |
| group_id: values.group_id, | |
| max_tokens: 0, | |
| }), |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/generic-api-key-config.ts`
around lines 64 - 70, The submitTransform currently sets api_base to an empty
string when base_url is missing (api_base: values.base_url || ''), which may not
match backend expectations; update submitTransform to only include the api_base
property when values.base_url is present (truthy) — construct the payload object
with instance_name, api_key, group_id, max_tokens, and then conditionally add
api_base = values.base_url only if values.base_url is non-empty so the field is
omitted entirely when not provided.
| name: 'model_name', | ||
| label: 'addEndpointID', | ||
| type: FormFieldType.Text, | ||
| required: true, | ||
| placeholder: 'endpointIDMessage', | ||
| shouldRender: 'hideWhenInstanceExists', | ||
| validation: { message: 'endpointIDMessage' }, | ||
| }, |
There was a problem hiding this comment.
VolcEngine uses endpoint_id in transforms but the form field is model_name.
verifyTransform/submitTransform read values.endpoint_id, but no endpoint_id field exists, so endpoint_id is always undefined in requests.
Suggested fix
verifyTransform: (values, modelInfo) => ({
apiKey: JSON.stringify({
ark_api_key: values.api_key,
- endpoint_id: values.endpoint_id,
+ endpoint_id: values.model_name,
}),
modelInfo,
}),
submitTransform: (values, modelInfo) => ({
instance_name: values.instance_name,
llm_factory: LLMFactory.VolcEngine,
- endpoint_id: values.endpoint_id,
+ endpoint_id: values.model_name,
ark_api_key: values.api_key,
model_info: modelInfo,
}),Also applies to: 168-181
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/provider-config-map.ts`
around lines 141 - 148, The form field currently named "model_name" (in
provider-config-map.ts) is causing values.endpoint_id to be undefined because
verifyTransform and submitTransform expect endpoint_id; rename the field's name
from "model_name" to "endpoint_id" (and update its label/placeholder/validation
keys if they reference endpointID text) for the occurrence around the block with
name: 'model_name' and repeat the same rename for the second occurrence noted
(lines ~168-181) so that verifyTransform/submitTransform can read
values.endpoint_id correctly.
| verifyTransform: (values, modelInfo) => ({ | ||
| apiKey: JSON.stringify({ | ||
| spark_api_password: values.spark_api_password, | ||
| spark_app_id: values.spark_app_id, | ||
| spark_api_secret: values.spark_api_secret, | ||
| spark_api_key: values.spark_api_key, | ||
| }), | ||
| modelInfo, | ||
| }), | ||
| submitTransform: (values, modelInfo) => ({ | ||
| instance_name: values.instance_name, | ||
| llm_factory: LLMFactory.XunFeiSpark, | ||
| model_info: modelInfo, | ||
| }), |
There was a problem hiding this comment.
XunFeiSpark submit payload drops credential fields used during verify.
verifyTransform sends spark_* credentials, but submitTransform persists only instance_name, llm_factory, and model_info. This can break provider creation/update due to missing auth config.
Suggested fix
submitTransform: (values, modelInfo) => ({
instance_name: values.instance_name,
llm_factory: LLMFactory.XunFeiSpark,
+ api_key: JSON.stringify({
+ spark_api_password: values.spark_api_password,
+ spark_app_id: values.spark_app_id,
+ spark_api_secret: values.spark_api_secret,
+ spark_api_key: values.spark_api_key,
+ }),
model_info: modelInfo,
}),📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.
| verifyTransform: (values, modelInfo) => ({ | |
| apiKey: JSON.stringify({ | |
| spark_api_password: values.spark_api_password, | |
| spark_app_id: values.spark_app_id, | |
| spark_api_secret: values.spark_api_secret, | |
| spark_api_key: values.spark_api_key, | |
| }), | |
| modelInfo, | |
| }), | |
| submitTransform: (values, modelInfo) => ({ | |
| instance_name: values.instance_name, | |
| llm_factory: LLMFactory.XunFeiSpark, | |
| model_info: modelInfo, | |
| }), | |
| verifyTransform: (values, modelInfo) => ({ | |
| apiKey: JSON.stringify({ | |
| spark_api_password: values.spark_api_password, | |
| spark_app_id: values.spark_app_id, | |
| spark_api_secret: values.spark_api_secret, | |
| spark_api_key: values.spark_api_key, | |
| }), | |
| modelInfo, | |
| }), | |
| submitTransform: (values, modelInfo) => ({ | |
| instance_name: values.instance_name, | |
| llm_factory: LLMFactory.XunFeiSpark, | |
| api_key: JSON.stringify({ | |
| spark_api_password: values.spark_api_password, | |
| spark_app_id: values.spark_app_id, | |
| spark_api_secret: values.spark_api_secret, | |
| spark_api_key: values.spark_api_key, | |
| }), | |
| model_info: modelInfo, | |
| }), |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/provider-config-map.ts`
around lines 442 - 455, The submitTransform is dropping the spark_* credentials
sent during verify; update submitTransform (in the provider-config-map where
verifyTransform and submitTransform are defined) to include the Spark credential
fields (same shape used by verifyTransform, e.g., an apiKey or credentials JSON
containing spark_api_password, spark_app_id, spark_api_secret, spark_api_key)
alongside instance_name, llm_factory (LLMFactory.XunFeiSpark) and model_info so
the provider creation/update persists the auth config required for later use.
| export function applyChatToImage2Text( | ||
| modelType: string[] | string | undefined, | ||
| vision?: boolean, | ||
| ): string[] { | ||
| const arr = Array.isArray(modelType) | ||
| ? modelType | ||
| : modelType | ||
| ? [modelType] | ||
| : []; | ||
| if (arr.includes('chat') && vision) { | ||
| return [...arr, 'image2text']; | ||
| } | ||
| return arr; | ||
| } |
There was a problem hiding this comment.
Case-sensitive string matching may cause bugs.
Line 20 checks arr.includes('chat') without normalizing the case. If modelType contains 'Chat' or 'CHAT', the condition will fail and 'image2text' won't be added as expected. Consider normalizing to lowercase before comparison, or document that model type values are guaranteed to be lowercase.
🔧 Proposed fix with case normalization
export function applyChatToImage2Text(
modelType: string[] | string | undefined,
vision?: boolean,
): string[] {
const arr = Array.isArray(modelType)
? modelType
: modelType
? [modelType]
: [];
- if (arr.includes('chat') && vision) {
+ const normalizedArr = arr.map(t => t.toLowerCase());
+ if (normalizedArr.includes('chat') && vision) {
return [...arr, 'image2text'];
}
return arr;
}Note: This preserves the original casing in the returned array while normalizing only for the check.
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function applyChatToImage2Text( | |
| modelType: string[] | string | undefined, | |
| vision?: boolean, | |
| ): string[] { | |
| const arr = Array.isArray(modelType) | |
| ? modelType | |
| : modelType | |
| ? [modelType] | |
| : []; | |
| if (arr.includes('chat') && vision) { | |
| return [...arr, 'image2text']; | |
| } | |
| return arr; | |
| } | |
| export function applyChatToImage2Text( | |
| modelType: string[] | string | undefined, | |
| vision?: boolean, | |
| ): string[] { | |
| const arr = Array.isArray(modelType) | |
| ? modelType | |
| : modelType | |
| ? [modelType] | |
| : []; | |
| const normalizedArr = arr.map(t => t.toLowerCase()); | |
| if (normalizedArr.includes('chat') && vision) { | |
| return [...arr, 'image2text']; | |
| } | |
| return arr; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/utils.ts`
around lines 11 - 24, The function applyChatToImage2Text uses a case-sensitive
check arr.includes('chat') which will miss variants like 'Chat' or 'CHAT';
update the check to perform a case-insensitive comparison by inspecting arr
items lowercased (e.g., using arr.some(item => String(item).toLowerCase() ===
'chat')) while still returning the original arr values (so preserve original
casing in the returned array) and keep the vision guard and returned addition of
'image2text' otherwise unchanged.
| listProviderModels: { | ||
| url: listProviderModels, | ||
| method: 'get', | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find callsites and inspect whether second arg `true` is passed.
rg -n --type=ts --type=tsx -C3 '\blistProviderModels\s*\(' webRepository: infiniflow/ragflow
Length of output: 90
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# 1) Find all callsites of listProviderModels in the web directory (tsx included via globs)
rg -n -C3 'listProviderModels\s*\(' web -g'*.ts' -g'*.tsx'
echo "----"
# 2) Show definition in llm-service.ts around listProviderModels
rg -n -C2 'listProviderModels' web/src/services/llm-service.ts
echo "----"
# Print the function/service signature area (first ~120 lines or around definition)
sed -n '1,140p' web/src/services/llm-service.ts
echo "----"
# 3) Print the likely hook file(s) that call it (search targets from above)
# (Re-run rg to extract filenames, then print small windows around each match)
matches=$(rg -n 'listProviderModels\s*\(' web -g'*.ts' -g'*.tsx' --format '%f:%l')
echo "$matches" | awk -F: '{print $1}' | sort -uRepository: infiniflow/ragflow
Length of output: 3882
Fix listProviderModels GET callsite to pass native axios config mode (true).
listProviderModels is registered as method: 'get' in web/src/services/llm-service.ts. One callsite, web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-picker.ts (around line 169), invokes listProviderModels({ ... }) without the required second argument—update it to listProviderModels({ ... }, true). (Another callsite in web/src/hooks/use-llm-request.tsx already passes true.)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/services/llm-service.ts` around lines 49 - 52, A GET endpoint config
named listProviderModels is being called without the required second argument
(native axios config mode) in the use-list-models-picker hook; update the
callsite that currently does listProviderModels({ ... }) to call
listProviderModels({ ... }, true) so the native axios mode is enabled (note: the
other callsite in use-llm-request already passes true).
Source: Learnings
What problem does this PR solve?
feat:Unify the 'Add Model Provider' modal
Type of change