Skip to content

fix(model-provider): replace per-card auto-save with batch Save-all - #17025

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
dcc123456:fix/model-provider-save
Jul 17, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
dcc123456:fix/model-provider-save

Conversation

@dcc123456

Copy link
Copy Markdown
Collaborator

Summary

fix(model-provider): replace per-card auto-save with batch Save-all

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code labels Jul 17, 2026
@dcc123456
dcc123456 requested a review from wangq8 July 17, 2026 03:15
@dcc123456 dcc123456 added 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration labels Jul 17, 2026
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Provider instance save workflow

Layer / File(s) Summary
Save contracts and card orchestration
web/src/pages/user-setting/setting-model/instance-card/interface.ts, web/src/pages/user-setting/setting-model/instance-card/hooks.tsx, web/src/pages/user-setting/setting-model/instance-card/*-instance-card.tsx
Provider cards now expose imperative validation, payload, and baseline methods, replacing card-level auto-save with parent-controlled persistence.
Draft and saved card editing
web/src/pages/user-setting/setting-model/instance-card/components/*
Draft forms are immediately editable, and saved instance names support inline rename with blur, Enter, and Escape handling.
Draft model catalog and mutations
web/src/pages/user-setting/setting-model/instance-card/models-section/*
Draft model additions, removals, and batch toggles are maintained locally until the instance is saved. Catalog fetching uses current credentials.
Page-level batch save and localization
web/src/pages/user-setting/setting-model/index.tsx, web/src/pages/user-setting/setting-model/layout/provider-header-bar.tsx, web/src/locales/*
The settings page validates and persists dirty cards through a top-level Save button, with updated API/documentation links and translations.

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
Loading

Possibly related PRs

Suggested reviewers: lynn-inf

Poem

I’m a rabbit with buttons to press,
Saving all cards in one neat success.
Draft models hop into line,
Names rename with a double-click shine,
And stale auto-saves vanish from sight.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 76.47% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description only repeats the title and lacks the required brief summary and background context. Add a short Summary section explaining what the PR changes and why, with enough context for reviewers.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly matches the main change: replacing per-card auto-save with a batch Save all flow.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@dcc123456
dcc123456 marked this pull request as draft July 17, 2026 03:15
@dcc123456
dcc123456 marked this pull request as ready for review July 17, 2026 03:15

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Give 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 lift

Make the API-key gate reactive.

Typing into DynamicForm does not rerender ModelsSection, so a VolcEngine draft mounted with an empty key retains credsReady = false and never auto-fetches after the key is entered. Subscribe with the form’s watch() 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 win

Use useTranslation directly.

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 win

Remove the duplicated compatibility prop surfaces.

  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx#L76-L95: type the component with canonical ProviderInstanceCardProps.
  • 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 canonical ProviderInstanceCardProps.
  • 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 win

Extract 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c698f8 and d36ff7f.

📒 Files selected for processing (14)
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/instance-name-section.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/somark-instance-card.tsx
  • web/src/pages/user-setting/setting-model/layout/provider-header-bar.tsx

Comment on lines +179 to +190
// 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.ts

Repository: 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.tsx

Repository: 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.tsx

Repository: 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.tsx

Repository: 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.tsx

Repository: 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.

Comment on lines +203 to +231
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([]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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.

Comment on lines +211 to +234
// 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),
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Comment on lines +354 to +383
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,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Comment on lines +589 to +597
<div className="pt-3">
<ModelsSection
providerName={providerName}
instanceName={instance.instance_name || '__draft__'}
instance={instance}
hideActions={false}
hideIfEmpty={false}
getFormValues={() => form.getValues()}
/>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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.

Comment on lines +150 to +170
{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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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

Comment on lines +336 to +340
} else {
verifyArgs = {
api_key: values.api_key ?? '',
base_url: values.base_url ?? values.api_base,
model_info: values.model_info,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Suggested change
} 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.

Comment on lines 568 to +583
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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.

Comment on lines +462 to +470
/**
* 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Comment on lines +165 to +178
// ── 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,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

  1. 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.

  2. Clean imperative ref API. ProviderInstanceCardRef with validate(), getSavePayload(), markSaved() gives the parent full control while keeping card logic encapsulated. The type is well-defined in interface.ts.

  3. 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.

  4. 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.

  5. Inline rename for saved cards. Double-click the name to edit it, Enter/blur to commit, Escape to cancel. Clean and expected behavior.

  6. Sequential batch save with error handling. handleSaveAll stops on first failure, preserving the error in the form UI. No silent data loss.

  7. Cross-card consistency. Bedrock, SoMark, and generic cards all follow the same pattern now — forwardRef with validate + getSavePayload + markSaved.

🔍 Concerns

🔴 Functional issues flagged by CodeRabbit (11 items)

Several of these merit attention before merge:

  • ModelsSection API-key gate is not reactive — DynamicForm changes don't trigger re-render of ModelsSection, 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 getSavePayload could send a sparse payload that overwrites credentials/models. A collapsed rename should either fetch details first or route through a sparse update.

  • getSavePayload for Bedrock/SoMark may not include the edited instance name — The inline rename updates editedInstanceName, but buildPayload inside getSavePayload references instance.instance_name not editedInstanceName for saved cards. Need to verify the rename value flows into the save payload.

  • Sequential batch API calls — One await per 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.

  • canSave is a conservative proxy. draftIds.length > 0 || instances.length > 0 means 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 onDoubleClick only — 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.)

  • useVerifyProvider now accepts a verifyTransform — 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 getSavePayload returns null for clean saved cards
  • Validate that getSavePayload returns a payload for dirty cards
  • Validate the batch handleSaveAll flow 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 ⚠️ — the direction is correct and the new architecture is much cleaner than the auto-save approach. However, the 11 CodeRabbit findings include real functional concerns (non-reactive ModelsSection key gate, collapsed-rename safety, rename value propagation) that should be addressed before merge.

@wangq8
wangq8 merged commit c5cf9b4 into infiniflow:main Jul 17, 2026
13 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants