Skip to content

feat: 二次确认添加重定向前模型 && 重定向后模式视为已有模型 - #2277

Merged
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
seefs001:feature/model_list_fetch
Nov 23, 2025
Merged

feat: 二次确认添加重定向前模型 && 重定向后模式视为已有模型#2277
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
seefs001:feature/model_list_fetch

Conversation

@seefs001

@seefs001 seefs001 commented Nov 22, 2025

Copy link
Copy Markdown
Collaborator

fix #2198 #2187

Summary by CodeRabbit

New Features

  • Added model redirect mapping suggestions in channel configuration dialogs, helping users identify redirected models
  • Visual indicators now display for models derived from redirect mappings with informational tooltips
  • Added confirmation dialog when mapped models are missing from the model list, with options to add them or proceed

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Nov 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Extract and normalize model redirect configurations from channel model mappings to enable models defined in redirects to be treated as available during channel setup. Updates EditChannelModal and ModelSelectModal to validate, deduplicate, and display mapped models, with UI indicators for redirected-only models.

Changes

Cohort / File(s) Summary
Edit Modal: Model Mapping & Redirect Logic
web/src/components/table/channels/modals/EditChannelModal.jsx
Adds redirectModelList memoized function to extract, validate, and normalize model redirect values from model_mapping JSON. Introduces initialModelsRef and initialModelMappingRef to track initial channel data for change detection. Adds hasModelConfigChanged logic to detect model or mapping differences. Introduces confirmMissingModelMappings modal function offering cancel/submit/add options when mapped models are absent from the model list. Modifies submit workflow to parse and validate model_mapping, normalize models (trim/dedupe), and optionally augment models list with missing redirects. Passes normalized redirectModelList to ModelSelectModal as redirectModels prop. Implements early reset behavior for new/edit state transitions.
Model Selection: Redirect Display & Categorization
web/src/components/table/channels/modals/ModelSelectModal.jsx
Adds redirectModels prop to component signature. Introduces useMemo-based performance optimizations to normalize and deduplicate model names, deriving normalizedRedirectModels, normalizedSelectedSet, classificationSet (union of selected and redirect models), and redirectOnlySet (redirect-exclusive models). Replaces direct string checks with centralized isExistingModel() helper based on classificationSet. Updates model filtering to safely coerce null/undefined to lowercase strings. Reworks model categorization logic using isExistingModel for new vs. existing determination. Enhances UI rendering with conditional Tooltip (via new imports of Tooltip and IconInfoCircle components) displaying "来自模型重定向,尚未加入模型列表" label next to redirect-only models.

Sequence Diagram

sequenceDiagram
    participant User
    participant EditChannelModal
    participant ModelSelectModal
    participant Validation

    User->>EditChannelModal: Open channel editor
    EditChannelModal->>EditChannelModal: Extract redirectModelList from model_mapping JSON
    EditChannelModal->>EditChannelModal: Store initial models & mapping in refs
    
    User->>ModelSelectModal: Open model selection
    EditChannelModal->>ModelSelectModal: Pass redirectModels (normalized redirect values)
    ModelSelectModal->>ModelSelectModal: Classify models (existing vs new vs redirect-only)
    ModelSelectModal->>User: Render models with Tooltip for redirect-only items

    User->>EditChannelModal: Modify models & submit
    EditChannelModal->>Validation: Compare with initial state (hasModelConfigChanged)
    
    alt Models in mapping but not in list
        Validation->>EditChannelModal: Check for missing models
        EditChannelModal->>User: Show confirmMissingModelMappings modal
        User->>EditChannelModal: Choose action (cancel/submit/add missing)
        opt User selects "add missing"
            EditChannelModal->>EditChannelModal: Augment models list with missing redirects
        end
    end
    
    EditChannelModal->>EditChannelModal: Normalize final models (trim, dedupe)
    EditChannelModal->>Validation: Submit with normalized models & mapping
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40–50 minutes

Areas requiring extra attention:

  • Model normalization and deduplication logic in redirectModelList and the memoized derivations in ModelSelectModal to ensure no edge cases are missed (null/undefined handling, JSON parsing resilience)
  • Change detection mechanism across initialModelsRef and initialModelMappingRef — verify refs are properly initialized, cleared, and compared
  • Modal confirmation flow in confirmMissingModelMappings and the branching logic to add missing models; test all three user choices
  • Integration between EditChannelModal and ModelSelectModal prop passing, particularly the flow of redirectModels and its impact on existing model selection workflows
  • UI rendering correctness for the Tooltip and InfoIcon placement within model checkboxes, especially for accessibility and styling
  • Edge cases: empty mapping, invalid JSON in model_mapping, duplicate models in both list and redirects

Poem

🐰 A clever redirect, we hop with glee—
Models that map where they're meant to be!
No extra names in the list to add,
Just follow the mapping, now isn't that rad? ✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: implementing secondary confirmation for adding pre-redirect models and treating post-redirect models as existing models.
Linked Issues check ✅ Passed The PR implements the core requirement from issue #2198: models defined via redirection are now treated as available without requiring manual addition to the channel list.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing model redirection functionality and treating redirected models as existing models, which aligns with the stated objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 and usage tips.

@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: 0

🧹 Nitpick comments (5)
web/src/components/table/channels/modals/ModelSelectModal.jsx (2)

41-46: Redirect model normalization & classification look correct; consider minor hook-deps cleanup

The logic around redirectModels, normalizedRedirectModels, normalizedSelectedSet, and classificationSet correctly treats both selected models and redirect targets as “existing”, which aligns with the need to surface redirect targets in the existing-model tab. Using Set + useMemo is a good choice for performance and deduping.

One minor point: normalizeModelName is used inside the useMemo hooks but is not part of their dependency arrays. This is semantically safe here (no external closure state), but it may trip react-hooks/exhaustive-deps. If that lint rule is enabled, consider wrapping normalizeModelName in useCallback and adding it to the dependency arrays, or adding an inline disable if you intentionally rely on the current behavior.

Also applies to: 55-91, 94-94, 98-103


272-285: Redirect-only tooltip integration is reasonable; watch translation and accessibility

Showing an info icon + tooltip for models in redirectOnlySet is a nice way to surface “redirect-only, not in models list” status, and the normalization with normalizeModelName keeps it consistent with earlier sets.

Just ensure the translation key for t('来自模型重定向,尚未加入模型列表') is added, and consider whether the IconInfoCircle inside Tooltip needs any ARIA attributes for screen readers beyond what Tooltip already provides.

web/src/components/table/channels/modals/EditChannelModal.jsx (3)

247-248: Change-detection for models/mapping works but is order- and formatting-sensitive

Using initialModelsRef / initialModelMappingRef plus hasModelConfigChanged gives you a clear way to only prompt about missing mapped models when the model configuration actually changed, which is good.

Note, though:

  • normalizedModels are compared to initialModels by index, so reordering the same set of models will count as a change.
  • model_mapping is compared as trimmed strings, so reformatting or reordering keys (without semantic change) will also be treated as “changed”.

If you’d prefer purely semantic detection, you could compare model sets (e.g., sorted arrays or Sets) and parse model_mapping to compare objects instead of strings; otherwise the current behavior is acceptable but a bit more eager to show the confirmation dialog.

Also applies to: 624-627, 863-868, 1001-1015


943-999: Missing-model confirmation flow is good; ensure the confirm modal always resolves the Promise

The confirmMissingModelMappings helper and its integration in submit nicely implement the “second confirmation” flow and give users three clear choices (cancel / submit / add), with the 'add' branch correctly merging missingModels into localInputs.models and syncing via handleInputChange.

One edge case: the Modal.confirm config doesn’t specify an onCancel handler. If Semi UI’s confirm dialog can be closed via overlay click or ESC, the returned Promise may never resolve, leaving await confirmMissingModelMappings(...) hanging. To be safe, consider wiring onCancel to modal.destroy(); resolve('cancel'); so that every close path settles the Promise.

Please confirm from @douyinfe/semi-ui docs whether Modal.confirm is non-closable by mask/ESC by default; if it is closable, adding onCancel as described would avoid a stuck submit flow.

Also applies to: 1123-1146


1100-1115: Model mapping validation and model normalization are sensible; minor duplication only

The new block that:

  • checks model_mapping is a non-empty string,
  • validates it via verifyJSON + JSON.parse with user-friendly messages, and
  • then normalizes localInputs.models by trimming and filtering empties,

is sound and will prevent malformed mappings from slipping through while also cleaning up the model list.

There is a small duplication in that verifyJSON already parses the JSON and then you call JSON.parse again; if you want to micro-optimize, you could skip verifyJSON here and rely on a single try/catch JSON.parse with the same error message. Functionally, though, the current implementation is fine.

Also applies to: 1117-1121

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between efb8f1f and 7a2bd38.

📒 Files selected for processing (2)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (7 hunks)
  • web/src/components/table/channels/modals/ModelSelectModal.jsx (4 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the applyModelMapping function transforms the models list by replacing original model names (mapping values) with display names (mapping keys). The database stores this transformed list containing mapped keys. On channel load, data.models contains these mapped display names, making the initialization filter if (data.models.includes(key)) correct.
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the database stores mapped keys (display names) in the models field after applying model mapping transformations. When loading a channel, data.models contains the mapped keys, not the original model names. The filtering logic if (data.models.includes(key)) in the initialization is correct.
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the applyModelMapping function transforms the models list by replacing original model names (mapping values) with display names (mapping keys). The database stores this transformed list containing mapped keys. On channel load, data.models contains these mapped display names, making the initialization filter if (data.models.includes(key)) correct.

Applied to files:

  • web/src/components/table/channels/modals/ModelSelectModal.jsx
  • web/src/components/table/channels/modals/EditChannelModal.jsx
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the database stores mapped keys (display names) in the models field after applying model mapping transformations. When loading a channel, data.models contains the mapped keys, not the original model names. The filtering logic if (data.models.includes(key)) in the initialization is correct.

Applied to files:

  • web/src/components/table/channels/modals/ModelSelectModal.jsx
  • web/src/components/table/channels/modals/EditChannelModal.jsx
🧬 Code graph analysis (1)
web/src/components/table/channels/modals/EditChannelModal.jsx (1)
web/src/helpers/utils.jsx (5)
  • i (468-468)
  • i (480-480)
  • verifyJSON (265-272)
  • verifyJSON (265-272)
  • showInfo (161-163)
🔇 Additional comments (1)
web/src/components/table/channels/modals/EditChannelModal.jsx (1)

193-216: Redirect model extraction for ModelSelectModal is robust and aligned with intent

redirectModelList cleanly parses inputs.model_mapping, validates it’s a non-array object, trims string values, dedupes with Set, and gracefully falls back to [] on invalid/empty JSON. Passing this as redirectModels into ModelSelectModal is a solid way to mark redirect targets as “existing” when fetching upstream models.

No functional issues stand out here.

Also applies to: 3067-3072

@Calcium-Ion
Calcium-Ion merged commit a465597 into QuantumNous:main Nov 23, 2025
1 check passed
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
…fetch

feat: 二次确认添加重定向前模型 && 重定向后模式视为已有模型
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

渠道模型重定向中定义的模型应该调用时认为存在,而非在调用时报错此模型不存在

2 participants