Repository navigation
fix(model-provider): replace per-card auto-save with batch Save-all - #17025
Conversation
📝 WalkthroughWalkthroughChangesProvider instance save workflow
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant ProviderHeaderBar
participant SettingModelV2
participant ProviderInstanceCard
participant ProviderInstanceAPI
User->>ProviderHeaderBar: click Save all
ProviderHeaderBar->>SettingModelV2: invoke onSave
SettingModelV2->>ProviderInstanceCard: validate and collect payload
SettingModelV2->>ProviderInstanceAPI: add or update dirty instances
SettingModelV2->>ProviderInstanceCard: mark saved
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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: 11
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
web/src/pages/user-setting/setting-model/layout/provider-header-bar.tsx (1)
73-80: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winGive the API link an accurate accessible name.
The arrow now opens the provider’s API-key page, but screen readers still announce “Documentation link.” Use a dedicated localized API-key/API-console 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/layout/provider-header-bar.tsx` around lines 73 - 80, Update the API link anchor in the provider header bar to use a dedicated localized API-key or API-console accessible label instead of the documentation label. Replace the tSetting('docLink') reference on the apiLink anchor while preserving its existing link behavior and styling.web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx (1)
64-90: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftMake the API-key gate reactive.
Typing into
DynamicFormdoes not rerenderModelsSection, so a VolcEngine draft mounted with an empty key retainscredsReady = falseand never auto-fetches after the key is entered. Subscribe with the form’swatch()API or pass watched credential state into this component.🤖 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/instance-card/models-section/index.tsx` around lines 64 - 90, The API-key gate in ModelsSection is not reactive to DynamicForm input changes. Update the currentCreds/resolveCreds flow used by useModelsCatalog so it subscribes to the form’s watch API (or receives equivalent watched credential state), causing ModelsSection and the apiKeyValue passed to useModelsCatalog to update immediately when the API key is entered.
🧹 Nitpick comments (3)
web/src/pages/user-setting/setting-model/layout/provider-header-bar.tsx (1)
20-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
useTranslationdirectly.Proposed fix
-import { useTranslate } from '`@/hooks/common-hooks`'; +import { useTranslation } from 'react-i18next'; - const { t: tSetting } = useTranslate('setting'); + const { t: tSetting } = useTranslation('translation', { + keyPrefix: 'setting', + });As per coding guidelines, “Prefer useTranslation from react-i18next over project-wrapped utilities such as useTranslate.”
Also applies to: 49-49
🤖 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/layout/provider-header-bar.tsx` at line 20, Replace the project-wrapped useTranslate imports and usages in provider-header-bar.tsx with useTranslation directly from react-i18next, including the additional occurrence, while preserving the existing translation behavior.Source: Coding guidelines
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx (2)
76-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the duplicated compatibility prop surfaces.
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx#L76-L95: type the component with canonicalProviderInstanceCardProps.web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx#L669-L672: delete the compatibility re-export.web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx#L95-L129: type the component with canonicalProviderInstanceCardProps.web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx#L718-L721: delete the compatibility re-export.As per coding guidelines, “Prefer deletion over compatibility shims” and “reduce public surface area.”
🤖 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/instance-card/bedrock-instance-card.tsx` around lines 76 - 95, Replace the custom BedrockInstanceCardProps and Somark card prop interfaces with the canonical ProviderInstanceCardProps type for their respective forwardRef components. Remove the compatibility re-exports at web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx:669-672 and web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx:718-721, preserving the existing component exports and behavior.Source: Coding guidelines
565-568: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the new JSX event handlers.
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx#L565-L568: reference a named draft-name handler.web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx#L636-L639: reference a named draft-name handler.web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsx#L80-L84: reference named model getter/change callbacks.As per coding guidelines, “Do not define arrow functions directly on JSX event props; extract event handlers and reference named handlers instead.”
🤖 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/instance-card/bedrock-instance-card.tsx` around lines 565 - 568, Extract the inline JSX callbacks into named handlers: in web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx lines 565-568 and web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx lines 636-639, define and reference named draft-name change handlers; in web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsx lines 80-84, define and reference named model getter and change callbacks. Preserve the existing state updates and model behavior.Source: Coding guidelines
🤖 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/pages/user-setting/setting-model/index.tsx`:
- Around line 203-231: Update the sequential batch around addProviderInstance
and updateProviderInstance to track each entry’s ID and persist success per card
immediately. After any successful request, remove that entry’s ID from draft
state when it is a draft, and call ref.markSaved() for every successful saved
card, including apiKind: 'add'; retain failed entries for retry and avoid
clearing all drafts after a later failure.
- Around line 211-234: The batch-save flow must ignore completion updates when
the provider has changed while requests are pending. Snapshot the active
provider before starting the batch, then guard setDraftIds([]), query
invalidation, and related saved-instance state updates so they only run if the
current provider still matches that snapshot; preserve normal completion
behavior for the original provider.
- Around line 179-190: Update the save flow around trigger() so untouched saved
cards are not validated before their payload is inspected. Validate draft cards
and only dirty saved cards, or derive getSavePayload() first and validate saved
cards only when it returns a non-null payload, while preserving the existing
behavior of blocking the save when any pending card is invalid.
In
`@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx`:
- Around line 589-597: Update the ModelsSection usage in the instance-card form
so draft model selections are wired through onInstanceModelsChange and included
by buildPayload() when saving all; alternatively remove this section if draft
model editing is not supported. Ensure selections are not kept only in local
state and silently discarded.
- Around line 354-383: The imperative save payload builders must serialize the
edited instance name instead of always using the persisted name. In
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx:354-383,
update getSavePayload to track and use the trimmed edited Bedrock name for saved
instances; apply the same change in
web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx:386-415
for the SoMark name, while preserving draft validation and existing payload
metadata.
In
`@web/src/pages/user-setting/setting-model/instance-card/components/instance-name-section.tsx`:
- Line 34: Remove the stale documentation comment stating that helper text
explains the workflow near the instance-name section. Do not alter the rendered
component behavior or surrounding documentation that remains accurate.
In
`@web/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsx`:
- Around line 150-170: The inline rename trigger around the instance-name static
div is not keyboard-accessible and defines an event handler directly in JSX.
Replace or augment it with a focusable edit control that starts rename via Enter
and Space, extract the activation and existing double-click logic into named
handlers near startRename, and reference those handlers from JSX while
preserving event propagation behavior.
In `@web/src/pages/user-setting/setting-model/instance-card/hooks.tsx`:
- Around line 568-583: Extract a shared canonical payload normalizer from
submitTransform and use it to build both the baseline signature and current save
signatures. Update the baseline construction near baselinePayloadRef.current to
pass the same source values through this normalizer, preserving canonical
defaults such as api_key and region and avoiding a separately assembled payload
that can mark untouched cards dirty.
- Around line 336-340: Update the generic verification payload in the else
branch of the save flow to use the same credential-building logic as
buildApiKeyValue, including group_id, api_version, and provider_order rather
than only values.api_key. Keep the existing base_url, model_info, and other
verification fields unchanged.
In
`@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts`:
- Around line 462-470: Extend the draft mutator contract beside addDraftModel,
removeDraftModel, and setDraftModelsList with an updateDraftModel callback, then
update useModelEdit.handleEditSubmit() to invoke it for draft instances instead
of PATCHing instanceName (__draft__). Preserve the existing backend update path
for saved cards.
In
`@web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx`:
- Around line 165-178: Update the save flow around useInstanceSaveState and its
getSavePayload usage so a collapsed instance cannot perform a full rename save
until its credentials and models have been loaded. Ensure the details fetch
completes before enabling or submitting the rename, or route collapsed renames
through a sparse update that preserves api_key, base_url, and model_info; apply
the same protection to the additional rename path.
---
Outside diff comments:
In
`@web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx`:
- Around line 64-90: The API-key gate in ModelsSection is not reactive to
DynamicForm input changes. Update the currentCreds/resolveCreds flow used by
useModelsCatalog so it subscribes to the form’s watch API (or receives
equivalent watched credential state), causing ModelsSection and the apiKeyValue
passed to useModelsCatalog to update immediately when the API key is entered.
In `@web/src/pages/user-setting/setting-model/layout/provider-header-bar.tsx`:
- Around line 73-80: Update the API link anchor in the provider header bar to
use a dedicated localized API-key or API-console accessible label instead of the
documentation label. Replace the tSetting('docLink') reference on the apiLink
anchor while preserving its existing link behavior and styling.
---
Nitpick comments:
In
`@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx`:
- Around line 76-95: Replace the custom BedrockInstanceCardProps and Somark card
prop interfaces with the canonical ProviderInstanceCardProps type for their
respective forwardRef components. Remove the compatibility re-exports at
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx:669-672
and
web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx:718-721,
preserving the existing component exports and behavior.
- Around line 565-568: Extract the inline JSX callbacks into named handlers: in
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
lines 565-568 and
web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx
lines 636-639, define and reference named draft-name change handlers; in
web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsx
lines 80-84, define and reference named model getter and change callbacks.
Preserve the existing state updates and model behavior.
In `@web/src/pages/user-setting/setting-model/layout/provider-header-bar.tsx`:
- Line 20: Replace the project-wrapped useTranslate imports and usages in
provider-header-bar.tsx with useTranslation directly from react-i18next,
including the additional occurrence, while preserving the existing translation
behavior.
🪄 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: 33dd7868-aa4d-441a-ab00-03a6cd443f22
📒 Files selected for processing (14)
web/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsxweb/src/pages/user-setting/setting-model/instance-card/components/instance-name-section.tsxweb/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsxweb/src/pages/user-setting/setting-model/instance-card/hooks.tsxweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsxweb/src/pages/user-setting/setting-model/layout/provider-header-bar.tsx
| // 1. Validate every card up front. Block all saves if any is invalid. | ||
| const validations = await Promise.all( | ||
| refs.map(async (r) => ({ ref: r, valid: await r.validate() })), | ||
| ); | ||
| if (validations.some((v) => !v.valid)) { | ||
| return; | ||
| } | ||
|
|
||
| // 2. Collect dirty payloads (null = nothing to save for this card). | ||
| const entries = validations | ||
| .map((v) => ({ ref: v.ref, payload: v.ref.getSavePayload() })) | ||
| .filter((e) => e.payload !== null); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
set -e
printf '\n== outline ==\n'
ast-grep outline web/src/pages/user-setting/setting-model/index.tsx --view expanded || true
printf '\n== targeted lines ==\n'
sed -n '120,260p' web/src/pages/user-setting/setting-model/index.tsx
printf '\n== search refs ==\n'
rg -n "validate\\(|getSavePayload\\(|apiKind: 'add'|base_url|api_key|load.*details|baseline|dirty" web/src/pages/user-setting -g '*.ts' -g '*.tsx'Repository: infiniflow/ragflow
Length of output: 39416
🏁 Script executed:
set -e
printf '\n== outline hooks ==\n'
ast-grep outline web/src/pages/user-setting/setting-model/instance-card/hooks.tsx --view expanded || true
printf '\n== targeted hooks slice ==\n'
sed -n '420,720p' web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
printf '\n== provider-instance-card slice ==\n'
sed -n '1,260p' web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx
printf '\n== interface slice ==\n'
sed -n '1,180p' web/src/pages/user-setting/setting-model/instance-card/interface.tsRepository: infiniflow/ragflow
Length of output: 28071
🏁 Script executed:
set -e
printf '\n== useLazyInstanceDetails / initial-values / reset ==\n'
sed -n '236,420p' web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
printf '\n== saved card body ==\n'
sed -n '1,260p' web/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsx
printf '\n== draft card body ==\n'
sed -n '1,240p' web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsxRepository: infiniflow/ragflow
Length of output: 17199
🏁 Script executed:
set -e
printf '\n== useProviderInitialValues ==\n'
sed -n '166,236p' web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
printf '\n== fetch provider instance hook usage ==\n'
rg -n "useFetchProviderInstance|providerInstances|showProviderInstance|list endpoint|api_key / base_url" web/src/pages/user-setting/setting-model -g '*.ts' -g '*.tsx'Repository: infiniflow/ragflow
Length of output: 5935
🏁 Script executed:
set -e
printf '\n== provider instance type ==\n'
sed -n '1,220p' web/src/interfaces/database/llm.ts
printf '\n== provider fields required rules search ==\n'
rg -n "name: 'api_key'|name: 'base_url'|required: true|required:" web/src/pages/user-setting/setting-model/provider-schema/field-config -g '*.ts' -g '*.tsx'Repository: infiniflow/ragflow
Length of output: 10599
🏁 Script executed:
set -e
printf '\n== generic api key config ==\n'
sed -n '1,120p' web/src/pages/user-setting/setting-model/provider-schema/field-config/generic-api-key-config.ts
printf '\n== one provider config with required api_key ==\n'
sed -n '1,130p' web/src/pages/user-setting/setting-model/provider-schema/field-config/provider-config-map.ts
printf '\n== dynamic form validation rules search ==\n'
rg -n "required:\\s*true|rules\\.|register\\(|trigger\\(" web/src/components/dynamic-form -g '*.ts' -g '*.tsx'Repository: infiniflow/ragflow
Length of output: 7305
🏁 Script executed:
set -e
printf '\n== dynamic form component outline ==\n'
fd -a 'dynamic-form*' web/src/components
printf '\n== dynamic form files ==\n'
git ls-files web/src/components/dynamic-form
printf '\n== dynamic form implementation slices ==\n'
sed -n '1,260p' web/src/components/dynamic-form/index.tsx
sed -n '260,520p' web/src/components/dynamic-form/index.tsxRepository: infiniflow/ragflow
Length of output: 402
🏁 Script executed:
set -e
printf '\n== dynamic form outline ==\n'
ast-grep outline web/src/components/dynamic-form.tsx --view expanded || true
printf '\n== dynamic form slice ==\n'
sed -n '1,260p' web/src/components/dynamic-form.tsx
printf '\n== provider fields / hideWhenInstanceExists ==\n'
sed -n '1,280p' web/src/pages/user-setting/setting-model/hooks.tsxRepository: infiniflow/ragflow
Length of output: 16151
🏁 Script executed:
set -e
printf '\n== dynamic-form render / shouldRender / trigger usage ==\n'
rg -n "shouldRender|trigger\\(|generateSchema|resolver|hidden" web/src/components/dynamic-form.tsx
printf '\n== dynamic-form render slice around field rendering ==\n'
sed -n '260,720p' web/src/components/dynamic-form.tsxRepository: infiniflow/ragflow
Length of output: 14984
🏁 Script executed:
set -e
printf '\n== fetch provider instances hook ==\n'
rg -n "useFetchProviderInstances|providerInstances|showProviderInstance" web/src -g '*.ts' -g '*.tsx'
printf '\n== API request bodies / response types ==\n'
rg -n "interface IProviderInstance|api_key.*response|showProviderInstance|provider instance" web/src -g '*.ts' -g '*.tsx'Repository: infiniflow/ragflow
Length of output: 4339
Validate only cards with a pending save web/src/pages/user-setting/setting-model/index.tsx:179-190
trigger() runs on every mounted card before getSavePayload() filters out untouched saves. For saved cards, a collapsed instance whose showProviderInstance details haven’t loaded yet can still fail on required api_key/base_url and block saving other cards. Validate drafts and dirty saved cards only, or gate saved-card validation on a non-null payload.
🤖 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 179 - 190,
Update the save flow around trigger() so untouched saved cards are not validated
before their payload is inspected. Validate draft cards and only dirty saved
cards, or derive getSavePayload() first and validate saved cards only when it
returns a non-null payload, while preserving the existing behavior of blocking
the save when any pending card is invalid.
| for (const { ref, payload } of entries) { | ||
| if (!payload) continue; | ||
| if (payload.apiKind === 'add') { | ||
| const ret = await addProviderInstance(payload.payload as any); | ||
| if (ret?.code !== 0) { | ||
| // Stop on the first failure so the user can see the error. | ||
| return; | ||
| } | ||
| // Remember the just-saved name so the persisted card mounts | ||
| // expanded once it surfaces via the invalidated instances | ||
| // query below. | ||
| if (payload.isDraft) { | ||
| setNewlySavedInstanceName(payload.instanceName); | ||
| } | ||
| } else { | ||
| const ret = await updateProviderInstance(payload.payload as any); | ||
| if (ret?.code !== 0) { | ||
| return; | ||
| } | ||
| // Saved card: update its dirty baseline so the next save | ||
| // short-circuits. Drafts are removed below so they don't | ||
| // need this. | ||
| ref.markSaved(); | ||
| } | ||
| } | ||
| }, | ||
| [ | ||
| addProviderInstance, | ||
| selection, | ||
| queryClient, | ||
| providerQueryName, | ||
| removeDraft, | ||
| ], | ||
| ); | ||
| // 4. Clear drafts (all valid drafts were just persisted) and | ||
| // invalidate the instance query so the newly-saved cards | ||
| // appear in the persisted list. | ||
| setDraftIds([]); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Persist per-card success state during the sequential batch.
If draft A succeeds and a later request fails, draft A remains visible and will be submitted again on retry. Additionally, saved Bedrock/SoMark cards using apiKind: 'add' never call markSaved(). Keep each entry’s ID, then remove successful drafts and re-baseline every successful saved card immediately.
🤖 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 203 - 231,
Update the sequential batch around addProviderInstance and
updateProviderInstance to track each entry’s ID and persist success per card
immediately. After any successful request, remove that entry’s ID from draft
state when it is a draft, and call ref.markSaved() for every successful saved
card, including apiKind: 'add'; retain failed entries for retry and avoid
clearing all drafts after a later failure.
| // Remember the just-saved name so the persisted card mounts | ||
| // expanded once it surfaces via the invalidated instances | ||
| // query below. | ||
| if (payload.isDraft) { | ||
| setNewlySavedInstanceName(payload.instanceName); | ||
| } | ||
| } else { | ||
| const ret = await updateProviderInstance(payload.payload as any); | ||
| if (ret?.code !== 0) { | ||
| return; | ||
| } | ||
| // Saved card: update its dirty baseline so the next save | ||
| // short-circuits. Drafts are removed below so they don't | ||
| // need this. | ||
| ref.markSaved(); | ||
| } | ||
| } | ||
| }, | ||
| [ | ||
| addProviderInstance, | ||
| selection, | ||
| queryClient, | ||
| providerQueryName, | ||
| removeDraft, | ||
| ], | ||
| ); | ||
| // 4. Clear drafts (all valid drafts were just persisted) and | ||
| // invalidate the instance query so the newly-saved cards | ||
| // appear in the persisted list. | ||
| setDraftIds([]); | ||
| queryClient.invalidateQueries({ | ||
| queryKey: LlmKeys.providerInstances(providerQueryName), | ||
| }); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Guard batch completion against provider changes.
The user can switch providers while these requests are pending. Completion from provider A can then call setDraftIds([]) and erase unsaved drafts created under provider B. Snapshot the batch provider and ignore stale state updates, or disable provider navigation while saving.
🤖 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 211 - 234,
The batch-save flow must ignore completion updates when the provider has changed
while requests are pending. Snapshot the active provider before starting the
batch, then guard setDraftIds([]), query invalidation, and related
saved-instance state updates so they only run if the current provider still
matches that snapshot; preserve normal completion behavior for the original
provider.
| const getSavePayload = useCallback(() => { | ||
| const trimmed = draftNameRef.current.trim(); | ||
| if (isDraft) { | ||
| if (!trimmed) return null; | ||
| const values = form.getValues(); | ||
| const payload = buildPayload(values, trimmed); | ||
| return { | ||
| payload, | ||
| instanceName: trimmed, | ||
| isDraft: true, | ||
| // Bedrock drafts use the add endpoint (no id). | ||
| apiKind: 'add' as const, | ||
| }; | ||
| } | ||
| const values = form.getValues(); | ||
| const payload = buildPayload(values, instance.instance_name); | ||
| const finalPayload = { | ||
| ...payload, | ||
| id: instanceDetails?.id || instance.id, | ||
| }; | ||
| const sig = JSON.stringify(finalPayload); | ||
| if (sig === lastSavedSigRef.current) return; | ||
| blurSavingRef.current = true; | ||
| try { | ||
| const ret = await addProviderInstance(finalPayload as any); | ||
| if (ret?.code === 0) { | ||
| lastSavedSigRef.current = sig; | ||
| } | ||
| } finally { | ||
| blurSavingRef.current = false; | ||
| } | ||
| if (sig === baselinePayloadRef.current) return null; | ||
| return { | ||
| payload: finalPayload, | ||
| instanceName: instance.instance_name, | ||
| isDraft: false, | ||
| // Bedrock saved cards update via `addProviderInstance` with an `id` | ||
| // (matches the legacy auto-save behaviour). | ||
| apiKind: 'add' as const, | ||
| }; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Specialized cards cannot participate in saved-instance renaming. Both new imperative implementations hardcode the persisted name.
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx#L354-L383: track and serialize the edited Bedrock name.web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx#L386-L415: track and serialize the edited SoMark name.
📍 Affects 2 files
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx#L354-L383(this comment)web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx#L386-L415
🤖 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/instance-card/bedrock-instance-card.tsx`
around lines 354 - 383, The imperative save payload builders must serialize the
edited instance name instead of always using the persisted name. In
web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx:354-383,
update getSavePayload to track and use the trimmed edited Bedrock name for saved
instances; apply the same change in
web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx:386-415
for the SoMark name, while preserving draft validation and existing payload
metadata.
| <div className="pt-3"> | ||
| <ModelsSection | ||
| providerName={providerName} | ||
| instanceName={instance.instance_name || '__draft__'} | ||
| instance={instance} | ||
| hideActions={false} | ||
| hideIfEmpty={false} | ||
| getFormValues={() => form.getValues()} | ||
| /> |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Persist draft model selections or remove this section.
Draft model mutations are local, but this ModelsSection has no onInstanceModelsChange connection and buildPayload() only serializes the form’s single model. Models selected here are therefore silently dropped by Save all.
🤖 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/instance-card/bedrock-instance-card.tsx`
around lines 589 - 597, Update the ModelsSection usage in the instance-card form
so draft model selections are wired through onInstanceModelsChange and included
by buildPayload() when saving all; alternatively remove this section if draft
model editing is not supported. Ensure selections are not kept only in local
state and silently discarded.
| {renaming ? ( | ||
| <Input | ||
| ref={renameInputRef} | ||
| value={renameValue} | ||
| onChange={(e) => setRenameValue(e.target.value)} | ||
| onBlur={commitRename} | ||
| onKeyDown={handleRenameKeyDown} | ||
| onClick={(e) => e.stopPropagation()} | ||
| onDoubleClick={(e) => e.stopPropagation()} | ||
| className="text-sm font-medium h-7" | ||
| data-testid="instance-name-rename-input" | ||
| /> | ||
| ) : ( | ||
| <div | ||
| className="text-sm font-medium truncate overflow-hidden flex-1 cursor-text" | ||
| onDoubleClick={(e) => { | ||
| e.stopPropagation(); | ||
| startRename(); | ||
| }} | ||
| title={tSetting('editInstanceName')} | ||
| data-testid="instance-name-static" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Make inline rename keyboard-accessible.
Rename can only be started by double-clicking a non-focusable <div>. Provide a focusable edit control with Enter/Space activation, and extract the newly added inline event handlers.
As per coding guidelines, “Do not define arrow functions directly on JSX event props; extract event handlers and reference named handlers instead.”
🤖 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/instance-card/components/saved-mode-card.tsx`
around lines 150 - 170, The inline rename trigger around the instance-name
static div is not keyboard-accessible and defines an event handler directly in
JSX. Replace or augment it with a focusable edit control that starts rename via
Enter and Space, extract the activation and existing double-click logic into
named handlers near startRename, and reference those handlers from JSX while
preserving event propagation behavior.
Source: Coding guidelines
| } else { | ||
| verifyArgs = { | ||
| api_key: values.api_key ?? '', | ||
| base_url: values.base_url ?? values.api_base, | ||
| model_info: values.model_info, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Include nested credentials in generic verification.
The save path bundles group_id, api_version, and provider_order through buildApiKeyValue, but verification sends only values.api_key. Providers requiring those fields will verify with incomplete credentials.
Proposed fix
} else {
verifyArgs = {
- api_key: values.api_key ?? '',
+ api_key: buildApiKeyValue(values) ?? '',
base_url: values.base_url ?? values.api_base,
model_info: values.model_info,
};📝 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.
| } else { | |
| verifyArgs = { | |
| api_key: values.api_key ?? '', | |
| base_url: values.base_url ?? values.api_base, | |
| model_info: values.model_info, | |
| } else { | |
| verifyArgs = { | |
| api_key: buildApiKeyValue(values) ?? '', | |
| base_url: values.base_url ?? values.api_base, | |
| model_info: values.model_info, |
🤖 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/instance-card/hooks.tsx` around
lines 336 - 340, Update the generic verification payload in the else branch of
the save flow to use the same credential-building logic as buildApiKeyValue,
including group_id, api_version, and provider_order rather than only
values.api_key. Keep the existing base_url, model_info, and other verification
fields unchanged.
| const baseline = { | ||
| provider_name: providerName, | ||
| instance_name: instanceName, | ||
| id: resolvedId, | ||
| api_key: buildApiKeyValue(initialValues), | ||
| base_url: initialValues.base_url ?? initialValues.api_base, | ||
| region: initialValues.region, | ||
| // model_info baseline is `[]`; `markModelsEdited` rewrites it after | ||
| // a model PATCH so the next top-save short-circuits. The first | ||
| // save after the models initially load may re-send the same | ||
| // model_info (idempotent) - acceptable, matches the old | ||
| // `lastSavedPayloadRef` seeding behaviour. | ||
| model_info: [] as IModelInfo[], | ||
| verify: false, | ||
| }; | ||
| lastSavedPayloadRef.current = JSON.stringify(baseline); | ||
| baselinePayloadRef.current = JSON.stringify(baseline); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Build the baseline through the same canonical payload path.
This baseline bypasses submitTransform and also differs on defaults such as api_key (undefined versus '') and region (undefined versus 'default'). Untouched saved cards can therefore appear dirty and be overwritten by “Save all.” Extract one payload normalizer and use it for both baseline and current signatures.
🤖 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/instance-card/hooks.tsx` around
lines 568 - 583, Extract a shared canonical payload normalizer from
submitTransform and use it to build both the baseline signature and current save
signatures. Update the baseline construction near baselinePayloadRef.current to
pass the same source values through this normalizer, preserving canonical
defaults such as api_key and region and avoiding a separately assembled payload
that can mark untouched cards dirty.
| /** | ||
| * Local mutators for the draft instance's model list. Required when | ||
| * `isDraftInstance` is true so per-model add / remove / batch updates | ||
| * stay local until the host saves the instance. Ignored for saved | ||
| * cards (the backend mutations below fire as before). | ||
| */ | ||
| addDraftModel?: (model: IProviderModelItem) => void; | ||
| removeDraftModel?: (name: string) => void; | ||
| setDraftModelsList?: (models: IProviderModelItem[]) => void; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Keep draft model edits local as well.
The new draft contract covers add/remove/batch operations, but useModelEdit.handleEditSubmit() still PATCHes instanceName, which is __draft__ for unsaved cards. Add an updateDraftModel callback and skip the backend request for drafts.
🤖 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/instance-card/models-section/hooks.ts`
around lines 462 - 470, Extend the draft mutator contract beside addDraftModel,
removeDraftModel, and setDraftModelsList with an updateDraftModel callback, then
update useModelEdit.handleEditSubmit() to invoke it for draft instances instead
of PATCHing instanceName (__draft__). Preserve the existing backend update path
for saved cards.
| // ── Save state (payload builder + dirty tracking) ─────────────── | ||
| const { getSavePayload, markSaved, markModelsEdited } = useInstanceSaveState({ | ||
| formRef, | ||
| providerName, | ||
| instanceName: instance.instance_name, | ||
| editedInstanceName, | ||
| instanceId: instance.id, | ||
| isDraft, | ||
| nameSaved, | ||
| draftName, | ||
| isDraft ? onSaved : undefined, | ||
| instanceDetails, | ||
| initialValues, | ||
| modelInfoRef, | ||
| ); | ||
| submitTransform: providerConfig.submitTransform, | ||
| }); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Load full instance details before saving a collapsed rename.
A collapsed card can be renamed before its credentials and models are fetched. getSavePayload() then builds a full update from incomplete form defaults and an empty modelInfoRef, potentially clearing api_key, base_url, or model_info. Fetch details before enabling/saving rename, or use a sparse rename operation.
Also applies to: 231-234
🤖 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/instance-card/provider-instance-card.tsx`
around lines 165 - 178, Update the save flow around useInstanceSaveState and its
getSavePayload usage so a collapsed instance cannot perform a full rename save
until its credentials and models have been loaded. Ensure the details fetch
completes before enabling or submitting the rename, or route collapsed renames
through a sparse update that preserves api_key, base_url, and model_info; apply
the same protection to the additional rename path.
wangq8
left a comment
There was a problem hiding this comment.
Review: PR #17025 — fix(model-provider): replace per-card auto-save with batch Save-all (+1314/-1271, 14 files)
Summary
A major UX refactor of the model provider settings page. Removes the per-card auto-save (blur/change-driven saves per instance card) and replaces it with a single "Save all" button at the top of the provider pane. Draft cards no longer have the two-stage "save name first, then edit fields" gating — all fields are editable from the start, and the parent drives persistence through an imperative ref API.
Author: @dcc123456
What changed (14 files)
| File | Δ | Key changes |
|---|---|---|
setting-model/index.tsx |
+150/-68 | Added cardRefs registry, handleSaveAll batch save, saving/canSave state; removed handleDraftSave/handleNameSaved |
instance-card/hooks.tsx |
+266/-374 | Removed useDraftAutoSave, useSaveInstanceName, added verifyTransform to useVerifyProvider, new useInstanceSaveState w/ baseline dirty tracking |
instance-card/interface.ts |
+66/-16 | Added ProviderInstanceCardRef (validate, getSavePayload, markSaved), InstanceSavePayload type |
bedrock-instance-card.tsx |
+172/-283 | Converted to forwardRef, removed auto-save / blur-save / watch-save, added baseline dirty tracking via baselinePayloadRef |
somark-instance-card.tsx |
+184/-308 | Same pattern as bedrock card |
provider-instance-card.tsx |
+148/-94 | Converted to forwardRef, dispatches to bedrock/somark/component sub-cards, exposes imperative ref |
saved-mode-card.tsx |
+101/-21 | Removed handleFieldsBlur, added inline rename (double-click → input → Enter/blur commit) |
draft-mode-card.tsx |
+35/-43 | Removed fieldset lock & handleSaveName — all fields editable from start |
provider-header-bar.tsx |
+60/-7 | Added batch Save button with spinner |
instance-name-section.tsx |
+7/-29 | Removed Save button, Enter-to-save, helper text |
models-section/hooks.ts |
+88/-16 | Added updateDraftModel callback, removed onBlurSuppressRef from ModelsSection props |
models-section/index.tsx |
+35/-4 | Removed onBlurSuppressRef threading, keep API-key gate |
locales/en.ts / zh.ts |
+2/-8 | Added saveAll, removed instanceNameSaveTip/instanceNameSavePrompt/instanceNameLockedHint |
✅ What's good
-
Clear UX improvement. The per-card auto-save was fragile — debounce timing, blur vs click race conditions, portal-based controls not triggering blurs, and failed saves silently lost data. A single explicit "Save all" button is far more predictable.
-
Clean imperative ref API.
ProviderInstanceCardRefwithvalidate(),getSavePayload(),markSaved()gives the parent full control while keeping card logic encapsulated. The type is well-defined ininterface.ts. -
Dirty tracking is solid. Using
JSON.stringify(baselinePayloadRef)vs current payload to skip redundant saves is simple and correct. The baseline is rebuilt on details load. -
Two-stage gating removed. The name-save-first pattern was confusing UX — "save the name to unlock the form." Now all fields are editable immediately. This is a better UX pattern.
-
Inline rename for saved cards. Double-click the name to edit it, Enter/blur to commit, Escape to cancel. Clean and expected behavior.
-
Sequential batch save with error handling.
handleSaveAllstops on first failure, preserving the error in the form UI. No silent data loss. -
Cross-card consistency. Bedrock, SoMark, and generic cards all follow the same pattern now —
forwardRefwithvalidate+getSavePayload+markSaved.
🔍 Concerns
🔴 Functional issues flagged by CodeRabbit (11 items)
Several of these merit attention before merge:
-
ModelsSection API-key gate is not reactive —
DynamicFormchanges don't trigger re-render ofModelsSection, so if a draft is mounted with an empty key, typing a key later won't auto-fetch available models. This is a real UX issue. -
Collapsed-card rename safety — If a collapsed card hasn't fetched its instance details yet, the rename
getSavePayloadcould send a sparse payload that overwrites credentials/models. A collapsed rename should either fetch details first or route through a sparse update. -
getSavePayloadfor Bedrock/SoMark may not include the edited instance name — The inline rename updateseditedInstanceName, butbuildPayloadinsidegetSavePayloadreferencesinstance.instance_namenoteditedInstanceNamefor saved cards. Need to verify the rename value flows into the save payload. -
Sequential batch API calls — One
awaitper dirty card. If a user has 10 dirty cards and the 3rd fails, cards 4-10 are never saved. The user must fix the error and re-save everything. Consider collecting failures and continuing, or at least adding a log.
🟡 Code quality / architecture
-
1314 lines changed is high risk. This is effectively a rewrite of the instance card module. Given that auto-save and the draft lifecycle were central to the prior architecture, the surface for regressions is broad.
-
canSaveis a conservative proxy.draftIds.length > 0 || instances.length > 0means the Save button is enabled even when no card is actually dirty. This is fine UX-wise (saving a clean state is a no-op) but could be misleading. The button label and disabled state could be more precise. -
Inline rename accessibility. The rename is triggered by
onDoubleClickonly — no keyboard-triggered way to start a rename. Consider also adding a right-click context menu or an edit button for keyboard users. (CodeRabbit flagged this.) -
useVerifyProvidernow accepts averifyTransform— This is good for providers like OpenDataLoader with non-standard field names. But it's only wired for the generic card path; Bedrock/SoMark cards don't pass one. This is consistent since those cards build their own verify payloads, but worth verifying there's no regression.
🟠 Locales cleanup
Removing instanceNameSaveTip, instanceNameSavePrompt, instanceNameLockedHint is correct (the two-stage name gate is gone). There are no remaining references to these keys.
🟣 Test coverage
I don't see test changes in the diff. Given the extent of the refactor, adding or updating tests for the batch save flow would be valuable — specifically:
- Validate that
getSavePayloadreturnsnullfor clean saved cards - Validate that
getSavePayloadreturns a payload for dirty cards - Validate the batch
handleSaveAllflow with multiple cards
🔮 Regression risk
Moderate. The refactor is thorough and the new architecture is cleaner, but:
- Every card type (generic, Bedrock, SoMark) was substantially rewritten
- The auto-save → batch-save transition touches every user interaction path (edit, verify, delete, collapse/expand)
- 11 CodeRabbit findings remain unaddressed, including functional issues
I would recommend addressing the functional CodeRabbit items (especially the reactive API-key gate and collapsed-card rename safety) before merging. The architectural direction is strong; the execution needs a final polish pass.
🏁 Verdict
Approve with reservations
Summary
fix(model-provider): replace per-card auto-save with batch Save-all