Repository navigation
Conversation
…port - Fix aliVoiceCloneHandler to properly handle unmarshal errors - Use cloneResp.Usage.Count instead of estimated prompt tokens to avoid overcharging Qwen list/delete operations - Set VoiceCloneFixedPrice context for MiniMax speech model clone responses - Add ContextKeyVoiceCloneFixedPrice and fixed-price billing in PostAudioConsumeQuota - Add unit test for MiniMax voice clone unlock price setting - Add VoiceCloneUnlockRatio support in classic frontend pricing settings - Fix classic frontend build compatibility (pin deps, remove vitePluginSemi, add icon fallbacks for new providers) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
… and upstream error Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds a new audio voice-clone relay mode with DTO/validation, adaptor/handler implementations for Ali and MiniMax, ratio-setting persistence/exposure (voice_clone_unlock_ratio, video_resolution_ratio), quota/billing changes including fixed unlock price, frontend UI wiring, tests, and a Docker CI workflow. ChangesVoice Clone Audio Relay & Pricing
Sequence Diagram: sequenceDiagram
participant Client
participant Router
participant Validator
participant RelayHandler
participant ChannelAdaptor
participant UpstreamService
participant QuotaService
Client->>Router: POST /v1/audio/voice-clone
Router->>Validator: GetAndValidAudioVoiceCloneRequest
Validator->>RelayHandler: AudioVoiceCloneRequest
RelayHandler->>ChannelAdaptor: ConvertAudioRequest (Ali/MiniMax)
ChannelAdaptor->>UpstreamService: upstream TTS/voice-clone request
UpstreamService-->>ChannelAdaptor: response (audio/json + usage)
ChannelAdaptor->>RelayHandler: parsed response + token usage
RelayHandler->>QuotaService: PostAudioConsumeQuota (may include fixed price)
QuotaService-->>RelayHandler: quota settled
RelayHandler->>Client: audio/json + usage metadata
Estimated code review effort: Possibly related PRs
Suggested reviewers
✨ Finishing Touches🧪 Generate unit tests (beta)
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: 16
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
web/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.js (1)
246-280:⚠️ Potential issue | 🟠 Major | ⚡ Quick winVoice clone unlock price incorrectly treated as inputPrice-dependent.
voiceCloneUnlockPriceis a fixed price per voice-clone operation and does not depend oninputPrice. Including it inhasDerivedPricing(line 254) and the rawRatios warning check (line 272) causes incorrect warnings when users set voice clone pricing without setting inputPrice.This misclassification results in:
- Line 287: false warning "按量计费下需要先填写输入价格,才能保存其它价格项" when only voice clone price is set
- Line 275-279: misleading warning about "未显式设置输入倍率的扩展倍率" for a field that isn't a ratio
Recommended fix
const hasDerivedPricing = [ model.inputPrice, model.completionPrice, model.cachePrice, model.createCachePrice, model.imagePrice, model.audioInputPrice, model.audioOutputPrice, - model.voiceCloneUnlockPrice, ].some(hasValue); ... if ( !hasValue(model.inputPrice) && [ model.rawRatios.completionRatio, model.rawRatios.cacheRatio, model.rawRatios.createCacheRatio, model.rawRatios.imageRatio, model.rawRatios.audioRatio, model.rawRatios.audioCompletionRatio, - model.rawRatios.voiceCloneUnlockRatio, ].some(hasValue) ) {🤖 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/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.js` around lines 246 - 280, The code incorrectly treats voiceCloneUnlockPrice/voiceCloneUnlockRatio as derived from inputPrice; remove model.voiceCloneUnlockPrice from the hasDerivedPricing array and remove model.rawRatios.voiceCloneUnlockRatio from the rawRatios.some(...) check so voice clone unlock remains a standalone fixed-price item (update the arrays referenced in useModelPricingEditorState: hasDerivedPricing and the rawRatios list used for the inputPrice-dependent warning).web/default/src/features/system-settings/models/model-ratio-visual-editor.tsx (1)
1069-1083:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCustom
memoequality check is missingvoiceCloneUnlockRatiocomparison.The component won't re-render when
voiceCloneUnlockRatioprop changes because it's not included in the equality check. This will cause stale data to be displayed.🐛 Fix: Add voiceCloneUnlockRatio to memo equality check
(prevProps, nextProps) => { return ( prevProps.modelPrice === nextProps.modelPrice && prevProps.modelRatio === nextProps.modelRatio && prevProps.cacheRatio === nextProps.cacheRatio && prevProps.createCacheRatio === nextProps.createCacheRatio && prevProps.completionRatio === nextProps.completionRatio && prevProps.imageRatio === nextProps.imageRatio && prevProps.audioRatio === nextProps.audioRatio && prevProps.audioCompletionRatio === nextProps.audioCompletionRatio && + prevProps.voiceCloneUnlockRatio === nextProps.voiceCloneUnlockRatio && prevProps.billingMode === nextProps.billingMode && prevProps.billingExpr === nextProps.billingExpr && prevProps.onChange === nextProps.onChange ) }🤖 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/default/src/features/system-settings/models/model-ratio-visual-editor.tsx` around lines 1069 - 1083, The custom memo equality comparator (the arrow function passed to React.memo in the ModelRatioVisualEditor component) omits the voiceCloneUnlockRatio prop, so updates to voiceCloneUnlockRatio won't trigger re-renders; update the comparator to include a comparison for prevProps.voiceCloneUnlockRatio === nextProps.voiceCloneUnlockRatio alongside the existing checks (e.g., add this check with the other prop comparisons such as modelPrice, modelRatio, cacheRatio, etc.) so the component will re-render when voiceCloneUnlockRatio changes.relay/channel/minimax/tts.go (1)
123-196:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winUse
common.Unmarshalinstead ofencoding/json.Line 136 uses
encoding/json.Unmarshaldirectly for application-level response parsing. As per coding guidelines, all JSON marshal/unmarshal operations in business code must use wrapper functions fromcommon/json.go.🔧 Proposed fix
+ "github.com/QuantumNous/new-api/common"Then update line 136:
// Parse response var minimaxResp MiniMaxTTSResponse - if unmarshalErr := json.Unmarshal(body, &minimaxResp); unmarshalErr != nil { + if unmarshalErr := common.Unmarshal(body, &minimaxResp); unmarshalErr != nil { return nil, types.NewErrorWithStatusCode( fmt.Errorf("failed to unmarshal minimax TTS response: %w", unmarshalErr), types.ErrorCodeBadResponseBody, http.StatusInternalServerError, ) }As per coding guidelines:
**/*.go: Use wrapper functions fromcommon/json.gofor all JSON marshal/unmarshal operations.🤖 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 `@relay/channel/minimax/tts.go` around lines 123 - 196, The code in handleTTSResponse uses encoding/json.Unmarshal to parse the MiniMaxTTSResponse; replace that call with the project wrapper common.Unmarshal (the helper from common/json.go) when unmarshalling into the MiniMaxTTSResponse variable (minimaxResp) and propagate its error into the existing types.NewErrorWithStatusCode error path exactly where json.Unmarshal is currently used so behavior and error wrapping remain the same.web/classic/package.json (1)
77-90:⚠️ Potential issue | 🟠 Major | ⚡ Quick winFix vite lockfile mismatch vs peerDependency.
web/classic/package.jsonpinsviteto5.1.0, and@douyinfe/vite-plugin-semideclares an exact peerDependency onvite: "5.1.0", butweb/classic/bun.lockresolvesvite@5.4.11. Update/regeneratebun.lockso the lockedviteversion matches the pinned5.1.0(or adjust the package.json versions consistently).🤖 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/classic/package.json` around lines 77 - 90, package.json pins "vite": "5.1.0" while `@douyinfe/vite-plugin-semi` requires vite 5.1.0 but bun.lock currently resolves vite@5.4.11; fix by making the declared and locked vite versions consistent: either update web/classic/package.json's "vite" entry to the resolved 5.4.11 (or a compatible range) and then regenerate bun.lock, or keep "vite": "5.1.0" and delete/regenerate web/classic/bun.lock so it locks 5.1.0; regenerate the lockfile by removing bun.lock (if necessary) and running bun install (or the project’s standard lock regen command) so bun.lock matches the package.json and satisfies `@douyinfe/vite-plugin-semi`'s peerDependency.
🧹 Nitpick comments (4)
setting/ratio_setting/model_ratio.go (1)
809-815: 💤 Low valueConsider normalizing model name in
GetVoiceCloneUnlockRatio.Other ratio getters like
GetAudioRatioandGetModelRatiocallFormatMatchingModelName(name)before lookup. This function doesn't, which may cause lookup failures for models with thinking budget suffixes or gizmo patterns.♻️ Suggested fix
func GetVoiceCloneUnlockRatio(name string) (float64, bool) { + name = FormatMatchingModelName(name) ratio, ok := voiceCloneUnlockRatioMap.Get(name) if !ok { return 0, false } return ratio, true }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@setting/ratio_setting/model_ratio.go` around lines 809 - 815, Normalize the incoming model name with FormatMatchingModelName before looking up in voiceCloneUnlockRatioMap: in GetVoiceCloneUnlockRatio(name string) call formatted := FormatMatchingModelName(name) (or similar) and use that formatted value for the Get lookup on voiceCloneUnlockRatioMap so models with thinking budget suffixes or gizmo patterns resolve the same as GetAudioRatio/GetModelRatio.types/price_data.go (1)
41-43: 💤 Low value
ToSetting()doesn't include new fields.The new
FreeModelandVoiceCloneUnlockRatiofields are not included in theToSetting()output. If this method is used for debugging or logging, consider adding them for completeness.♻️ Suggested update
func (p *PriceData) ToSetting() string { - return fmt.Sprintf("ModelPrice: %f, ModelRatio: %f, CompletionRatio: %f, CacheRatio: %f, GroupRatio: %f, UsePrice: %t, CacheCreationRatio: %f, CacheCreation5mRatio: %f, CacheCreation1hRatio: %f, QuotaToPreConsume: %d, ImageRatio: %f, AudioRatio: %f, AudioCompletionRatio: %f", p.ModelPrice, p.ModelRatio, p.CompletionRatio, p.CacheRatio, p.GroupRatioInfo.GroupRatio, p.UsePrice, p.CacheCreationRatio, p.CacheCreation5mRatio, p.CacheCreation1hRatio, p.QuotaToPreConsume, p.ImageRatio, p.AudioRatio, p.AudioCompletionRatio) + return fmt.Sprintf("ModelPrice: %f, ModelRatio: %f, CompletionRatio: %f, CacheRatio: %f, GroupRatio: %f, UsePrice: %t, CacheCreationRatio: %f, CacheCreation5mRatio: %f, CacheCreation1hRatio: %f, QuotaToPreConsume: %d, ImageRatio: %f, AudioRatio: %f, AudioCompletionRatio: %f, VoiceCloneUnlockRatio: %f, FreeModel: %t", p.ModelPrice, p.ModelRatio, p.CompletionRatio, p.CacheRatio, p.GroupRatioInfo.GroupRatio, p.UsePrice, p.CacheCreationRatio, p.CacheCreation5mRatio, p.CacheCreation1hRatio, p.QuotaToPreConsume, p.ImageRatio, p.AudioRatio, p.AudioCompletionRatio, p.VoiceCloneUnlockRatio, p.FreeModel) }🤖 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 `@types/price_data.go` around lines 41 - 43, The ToSetting() method on PriceData omits the newly added FreeModel and VoiceCloneUnlockRatio fields; update PriceData.ToSetting() to include p.FreeModel and p.VoiceCloneUnlockRatio in the formatted output string (alongside existing fields like p.ModelPrice, p.GroupRatioInfo.GroupRatio, p.UsePrice, etc.) so logs/debug output reflects the new fields.web/classic/src/pages/Home/index.jsx (1)
63-84: ⚡ Quick winDuplicate implementation of createFallbackLobeIcon with inconsistent approach.
This helper is duplicated from
web/classic/src/helpers/render.jsx(lines 98-109), but with a different implementation:
- Here (Home/index.jsx): Uses
Typography.Textwith custom circular styling- In render.jsx: Uses
AvatarcomponentBoth achieve similar results, but the inconsistency makes maintenance harder. This was already flagged in the
render.jsxreview, but the implementation difference deserves note.Extract to a shared utility with a consistent implementation (prefer the
Avatarapproach fromrender.jsxas it's more semantic).🤖 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/classic/src/pages/Home/index.jsx` around lines 63 - 84, The createFallbackLobeIcon helper in Home/index.jsx duplicates the implementation found in helpers/render.jsx but with a different UI approach; extract a single shared utility (e.g., export createFallbackLobeIcon from a new or existing shared helpers module) that uses the Avatar-based implementation from helpers/render.jsx, replace the local createFallbackLobeIcon and its FallbackIcon usage in Home/index.jsx with an import of the shared function, and update any other call sites (including the original render.jsx) to import the same shared utility so both files use the consistent Avatar-based implementation.web/classic/src/helpers/render.jsx (1)
98-109: ⚡ Quick winConsider extracting createFallbackLobeIcon to a shared utility module.
This helper is duplicated in
web/classic/src/pages/Home/index.jsx(lines 63-84). To maintain DRY principles, consider extracting it to a shared utility module (e.g.,web/classic/src/helpers/iconUtils.js) and importing it in both files.♻️ Suggested refactor
Create
web/classic/src/helpers/iconUtils.js:import { Avatar } from '`@douyinfe/semi-ui`'; export function createFallbackLobeIcon(label) { const FallbackIcon = ({ size = 14 }) => ( <Avatar size={typeof size === 'number' && size <= 16 ? 'extra-extra-small' : 'small'} style={{ backgroundColor: 'var(--semi-color-fill-1)', color: 'var(--semi-color-text-0)' }} > {label} </Avatar> ); FallbackIcon.Color = FallbackIcon; return FallbackIcon; }Then import in both
render.jsxandHome/index.jsx:+import { createFallbackLobeIcon } from '../../helpers/iconUtils'; -function createFallbackLobeIcon(label) { - // ... duplicated code -}🤖 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/classic/src/helpers/render.jsx` around lines 98 - 109, The createFallbackLobeIcon helper is duplicated; extract it into a shared utility module by exporting a single function createFallbackLobeIcon that imports Avatar, returns the FallbackIcon component (preserving the size logic and the FallbackIcon.Color = FallbackIcon assignment), then replace the local definitions in both places with an import of createFallbackLobeIcon and remove the duplicates so both files call the shared function.
🤖 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 `@dto/audio.go`:
- Around line 55-69: The GetTokenCountMeta method in AudioVoiceCloneRequest uses
encoding/json.Unmarshal to parse r.Input; replace that call with the project's
wrapper common.Unmarshal (and remove direct encoding/json usage) so the Input
bytes are decoded via common.Unmarshal into the local input struct; ensure
imports are updated to reference the common package and keep the same behavior
of assigning text = input.Text when unmarshalling succeeds.
In `@relay/channel/ali/tts.go`:
- Around line 136-157: In convertAliVoiceClone replace direct calls to
encoding/json with the project wrappers: use common.Unmarshal to parse body into
payload (instead of json.Unmarshal) and use common.Marshal to serialize payload
to jsonData (instead of json.Marshal); update error handling to return the same
errors from those calls and ensure the imports reflect use of common package
rather than encoding/json where json was previously referenced.
- Around line 56-95: The code in convertOpenAIToAliTTS calls json.Unmarshal to
parse request.Metadata and encoding/json via common.Marshal to serialize aliReq;
replace json.Unmarshal with common.Unmarshal when decoding metadata into
metadata map and ensure the existing common.Marshal is used for serializing
aliReq (or change the current encoding/json marshal call to common.Marshal) so
all JSON ops use the wrapper in common/json.go; update error messages if needed
to reflect using common.Unmarshal/common.Marshal and keep the rest of the logic
(parameters merging, AliTTSRequest construction, niling Parameters) unchanged.
- Around line 97-134: The code in convertOpenAIToAliMiniMaxTTS uses
encoding/json.Unmarshal to parse request.Metadata (the json.Unmarshal call
around the metadata handling) which violates the guideline; replace that call
with common.Unmarshal (the wrapper in common/json.go) and keep the existing
error handling/variable flow (unmarshal into metadata map[string]interface{} and
then merge into input), ensuring imports are updated to remove encoding/json if
unused.
In `@relay/channel/minimax/adaptor.go`:
- Around line 46-55: Replace direct calls to encoding/json in the payload
manipulation block: instead of json.Unmarshal(body, &payload) and
json.Marshal(payload) use the repo wrappers common.Unmarshal(body, &payload) and
common.Marshal(payload) and preserve the same error handling and delete(payload,
"model") step; ensure the import of encoding/json is removed if no longer used
and keep returning bytes.NewReader(jsonData) as before.
In `@relay/channel/minimax/tts.go`:
- Around line 198-245: Replace the direct call to encoding/json.Unmarshal in
handleVoiceCloneResponse with the project's wrapper common.Unmarshal (call
common.Unmarshal(body, &cloneResp)), and update error handling so that if
common.Unmarshal returns an error you return a types.NewErrorWithStatusCode
describing the parse failure (similar to the existing read error handling)
instead of proceeding; keep the existing logic that checks
cloneResp.BaseResp.StatusCode after successful unmarshal. Use the symbols
handleVoiceCloneResponse, MiniMaxVoiceCloneResponse, common.Unmarshal, and
types.NewErrorWithStatusCode to locate and modify the code.
In `@service/quota.go`:
- Around line 326-335: In PostAudioConsumeQuota fix the bug where
voiceCloneFixedPrice is lost when tieredOk is true: after the existing branch
that sets quota = tieredQuota, re-compute/apply the voice clone fixed quota
using ContextKeyVoiceCloneFixedPrice (as was done earlier with
voiceCloneFixedPrice -> voiceCloneFixedQuota) and add it to quota so the unlock
fee is preserved; alternatively, if you prefer the tiered path, pass the voice
clone price into TryTieredSettle/ComputeTieredQuotaWithRequest so tieredQuota
already includes the unlock fee—update either the code that reads
ContextKeyVoiceCloneFixedPrice or the tiered expression inputs to ensure the
fixed unlock fee is always reflected in the final quota.
In `@web/classic/package.json`:
- Around line 7-10: package.json pins `@lobehub/icons` to 1.20.0 but bun.lock
resolves `@lobehub/icons`@2.1.0, causing deterministic-install mismatch; update
the lockfile to match the intended version or change the package.json version to
2.1.0. Reproduce the install locally and run the package manager that generates
bun.lock (e.g., bun install) to regenerate web/classic/bun.lock so it contains
an entry for `@lobehub/icons`@1.20.0 if you intend to keep 1.20.0, or update
web/classic/package.json to "`@lobehub/icons`": "2.1.0" and then regenerate
bun.lock to ensure bun.lock and package.json are consistent. Ensure the
resulting bun.lock contains the `@lobehub/icons` entry matching the pinned version
and commit both files.
In `@web/classic/src/helpers/render.jsx`:
- Line 122: Replace the incorrect aliasing of SiLinkedin to SiOpenid: remove the
line "const SiLinkedin = SiOpenid", import SiLinkedin from "react-icons/si"
alongside SiOpenid at the top of render.jsx, and ensure
oauthProviderIconMap.linkedin points to SiLinkedin while
oauthProviderIconMap.openid continues to use SiOpenid.
In `@web/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.js`:
- Line 229: The hasConflict check incorrectly treats the voice-clone unlock
value as mutually exclusive with fixed pricing; update
useModelPricingEditorState's conflict logic (the hasConflict boolean) to remove
voiceCloneUnlockPrice/voiceCloneUnlockRatio from the conflicting fields list so
voiceCloneUnlockPrice can coexist with fixedPrice; keep all other conflict
checks unchanged and ensure any references to voiceCloneUnlock* remain used only
for additive pricing, not for determining per-request vs per-token conflicts.
- Around line 426-433: Summary: The serialization currently prefers
model.rawRatios.voiceCloneUnlockRatio when inputPrice is null, which discards UI
edits in voiceCloneUnlockPrice; instead always prefer the UI field. Fix: In the
serialization block that sets result.VoiceCloneUnlockRatio (the code using
hasValue(model.rawRatios.voiceCloneUnlockRatio) and voiceCloneUnlockPrice),
change the branch ordering so that if voiceCloneUnlockPrice !== null you set
result.VoiceCloneUnlockRatio = toNormalizedNumber(voiceCloneUnlockPrice) first;
only if voiceCloneUnlockPrice is null fall back to
model.rawRatios.voiceCloneUnlockRatio via hasValue(...) and
toNormalizedNumber(...). Update the code around result.VoiceCloneUnlockRatio to
reflect this precedence so user edits in voiceCloneUnlockPrice are never
discarded.
In `@web/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsx`:
- Line 272: The code treats voice_clone_unlock_ratio as a per-token "ratio"
field; remove 'voice_clone_unlock_ratio' from ratioSyncFields and create a new
addonSyncFields (or similar) to hold voice_clone_unlock_ratio so it is its own
pricing dimension, update getBillingCategory to return the new addon category
for fields in addonSyncFields, update getLocalBillingCategory to ignore
addonSyncFields when deciding between 'price' and 'ratio' modes, stop deleting
VoiceCloneUnlockRatio when switching modes (remove the deletion in the code that
removes addon fields), and adjust conflict detection logic to allow addon fields
(voice_clone_unlock_ratio/VoiceCloneUnlockRatio) to coexist with either
ModelPrice mode so they no longer cause false conflicts.
In `@web/default/src/features/system-settings/models/constants.ts`:
- Line 69: RATIO_TYPE_OPTIONS contains a literal label
'voice_clone_unlock_ratio' which is passed to getSyncFieldLabel and
t(opt.label), but no translation exists; add the key "voice_clone_unlock_ratio"
with appropriate translated strings to each locale JSON in
web/default/src/i18n/locales/*.json (matching the style/keys used for existing
ratio labels like "model_ratio" and "audio_completion_ratio") so t(opt.label)
returns localized text for getSyncFieldLabel.
In `@web/default/src/features/system-settings/models/model-pricing-sheet.tsx`:
- Around line 217-222: The voiceCloneUnlock lane is a fixed one-time fee but is
being treated as a per-token lane in laneConfigs and PriceLane helper text;
update the UI so voiceCloneUnlock is not shown with "USD price per 1M tokens"
and not subject to ratio derivation: modify laneConfigs/deriveLaneRatio logic to
skip ratio math for key === 'voiceCloneUnlock' (leave data.voiceCloneUnlockRatio
passed through as-is) and in the PriceLane rendering branch detect key ===
'voiceCloneUnlock' and show a custom helper text like "$ per unlock" (or move
the field out of the token lane grid into a separate fixed-price field) so the
label/behavior matches the one-time semantics.
In `@web/default/src/features/system-settings/models/model-ratio-form.tsx`:
- Line 52: The JSON edit mode is missing a FormField for VoiceCloneUnlockRatio
so users can't view/edit that value; add a FormField entry in the JSON mode
section (the same pattern used by other ratio fields like AudioCompletionRatio)
using form.control and name='VoiceCloneUnlockRatio' and render the field with
FormItem/FormLabel/FormControl/Textarea/FormDescription/FormMessage to match how
ModelRatioVisualEditor passes voiceCloneUnlockRatio and keep labels/descriptions
consistent with other ratio fields.
In `@web/default/src/features/system-settings/models/upstream-ratio-sync.tsx`:
- Around line 374-375: The code currently treats VoiceCloneUnlockRatio as
mutually exclusive with model_price and may delete it during performSync;
instead, stop removing/suppressing currentRatios.VoiceCloneUnlockRatio[model]
when model_price is selected. Update performSync (and any logic that builds the
ratio payload) to exclude only the model-specific ratio fields (e.g.,
AudioCompletionRatio, ModelPrice) from mutual-exclusion but always preserve or
explicitly sync VoiceCloneUnlockRatio for a model if present in currentRatios;
reference performSync, currentRatios, VoiceCloneUnlockRatio, and model_price to
locate and change the conditional so VoiceCloneUnlockRatio is not wiped.
---
Outside diff comments:
In `@relay/channel/minimax/tts.go`:
- Around line 123-196: The code in handleTTSResponse uses
encoding/json.Unmarshal to parse the MiniMaxTTSResponse; replace that call with
the project wrapper common.Unmarshal (the helper from common/json.go) when
unmarshalling into the MiniMaxTTSResponse variable (minimaxResp) and propagate
its error into the existing types.NewErrorWithStatusCode error path exactly
where json.Unmarshal is currently used so behavior and error wrapping remain the
same.
In `@web/classic/package.json`:
- Around line 77-90: package.json pins "vite": "5.1.0" while
`@douyinfe/vite-plugin-semi` requires vite 5.1.0 but bun.lock currently resolves
vite@5.4.11; fix by making the declared and locked vite versions consistent:
either update web/classic/package.json's "vite" entry to the resolved 5.4.11 (or
a compatible range) and then regenerate bun.lock, or keep "vite": "5.1.0" and
delete/regenerate web/classic/bun.lock so it locks 5.1.0; regenerate the
lockfile by removing bun.lock (if necessary) and running bun install (or the
project’s standard lock regen command) so bun.lock matches the package.json and
satisfies `@douyinfe/vite-plugin-semi`'s peerDependency.
In `@web/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.js`:
- Around line 246-280: The code incorrectly treats
voiceCloneUnlockPrice/voiceCloneUnlockRatio as derived from inputPrice; remove
model.voiceCloneUnlockPrice from the hasDerivedPricing array and remove
model.rawRatios.voiceCloneUnlockRatio from the rawRatios.some(...) check so
voice clone unlock remains a standalone fixed-price item (update the arrays
referenced in useModelPricingEditorState: hasDerivedPricing and the rawRatios
list used for the inputPrice-dependent warning).
In
`@web/default/src/features/system-settings/models/model-ratio-visual-editor.tsx`:
- Around line 1069-1083: The custom memo equality comparator (the arrow function
passed to React.memo in the ModelRatioVisualEditor component) omits the
voiceCloneUnlockRatio prop, so updates to voiceCloneUnlockRatio won't trigger
re-renders; update the comparator to include a comparison for
prevProps.voiceCloneUnlockRatio === nextProps.voiceCloneUnlockRatio alongside
the existing checks (e.g., add this check with the other prop comparisons such
as modelPrice, modelRatio, cacheRatio, etc.) so the component will re-render
when voiceCloneUnlockRatio changes.
---
Nitpick comments:
In `@setting/ratio_setting/model_ratio.go`:
- Around line 809-815: Normalize the incoming model name with
FormatMatchingModelName before looking up in voiceCloneUnlockRatioMap: in
GetVoiceCloneUnlockRatio(name string) call formatted :=
FormatMatchingModelName(name) (or similar) and use that formatted value for the
Get lookup on voiceCloneUnlockRatioMap so models with thinking budget suffixes
or gizmo patterns resolve the same as GetAudioRatio/GetModelRatio.
In `@types/price_data.go`:
- Around line 41-43: The ToSetting() method on PriceData omits the newly added
FreeModel and VoiceCloneUnlockRatio fields; update PriceData.ToSetting() to
include p.FreeModel and p.VoiceCloneUnlockRatio in the formatted output string
(alongside existing fields like p.ModelPrice, p.GroupRatioInfo.GroupRatio,
p.UsePrice, etc.) so logs/debug output reflects the new fields.
In `@web/classic/src/helpers/render.jsx`:
- Around line 98-109: The createFallbackLobeIcon helper is duplicated; extract
it into a shared utility module by exporting a single function
createFallbackLobeIcon that imports Avatar, returns the FallbackIcon component
(preserving the size logic and the FallbackIcon.Color = FallbackIcon
assignment), then replace the local definitions in both places with an import of
createFallbackLobeIcon and remove the duplicates so both files call the shared
function.
In `@web/classic/src/pages/Home/index.jsx`:
- Around line 63-84: The createFallbackLobeIcon helper in Home/index.jsx
duplicates the implementation found in helpers/render.jsx but with a different
UI approach; extract a single shared utility (e.g., export
createFallbackLobeIcon from a new or existing shared helpers module) that uses
the Avatar-based implementation from helpers/render.jsx, replace the local
createFallbackLobeIcon and its FallbackIcon usage in Home/index.jsx with an
import of the shared function, and update any other call sites (including the
original render.jsx) to import the same shared utility so both files use the
consistent Avatar-based implementation.
🪄 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: 592e0d60-a725-4a6b-9d72-429402cc56c8
📒 Files selected for processing (44)
controller/option.gocontroller/ratio_sync.gocontroller/relay.godto/audio.gomodel/option.gorelay/audio_handler.gorelay/channel/ali/adaptor.gorelay/channel/ali/constants.gorelay/channel/ali/dto.gorelay/channel/ali/tts.gorelay/channel/ali/tts_test.gorelay/channel/minimax/adaptor.gorelay/channel/minimax/constants.gorelay/channel/minimax/relay-minimax.gorelay/channel/minimax/tts.gorelay/channel/task/ali/adaptor.gorelay/constant/relay_mode.gorelay/helper/valid_request.gorouter/relay-router.goservice/quota.gosetting/ratio_setting/exposed_cache.gosetting/ratio_setting/model_ratio.gotypes/price_data.goweb/classic/package.jsonweb/classic/src/components/settings/RatioSetting.jsxweb/classic/src/helpers/render.jsxweb/classic/src/pages/Home/index.jsxweb/classic/src/pages/Setting/Ratio/ModelRatioSettings.jsxweb/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsxweb/classic/src/pages/Setting/Ratio/components/ModelPricingEditor.jsxweb/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.jsweb/classic/vite.config.jsweb/default/src/features/models/components/drawers/model-mutate-drawer.tsxweb/default/src/features/system-settings/billing/index.tsxweb/default/src/features/system-settings/billing/section-registry.tsxweb/default/src/features/system-settings/models/constants.tsweb/default/src/features/system-settings/models/index.tsxweb/default/src/features/system-settings/models/model-pricing-sheet.tsxweb/default/src/features/system-settings/models/model-ratio-form.tsxweb/default/src/features/system-settings/models/model-ratio-visual-editor.tsxweb/default/src/features/system-settings/models/ratio-settings-card.tsxweb/default/src/features/system-settings/models/upstream-ratio-sync-helpers.tsweb/default/src/features/system-settings/models/upstream-ratio-sync.tsxweb/default/src/features/system-settings/types.ts
💤 Files with no reviewable changes (1)
- web/classic/vite.config.js
| func (r *AudioVoiceCloneRequest) GetTokenCountMeta() *types.TokenCountMeta { | ||
| text := r.Text | ||
| if text == "" && len(r.Input) > 0 { | ||
| var input struct { | ||
| Text string `json:"text"` | ||
| } | ||
| if json.Unmarshal(r.Input, &input) == nil { | ||
| text = input.Text | ||
| } | ||
| } | ||
| return &types.TokenCountMeta{ | ||
| CombineText: text, | ||
| TokenType: types.TokenTypeTextNumber, | ||
| } | ||
| } |
There was a problem hiding this comment.
Use common.Unmarshal instead of encoding/json.
Line 61 directly imports and uses encoding/json.Unmarshal for application-level deserialization of the Input payload. As per coding guidelines, all JSON marshal/unmarshal operations in business code must use wrapper functions from common/json.go.
🔧 Proposed fix
func (r *AudioVoiceCloneRequest) GetTokenCountMeta() *types.TokenCountMeta {
text := r.Text
if text == "" && len(r.Input) > 0 {
var input struct {
Text string `json:"text"`
}
- if json.Unmarshal(r.Input, &input) == nil {
+ if common.Unmarshal(r.Input, &input) == nil {
text = input.Text
}
}As per coding guidelines: **/*.go: Use wrapper functions from common/json.go for all JSON marshal/unmarshal operations: common.Marshal(), common.Unmarshal(), common.UnmarshalJsonStr(), common.DecodeJson(), common.GetJsonType(). Do NOT directly import or call encoding/json in business code.
🤖 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 `@dto/audio.go` around lines 55 - 69, The GetTokenCountMeta method in
AudioVoiceCloneRequest uses encoding/json.Unmarshal to parse r.Input; replace
that call with the project's wrapper common.Unmarshal (and remove direct
encoding/json usage) so the Input bytes are decoded via common.Unmarshal into
the local input struct; ensure imports are updated to reference the common
package and keep the same behavior of assigning text = input.Text when
unmarshalling succeeds.
| func convertOpenAIToAliTTS(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | ||
| if isAliMiniMaxSpeechModel(request.Model) { | ||
| return convertOpenAIToAliMiniMaxTTS(c, info, request) | ||
| } | ||
|
|
||
| parameters := map[string]interface{}{} | ||
| if request.ResponseFormat != "" { | ||
| parameters["format"] = request.ResponseFormat | ||
| } | ||
| if request.Speed != nil { | ||
| parameters["speed"] = *request.Speed | ||
| } | ||
| if len(request.Metadata) > 0 { | ||
| var metadata map[string]interface{} | ||
| if err := json.Unmarshal(request.Metadata, &metadata); err != nil { | ||
| return nil, fmt.Errorf("error unmarshalling metadata to ali tts parameters: %w", err) | ||
| } | ||
| for key, value := range metadata { | ||
| parameters[key] = value | ||
| } | ||
| } | ||
|
|
||
| aliReq := AliTTSRequest{ | ||
| Model: request.Model, | ||
| Input: AliTTSInput{ | ||
| Text: request.Input, | ||
| Voice: request.Voice, | ||
| }, | ||
| Parameters: parameters, | ||
| } | ||
| if len(parameters) == 0 { | ||
| aliReq.Parameters = nil | ||
| } | ||
|
|
||
| jsonData, err := common.Marshal(aliReq) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("error marshalling ali tts request: %w", err) | ||
| } | ||
| return bytes.NewReader(jsonData), nil | ||
| } |
There was a problem hiding this comment.
Use common.Unmarshal and common.Marshal instead of encoding/json.
Lines 70, 90 use encoding/json directly for application-level JSON operations (unmarshalling metadata and marshalling the request). As per coding guidelines, all JSON marshal/unmarshal operations in business code must use wrapper functions from common/json.go.
🔧 Proposed fix
if len(request.Metadata) > 0 {
var metadata map[string]interface{}
- if err := json.Unmarshal(request.Metadata, &metadata); err != nil {
+ if err := common.Unmarshal(request.Metadata, &metadata); err != nil {
return nil, fmt.Errorf("error unmarshalling metadata to ali tts parameters: %w", err)
}As per coding guidelines: **/*.go: Use wrapper functions from common/json.go for all JSON marshal/unmarshal operations.
📝 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.
| func convertOpenAIToAliTTS(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | |
| if isAliMiniMaxSpeechModel(request.Model) { | |
| return convertOpenAIToAliMiniMaxTTS(c, info, request) | |
| } | |
| parameters := map[string]interface{}{} | |
| if request.ResponseFormat != "" { | |
| parameters["format"] = request.ResponseFormat | |
| } | |
| if request.Speed != nil { | |
| parameters["speed"] = *request.Speed | |
| } | |
| if len(request.Metadata) > 0 { | |
| var metadata map[string]interface{} | |
| if err := json.Unmarshal(request.Metadata, &metadata); err != nil { | |
| return nil, fmt.Errorf("error unmarshalling metadata to ali tts parameters: %w", err) | |
| } | |
| for key, value := range metadata { | |
| parameters[key] = value | |
| } | |
| } | |
| aliReq := AliTTSRequest{ | |
| Model: request.Model, | |
| Input: AliTTSInput{ | |
| Text: request.Input, | |
| Voice: request.Voice, | |
| }, | |
| Parameters: parameters, | |
| } | |
| if len(parameters) == 0 { | |
| aliReq.Parameters = nil | |
| } | |
| jsonData, err := common.Marshal(aliReq) | |
| if err != nil { | |
| return nil, fmt.Errorf("error marshalling ali tts request: %w", err) | |
| } | |
| return bytes.NewReader(jsonData), nil | |
| } | |
| func convertOpenAIToAliTTS(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | |
| if isAliMiniMaxSpeechModel(request.Model) { | |
| return convertOpenAIToAliMiniMaxTTS(c, info, request) | |
| } | |
| parameters := map[string]interface{}{} | |
| if request.ResponseFormat != "" { | |
| parameters["format"] = request.ResponseFormat | |
| } | |
| if request.Speed != nil { | |
| parameters["speed"] = *request.Speed | |
| } | |
| if len(request.Metadata) > 0 { | |
| var metadata map[string]interface{} | |
| if err := common.Unmarshal(request.Metadata, &metadata); err != nil { | |
| return nil, fmt.Errorf("error unmarshalling metadata to ali tts parameters: %w", err) | |
| } | |
| for key, value := range metadata { | |
| parameters[key] = value | |
| } | |
| } | |
| aliReq := AliTTSRequest{ | |
| Model: request.Model, | |
| Input: AliTTSInput{ | |
| Text: request.Input, | |
| Voice: request.Voice, | |
| }, | |
| Parameters: parameters, | |
| } | |
| if len(parameters) == 0 { | |
| aliReq.Parameters = nil | |
| } | |
| jsonData, err := common.Marshal(aliReq) | |
| if err != nil { | |
| return nil, fmt.Errorf("error marshalling ali tts request: %w", err) | |
| } | |
| return bytes.NewReader(jsonData), nil | |
| } |
🤖 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 `@relay/channel/ali/tts.go` around lines 56 - 95, The code in
convertOpenAIToAliTTS calls json.Unmarshal to parse request.Metadata and
encoding/json via common.Marshal to serialize aliReq; replace json.Unmarshal
with common.Unmarshal when decoding metadata into metadata map and ensure the
existing common.Marshal is used for serializing aliReq (or change the current
encoding/json marshal call to common.Marshal) so all JSON ops use the wrapper in
common/json.go; update error messages if needed to reflect using
common.Unmarshal/common.Marshal and keep the rest of the logic (parameters
merging, AliTTSRequest construction, niling Parameters) unchanged.
| func convertOpenAIToAliMiniMaxTTS(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | ||
| input := map[string]interface{}{ | ||
| "text": request.Input, | ||
| } | ||
| voiceSetting := map[string]interface{}{} | ||
| if request.Voice != "" { | ||
| voiceSetting["voice_id"] = request.Voice | ||
| } | ||
| if request.Speed != nil { | ||
| voiceSetting["speed"] = *request.Speed | ||
| } | ||
| if len(voiceSetting) > 0 { | ||
| input["voice_setting"] = voiceSetting | ||
| } | ||
| if request.ResponseFormat != "" { | ||
| input["audio_setting"] = map[string]interface{}{ | ||
| "format": request.ResponseFormat, | ||
| } | ||
| } | ||
| if len(request.Metadata) > 0 { | ||
| var metadata map[string]interface{} | ||
| if err := json.Unmarshal(request.Metadata, &metadata); err != nil { | ||
| return nil, fmt.Errorf("error unmarshalling metadata to ali minimax tts input: %w", err) | ||
| } | ||
| for key, value := range metadata { | ||
| input[key] = value | ||
| } | ||
| } | ||
| aliReq := map[string]interface{}{ | ||
| "model": request.Model, | ||
| "input": input, | ||
| } | ||
| jsonData, err := common.Marshal(aliReq) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("error marshalling ali minimax tts request: %w", err) | ||
| } | ||
| return bytes.NewReader(jsonData), nil | ||
| } |
There was a problem hiding this comment.
Use common.Unmarshal and common.Marshal instead of encoding/json.
Lines 118, 129 use encoding/json directly. As per coding guidelines, all JSON marshal/unmarshal operations in business code must use wrapper functions from common/json.go.
🔧 Proposed fix
if len(request.Metadata) > 0 {
var metadata map[string]interface{}
- if err := json.Unmarshal(request.Metadata, &metadata); err != nil {
+ if err := common.Unmarshal(request.Metadata, &metadata); err != nil {
return nil, fmt.Errorf("error unmarshalling metadata to ali minimax tts input: %w", err)
}
for key, value := range metadata {
input[key] = value
}
}
aliReq := map[string]interface{}{
"model": request.Model,
"input": input,
}
- jsonData, err := common.Marshal(aliReq)
+ jsonData, err := common.Marshal(aliReq)(Note: Line 129 already uses common.Marshal correctly; only line 118 needs fixing.)
As per coding guidelines: **/*.go: Use wrapper functions from common/json.go for all JSON marshal/unmarshal operations.
📝 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.
| func convertOpenAIToAliMiniMaxTTS(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | |
| input := map[string]interface{}{ | |
| "text": request.Input, | |
| } | |
| voiceSetting := map[string]interface{}{} | |
| if request.Voice != "" { | |
| voiceSetting["voice_id"] = request.Voice | |
| } | |
| if request.Speed != nil { | |
| voiceSetting["speed"] = *request.Speed | |
| } | |
| if len(voiceSetting) > 0 { | |
| input["voice_setting"] = voiceSetting | |
| } | |
| if request.ResponseFormat != "" { | |
| input["audio_setting"] = map[string]interface{}{ | |
| "format": request.ResponseFormat, | |
| } | |
| } | |
| if len(request.Metadata) > 0 { | |
| var metadata map[string]interface{} | |
| if err := json.Unmarshal(request.Metadata, &metadata); err != nil { | |
| return nil, fmt.Errorf("error unmarshalling metadata to ali minimax tts input: %w", err) | |
| } | |
| for key, value := range metadata { | |
| input[key] = value | |
| } | |
| } | |
| aliReq := map[string]interface{}{ | |
| "model": request.Model, | |
| "input": input, | |
| } | |
| jsonData, err := common.Marshal(aliReq) | |
| if err != nil { | |
| return nil, fmt.Errorf("error marshalling ali minimax tts request: %w", err) | |
| } | |
| return bytes.NewReader(jsonData), nil | |
| } | |
| func convertOpenAIToAliMiniMaxTTS(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | |
| input := map[string]interface{}{ | |
| "text": request.Input, | |
| } | |
| voiceSetting := map[string]interface{}{} | |
| if request.Voice != "" { | |
| voiceSetting["voice_id"] = request.Voice | |
| } | |
| if request.Speed != nil { | |
| voiceSetting["speed"] = *request.Speed | |
| } | |
| if len(voiceSetting) > 0 { | |
| input["voice_setting"] = voiceSetting | |
| } | |
| if request.ResponseFormat != "" { | |
| input["audio_setting"] = map[string]interface{}{ | |
| "format": request.ResponseFormat, | |
| } | |
| } | |
| if len(request.Metadata) > 0 { | |
| var metadata map[string]interface{} | |
| if err := common.Unmarshal(request.Metadata, &metadata); err != nil { | |
| return nil, fmt.Errorf("error unmarshalling metadata to ali minimax tts input: %w", err) | |
| } | |
| for key, value := range metadata { | |
| input[key] = value | |
| } | |
| } | |
| aliReq := map[string]interface{}{ | |
| "model": request.Model, | |
| "input": input, | |
| } | |
| jsonData, err := common.Marshal(aliReq) | |
| if err != nil { | |
| return nil, fmt.Errorf("error marshalling ali minimax tts request: %w", err) | |
| } | |
| return bytes.NewReader(jsonData), nil | |
| } |
🤖 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 `@relay/channel/ali/tts.go` around lines 97 - 134, The code in
convertOpenAIToAliMiniMaxTTS uses encoding/json.Unmarshal to parse
request.Metadata (the json.Unmarshal call around the metadata handling) which
violates the guideline; replace that call with common.Unmarshal (the wrapper in
common/json.go) and keep the existing error handling/variable flow (unmarshal
into metadata map[string]interface{} and then merge into input), ensuring
imports are updated to remove encoding/json if unused.
| func convertAliVoiceClone(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | ||
| storage, err := common.GetBodyStorage(c) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| body, err := storage.Bytes() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| var payload map[string]interface{} | ||
| if err := json.Unmarshal(body, &payload); err != nil { | ||
| return nil, err | ||
| } | ||
| if request.Model != "" { | ||
| payload["model"] = request.Model | ||
| } | ||
| jsonData, err := json.Marshal(payload) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return bytes.NewReader(jsonData), nil | ||
| } |
There was a problem hiding this comment.
Use common.Unmarshal and common.Marshal instead of encoding/json.
Lines 146, 152 use encoding/json directly for unmarshalling and marshalling the voice-clone payload. As per coding guidelines, all JSON marshal/unmarshal operations in business code must use wrapper functions from common/json.go.
🔧 Proposed fix
var payload map[string]interface{}
- if err := json.Unmarshal(body, &payload); err != nil {
+ if err := common.Unmarshal(body, &payload); err != nil {
return nil, err
}
if request.Model != "" {
payload["model"] = request.Model
}
- jsonData, err := json.Marshal(payload)
+ jsonData, err := common.Marshal(payload)
if err != nil {
return nil, err
}As per coding guidelines: **/*.go: Use wrapper functions from common/json.go for all JSON marshal/unmarshal operations.
📝 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.
| func convertAliVoiceClone(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | |
| storage, err := common.GetBodyStorage(c) | |
| if err != nil { | |
| return nil, err | |
| } | |
| body, err := storage.Bytes() | |
| if err != nil { | |
| return nil, err | |
| } | |
| var payload map[string]interface{} | |
| if err := json.Unmarshal(body, &payload); err != nil { | |
| return nil, err | |
| } | |
| if request.Model != "" { | |
| payload["model"] = request.Model | |
| } | |
| jsonData, err := json.Marshal(payload) | |
| if err != nil { | |
| return nil, err | |
| } | |
| return bytes.NewReader(jsonData), nil | |
| } | |
| func convertAliVoiceClone(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) { | |
| storage, err := common.GetBodyStorage(c) | |
| if err != nil { | |
| return nil, err | |
| } | |
| body, err := storage.Bytes() | |
| if err != nil { | |
| return nil, err | |
| } | |
| var payload map[string]interface{} | |
| if err := common.Unmarshal(body, &payload); err != nil { | |
| return nil, err | |
| } | |
| if request.Model != "" { | |
| payload["model"] = request.Model | |
| } | |
| jsonData, err := common.Marshal(payload) | |
| if err != nil { | |
| return nil, err | |
| } | |
| return bytes.NewReader(jsonData), nil | |
| } |
🤖 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 `@relay/channel/ali/tts.go` around lines 136 - 157, In convertAliVoiceClone
replace direct calls to encoding/json with the project wrappers: use
common.Unmarshal to parse body into payload (instead of json.Unmarshal) and use
common.Marshal to serialize payload to jsonData (instead of json.Marshal);
update error handling to return the same errors from those calls and ensure the
imports reflect use of common package rather than encoding/json where json was
previously referenced.
| var payload map[string]interface{} | ||
| if err := json.Unmarshal(body, &payload); err != nil { | ||
| return nil, err | ||
| } | ||
| delete(payload, "model") | ||
| jsonData, err := json.Marshal(payload) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return bytes.NewReader(jsonData), nil |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Use common JSON wrappers instead of encoding/json directly.
The newly added voice-clone branch calls json.Unmarshal/json.Marshal directly. Per repo convention, application-level (de)serialization must go through the common/json.go wrappers. common is already imported here, so this is a localized swap.
♻️ Proposed change
- var payload map[string]interface{}
- if err := json.Unmarshal(body, &payload); err != nil {
- return nil, err
- }
- delete(payload, "model")
- jsonData, err := json.Marshal(payload)
- if err != nil {
- return nil, err
- }
+ var payload map[string]interface{}
+ if err := common.Unmarshal(body, &payload); err != nil {
+ return nil, err
+ }
+ delete(payload, "model")
+ jsonData, err := common.Marshal(payload)
+ if err != nil {
+ return nil, err
+ }As per coding guidelines: "All JSON marshal/unmarshal operations MUST use wrapper functions from common/json.go ... Do NOT directly import or call encoding/json in business code."
🤖 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 `@relay/channel/minimax/adaptor.go` around lines 46 - 55, Replace direct calls
to encoding/json in the payload manipulation block: instead of
json.Unmarshal(body, &payload) and json.Marshal(payload) use the repo wrappers
common.Unmarshal(body, &payload) and common.Marshal(payload) and preserve the
same error handling and delete(payload, "model") step; ensure the import of
encoding/json is removed if no longer used and keep returning
bytes.NewReader(jsonData) as before.
| 'image_ratio', | ||
| 'audio_ratio', | ||
| 'audio_completion_ratio', | ||
| 'voice_clone_unlock_ratio', |
There was a problem hiding this comment.
Voice clone unlock price misclassified in upstream sync billing category logic.
voice_clone_unlock_ratio represents a fixed price per voice-clone operation and should be independent of the billing mode (per-request vs. per-token). However, the current implementation incorrectly treats it as a per-token ratio field:
- Line 272: Added to
ratioSyncFieldsarray, which determines 'ratio' billing category - Lines 461-463: Presence of
VoiceCloneUnlockRatiocausesgetLocalBillingCategoryto return'ratio'even when model uses per-request pricing - Lines 325-331:
getBillingCategorydefaults all non-price/tiered fields to'ratio' - Line 559:
VoiceCloneUnlockRatiois deleted when switching to price mode
This causes:
- False conflict detection between
ModelPriceandVoiceCloneUnlockRatio - Loss of voice clone pricing when syncing models that use per-request billing
- Incorrect categorization in the sync UI
Voice clone unlock pricing is an additive charge that should coexist with either billing mode, not conflict with them.
Recommended fix approach
The fix requires treating voice_clone_unlock_ratio as a separate pricing dimension:
- Remove it from
ratioSyncFieldsand create a separate category (e.g.,addonSyncFields) - Update
getBillingCategoryto return a new category for addon fields - Update
getLocalBillingCategoryto ignore addon fields when determining mode - Don't delete addon fields when switching between price/ratio modes (remove line 559)
- Update conflict detection logic to allow addons with any billing mode
This ensures voice clone pricing is preserved regardless of the base billing mode.
Also applies to: 325-331, 461-463, 559-559
🤖 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/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsx` at line 272, The
code treats voice_clone_unlock_ratio as a per-token "ratio" field; remove
'voice_clone_unlock_ratio' from ratioSyncFields and create a new addonSyncFields
(or similar) to hold voice_clone_unlock_ratio so it is its own pricing
dimension, update getBillingCategory to return the new addon category for fields
in addonSyncFields, update getLocalBillingCategory to ignore addonSyncFields
when deciding between 'price' and 'ratio' modes, stop deleting
VoiceCloneUnlockRatio when switching modes (remove the deletion in the code that
removes addon fields), and adjust conflict detection logic to allow addon fields
(voice_clone_unlock_ratio/VoiceCloneUnlockRatio) to coexist with either
ModelPrice mode so they no longer cause false conflicts.
| { label: 'Image ratio', value: 'image_ratio' }, | ||
| { label: 'Audio ratio', value: 'audio_ratio' }, | ||
| { label: 'Audio completion ratio', value: 'audio_completion_ratio' }, | ||
| { label: 'Voice clone unlock ratio', value: 'voice_clone_unlock_ratio' }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify the new ratio-type label exists in the i18n catalogs.
fd -e json . web/default --exec rg -l 'Voice clone unlock ratio' {} \;
echo "--- existing sibling key for comparison ---"
fd -e json . web/default --exec rg -l 'Audio completion ratio' {} \;Repository: QuantumNous/new-api
Length of output: 329
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# 1) Inspect the constants file around the cited line and header comment expectations.
FILE="web/default/src/features/system-settings/models/constants.ts"
echo "---- file excerpt ($FILE) ----"
nl -ba "$FILE" | sed -n '40,95p'
# 2) Locate getSyncFieldLabel to confirm how t() is applied.
echo "---- getSyncFieldLabel usages/impl ----"
rg -n "getSyncFieldLabel" web/default/src/features/system-settings/models/constants.ts web/default/src/features/system-settings -S || true
# 3) Search for the new label string in locale catalogs (content match).
echo "---- search for exact phrase in locale JSON ----"
fd -e json . web/default/src/i18n/locales --exec rg -n "Voice clone unlock ratio" {} \;
# 4) Search for a likely key pattern: if the label is expected to be an i18n key, it may appear as a key string in catalogs.
# We’ll also search for a shorter fragment to reduce false negatives due to whitespace/quotes.
echo "---- search for fragment "Voice clone" in locale JSON keys ----"
fd -e json . web/default/src/i18n/locales --exec rg -n "\"Voice clone\"|Voice clone" {} \;
# 5) Also check whether the code uses labelKey anywhere for this options list.
echo "---- search for labelKey in system-settings constants/models ----"
rg -n "labelKey" web/default/src/features/system-settings -S || trueRepository: QuantumNous/new-api
Length of output: 210
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="web/default/src/features/system-settings/models/constants.ts"
echo "---- file excerpt ($FILE) ----"
cat -n "$FILE" | sed -n '40,95p'
echo "---- getSyncFieldLabel occurrences (constants + feature) ----"
rg -n "getSyncFieldLabel" web/default/src/features/system-settings/models/constants.ts web/default/src/features/system-settings -S || true
echo "---- search for exact phrase in locale JSON (content match) ----"
fd -e json . web/default/src/i18n/locales --exec rg -n "Voice clone unlock ratio" {} \; || true
echo "---- search for fragment \"Voice clone\" in locale JSON ----"
fd -e json . web/default/src/i18n/locales --exec rg -n "\"Voice clone\"|Voice clone" {} \; || true
echo "---- search for labelKey usage in system-settings ----"
rg -n "labelKey" web/default/src/features/system-settings -S || trueRepository: QuantumNous/new-api
Length of output: 4478
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the helper that builds the i18n key via t()
FILE="web/default/src/features/system-settings/models/upstream-ratio-sync-helpers.ts"
echo "---- getSyncFieldLabel implementation ($FILE) ----"
cat -n "$FILE" | sed -n '1,140p'
# Check which of the existing labels are present in locale catalogs (to infer keying strategy)
echo "---- locale keys/strings containing existing label text ----"
for s in "Model ratio" "Audio completion ratio" "Completion ratio" "Cache ratio"; do
echo "== $s =="
fd -e json . web/default/src/i18n/locales --exec rg -n "$s" {} \; || true
done
# Search for likely new i18n key variants
echo "---- search for voice_clone_unlock_ratio key string ----"
fd -e json . web/default/src/i18n/locales --exec rg -n "voice_clone_unlock_ratio" {} \; || true
echo "---- search for 'Voice clone unlock ratio' again, but in keys and values (same exact match) ----"
fd -e json . web/default/src/i18n/locales --exec rg -n "Voice clone unlock ratio" {} \; || trueRepository: QuantumNous/new-api
Length of output: 5909
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "---- search for fragments for the new label ----"
fd -e json . web/default/src/i18n/locales --exec rg -n "clone unlock" {} \; || true
fd -e json . web/default/src/i18n/locales --exec rg -n "voice_clone" {} \; || true
fd -e json . web/default/src/i18n/locales --exec rg -n "Voice clone" {} \; || trueRepository: QuantumNous/new-api
Length of output: 112
Add missing i18n key for “Voice clone unlock ratio”
getSyncFieldLabel renders t(opt.label) where opt.label is the literal string from RATIO_TYPE_OPTIONS. The locale catalogs in web/default/src/i18n/locales/*.json contain other ratio-label keys (e.g., “Model ratio”, “Audio completion ratio”) but no entry for “Voice clone unlock ratio”, so non-English locales won’t be localized.
🤖 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/default/src/features/system-settings/models/constants.ts` at line 69,
RATIO_TYPE_OPTIONS contains a literal label 'voice_clone_unlock_ratio' which is
passed to getSyncFieldLabel and t(opt.label), but no translation exists; add the
key "voice_clone_unlock_ratio" with appropriate translated strings to each
locale JSON in web/default/src/i18n/locales/*.json (matching the style/keys used
for existing ratio labels like "model_ratio" and "audio_completion_ratio") so
t(opt.label) returns localized text for getSyncFieldLabel.
| { | ||
| key: 'voiceCloneUnlock', | ||
| titleKey: 'Voice clone unlock price', | ||
| descriptionKey: 'One-time fee for first use of cloned voice (e.g., MiniMax charges 9.9 yuan).', | ||
| placeholder: '9.9', | ||
| }, |
There was a problem hiding this comment.
Voice clone unlock price has different semantics than token-based lanes.
The voiceCloneUnlock lane represents a one-time fixed fee per voice clone unlock, not a per-token price. However:
- It's grouped with per-token price lanes in
laneConfigsand will display "USD price per 1M tokens" (line 1058) when enabled. - The
deriveLaneRatiologic attempts to calculate ratios based on the prompt price, but voice clone unlock is an absolute value.
Looking at line 272, the value is correctly passed through without ratio derivation (data.voiceCloneUnlockRatio || ''). However, the PriceLane component's helper text is misleading.
Consider either:
- Rendering
voiceCloneUnlockas a separate fixed-price field outside the lane grid, or - Customizing the helper text for this specific lane (e.g., "$ per unlock" instead of "USD price per 1M tokens").
🤖 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/default/src/features/system-settings/models/model-pricing-sheet.tsx`
around lines 217 - 222, The voiceCloneUnlock lane is a fixed one-time fee but is
being treated as a per-token lane in laneConfigs and PriceLane helper text;
update the UI so voiceCloneUnlock is not shown with "USD price per 1M tokens"
and not subject to ratio derivation: modify laneConfigs/deriveLaneRatio logic to
skip ratio math for key === 'voiceCloneUnlock' (leave data.voiceCloneUnlockRatio
passed through as-is) and in the PriceLane rendering branch detect key ===
'voiceCloneUnlock' and show a custom helper text like "$ per unlock" (or move
the field out of the token lane grid into a separate fixed-price field) so the
label/behavior matches the one-time semantics.
| ImageRatio: string | ||
| AudioRatio: string | ||
| AudioCompletionRatio: string | ||
| VoiceCloneUnlockRatio: string |
There was a problem hiding this comment.
JSON edit mode missing VoiceCloneUnlockRatio field.
The visual edit mode correctly passes voiceCloneUnlockRatio to ModelRatioVisualEditor, but the JSON edit mode (lines 177-350) does not include a <FormField> for VoiceCloneUnlockRatio. Users switching to JSON mode won't be able to view or edit this field.
Add a FormField for VoiceCloneUnlockRatio in the JSON mode section to match other ratio fields:
Proposed addition after AudioCompletionRatio FormField (around line 326)
<FormField
control={form.control}
name='VoiceCloneUnlockRatio'
render={({ field }) => (
<FormItem>
<FormLabel>{t('Voice clone unlock ratio')}</FormLabel>
<FormControl>
<Textarea rows={6} {...field} />
</FormControl>
<FormDescription>
{t('Fixed fee for voice clone unlock per model.')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>Also applies to: 139-139
🤖 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/default/src/features/system-settings/models/model-ratio-form.tsx` at line
52, The JSON edit mode is missing a FormField for VoiceCloneUnlockRatio so users
can't view/edit that value; add a FormField entry in the JSON mode section (the
same pattern used by other ratio fields like AudioCompletionRatio) using
form.control and name='VoiceCloneUnlockRatio' and render the field with
FormItem/FormLabel/FormControl/Textarea/FormDescription/FormMessage to match how
ModelRatioVisualEditor passes voiceCloneUnlockRatio and keep labels/descriptions
consistent with other ratio fields.
| currentRatios.AudioCompletionRatio[model] !== undefined || | ||
| currentRatios.VoiceCloneUnlockRatio[model] !== undefined |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect how the backend treats the voice-clone unlock fixed price relative to model price / ratios.
rg -nP -C4 'VoiceCloneUnlock|ContextKeyVoiceCloneFixedPrice|VoiceCloneFixedPrice' --type=goRepository: QuantumNous/new-api
Length of output: 10328
Stop wiping VoiceCloneUnlockRatio when model_price is selected (upstream-ratio-sync.tsx:374-375, 416)
Backend treats voice_clone_unlock_ratio as an independent fixed unlock fee: relay/channel/ali/tts.go sets service.ContextKeyVoiceCloneFixedPrice from ratio_setting.GetVoiceCloneUnlockRatio(...), and service/quota.go adds it to quota when voiceCloneFixedPrice > 0. If performSync deletes VoiceCloneUnlockRatio when model_price is chosen, the unlock fee will be lost for those models. Keep it out of the ratio/model_price mutual-exclusion (or otherwise ensure it’s still synced/applied).
🤖 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/default/src/features/system-settings/models/upstream-ratio-sync.tsx`
around lines 374 - 375, The code currently treats VoiceCloneUnlockRatio as
mutually exclusive with model_price and may delete it during performSync;
instead, stop removing/suppressing currentRatios.VoiceCloneUnlockRatio[model]
when model_price is selected. Update performSync (and any logic that builds the
ratio payload) to exclude only the model-specific ratio fields (e.g.,
AudioCompletionRatio, ModelPrice) from mutual-exclusion but always preserve or
explicitly sync VoiceCloneUnlockRatio for a model if present in currentRatios;
reference performSync, currentRatios, VoiceCloneUnlockRatio, and model_price to
locate and change the conditional so VoiceCloneUnlockRatio is not wiped.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
relay/channel/task/ali/billing_test.go (1)
9-114: ⚡ Quick winConsider adding test isolation and cleanup.
All test functions call
ratio_setting.InitRatioSettings()but none reset or clean up the state afterward. If tests run in parallel or state persists between tests (especially line 72'sUpdateVideoResolutionRatioByJSONString), this could cause flaky failures or unexpected interactions.Consider either:
- Adding
t.Parallel()with proper isolation, or- Resetting the ratio settings state in a
deferort.Cleanup()call.🤖 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 `@relay/channel/task/ali/billing_test.go` around lines 9 - 114, Tests mutate global ratio state via ratio_setting.InitRatioSettings() and UpdateVideoResolutionRatioByJSONString but never restore it, causing cross-test pollution; fix by adding isolation—either mark tests parallel with t.Parallel() and ensure each test re-initializes state, or register a cleanup that resets state (call ratio_setting.InitRatioSettings() or a provided Reset function) via t.Cleanup() at the start of each test (notably TestProcessAliOtherRatios_UsesConfigOverride and others using UpdateVideoResolutionRatioByJSONString) so global VideoResolutionRatio state is deterministically restored after each test.
🤖 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/default/src/features/system-settings/models/model-pricing-sheet.tsx`:
- Around line 229-234: The videoResolution lane is being treated as a numeric
per-token lane but must accept a JSON object and be handled separately; update
the code to remove 'videoResolution' (and 'voiceCloneUnlock') from the per-token
pipeline (laneConfigs/deriveLaneRatio) and instead surface them as standalone
fields with their own input handling: stop rendering videoResolution via
PriceLane/PriceInput and bypass handleLanePriceChange/numericDraftRegex for it,
stop calling deriveLaneRatio('videoResolution', ...) from syncLaneRatios, and
add a dedicated controlled input component that accepts free-text/JSON for
videoResolution (and a fixed-value control for voiceCloneUnlock) and passes the
raw value through to save unchanged. Ensure references: PriceLane, PriceInput,
handleLanePriceChange, syncLaneRatios, deriveLaneRatio, laneConfigs,
videoResolution, and voiceCloneUnlock are updated accordingly.
---
Nitpick comments:
In `@relay/channel/task/ali/billing_test.go`:
- Around line 9-114: Tests mutate global ratio state via
ratio_setting.InitRatioSettings() and UpdateVideoResolutionRatioByJSONString but
never restore it, causing cross-test pollution; fix by adding isolation—either
mark tests parallel with t.Parallel() and ensure each test re-initializes state,
or register a cleanup that resets state (call ratio_setting.InitRatioSettings()
or a provided Reset function) via t.Cleanup() at the start of each test (notably
TestProcessAliOtherRatios_UsesConfigOverride and others using
UpdateVideoResolutionRatioByJSONString) so global VideoResolutionRatio state is
deterministically restored after each test.
🪄 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: aa830e6d-de03-4e47-a10c-89fba3544e23
📒 Files selected for processing (24)
controller/option.gocontroller/ratio_sync.gomodel/option.gorelay/channel/task/ali/adaptor.gorelay/channel/task/ali/billing_test.gosetting/ratio_setting/exposed_cache.gosetting/ratio_setting/model_ratio.goweb/classic/src/components/settings/RatioSetting.jsxweb/classic/src/pages/Setting/Ratio/ModelRatioSettings.jsxweb/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsxweb/classic/src/pages/Setting/Ratio/components/ModelPricingEditor.jsxweb/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.jsweb/default/src/features/models/components/drawers/model-mutate-drawer.tsxweb/default/src/features/system-settings/billing/index.tsxweb/default/src/features/system-settings/billing/section-registry.tsxweb/default/src/features/system-settings/models/constants.tsweb/default/src/features/system-settings/models/index.tsxweb/default/src/features/system-settings/models/model-pricing-sheet.tsxweb/default/src/features/system-settings/models/model-ratio-form.tsxweb/default/src/features/system-settings/models/model-ratio-visual-editor.tsxweb/default/src/features/system-settings/models/ratio-settings-card.tsxweb/default/src/features/system-settings/models/upstream-ratio-sync-helpers.tsweb/default/src/features/system-settings/models/upstream-ratio-sync.tsxweb/default/src/features/system-settings/types.ts
✅ Files skipped from review due to trivial changes (1)
- web/default/src/features/system-settings/models/upstream-ratio-sync-helpers.ts
🚧 Files skipped from review as they are similar to previous changes (14)
- web/default/src/features/system-settings/billing/index.tsx
- web/default/src/features/models/components/drawers/model-mutate-drawer.tsx
- controller/ratio_sync.go
- web/default/src/features/system-settings/billing/section-registry.tsx
- web/classic/src/components/settings/RatioSetting.jsx
- setting/ratio_setting/exposed_cache.go
- web/default/src/features/system-settings/models/index.tsx
- model/option.go
- web/default/src/features/system-settings/types.ts
- controller/option.go
- web/classic/src/pages/Setting/Ratio/ModelRatioSettings.jsx
- web/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsx
- web/classic/src/pages/Setting/Ratio/components/ModelPricingEditor.jsx
- web/default/src/features/system-settings/models/upstream-ratio-sync.tsx
| { | ||
| key: 'videoResolution', | ||
| titleKey: 'Video resolution ratio', | ||
| descriptionKey: 'Model-specific resolution multipliers (e.g., 720P: 2, 1080P: 3.33).', | ||
| placeholder: '{}', | ||
| }, |
There was a problem hiding this comment.
videoResolution lane cannot work through the numeric per-token lane machinery.
This lane is documented to hold a JSON map of resolution multipliers (placeholder {}, e.g. 720P: 2, 1080P: 3.33), but it is wired into the same per-token price/ratio pipeline as numeric lanes, which makes it non-functional:
- It renders via
PriceLane→PriceInput, andhandleLanePriceChange(Line 596) rejects any input not matchingnumericDraftRegex, so a JSON object can never be typed. - When the lane is enabled or the input price changes,
syncLaneRatios(Line 561) callsderiveLaneRatio('videoResolution', …)(Line 541).toNumberOrNullon a JSON string returnsnull, sovideoResolutionRatiois silently reset to''— losing any preloaded value on the next prompt-price edit.
videoResolution (and voiceCloneUnlock) are not per-token ratios; they should be excluded from laneConfigs/deriveLaneRatio and surfaced as standalone fields with their own input handling (free-text/JSON for videoResolution, fixed value for voiceCloneUnlock), passed through verbatim on save.
🤖 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/default/src/features/system-settings/models/model-pricing-sheet.tsx`
around lines 229 - 234, The videoResolution lane is being treated as a numeric
per-token lane but must accept a JSON object and be handled separately; update
the code to remove 'videoResolution' (and 'voiceCloneUnlock') from the per-token
pipeline (laneConfigs/deriveLaneRatio) and instead surface them as standalone
fields with their own input handling: stop rendering videoResolution via
PriceLane/PriceInput and bypass handleLanePriceChange/numericDraftRegex for it,
stop calling deriveLaneRatio('videoResolution', ...) from syncLaneRatios, and
add a dedicated controlled input component that accepts free-text/JSON for
videoResolution (and a fixed-value control for voiceCloneUnlock) and passes the
raw value through to save unchanged. Ensure references: PriceLane, PriceInput,
handleLanePriceChange, syncLaneRatios, deriveLaneRatio, laneConfigs,
videoResolution, and voiceCloneUnlock are updated accordingly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 @.github/workflows/docker-build-branch.yml:
- Around line 18-19: The checkout step currently uses actions/checkout@v4 which
defaults persist-credentials to true; update the "Check out" step (uses:
actions/checkout@v4) to explicitly set persist-credentials: false so the runner
does not persist the GITHUB_TOKEN in the local git config for the job.
- Line 19: The workflow is using floating action tags and leaving checkout
credentials persisted; replace uses: actions/checkout@v4,
docker/setup-buildx-action@v3, and docker/build-push-action@v6 with their
corresponding immutable commit SHAs and add persist-credentials: false under the
checkout step (the actions/checkout block) to avoid storing the token in git
config; ensure you update the three uses lines to exact commit SHAs and add the
with: persist-credentials: false key to the actions/checkout invocation.
🪄 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: 82248acc-1686-4606-861d-7b6b2d456ed9
📒 Files selected for processing (1)
.github/workflows/docker-build-branch.yml
| - name: Check out | ||
| uses: actions/checkout@v4 |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file=".github/workflows/docker-build-branch.yml"
echo "== File = $file =="
if [ -f "$file" ]; then
nl -ba "$file" | sed -n '1,120p'
else
echo "Missing file: $file" >&2
exit 1
fi
echo "== Searching for checkout usage and persist-credentials =="
rg -n "actions/checkout@|persist-credentials" .github/workflows/docker-build-branch.yml || trueRepository: QuantumNous/new-api
Length of output: 179
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file=".github/workflows/docker-build-branch.yml"
echo "== Listing file =="
ls -la "$file" 2>/dev/null || { echo "Missing file: $file" >&2; exit 1; }
echo "== First 120 lines (with numbers) =="
awk '{printf "%6d\t%s\n", NR, $0}' "$file" | sed -n '1,120p'
echo "== Grep checkout and persist-credentials in workflow =="
rg -n "actions/checkout@|persist-credentials" "$file" || trueRepository: QuantumNous/new-api
Length of output: 1298
🌐 Web query:
GitHub actions checkout v4 persist-credentials default value
💡 Result:
The default value for the persist-credentials input in the GitHub Actions actions/checkout action (including version 4) is true [1][2][3]. When this setting is enabled (the default), the authentication token or SSH key used to check out the repository is persisted in the local Git configuration [1][3]. This allows subsequent steps in the same job to execute authenticated Git commands using those credentials [1][3]. The action automatically removes these credentials during the post-job cleanup phase [1][3]. If you wish to prevent this behavior—for example, to enhance security or use different credentials in later steps—you can explicitly set persist-credentials to false in your workflow file [1][3]: - uses: actions/checkout@v4 with: persist-credentials: false
Citations:
- 1: https://github.com/actions/checkout/tree/v4
- 2: https://github.com/actions/checkout
- 3: https://spacelift.io/blog/github-actions-checkout
Disable checkout credential persistence.
actions/checkout@v4 defaults persist-credentials to true, which persists the token in the runner’s local git config for the job. Set it to false on the checkout step.
Suggested hardening diff
- name: Check out
uses: actions/checkout@v4
+ with:
+ persist-credentials: false🧰 Tools
🪛 zizmor (1.25.2)
[warning] 18-19: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false
(artipacked)
[error] 19-19: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)
(unpinned-uses)
🤖 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 @.github/workflows/docker-build-branch.yml around lines 18 - 19, The checkout
step currently uses actions/checkout@v4 which defaults persist-credentials to
true; update the "Check out" step (uses: actions/checkout@v4) to explicitly set
persist-credentials: false so the runner does not persist the GITHUB_TOKEN in
the local git config for the job.
|
|
||
| steps: | ||
| - name: Check out | ||
| uses: actions/checkout@v4 |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE=".github/workflows/docker-build-branch.yml"
if [ ! -f "$FILE" ]; then
echo "Missing: $FILE"
exit 1
fi
echo "== File: $FILE =="
nl -ba "$FILE" | sed -n '1,120p'
echo "== End =="Repository: QuantumNous/new-api
Length of output: 179
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE=".github/workflows/docker-build-branch.yml"
if [ ! -f "$FILE" ]; then
echo "Missing: $FILE"
exit 1
fi
echo "== File: $FILE =="
cat -n "$FILE" | sed -n '1,120p'
echo "== End =="Repository: QuantumNous/new-api
Length of output: 1123
Pin GitHub Actions to immutable commit SHAs and disable checkout credential persistence
actions/checkout@v4(line 19),docker/setup-buildx-action@v3(line 25), anddocker/build-push-action@v6(line 28) use moving@v*tags—pin eachuses:to a full commit SHA.- The checkout step (lines 18-19) doesn’t set
with: persist-credentials: false, leaving the token in git config by default.
Suggested hardening diff
- - name: Check out
- uses: actions/checkout@v4
+ - name: Check out
+ uses: actions/checkout@<FULL_LENGTH_COMMIT_SHA>
- - name: Set up Docker Buildx
- uses: docker/setup-buildx-action@v3
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@<FULL_LENGTH_COMMIT_SHA>
- - name: Build (no push)
- uses: docker/build-push-action@v6
+ - name: Build (no push)
+ uses: docker/build-push-action@<FULL_LENGTH_COMMIT_SHA>🧰 Tools
🪛 zizmor (1.25.2)
[warning] 18-19: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false
(artipacked)
[error] 19-19: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)
(unpinned-uses)
🤖 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 @.github/workflows/docker-build-branch.yml at line 19, The workflow is using
floating action tags and leaving checkout credentials persisted; replace uses:
actions/checkout@v4, docker/setup-buildx-action@v3, and
docker/build-push-action@v6 with their corresponding immutable commit SHAs and
add persist-credentials: false under the checkout step (the actions/checkout
block) to avoid storing the token in git config; ensure you update the three
uses lines to exact commit SHAs and add the with: persist-credentials: false key
to the actions/checkout invocation.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 @.github/workflows/docker-build-branch.yml:
- Around line 31-43: The workflow uses floating tags for third‑party actions in
the "Log in to GHCR" and "Extract metadata" steps (currently uses:
docker/login-action@v3 and docker/metadata-action@v5); replace those floating
tags with the corresponding immutable commit SHAs (e.g.,
docker/login-action@<full-commit-sha> and
docker/metadata-action@<full-commit-sha>) by finding the desired release commit
in each action's GitHub repo and updating the uses: fields so the steps "Log in
to GHCR" and "Extract metadata" reference the full SHA instead of a channel tag.
🪄 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: 6de3c6ce-e26c-4481-b087-8ed45e5bc3d5
📒 Files selected for processing (1)
.github/workflows/docker-build-branch.yml
| - name: Log in to GHCR | ||
| uses: docker/login-action@v3 | ||
| with: | ||
| registry: ${{ env.REGISTRY }} | ||
| username: ${{ github.actor }} | ||
| password: ${{ secrets.GITHUB_TOKEN }} | ||
|
|
||
| - name: Set up Docker Buildx | ||
| uses: docker/setup-buildx-action@v3 | ||
|
|
||
| - name: Extract metadata | ||
| id: meta | ||
| uses: docker/metadata-action@v5 |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ls -la .github/workflows || true
sed -n '1,200p' .github/workflows/docker-build-branch.yml | nl -ba | sed -n '1,140p'Repository: QuantumNous/new-api
Length of output: 779
🏁 Script executed:
#!/bin/bash
set -euo pipefail
cat -n .github/workflows/docker-build-branch.yml | sed -n '1,120p'Repository: QuantumNous/new-api
Length of output: 2106
Pin docker/login-action and docker/metadata-action to immutable SHAs in .github/workflows/docker-build-branch.yml.
uses: docker/login-action@v3 (line 32) and uses: docker/metadata-action@v5 (line 43) are floating tags; pin them to full commit SHAs to avoid unexpected upstream changes.
Suggested hardening diff
- name: Log in to GHCR
- uses: docker/login-action@v3
+ uses: docker/login-action@<FULL_LENGTH_COMMIT_SHA>
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
- uses: docker/metadata-action@v5
+ uses: docker/metadata-action@<FULL_LENGTH_COMMIT_SHA>
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}🧰 Tools
🪛 zizmor (1.25.2)
[error] 32-32: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)
(unpinned-uses)
[error] 39-39: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)
(unpinned-uses)
[error] 43-43: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)
(unpinned-uses)
🤖 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 @.github/workflows/docker-build-branch.yml around lines 31 - 43, The workflow
uses floating tags for third‑party actions in the "Log in to GHCR" and "Extract
metadata" steps (currently uses: docker/login-action@v3 and
docker/metadata-action@v5); replace those floating tags with the corresponding
immutable commit SHAs (e.g., docker/login-action@<full-commit-sha> and
docker/metadata-action@<full-commit-sha>) by finding the desired release commit
in each action's GitHub repo and updating the uses: fields so the steps "Log in
to GHCR" and "Extract metadata" reference the full SHA instead of a channel tag.
…rontends Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Add VoiceCloneUnlockRatio field to Pricing struct - Populate voice clone unlock ratio in updatePricing() - Display voice clone unlock in calculateModelPrice and getModelPriceItems - Add i18n entry for voice clone unlock label Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
51fdfc5 to
2b6f1df
Compare
为 DashScope 阿里百炼通道新增 Qwen(千问)和 MiniMax 的 TTS 语音合成、音色克隆、以及对应的计费逻辑,同时在 classic 和


default 两个前端补全 VoiceCloneUnlockRatio(音色克隆解锁价格)的设置支持。
新增 aliVoiceCloneHandler 字段 处理语音克隆请求的响应解析和用量计算
修复promptTokens直接取 cloneResp.Usage.Count 而非 info.GetEstimatePromptTokens(),避免 Qwen
list/delete(usage.count=0)被错误估值为创建价导致瞎78扣费
在 PostAudioConsumeQuota 中新增 ContextKeyVoiceCloneFixedPrice 常量
读取 context
中的音色克隆解锁固定价格并叠加到 quota 中,日志和 other 字段同步记录
测试覆盖 MiniMax 解锁价格设置、Qwen list 不设解锁价格、unmarshal
错误处理、上游错误处理
前端补全 VoiceCloneUnlockRatio 字段
破坏性变更 移除
vitePluginSemi、@lobehub/icons fallback (高版本反复安装不上恶心到我了bushi)
API 真实请求验证:
POST /v1/audio/speech qwen3-tts-flash → 302 (OSS redirect)
POST /v1/audio/speech MiniMax/speech-02-turbo → 200 audio/mpeg
POST /v1/audio/voice-clone qwen-voice-enrollment list → 200, usage.count=0, quota=0
POST /v1/audio/voice-clone MiniMax/speech-02-turbo voice_clone → 200, 解锁价格 9.9 + usage.characters 计费
后端配置:
{
"minimax-tts": 9.9, "MiniMax/speech-01-hd": 9.9,
"MiniMax/speech-01-turbo": 9.9, "MiniMax/speech-02-hd": 9.9,
}

经典前端"分组与模型定价设置"页面中 VoiceCloneUnlockRatio(音色克隆解锁价格)字段正常显示
Summary by CodeRabbit
New Features
Tests
Chores