Repository navigation
Conversation
WalkthroughThis pull request introduces period-based token quota support, enabling daily and monthly rate limiting on tokens. Backend changes add quota validation, state management, and enforcement across the token lifecycle. Frontend updates include UI components for quota configuration, display columns, and multilingual support. Changes
Sequence DiagramsequenceDiagram
actor Client
participant Controller as Token Controller
participant Model as Token Model
participant DB as Database
participant Service as Quota Service
Client->>Controller: POST /token (with period_quota)
Controller->>Model: ValidateTokenQuotaPeriodConfig()
Model-->>Controller: Config valid or error
alt Invalid config
Controller-->>Client: 400 API Error
else Valid config
Controller->>Model: ApplyPeriodQuotaConfig()
Model->>Model: ResetPeriodQuotaWindow()
Model->>DB: INSERT token with quota fields
DB-->>Model: Success
Controller-->>Client: 200 Created token
end
Client->>Service: Use token (PreConsumeTokenQuota)
Service->>Model: GetTokenById()
Model->>DB: SELECT token
DB-->>Model: Token with period quota state
Model-->>Service: Token
Service->>Model: RefreshPeriodQuotaWindowIfNeeded()
Model->>Model: Check if window expired
alt Window expired
Model->>Model: ResetPeriodQuotaWindow()
Model->>DB: UPDATE quota_used_in_period = 0
else Window active
Model->>DB: SELECT current quota_used_in_period
end
DB-->>Model: Updated state
Service->>Service: Check IsPeriodQuotaEnabled()
Service->>Service: Verify quota_used + request <= quota_limit
alt Quota exceeded
Service-->>Client: PeriodQuotaExceededError
else Quota available
Service->>Model: DecreaseTokenQuota()
Model->>DB: UPDATE quota_used_in_period
DB-->>Model: Success
Service-->>Client: Quota consumed
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~65 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment Tip CodeRabbit can scan for known vulnerabilities in your dependencies using OSV Scanner.OSV Scanner will automatically detect and report security vulnerabilities in your project's dependencies. No additional configuration is required. |
There was a problem hiding this comment.
Actionable comments posted: 11
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@model/token_period_quota.go`:
- Around line 157-188: RefreshPeriodQuotaWindowIfNeeded and
persistPeriodQuotaState perform a non-atomic refresh/write that can race with
adjustTokenQuotaWithPeriod and overwrite recent quota increments; fix by
performing the refresh and persist inside the same CAS/row-lock pattern used by
adjustTokenQuotaWithPeriod (i.e., open a DB transaction, SELECT the token row
FOR UPDATE or use the same optimistic update/where-version clause), re-check
current period fields after acquiring the lock, compute/reset the in-memory
window only if still needed, then write the updated period fields back and
invalidate cache; if the refresh loses the race (fields changed after lock),
reload/merge quota_used_in_period from the DB and abort or retry the refresh so
you never clobber concurrent quota increments.
In `@model/token.go`:
- Around line 233-238: The read-before-mutate sequence can enqueue cacheSetToken
and repopulate Redis with the pre-mutation snapshot; fix by using a
side-effect-free lookup (use the variant of GetTokenByKey/GetTokenById that does
not enqueue cacheSetToken) when you only plan to mutate (e.g. before calling
RefreshPeriodQuotaWindowIfNeeded, adjusting QuotaUsedInPeriod, or checking
PeriodQuotaExceededError/QuotaLimit), or alternatively make the mutation path
write the updated token back to the cache instead of only deleting it; apply
this change for the occurrences around
RefreshPeriodQuotaWindowIfNeeded/IsPeriodQuotaEnabled/PeriodQuotaExceededError
and the other locations mentioned (lines ~409-417, ~448-456) to prevent stale
quota data.
In `@service/billing_session.go`:
- Around line 206-214: The current code calls
model.GetTokenById(s.relayInfo.TokenId) which performs a direct DB lookup on
every request; update this to use a cache-first approach or reuse the token
object stored during authentication: either modify model.GetTokenById to attempt
a cache lookup before falling back to DB (maintain behavior for GetTokenByKey)
or change the auth middleware to store the full token in the gin context (e.g.,
under "token" or similar) and here retrieve that token and call
token.IsPeriodQuotaEnabled() instead of calling GetTokenById; ensure you keep
the s.relayInfo.TokenId check and preserve error handling semantics when
migrating to the cached/context-stored token.
In `@service/quota.go`:
- Around line 452-455: The fallback lookup uses relayInfo.TokenKey without
normalizing the sk- prefix, so update the fallback in the
GetTokenById/GetTokenByKey flow to strip the "sk-" prefix before calling
model.GetTokenByKey; specifically, when token lookup by ID fails and
relayInfo.TokenKey != "", call
model.GetTokenByKey(strings.TrimPrefix(relayInfo.TokenKey, "sk-"), true) instead
of passing relayInfo.TokenKey raw so the lookup matches other sites (see usages
around GetTokenById and GetTokenByKey).
In `@web/src/i18n/locales/fr.json`:
- Around line 3286-3302: The values for the new keys ("周期额度", "请选择周期额度", "每日额度",
"每月额度", "周期额度上限", "请输入周期额度上限", "未启用周期额度时将忽略该值", "周期额度上限必须大于 0", "额度时间范围",
"请选择额度时间范围", "额度时间范围内上限", "请输入额度时间范围内上限", "未启用额度时间范围时将忽略该值", "额度时间范围内上限必须大于 0",
"当前周期已用额度", "下次重置时间", "未启用") currently contain English text and must be replaced
with proper French translations; update the right-hand side strings in the
fr.json entries for each of those keys to their French equivalents (e.g., "周期额度"
-> "Quota périodique", "请选择周期额度" -> "Sélectionnez un quota périodique", etc.) so
the French locale displays French text instead of English. Ensure grammar and
accents are correct and keep the key names unchanged.
In `@web/src/i18n/locales/ja.json`:
- Around line 3267-3283: Replace the English values for the listed keys with
proper Japanese translations: change "周期额度" -> "周期クォータ", "每日额度" -> "日次クォータ",
"每月额度" -> "月次クォータ", "周期额度上限" -> "周期クォータ上限", "当前周期已用额度" -> "当期使用済みクォータ", and
"下次重置时间" -> "次回リセット日時"; for "未启用" reuse the existing Japanese translation "無効"
already present elsewhere in the locale (avoid creating a conflicting duplicate
key), and ensure the JSON keys "请选择周期额度", "周期额度上限必须大于 0", "额度时间范围", "请选择额度时间范围",
"额度时间范围内上限", "请输入额度时间范围内上限", "未启用额度时间范围时将忽略该值", and "额度时间范围内上限必须大于 0" remain
properly translated into Japanese consistent with project style if needed.
In `@web/src/i18n/locales/ru.json`:
- Around line 3300-3316: The new block adds English translations for
quota-related keys (e.g., "周期额度", "请选择周期额度", "每日额度", "每月额度", "周期额度上限",
"请输入周期额度上限", "未启用周期额度时将忽略该值", "周期额度上限必须大于 0", "额度时间范围", "请选择额度时间范围",
"额度时间范围内上限", "请输入额度时间范围内上限", "未启用额度时间范围时将忽略该值", "额度时间范围内上限必须大于 0", "当前周期已用额度",
"下次重置时间") but leaves them in English and re-declares "未启用"; instead, replace
these English values with proper Russian translations and remove the duplicate
"未启用" entry so the locale uses the existing Russian value already defined
earlier (do not change the original key name "未启用"); update only the values for
the listed keys in ru.json to their Russian equivalents.
In `@web/src/i18n/locales/vi.json`:
- Around line 3837-3852: The Vietnamese locale file vi.json contains new
translation keys (e.g., "周期额度", "请选择周期额度", "每日额度", "每月额度", "周期额度上限", "额度时间范围",
"当前周期已用额度", "下次重置时间") whose values are still in English; update each of these
values to proper Vietnamese translations so the token quota UI is fully
localized (replace "Period quota", "Daily quota", "Monthly quota", "Period quota
limit", "Quota time range", "Used in current period", "Next reset time", etc.,
with their Vietnamese equivalents) and ensure consistency with existing vi.json
phrasing and tone.
- Line 3853: The translation key "未启用" is duplicated in the nested "translation"
object (once at Line ~1669 as "Chưa bật" and again at Line ~3853 as "Disabled"),
causing the last occurrence to override the correct Vietnamese text; remove or
replace the duplicate English entry so the Vietnamese value ("Chưa bật") remains
the sole value for the "未启用" key in vi.json (and apply the same de-duplication
fix to the other locale files where "未启用" is duplicated), ensuring the correct
translation is preserved in the "translation" object.
In `@web/src/i18n/locales/zh-CN.json`:
- Line 2958: The locale file contains a duplicate key "未启用" (already defined
earlier) which should be removed to avoid ambiguous resolution; locate the
duplicate "未启用" entry in zh-CN.json (the instance around the reported diff) and
delete it or consolidate it with the original definition so only one "未启用" key
remains, then run the i18n toolchain (bun run i18n:extract, bun run i18n:sync,
bun run i18n:lint) to verify and fix any remaining i18n issues.
In `@web/src/i18n/locales/zh-TW.json`:
- Line 2967: The file contains a duplicate translation key "未启用" (Chinese key)
defined twice; remove the redundant entry (the one at the later occurrence) so
only the original definition remains (the earlier "未启用": "未啟用"), and then run
the i18n linter (bun run i18n:lint) to validate the JSON. Ensure you update the
JSON object by deleting the duplicate key and saving a valid flat JSON
structure.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8fe953f2-6e13-454c-8d55-ba1ef6b023f3
📒 Files selected for processing (19)
controller/token.gocontroller/token_test.gomodel/task_cas_test.gomodel/token.gomodel/token_period_quota.gomodel/token_period_quota_test.goservice/billing_session.goservice/billing_session_test.goservice/quota.goservice/task_billing_test.goweb/src/components/table/tokens/TokensColumnDefs.jsxweb/src/components/table/tokens/modals/EditTokenModal.jsxweb/src/i18n/locales/en.jsonweb/src/i18n/locales/fr.jsonweb/src/i18n/locales/ja.jsonweb/src/i18n/locales/ru.jsonweb/src/i18n/locales/vi.jsonweb/src/i18n/locales/zh-CN.jsonweb/src/i18n/locales/zh-TW.json
| func (token *Token) persistPeriodQuotaState() error { | ||
| if token == nil || token.Id == 0 { | ||
| return nil | ||
| } | ||
|
|
||
| if err := DB.Model(&Token{}).Where("id = ?", token.Id).Select( | ||
| "quota_period", | ||
| "quota_limit", | ||
| "quota_used_in_period", | ||
| "quota_last_reset_time", | ||
| "quota_next_reset_time", | ||
| ).Updates(token).Error; err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if common.RedisEnabled && token.Key != "" { | ||
| if err := cacheDeleteToken(token.Key); err != nil { | ||
| common.SysLog("failed to invalidate token cache: " + err.Error()) | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (token *Token) RefreshPeriodQuotaWindowIfNeeded() error { | ||
| if token == nil || !token.IsPeriodQuotaEnabled() { | ||
| return nil | ||
| } | ||
| if !token.RefreshPeriodQuotaWindow(time.Now()) { | ||
| return nil | ||
| } | ||
| return token.persistPeriodQuotaState() | ||
| } |
There was a problem hiding this comment.
Make period-window refresh atomic with quota consumption.
RefreshPeriodQuotaWindowIfNeeded resets the in-memory token and persistPeriodQuotaState then unconditionally writes that snapshot back. Around a day/month boundary, another request can consume quota through adjustTokenQuotaWithPeriod between those two steps, and this write will overwrite the freshly incremented quota_used_in_period back to 0. That undercounts the new window and can let the token overspend. Please protect the refresh with the same row-lock/CAS semantics as adjustTokenQuotaWithPeriod, and reload the current period fields if the refresh loses that race.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@model/token_period_quota.go` around lines 157 - 188,
RefreshPeriodQuotaWindowIfNeeded and persistPeriodQuotaState perform a
non-atomic refresh/write that can race with adjustTokenQuotaWithPeriod and
overwrite recent quota increments; fix by performing the refresh and persist
inside the same CAS/row-lock pattern used by adjustTokenQuotaWithPeriod (i.e.,
open a DB transaction, SELECT the token row FOR UPDATE or use the same
optimistic update/where-version clause), re-check current period fields after
acquiring the lock, compute/reset the in-memory window only if still needed,
then write the updated period fields back and invalidate cache; if the refresh
loses the race (fields changed after lock), reload/merge quota_used_in_period
from the DB and abort or retry the refresh so you never clobber concurrent quota
increments.
| if err := token.RefreshPeriodQuotaWindowIfNeeded(); err != nil { | ||
| return token, err | ||
| } | ||
| if token.IsPeriodQuotaEnabled() && token.QuotaUsedInPeriod >= token.QuotaLimit { | ||
| return token, token.PeriodQuotaExceededError() | ||
| } |
There was a problem hiding this comment.
Avoid cache-populating reads before mutating period-quota state.
GetTokenByKey(..., false) and GetTokenById(...) can enqueue an async cacheSetToken on the read path. These new branches then refresh/adjust the same token and only delete the Redis entry; if the queued cache write lands after that delete, Redis is repopulated with the pre-refresh/pre-adjust snapshot, so later cached reads can see stale quota_used_in_period / reset timestamps. Use a side-effect-free lookup here, or have the mutation path write back the updated snapshot instead of relying on delete-only invalidation.
Also applies to: 409-417, 448-456
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@model/token.go` around lines 233 - 238, The read-before-mutate sequence can
enqueue cacheSetToken and repopulate Redis with the pre-mutation snapshot; fix
by using a side-effect-free lookup (use the variant of
GetTokenByKey/GetTokenById that does not enqueue cacheSetToken) when you only
plan to mutate (e.g. before calling RefreshPeriodQuotaWindowIfNeeded, adjusting
QuotaUsedInPeriod, or checking PeriodQuotaExceededError/QuotaLimit), or
alternatively make the mutation path write the updated token back to the cache
instead of only deleting it; apply this change for the occurrences around
RefreshPeriodQuotaWindowIfNeeded/IsPeriodQuotaEnabled/PeriodQuotaExceededError
and the other locations mentioned (lines ~409-417, ~448-456) to prevent stale
quota data.
| if s.relayInfo.TokenId > 0 { | ||
| token, err := model.GetTokenById(s.relayInfo.TokenId) | ||
| if err != nil { | ||
| return false | ||
| } | ||
| if token.IsPeriodQuotaEnabled() { | ||
| return false | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check if token is already loaded before shouldTrust is called, and verify GetTokenById caching behavior.
# 1. Find where token_quota context value is set (indicates token already loaded)
echo "=== Where token_quota is set in context ==="
rg -n "SetInt.*token_quota|Set.*\"token_quota\"" --type go -C3
# 2. Check GetTokenById implementation for caching
echo -e "\n=== GetTokenById implementation (check for cache-first logic) ==="
ast-grep --pattern 'func GetTokenById($id $_) ($_, $_) {
$$$
}'
# 3. Check if there's a cache-get before DB.First in token lookup
echo -e "\n=== Check for Redis cache read in token functions ==="
rg -n "cacheGetToken|GetTokenFromCache" --type go -C3Repository: QuantumNous/new-api
Length of output: 1684
🏁 Script executed:
#!/bin/bash
# 1. Find GetTokenById implementation
echo "=== GetTokenById function implementation ==="
rg -n "func GetTokenById" --type go -A 15
# 2. Check if token object is stored in context alongside token_quota
echo -e "\n=== Token object in context ==="
rg -n 'c\.Set.*"token' --type go | head -20
# 3. Check preConsume/shouldTrust callsite to see what's available
echo -e "\n=== preConsume and shouldTrust context ==="
rg -n "func.*shouldTrust|func.*preConsume" --type go -A 5 | head -30
# 4. Verify if GetTokenById is the main path or if there are alternatives
echo -e "\n=== GetTokenById usage in billing_session.go ==="
rg -n "GetTokenById" service/billing_session.go -B 3 -A 3Repository: QuantumNous/new-api
Length of output: 4019
GetTokenById performs direct database lookups without using the cache-first pattern.
model.GetTokenById (line 207) executes DB.First() synchronously on every relay request where TokenId > 0. This is a direct DB lookup without the cache-first pattern used by other token retrieval functions like GetTokenByKey (which calls cacheGetTokenByKey at model/token.go:290).
Since the token is already authenticated during middleware execution (middleware/auth.go:382), consider either:
- Adding cache-first logic to
GetTokenByIdto match the caching pattern used elsewhere in the codebase, or - Storing the full token object in the gin context alongside individual token properties, allowing reuse here.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@service/billing_session.go` around lines 206 - 214, The current code calls
model.GetTokenById(s.relayInfo.TokenId) which performs a direct DB lookup on
every request; update this to use a cache-first approach or reuse the token
object stored during authentication: either modify model.GetTokenById to attempt
a cache lookup before falling back to DB (maintain behavior for GetTokenByKey)
or change the auth middleware to store the full token in the gin context (e.g.,
under "token" or similar) and here retrieve that token and call
token.IsPeriodQuotaEnabled() instead of calling GetTokenById; ensure you keep
the s.relayInfo.TokenId check and preserve error handling semantics when
migrating to the cached/context-stored token.
| token, err := model.GetTokenById(relayInfo.TokenId) | ||
| if err != nil && relayInfo.TokenKey != "" { | ||
| token, err = model.GetTokenByKey(relayInfo.TokenKey, true) | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "GetTokenByKey definition:"
rg -n -C5 'func .*GetTokenByKey\(' model
echo
echo "Current GetTokenByKey call sites and key normalization:"
rg -n -C2 'GetTokenByKey\(|TrimPrefix\(.*"sk-"' service controller modelRepository: QuantumNous/new-api
Length of output: 3100
Strip the sk- prefix before calling GetTokenByKey in the fallback path.
Line 454 calls model.GetTokenByKey(relayInfo.TokenKey, true) without normalizing the key. All other call sites in the codebase (e.g., line 98 in the same file and controller/token.go:139) strip the sk- prefix before passing the key to GetTokenByKey. The new fallback should do the same:
token, err = model.GetTokenByKey(strings.TrimPrefix(relayInfo.TokenKey, "sk-"), true)Otherwise, the fallback lookup will fail to find tokens when TokenId is missing.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@service/quota.go` around lines 452 - 455, The fallback lookup uses
relayInfo.TokenKey without normalizing the sk- prefix, so update the fallback in
the GetTokenById/GetTokenByKey flow to strip the "sk-" prefix before calling
model.GetTokenByKey; specifically, when token lookup by ID fails and
relayInfo.TokenKey != "", call
model.GetTokenByKey(strings.TrimPrefix(relayInfo.TokenKey, "sk-"), true) instead
of passing relayInfo.TokenKey raw so the lookup matches other sites (see usages
around GetTokenById and GetTokenByKey).
| "周期额度": "Period quota", | ||
| "请选择周期额度": "Select a period quota", | ||
| "每日额度": "Daily quota", | ||
| "每月额度": "Monthly quota", | ||
| "周期额度上限": "Period quota limit", | ||
| "请输入周期额度上限": "Please enter the period quota limit", | ||
| "未启用周期额度时将忽略该值": "This value is ignored when period quota is disabled", | ||
| "周期额度上限必须大于 0": "Period quota limit must be greater than 0", | ||
| "额度时间范围": "Quota time range", | ||
| "请选择额度时间范围": "Select a quota time range", | ||
| "额度时间范围内上限": "Quota cap within the time range", | ||
| "请输入额度时间范围内上限": "Please enter the quota cap within the time range", | ||
| "未启用额度时间范围时将忽略该值": "This value is ignored when the quota time range is disabled", | ||
| "额度时间范围内上限必须大于 0": "The quota cap within the time range must be greater than 0", | ||
| "当前周期已用额度": "Used in current period", | ||
| "下次重置时间": "Next reset time", | ||
| "未启用": "Disabled" |
There was a problem hiding this comment.
Critical: English translations in French locale file
All newly added period quota translations (lines 3286-3302) contain English text instead of French. This will display English strings to French-speaking users, breaking the localization.
🇫🇷 Proposed French translations
- "周期额度": "Period quota",
+ "周期额度": "Quota périodique",
- "请选择周期额度": "Select a period quota",
+ "请选择周期额度": "Sélectionnez un quota périodique",
- "每日额度": "Daily quota",
+ "每日额度": "Quota quotidien",
- "每月额度": "Monthly quota",
+ "每月额度": "Quota mensuel",
- "周期额度上限": "Period quota limit",
+ "周期额度上限": "Limite de quota périodique",
- "请输入周期额度上限": "Please enter the period quota limit",
+ "请输入周期额度上限": "Veuillez saisir la limite de quota périodique",
- "未启用周期额度时将忽略该值": "This value is ignored when period quota is disabled",
+ "未启用周期额度时将忽略该值": "Cette valeur est ignorée lorsque le quota périodique est désactivé",
- "周期额度上限必须大于 0": "Period quota limit must be greater than 0",
+ "周期额度上限必须大于 0": "La limite de quota périodique doit être supérieure à 0",
- "额度时间范围": "Quota time range",
+ "额度时间范围": "Plage de temps du quota",
- "请选择额度时间范围": "Select a quota time range",
+ "请选择额度时间范围": "Sélectionnez une plage de temps du quota",
- "额度时间范围内上限": "Quota cap within the time range",
+ "额度时间范围内上限": "Plafond du quota dans la plage de temps",
- "请输入额度时间范围内上限": "Please enter the quota cap within the time range",
+ "请输入额度时间范围内上限": "Veuillez saisir le plafond du quota dans la plage de temps",
- "未启用额度时间范围时将忽略该值": "This value is ignored when the quota time range is disabled",
+ "未启用额度时间范围时将忽略该值": "Cette valeur est ignorée lorsque la plage de temps du quota est désactivée",
- "额度时间范围内上限必须大于 0": "The quota cap within the time range must be greater than 0",
+ "额度时间范围内上限必须大于 0": "Le plafond du quota dans la plage de temps doit être supérieur à 0",
- "当前周期已用额度": "Used in current period",
+ "当前周期已用额度": "Utilisé dans la période actuelle",
- "下次重置时间": "Next reset time",
+ "下次重置时间": "Prochaine réinitialisation",
- "未启用": "Disabled"
+ "未启用": "Désactivé"📝 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.
| "周期额度": "Period quota", | |
| "请选择周期额度": "Select a period quota", | |
| "每日额度": "Daily quota", | |
| "每月额度": "Monthly quota", | |
| "周期额度上限": "Period quota limit", | |
| "请输入周期额度上限": "Please enter the period quota limit", | |
| "未启用周期额度时将忽略该值": "This value is ignored when period quota is disabled", | |
| "周期额度上限必须大于 0": "Period quota limit must be greater than 0", | |
| "额度时间范围": "Quota time range", | |
| "请选择额度时间范围": "Select a quota time range", | |
| "额度时间范围内上限": "Quota cap within the time range", | |
| "请输入额度时间范围内上限": "Please enter the quota cap within the time range", | |
| "未启用额度时间范围时将忽略该值": "This value is ignored when the quota time range is disabled", | |
| "额度时间范围内上限必须大于 0": "The quota cap within the time range must be greater than 0", | |
| "当前周期已用额度": "Used in current period", | |
| "下次重置时间": "Next reset time", | |
| "未启用": "Disabled" | |
| "周期额度": "Quota périodique", | |
| "请选择周期额度": "Sélectionnez un quota périodique", | |
| "每日额度": "Quota quotidien", | |
| "每月额度": "Quota mensuel", | |
| "周期额度上限": "Limite de quota périodique", | |
| "请输入周期额度上限": "Veuillez saisir la limite de quota périodique", | |
| "未启用周期额度时将忽略该值": "Cette valeur est ignorée lorsque le quota périodique est désactivé", | |
| "周期额度上限必须大于 0": "La limite de quota périodique doit être supérieure à 0", | |
| "额度时间范围": "Plage de temps du quota", | |
| "请选择额度时间范围": "Sélectionnez une plage de temps du quota", | |
| "额度时间范围内上限": "Plafond du quota dans la plage de temps", | |
| "请输入额度时间范围内上限": "Veuillez saisir le plafond du quota dans la plage de temps", | |
| "未启用额度时间范围时将忽略该值": "Cette valeur est ignorée lorsque la plage de temps du quota est désactivée", | |
| "额度时间范围内上限必须大于 0": "Le plafond du quota dans la plage de temps doit être supérieur à 0", | |
| "当前周期已用额度": "Utilisé dans la période actuelle", | |
| "下次重置时间": "Prochaine réinitialisation", | |
| "未启用": "Désactivé" |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/i18n/locales/fr.json` around lines 3286 - 3302, The values for the
new keys ("周期额度", "请选择周期额度", "每日额度", "每月额度", "周期额度上限", "请输入周期额度上限",
"未启用周期额度时将忽略该值", "周期额度上限必须大于 0", "额度时间范围", "请选择额度时间范围", "额度时间范围内上限",
"请输入额度时间范围内上限", "未启用额度时间范围时将忽略该值", "额度时间范围内上限必须大于 0", "当前周期已用额度", "下次重置时间",
"未启用") currently contain English text and must be replaced with proper French
translations; update the right-hand side strings in the fr.json entries for each
of those keys to their French equivalents (e.g., "周期额度" -> "Quota périodique",
"请选择周期额度" -> "Sélectionnez un quota périodique", etc.) so the French locale
displays French text instead of English. Ensure grammar and accents are correct
and keep the key names unchanged.
| "周期额度": "Period quota", | ||
| "请选择周期额度": "Select a period quota", | ||
| "每日额度": "Daily quota", | ||
| "每月额度": "Monthly quota", | ||
| "周期额度上限": "Period quota limit", | ||
| "请输入周期额度上限": "Please enter the period quota limit", | ||
| "未启用周期额度时将忽略该值": "This value is ignored when period quota is disabled", | ||
| "周期额度上限必须大于 0": "Period quota limit must be greater than 0", | ||
| "额度时间范围": "Quota time range", | ||
| "请选择额度时间范围": "Select a quota time range", | ||
| "额度时间范围内上限": "Quota cap within the time range", | ||
| "请输入额度时间范围内上限": "Please enter the quota cap within the time range", | ||
| "未启用额度时间范围时将忽略该值": "This value is ignored when the quota time range is disabled", | ||
| "额度时间范围内上限必须大于 0": "The quota cap within the time range must be greater than 0", | ||
| "当前周期已用额度": "Used in current period", | ||
| "下次重置时间": "Next reset time", | ||
| "未启用": "Disabled" |
There was a problem hiding this comment.
Localize these new Russian strings and avoid re-declaring 未启用.
Line 1697 already defines 未启用 for this locale. Re-declaring it here switches every Russian t('未启用') usage to English "Disabled", and the rest of this new block is also still English, so the new token-quota UI regresses to mixed-language text.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/i18n/locales/ru.json` around lines 3300 - 3316, The new block adds
English translations for quota-related keys (e.g., "周期额度", "请选择周期额度", "每日额度",
"每月额度", "周期额度上限", "请输入周期额度上限", "未启用周期额度时将忽略该值", "周期额度上限必须大于 0", "额度时间范围",
"请选择额度时间范围", "额度时间范围内上限", "请输入额度时间范围内上限", "未启用额度时间范围时将忽略该值", "额度时间范围内上限必须大于 0",
"当前周期已用额度", "下次重置时间") but leaves them in English and re-declares "未启用"; instead,
replace these English values with proper Russian translations and remove the
duplicate "未启用" entry so the locale uses the existing Russian value already
defined earlier (do not change the original key name "未启用"); update only the
values for the listed keys in ru.json to their Russian equivalents.
| "周期额度": "Period quota", | ||
| "请选择周期额度": "Select a period quota", | ||
| "每日额度": "Daily quota", | ||
| "每月额度": "Monthly quota", | ||
| "周期额度上限": "Period quota limit", | ||
| "请输入周期额度上限": "Please enter the period quota limit", | ||
| "未启用周期额度时将忽略该值": "This value is ignored when period quota is disabled", | ||
| "周期额度上限必须大于 0": "Period quota limit must be greater than 0", | ||
| "额度时间范围": "Quota time range", | ||
| "请选择额度时间范围": "Select a quota time range", | ||
| "额度时间范围内上限": "Quota cap within the time range", | ||
| "请输入额度时间范围内上限": "Please enter the quota cap within the time range", | ||
| "未启用额度时间范围时将忽略该值": "This value is ignored when the quota time range is disabled", | ||
| "额度时间范围内上限必须大于 0": "The quota cap within the time range must be greater than 0", | ||
| "当前周期已用额度": "Used in current period", | ||
| "下次重置时间": "Next reset time", |
There was a problem hiding this comment.
Keep new vi.json values localized consistently
Most newly added values are English ("Period quota", "Daily quota", "Next reset time", etc.), while this is the Vietnamese locale file. This will create mixed-language UI in the new token quota flow.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/i18n/locales/vi.json` around lines 3837 - 3852, The Vietnamese locale
file vi.json contains new translation keys (e.g., "周期额度", "请选择周期额度", "每日额度",
"每月额度", "周期额度上限", "额度时间范围", "当前周期已用额度", "下次重置时间") whose values are still in
English; update each of these values to proper Vietnamese translations so the
token quota UI is fully localized (replace "Period quota", "Daily quota",
"Monthly quota", "Period quota limit", "Quota time range", "Used in current
period", "Next reset time", etc., with their Vietnamese equivalents) and ensure
consistency with existing vi.json phrasing and tone.
| "额度时间范围内上限必须大于 0": "The quota cap within the time range must be greater than 0", | ||
| "当前周期已用额度": "Used in current period", | ||
| "下次重置时间": "Next reset time", | ||
| "未启用": "Disabled" |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
python - <<'PY'
import json
from pathlib import Path
from collections import defaultdict
def find_dups(p: Path):
text = p.read_text(encoding='utf-8')
dups = []
def hook(pairs):
seen = {}
for k, _ in pairs:
seen[k] = seen.get(k, 0) + 1
for k, c in seen.items():
if c > 1:
dups.append((k, c))
return dict(pairs)
try:
json.loads(text, object_pairs_hook=hook)
except Exception as e:
print(f"[parse-error] {p}: {e}")
return
if dups:
print(f"[dups] {p}")
for k, c in dups:
print(f" key={k!r}, count={c}")
for p in Path("web/src/i18n/locales").glob("*.json"):
find_dups(p)
PYRepository: QuantumNous/new-api
Length of output: 467
🏁 Script executed:
#!/bin/bash
# Find the vi.json file and check its existence
if [ ! -f "web/src/i18n/locales/vi.json" ]; then
echo "File not found"
exit 1
fi
# Get line count
echo "=== File info ==="
wc -l web/src/i18n/locales/vi.json
# Search for all occurrences of "未启用" with line numbers and context
echo -e "\n=== All occurrences of '未启用' in vi.json ==="
rg -n "未启用" web/src/i18n/locales/vi.json -A 0 -B 0
# Extract the actual key-value pairs around those lines
echo -e "\n=== Context around first occurrence ==="
sed -n '1668,1670p' web/src/i18n/locales/vi.json
echo -e "\n=== Context around second occurrence ==="
sed -n '3852,3854p' web/src/i18n/locales/vi.json
# Parse the JSON to show actual key-value
echo -e "\n=== Parsed values using Python ==="
python3 <<'EOF'
import json
with open("web/src/i18n/locales/vi.json", 'r', encoding='utf-8') as f:
content = f.read()
# Find all line positions for the key
lines = content.split('\n')
occurrences = []
for idx, line in enumerate(lines, 1):
if '"未启用"' in line:
occurrences.append((idx, line.strip()))
print(f"Total occurrences: {len(occurrences)}")
for line_no, line_content in occurrences:
print(f"Line {line_no}: {line_content}")
# Also show what the parser sees (last value wins)
try:
data = json.loads(content)
print(f"\nFinal parsed value for '未启用': {data.get('未启用', 'NOT FOUND')}")
except json.JSONDecodeError as e:
print(f"JSON parse error: {e}")
EOFRepository: QuantumNous/new-api
Length of output: 1040
🏁 Script executed:
#!/bin/bash
# Validate JSON syntax
echo "=== JSON Validation ==="
python3 <<'EOF'
import json
import sys
try:
with open("web/src/i18n/locales/vi.json", 'r', encoding='utf-8') as f:
data = json.load(f)
print("✓ JSON is syntactically valid")
print(f"Total keys in parsed object: {len(data)}")
# Check if the key exists
if "未启用" in data:
print(f"✓ Key '未启用' exists in final parsed object")
print(f" Final value: {data['未启用']}")
else:
print("✗ Key '未启用' NOT in final parsed object")
except json.JSONDecodeError as e:
print(f"✗ JSON Parse Error: {e}")
print(f" Line {e.lineno}, Column {e.colno}")
sys.exit(1)
EOF
# Check other locale files for same pattern
echo -e "\n=== Checking if duplicate '未启用' exists in other locale files ==="
for file in web/src/i18n/locales/*.json; do
count=$(rg -c "\"未启用\":" "$file" 2>/dev/null || echo 0)
if [ "$count" -ge 2 ]; then
echo "$(basename $file): $count occurrences"
# Show line numbers and values
rg -n "\"未启用\":" "$file"
fi
doneRepository: QuantumNous/new-api
Length of output: 786
🏁 Script executed:
#!/bin/bash
# Check file structure - is it nested or flat?
echo "=== Checking vi.json structure (first 30 lines) ==="
head -30 web/src/i18n/locales/vi.json
echo -e "\n=== Checking vi.json structure (last 30 lines) ==="
tail -30 web/src/i18n/locales/vi.json
# Check if it's a nested structure
echo -e "\n=== Analyzing JSON structure ==="
python3 <<'EOF'
import json
with open("web/src/i18n/locales/vi.json", 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"Root type: {type(data)}")
print(f"Root keys: {list(data.keys())}")
if len(data) == 1:
only_key = list(data.keys())[0]
print(f"\nOnly root key: {only_key!r}")
inner_data = data[only_key]
print(f"Inner type: {type(inner_data)}")
if isinstance(inner_data, dict):
print(f"Inner keys count: {len(inner_data)}")
print(f"First 5 inner keys: {list(inner_data.keys())[:5]}")
if "未启用" in inner_data:
print(f"✓ Found '未启用' at second level: {inner_data['未启用']}")
EOF
# Compare with zh-CN.json
echo -e "\n=== Checking zh-CN.json structure (with identical duplicates) ==="
python3 <<'EOF'
import json
with open("web/src/i18n/locales/zh-CN.json", 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"Root type: {type(data)}")
print(f"Root keys: {len(list(data.keys()))}")
if len(data) == 1:
only_key = list(data.keys())[0]
inner_data = data[only_key]
print(f"Only root key: {only_key!r} (nested structure)")
if isinstance(inner_data, dict):
print(f"Inner keys count: {len(inner_data)}")
if "未启用" in inner_data:
print(f"✓ Found '未启用': {inner_data['未启用']}")
else:
print(f"Flat structure with {len(data)} root keys")
EOFRepository: QuantumNous/new-api
Length of output: 6852
🏁 Script executed:
#!/bin/bash
# Check if i18n:lint script exists and what it does
echo "=== Checking for i18n:lint script ==="
if [ -f "package.json" ] || [ -f "bun.lockb" ]; then
echo "Checking web package.json for i18n scripts..."
if [ -f "web/package.json" ]; then
cat web/package.json | grep -A 20 '"scripts"' || echo "No scripts section found"
fi
fi
# Check project.mdc rules
echo -e "\n=== Checking project.mdc for i18n guidelines ==="
if [ -f ".cursor/rules/project.mdc" ]; then
rg -A 5 "i18n" .cursor/rules/project.mdc || echo "No i18n rules found"
fi
# Check if there's any existing duplicate key detection or prevention
echo -e "\n=== Searching for duplicate key handling in codebase ==="
rg -i "duplicate.*key|key.*duplicate" web/src/i18n/ --type json --type ts --type tsx 2>/dev/null | head -20 || echo "No duplicate key handling found"Repository: QuantumNous/new-api
Length of output: 1281
Duplicate i18n key silently overrides Vietnamese translation
The nested "translation" object contains "未启用" twice: Line 1669 defines it as "Chưa bật" (Vietnamese), but Line 3853 redefines it as "Disabled" (English). JSON parsers keep the last value, so "Disabled" will be used globally, replacing the correct Vietnamese translation. This pattern exists in all 7 locale files (en.json, fr.json, ja.json, ru.json, vi.json, zh-CN.json, zh-TW.json).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/i18n/locales/vi.json` at line 3853, The translation key "未启用" is
duplicated in the nested "translation" object (once at Line ~1669 as "Chưa bật"
and again at Line ~3853 as "Disabled"), causing the last occurrence to override
the correct Vietnamese text; remove or replace the duplicate English entry so
the Vietnamese value ("Chưa bật") remains the sole value for the "未启用" key in
vi.json (and apply the same de-duplication fix to the other locale files where
"未启用" is duplicated), ensuring the correct translation is preserved in the
"translation" object.
| "额度时间范围内上限必须大于 0": "额度时间范围内上限必须大于 0", | ||
| "当前周期已用额度": "当前周期已用额度", | ||
| "下次重置时间": "下次重置时间", | ||
| "未启用": "未启用" |
There was a problem hiding this comment.
Avoid re-defining 未启用 in the same locale object.
Line 2958 duplicates a key already defined at Line 1347. This can cause ambiguous key resolution and i18n lint churn.
♻️ Proposed fix
- "下次重置时间": "下次重置时间",
- "未启用": "未启用"
+ "下次重置时间": "下次重置时间"Based on learnings: "Use CLI tools: bun run i18n:extract, bun run i18n:sync, bun run i18n:lint."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/i18n/locales/zh-CN.json` at line 2958, The locale file contains a
duplicate key "未启用" (already defined earlier) which should be removed to avoid
ambiguous resolution; locate the duplicate "未启用" entry in zh-CN.json (the
instance around the reported diff) and delete it or consolidate it with the
original definition so only one "未启用" key remains, then run the i18n toolchain
(bun run i18n:extract, bun run i18n:sync, bun run i18n:lint) to verify and fix
any remaining i18n issues.
| "额度时间范围内上限必须大于 0": "額度時間範圍內上限必須大於 0", | ||
| "当前周期已用额度": "當前週期已用額度", | ||
| "下次重置时间": "下次重置時間", | ||
| "未启用": "未啟用" |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Detect duplicate JSON keys in zh-TW locale file (read-only).
python - <<'PY'
import json
from pathlib import Path
from collections import defaultdict
path = Path("web/src/i18n/locales/zh-TW.json")
text = path.read_text(encoding="utf-8")
dups = defaultdict(int)
def hook(pairs):
seen = {}
for k, v in pairs:
if k in seen:
dups[k] += 1
seen[k] = v
return seen
json.loads(text, object_pairs_hook=hook)
if not dups:
print("No duplicate keys found.")
else:
print("Duplicate keys found:")
for k, n in sorted(dups.items(), key=lambda x: x[0]):
print(f"- {k}: {n} duplicate occurrence(s)")
PYRepository: QuantumNous/new-api
Length of output: 117
🏁 Script executed:
# Check lines 1351 and 2967 to confirm the duplicate key and values
sed -n '1350,1352p' web/src/i18n/locales/zh-TW.json
echo "---"
sed -n '2966,2968p' web/src/i18n/locales/zh-TW.jsonRepository: QuantumNous/new-api
Length of output: 165
🏁 Script executed:
# Check if i18n:lint is available and what it reports
cd web && bun run i18n:lint 2>&1 || echo "i18n:lint not available"Repository: QuantumNous/new-api
Length of output: 128
Remove duplicate translation key 未启用 at line 2967.
This key is already defined at line 1351 with the same value "未啟用". Duplicate keys in the JSON object violate the flat JSON structure requirement and create maintenance ambiguity. Per coding guidelines, translation files should be validated with bun run i18n:lint before merging.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/i18n/locales/zh-TW.json` at line 2967, The file contains a duplicate
translation key "未启用" (Chinese key) defined twice; remove the redundant entry
(the one at the later occurrence) so only the original definition remains (the
earlier "未启用": "未啟用"), and then run the i18n linter (bun run i18n:lint) to
validate the JSON. Ensure you update the JSON object by deleting the duplicate
key and saving a valid flat JSON structure.
This comment was marked as spam.
This comment was marked as spam.
|
我非常需要这个功能,什么时候可以合并? |
51fdfc5 to
2b6f1df
Compare
|
这个功能一直没有继续了吗? |
Add fail-closed shared principal budget ledgers with exact accounting, immutable archives and regression coverage. Refs: QuantumNous/new-api#5791 QuantumNous/new-api#5791 Refs: QuantumNous/new-api#3345 QuantumNous/new-api#3345 Refs: QuantumNous/new-api#6583 QuantumNous/new-api#6583 Refs: QuantumNous/new-api#8124 QuantumNous/new-api#8124 Refs: QuantumNous/new-api#1730 QuantumNous/new-api#1730 Refs: QuantumNous/new-api#8123 QuantumNous/new-api#8123
docs: finalize community improvement batches and validation Document eight implemented capabilities, review fixes, exact commits, CI evidence and upstream correspondence. Preserve identity, Redis and evaluation boundaries, and provide the model governance lifecycle/API guide. All functional PRs were reviewed and merged after successful regression tests and Verify CI. The running checkout and services were not changed. Refs: QuantumNous/new-api issue #1730 QuantumNous/new-api#1730 Refs: QuantumNous/new-api issue #2841 QuantumNous/new-api#2841 Refs: QuantumNous/new-api issue #3240 QuantumNous/new-api#3240 Refs: QuantumNous/new-api PR #3345 QuantumNous/new-api#3345 Refs: QuantumNous/new-api issue #4328 QuantumNous/new-api#4328 Refs: QuantumNous/new-api PR #4329 QuantumNous/new-api#4329 Refs: QuantumNous/new-api PR #4492 QuantumNous/new-api#4492 Refs: QuantumNous/new-api PR #5431 QuantumNous/new-api#5431 Refs: QuantumNous/new-api PR #5791 QuantumNous/new-api#5791 Refs: QuantumNous/new-api PR #6264 QuantumNous/new-api#6264 Refs: QuantumNous/new-api PR #6583 QuantumNous/new-api#6583 Refs: QuantumNous/new-api PR #6620 QuantumNous/new-api#6620 Refs: QuantumNous/new-api PR #6673 QuantumNous/new-api#6673 Refs: QuantumNous/new-api issue #6972 QuantumNous/new-api#6972 Refs: QuantumNous/new-api PR #7028 QuantumNous/new-api#7028 Refs: QuantumNous/new-api issue #7951 QuantumNous/new-api#7951 Refs: QuantumNous/new-api issue #7952 QuantumNous/new-api#7952 Refs: QuantumNous/new-api PR #7953 QuantumNous/new-api#7953 Refs: QuantumNous/new-api PR #7955 QuantumNous/new-api#7955 Refs: QuantumNous/new-api issue #8034 QuantumNous/new-api#8034 Refs: QuantumNous/new-api PR #8076 QuantumNous/new-api#8076 Refs: QuantumNous/new-api issue #8123 QuantumNous/new-api#8123 Refs: QuantumNous/new-api PR #8124 QuantumNous/new-api#8124 Refs: QuantumNous/new-api issue #8232 QuantumNous/new-api#8232 Refs: QuantumNous/new-api PR #8233 QuantumNous/new-api#8233 Refs: QuantumNous/new-api issue #8295 QuantumNous/new-api#8295 Refs: QuantumNous/new-api PR #8296 QuantumNous/new-api#8296 Refs: QuantumNous/new-api PR #8350 QuantumNous/new-api#8350 Refs: QuantumNous/new-api PR #8357 QuantumNous/new-api#8357 Refs: QuantumNous/new-api PR #8363 QuantumNous/new-api#8363 Refs: #99 #99 Refs: #100 #100 Refs: #101 #101 Refs: #102 #102 Refs: #103 #103 Refs: #104 #104 Refs: #105 #105 Refs: #106 #106 Refs: #107 #107 Refs: #108 #108 Refs: #109 #109 Documentation Verify CI passed: https://github.com/soulteary/yunqi/actions/runs/45003986698

Summary
This PR adds per-token period quota control for both regular users and admins on their own tokens.
Users can now configure a token with:
dailyquota limitmonthlyquota limitOnce the quota for the current period is reached, requests are blocked before forwarding upstream. The token becomes available again automatically when the next period starts.
What Changed
Backend
Frontend
Why
The project already supports total quota control, but not per-token daily/monthly budget control. This is useful for managed multi-user scenarios such as students, team members, and budget-constrained internal accounts.
Validation
bun run buildNotes
This PR is intentionally scoped to token-level period quotas only.
It does not include unrelated local task files or the usage log CSV export feature.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation