Skip to content

Qwentts + MiniMaxtts + TTS voice clone 计费 - #5201

Open
youyao666 wants to merge 18 commits into
QuantumNous:mainfrom
youyao666:main
Open

youyao666 wants to merge 18 commits into
QuantumNous:mainfrom
youyao666:main

Conversation

@youyao666

@youyao666 youyao666 commented May 30, 2026 •

Copy link
Copy Markdown

为 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,
ee6b68148d34a3289a2ca5539b4e01bf
c80538585e38cdf17e9cb34ca9be9891

"MiniMax/speech-02-turbo": 9.9, "MiniMax/speech-2.5-hd-preview": 9.9,
"MiniMax/speech-2.5-turbo-preview": 9.9, "qwen-tts": 11

}
经典前端"分组与模型定价设置"页面中 VoiceCloneUnlockRatio(音色克隆解锁价格)字段正常显示
b78d875abdb12693229d0a302eef3ff3

Summary by CodeRabbit

  • New Features

    • Voice‑clone support: new audio voice‑clone endpoints, relay routing, and integrations with Ali and MiniMax relays
    • Voice clone unlock pricing: configurable unlock‑ratio, optional fixed‑price billing with quota adjustments, and expanded UI for ratio/price and model pricing
    • Video resolution ratio: new per‑model resolution multipliers and billing support
  • Tests

    • Added tests for voice‑clone responses, billing adjustments, and ratio behaviors
  • Chores

    • Frontend dependency pinning, build config updates, icon/import adjustments, and CI Docker build/push workflow

youyao666 and others added 7 commits May 30, 2026 15:49
…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>
@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

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

Changes

Voice Clone Audio Relay & Pricing

Layer / File(s) Summary
Relay mode, router, DTO, validation
relay/constant/*, router/relay-router.go, dto/audio.go, relay/helper/valid_request.go
Adds RelayModeAudioVoiceClone, new POST routes, AudioVoiceCloneRequest DTO with token-count meta, and GetAndValidAudioVoiceCloneRequest validator.
AudioHelper integration
relay/audio_handler.go
AudioHelper accepts AudioVoiceCloneRequest and maps it to a unified dto.AudioRequest for adaptor conversion and downstream processing.
Ali adaptor, TTS & voice-clone handlers + tests
relay/channel/ali/*
Implements Ali request URL/header conversion, ConvertAudioRequest, aliTTSHandler and aliVoiceCloneHandler with usage accounting and unit tests.
MiniMax adaptor & handlers
relay/channel/minimax/*
Adds MiniMax voice-clone request conversion, endpoint routing, MiniMaxVoiceCloneResponse and handleVoiceCloneResponse with token accounting.
Option, model map, and controller sync
model/option.go, controller/option.go, controller/ratio_sync.go
Initialize and persist VoiceCloneUnlockRatio via ratio_setting APIs; include voice_clone_unlock_ratio in pricing sync fields and local data.
Ratio settings implementation
setting/ratio_setting/model_ratio.go, setting/ratio_setting/exposed_cache.go
Add default voice-clone unlock ratios and video-resolution ratios, runtime maps and JSON helpers, and expose new ratio keys in the exposed cache payload.
Quota, billing, and task adjustments
service/quota.go, types/price_data.go, relay/channel/task/ali/adaptor.go
Add context fixed-price key, include fixed unlock price in audio quota settlement, extend PriceData fields, and introduce AdjustBillingOnComplete with video-resolution overrides and tests.
Frontend (classic & default)
web/classic/*, web/default/*
Add VoiceCloneUnlockRatio and VideoResolutionRatio across UI: settings, model pricing editors, visual editor, upstream sync, types, and forms; plus minor package/icon tweaks.
Packaging & CI
web/classic/package.json, web/classic/vite.config.js, .github/workflows/docker-build-branch.yml
Pin frontend deps, remove vite semi plugin, and add Docker build-and-push workflow for branches.

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
Loading

Estimated code review effort:
🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • seefs001
  • creamlike1024

"I hopped in code with eager paws,
Ali sings and MiniMax claws,
Ratios set and quotas tuned,
Voice clones bloom — I hum and snooze! 🎶"

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 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 win

Voice clone unlock price incorrectly treated as inputPrice-dependent.

voiceCloneUnlockPrice is a fixed price per voice-clone operation and does not depend on inputPrice. Including it in hasDerivedPricing (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 win

Custom memo equality check is missing voiceCloneUnlockRatio comparison.

The component won't re-render when voiceCloneUnlockRatio prop 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 win

Use common.Unmarshal instead of encoding/json.

Line 136 uses encoding/json.Unmarshal directly for application-level response parsing. As per coding guidelines, all JSON marshal/unmarshal operations in business code must use wrapper functions from common/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 from common/json.go for 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 win

Fix vite lockfile mismatch vs peerDependency.

web/classic/package.json pins vite to 5.1.0, and @douyinfe/vite-plugin-semi declares an exact peerDependency on vite: "5.1.0", but web/classic/bun.lock resolves vite@5.4.11. Update/regenerate bun.lock so the locked vite version matches the pinned 5.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 value

Consider normalizing model name in GetVoiceCloneUnlockRatio.

Other ratio getters like GetAudioRatio and GetModelRatio call FormatMatchingModelName(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 FreeModel and VoiceCloneUnlockRatio fields are not included in the ToSetting() 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 win

Duplicate 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.Text with custom circular styling
  • In render.jsx: Uses Avatar component

Both achieve similar results, but the inconsistency makes maintenance harder. This was already flagged in the render.jsx review, but the implementation difference deserves note.

Extract to a shared utility with a consistent implementation (prefer the Avatar approach from render.jsx as 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 win

Consider 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.jsx and Home/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

📥 Commits

Reviewing files that changed from the base of the PR and between 230a359 and e435519.

📒 Files selected for processing (44)
  • controller/option.go
  • controller/ratio_sync.go
  • controller/relay.go
  • dto/audio.go
  • model/option.go
  • relay/audio_handler.go
  • relay/channel/ali/adaptor.go
  • relay/channel/ali/constants.go
  • relay/channel/ali/dto.go
  • relay/channel/ali/tts.go
  • relay/channel/ali/tts_test.go
  • relay/channel/minimax/adaptor.go
  • relay/channel/minimax/constants.go
  • relay/channel/minimax/relay-minimax.go
  • relay/channel/minimax/tts.go
  • relay/channel/task/ali/adaptor.go
  • relay/constant/relay_mode.go
  • relay/helper/valid_request.go
  • router/relay-router.go
  • service/quota.go
  • setting/ratio_setting/exposed_cache.go
  • setting/ratio_setting/model_ratio.go
  • types/price_data.go
  • web/classic/package.json
  • web/classic/src/components/settings/RatioSetting.jsx
  • web/classic/src/helpers/render.jsx
  • web/classic/src/pages/Home/index.jsx
  • 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/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.js
  • web/classic/vite.config.js
  • web/default/src/features/models/components/drawers/model-mutate-drawer.tsx
  • web/default/src/features/system-settings/billing/index.tsx
  • web/default/src/features/system-settings/billing/section-registry.tsx
  • web/default/src/features/system-settings/models/constants.ts
  • web/default/src/features/system-settings/models/index.tsx
  • web/default/src/features/system-settings/models/model-pricing-sheet.tsx
  • web/default/src/features/system-settings/models/model-ratio-form.tsx
  • web/default/src/features/system-settings/models/model-ratio-visual-editor.tsx
  • web/default/src/features/system-settings/models/ratio-settings-card.tsx
  • web/default/src/features/system-settings/models/upstream-ratio-sync-helpers.ts
  • web/default/src/features/system-settings/models/upstream-ratio-sync.tsx
  • web/default/src/features/system-settings/types.ts
💤 Files with no reviewable changes (1)
  • web/classic/vite.config.js

Comment thread dto/audio.go
Comment on lines +55 to +69
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,
}
}

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

Comment thread relay/channel/ali/tts.go
Comment on lines +56 to +95
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
}

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

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

Comment thread relay/channel/ali/tts.go
Comment on lines +97 to +134
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
}

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

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

Comment thread relay/channel/ali/tts.go
Comment on lines +136 to +157
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
}

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

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

Comment on lines +46 to +55
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

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.

🛠️ 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',

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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 ratioSyncFields array, which determines 'ratio' billing category
  • Lines 461-463: Presence of VoiceCloneUnlockRatio causes getLocalBillingCategory to return 'ratio' even when model uses per-request pricing
  • Lines 325-331: getBillingCategory defaults all non-price/tiered fields to 'ratio'
  • Line 559: VoiceCloneUnlockRatio is deleted when switching to price mode

This causes:

  • False conflict detection between ModelPrice and VoiceCloneUnlockRatio
  • 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:

  1. Remove it from ratioSyncFields and create a separate category (e.g., addonSyncFields)
  2. Update getBillingCategory to return a new category for addon fields
  3. Update getLocalBillingCategory to ignore addon fields when determining mode
  4. Don't delete addon fields when switching between price/ratio modes (remove line 559)
  5. 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' },

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 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 || true

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

Repository: 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" {} \; || true

Repository: 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" {} \; || true

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

Comment on lines +217 to +222
{
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',
},

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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:

  1. It's grouped with per-token price lanes in laneConfigs and will display "USD price per 1M tokens" (line 1058) when enabled.
  2. The deriveLaneRatio logic 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 voiceCloneUnlock as 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

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Comment on lines +374 to +375
currentRatios.AudioCompletionRatio[model] !== undefined ||
currentRatios.VoiceCloneUnlockRatio[model] !== undefined

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

🧩 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=go

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

youyao666 and others added 5 commits May 31, 2026 01:55
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>

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

🧹 Nitpick comments (1)
relay/channel/task/ali/billing_test.go (1)

9-114: ⚡ Quick win

Consider 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's UpdateVideoResolutionRatioByJSONString), this could cause flaky failures or unexpected interactions.

Consider either:

  • Adding t.Parallel() with proper isolation, or
  • Resetting the ratio settings state in a defer or t.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

📥 Commits

Reviewing files that changed from the base of the PR and between e435519 and d194498.

📒 Files selected for processing (24)
  • controller/option.go
  • controller/ratio_sync.go
  • model/option.go
  • relay/channel/task/ali/adaptor.go
  • relay/channel/task/ali/billing_test.go
  • setting/ratio_setting/exposed_cache.go
  • setting/ratio_setting/model_ratio.go
  • web/classic/src/components/settings/RatioSetting.jsx
  • 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/classic/src/pages/Setting/Ratio/hooks/useModelPricingEditorState.js
  • web/default/src/features/models/components/drawers/model-mutate-drawer.tsx
  • web/default/src/features/system-settings/billing/index.tsx
  • web/default/src/features/system-settings/billing/section-registry.tsx
  • web/default/src/features/system-settings/models/constants.ts
  • web/default/src/features/system-settings/models/index.tsx
  • web/default/src/features/system-settings/models/model-pricing-sheet.tsx
  • web/default/src/features/system-settings/models/model-ratio-form.tsx
  • web/default/src/features/system-settings/models/model-ratio-visual-editor.tsx
  • web/default/src/features/system-settings/models/ratio-settings-card.tsx
  • web/default/src/features/system-settings/models/upstream-ratio-sync-helpers.ts
  • web/default/src/features/system-settings/models/upstream-ratio-sync.tsx
  • web/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

Comment on lines +229 to +234
{
key: 'videoResolution',
titleKey: 'Video resolution ratio',
descriptionKey: 'Model-specific resolution multipliers (e.g., 720P: 2, 1080P: 3.33).',
placeholder: '{}',
},

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

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, and handleLanePriceChange (Line 596) rejects any input not matching numericDraftRegex, so a JSON object can never be typed.
  • When the lane is enabled or the input price changes, syncLaneRatios (Line 561) calls deriveLaneRatio('videoResolution', …) (Line 541). toNumberOrNull on a JSON string returns null, so videoResolutionRatio is 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>

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

📥 Commits

Reviewing files that changed from the base of the PR and between d194498 and 7e65900.

📒 Files selected for processing (1)
  • .github/workflows/docker-build-branch.yml

Comment on lines +18 to +19
- name: Check out
uses: actions/checkout@v4

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 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 || true

Repository: 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" || true

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


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

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 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), and docker/build-push-action@v6 (line 28) use moving @v* tags—pin each uses: 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>

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e65900 and 42467ba.

📒 Files selected for processing (1)
  • .github/workflows/docker-build-branch.yml

Comment on lines +31 to +43
- 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

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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

youyao666 and others added 4 commits May 31, 2026 11:40
…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>

This branch has not been deployed

No deployments
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.

1 participant