feat: /v1/chat/completion -> /v1/response - #2629
Conversation
WalkthroughAdds a compatibility mode converting OpenAI chat completions to the Responses API: DTO tweaks, conversion helpers, policy/config, relay integration for streaming and non-streaming response handling, service wrappers, and UI for global policy configuration. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Relay
participant Service
participant OpenAI_Responses
participant Relay_Handler
Client->>Relay: Send chat completions request
Relay->>Service: ShouldChatCompletionsUseResponses? (policy/global)
Service-->>Relay: boolean
alt Use Responses Path
Relay->>Service: ChatCompletionsRequestToResponsesRequest(req)
Service-->>Relay: OpenAIResponsesRequest
Relay->>Relay: applySystemPromptIfNeeded
Relay->>OpenAI_Responses: HTTP request to /responses (streaming or non-streaming)
OpenAI_Responses-->>Relay: responses payload or stream
alt Streaming
Relay->>Relay_Handler: OaiResponsesToChatStreamHandler(stream)
Relay_Handler->>Relay_Handler: process chunks, accumulate usage
Relay_Handler-->>Client: stream chat chunks and final usage
else Non-Streaming
Relay->>Relay_Handler: OaiResponsesToChatHandler(response)
Relay_Handler->>Service: ResponsesResponseToChatCompletionsResponse
Service-->>Relay_Handler: chat completion + usage
Relay_Handler-->>Client: final chat completion response
end
else Use Standard Path
Relay->>Relay: continue existing chat completions flow
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~65 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
web/src/components/settings/ModelSetting.jsx (1)
31-47: GuardJSON.parseto prevent settings page crash on invalid stored JSON.
JSON.parse(item.value)(Line 67) will throw if the option value is malformed; this currently takes down rendering for the whole settings view (now expanded to another key).Proposed change
- ) { - if (item.value !== '') { - item.value = JSON.stringify(JSON.parse(item.value), null, 2); - } - } + ) { + if (item.value !== '') { + try { + item.value = JSON.stringify(JSON.parse(item.value), null, 2); + } catch (e) { + // Keep raw value so user can fix it, and avoid crashing the page. + console.error(`Invalid JSON for option ${item.key}:`, e); + } + } + }Also applies to: 55-76
🤖 Fix all issues with AI agents
In @relay/channel/openai/chat_via_responses.go:
- Around line 21-61: The handler uses io.ReadAll(resp.Body) which can OOM on
large upstream responses; replace it with a capped read (e.g.,
io.ReadAll(io.LimitReader(resp.Body, N)) or call the repo's existing max-body
utility if available) using a sensible constant (like
service.MaxResponseBodyBytes) and detect when the limit is hit to return a
proper OpenAI error (use types.NewOpenAIError with
types.ErrorCodeReadResponseBodyFailed or a new error code). Update
OaiResponsesToChatHandler to use the limited reader, preserve existing error
wrapping for read failures, and ensure the rest of the function behaves
unchanged when the body is within limits.
- Around line 63-189: In OaiResponsesToChatStreamHandler, stop ignoring errors
from helper.ObjectData: capture its error return in every place it's called
(e.g., the calls that send helper.GenerateStartEmptyResponse,
helper.GenerateStopResponse and helper.GenerateFinalUsageResponse) and if err !=
nil return false from the StreamScannerHandler callback so the scanner aborts on
write failure; also add explicit handling for upstream error events (e.g., add a
"response.error" case that logs the error/returns false as appropriate) and
include a default branch in the switch to log or comment when
non-text/unsupported event types are received so they are not silently dropped.
In @relay/chat_completions_via_responses.go:
- Around line 72-160: The code unsafely asserts resp.(*http.Response) in
chatCompletionsViaResponses; replace it with a safe type assertion (e.g., hr, ok
:= resp.(*http.Response)) and if not ok return a proper OpenAI error (use
types.NewOpenAIError or types.NewError with types.ErrorCodeBadResponse or
ErrorCodeDoRequestFailed and an appropriate HTTP 500) so the function never
panics; update subsequent uses to reference the safely-asserted variable
(httpResp/hr) and ensure behavior and status-code mapping logic remain
unchanged.
In @relay/compatible_handler.go:
- Around line 83-95: The code reads nested fields on usage returned by
chatCompletionsViaResponses (usage.CompletionTokenDetails.AudioTokens and
usage.PromptTokensDetails.AudioTokens) without nil checks; guard against a nil
usage or nil/missing nested token detail structs by checking usage != nil and
that CompletionTokenDetails and PromptTokensDetails are non-nil (or provide zero
defaults) before accessing AudioTokens, and if any are missing fall back to
calling postConsumeQuota(c, info, usage) (or pass nil) instead of
PostAudioConsumeQuota; update the branch that computes containAudioTokens to use
these safe checks and keep the existing ratio_setting.ContainsAudioRatio /
ContainsAudioCompletionRatio logic.
In @service/openaicompat/chat_to_responses.go:
- Around line 37-262: Summary: ChatCompletionsRequestToResponsesRequest
currently swallows marshal errors for instructionsRaw, toolsRaw, toolChoiceRaw,
parallelToolCallsRaw, and textRaw and uses tool.Function.Name without validating
it. Fix: for each place where common.Marshal is called without checking the
error (instructionsRaw, toolsRaw, toolChoiceRaw, parallelToolCallsRaw, textRaw)
propagate and return marshal errors instead of ignoring them, mirroring the
existing inputRaw error pattern in ChatCompletionsRequestToResponsesRequest;
additionally validate that each tool in req.Tools with Type "function" has a
non-empty tool.Function.Name and return a clear error if missing before building
toolsRaw. Ensure the toolChoice handling also checks marshal/unmarshal errors
and returns them instead of discarding, and keep references to the symbols
ChatCompletionsRequestToResponsesRequest, req.Tools, tool.Function.Name,
instructionsRaw, toolsRaw, toolChoiceRaw, parallelToolCallsRaw, and textRaw to
locate the changes.
In @service/openaicompat/regex.go:
- Around line 8-31: The matchAnyRegex function currently uses
compiledRegexCache.Load then Store and an unchecked type assertion
re.(*regexp.Regexp), which can panic and allows duplicate compilation under
concurrency; change it to first attempt Load, and if missing compile the pattern
then call compiledRegexCache.LoadOrStore(pattern, compiled) to avoid a race,
then retrieve the stored value and perform a safe type assertion (val, ok :=
storedVal.(*regexp.Regexp)) and skip the pattern if the assertion fails; update
references in matchAnyRegex and keep compiledRegexCache as the sync.Map key,
using regexp.Compile for compilation and LoadOrStore to ensure only one compiled
regexp is stored.
In @service/openaicompat/responses_to_chat.go:
- Around line 44-81: The current logic only builds toolCalls when text == "", so
function_call outputs in resp.Output are ignored whenever any extracted text
exists; change the code that iterates resp.Output to always extract
function_call entries into toolCalls regardless of text, ensure you
normalize/validate callId (use out.CallId or out.ID and skip entries with empty
IDs), then set finishReason to "tool_calls" when toolCalls is non-empty and
attach them via msg.SetToolCalls(toolCalls) while clearing msg.Content only if
toolCalls exist; update references to variables toolCalls, text, resp.Output,
callId, finishReason, and Message.SetToolCalls accordingly.
🧹 Nitpick comments (5)
service/openaicompat/regex.go (1)
8-33: Consider cache growth/staleness (config-driven “leak”).If policies are edited over time,
compiledRegexCacheretains old patterns indefinitely. If patterns are user-configurable and can vary per save, this can become unbounded memory growth. Consider either:
- clearing cache on config reload, or
- using a bounded LRU keyed by pattern, or
- scoping the cache to the policy object lifecycle (if applicable).
web/src/pages/Setting/Model/SettingGlobalModel.jsx (1)
38-57: Add lightweight schema validation (beyond “valid JSON”) to prevent misconfiguration.
verifyJSONcatches syntax errors, but not shape/type issues (e.g.,channel_ids: "1"ormodel_patterns: {}), which can lead to confusing “policy doesn’t work” scenarios. Consider validating expected keys/types client-side (even minimal checks whenenabled: true) and showing a targeted error.Also applies to: 59-65, 75-85, 137-147, 219-255
service/openaicompat/responses_to_chat.go (2)
10-16: Consider falling back toresp’s ID whenidarg is empty.If callers pass an empty
id, the produced chat response will have an emptyId, which can be awkward for clients/logging. Ifdto.OpenAIResponsesResponseexposes an ID field, consider using it as a fallback.Also applies to: 83-99
101-133: Text concatenation may need separators depending on expected client rendering.
ExtractOutputTextFromResponsesconcatenates segments with no delimiter; if multipleoutput_textsegments exist, output can become hard to read. Consider adding\nbetween segments (or only when the next segment doesn’t already start with whitespace), if that matches existing behavior elsewhere.relay/chat_completions_via_responses.go (1)
21-70: Consider defensive role comparison with trimming.While the function is only called once per request (no double-application risk), role comparisons at lines 33 and 53 use direct string equality (
message.Role == systemRole). Addingstrings.TrimSpace()around both sides would be a defensive improvement to handle any unexpected whitespace in role fields:Suggested change
containSystemPrompt := false for _, message := range request.Messages { - if message.Role == systemRole { + if strings.TrimSpace(message.Role) == strings.TrimSpace(systemRole) { containSystemPrompt = true break }for i, message := range request.Messages { - if message.Role != systemRole { + if strings.TrimSpace(message.Role) != strings.TrimSpace(systemRole) { continue }
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
dto/openai_request.godto/openai_response.gorelay/channel/openai/chat_via_responses.gorelay/chat_completions_via_responses.gorelay/compatible_handler.goservice/openai_chat_responses_compat.goservice/openai_chat_responses_mode.goservice/openaicompat/chat_to_responses.goservice/openaicompat/policy.goservice/openaicompat/regex.goservice/openaicompat/responses_to_chat.gosetting/model_setting/global.goweb/src/components/settings/ModelSetting.jsxweb/src/pages/Setting/Model/SettingGlobalModel.jsx
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-08-08T17:12:43.157Z
Learnt from: RedwindA
Repo: QuantumNous/new-api PR: 1537
File: relay/gemini_handler.go:330-342
Timestamp: 2025-08-08T17:12:43.157Z
Learning: In the new-api repository, the `GeminiEmbeddingHandler` function in `relay/gemini_handler.go` is designed specifically for native Gemini embedding requests and therefore does not require the `ConvertGeminiRequest` step that is used in the chat handler. The embedding requests are already in the native Gemini format and don't need conversion.
Applied to files:
relay/compatible_handler.gorelay/channel/openai/chat_via_responses.go
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
Applied to files:
relay/compatible_handler.go
📚 Learning: 2025-08-21T06:31:11.073Z
Learnt from: jiajunly
Repo: QuantumNous/new-api PR: 1629
File: relay/channel/openai/relay-openai.go:170-174
Timestamp: 2025-08-21T06:31:11.073Z
Learning: In relay/channel/openai/relay-openai.go, the streaming logic for the AddThinkFirst feature is designed so that only the first chunk of a stream gets the "<think>\n" prefix. The final flush in the streaming handler intentionally uses addThink=false because the last chunk should never receive the prefix, even in single-chunk streams where the prefix would have been applied during normal processing.
Applied to files:
relay/channel/openai/chat_via_responses.go
🧬 Code graph analysis (4)
service/openaicompat/policy.go (2)
service/openai_chat_responses_mode.go (2)
ShouldChatCompletionsUseResponsesPolicy(8-10)ShouldChatCompletionsUseResponsesGlobal(12-14)setting/model_setting/global.go (2)
ChatCompletionsToResponsesPolicy(10-15)GetGlobalSettings(57-59)
service/openaicompat/responses_to_chat.go (1)
service/openai_chat_responses_compat.go (2)
ResponsesResponseToChatCompletionsResponse(12-14)ExtractOutputTextFromResponses(16-18)
relay/channel/openai/chat_via_responses.go (6)
service/http.go (1)
CloseResponseBodyGracefully(15-23)common/json.go (3)
Unmarshal(9-11)Marshal(21-23)UnmarshalJsonStr(13-15)relay/helper/common.go (5)
GetResponseID(158-161)ObjectData(109-118)GenerateStartEmptyResponse(168-184)GenerateStopResponse(186-199)GenerateFinalUsageResponse(201-211)service/openaicompat/responses_to_chat.go (2)
ResponsesResponseToChatCompletionsResponse(10-99)ExtractOutputTextFromResponses(101-133)service/usage_helpr.go (1)
ResponseText2Usage(22-29)relay/helper/stream_scanner.go (1)
StreamScannerHandler(37-272)
service/openai_chat_responses_mode.go (2)
service/openaicompat/policy.go (2)
ShouldChatCompletionsUseResponsesPolicy(5-10)ShouldChatCompletionsUseResponsesGlobal(12-18)setting/model_setting/global.go (1)
ChatCompletionsToResponsesPolicy(10-15)
🔇 Additional comments (11)
service/openai_chat_responses_compat.go (1)
1-18: LGTM as a thin service-layer facade.No extra logic; keeps call sites stable while moving compat logic under
service/openaicompat.dto/openai_response.go (1)
336-347: DTO extension is properly consumed.Verification confirms that
service/openaicompat/responses_to_chat.goalready reads all three new fields:Name(line 50),CallId(line 54), andArguments(line 63), mapping them correctly to theFunctionResponsestructure with appropriate validation and fallback logic. The change is safe.dto/openai_request.go (1)
795-820: No issues found with theTemperatureandTopPpointer type changes inOpenAIResponsesRequest.The assignments flagged in the review (
request.TopP = 0.999,request.TopP = 0, etc.) are not onOpenAIResponsesRequest—they operate onGeneralOpenAIRequest(whereTopPremainsfloat64) orClaudeRequest. The sole conversion function that createsOpenAIResponsesRequestinstances (inservice/openaicompat/chat_to_responses.go) already handles this correctly usingcommon.GetPointer(). The code compiles and runs without issues.Likely an incorrect or invalid review comment.
relay/compatible_handler.go (2)
78-83: Ensure system-prompt injection rules are identical across both paths.In the standard path, system prompt injection/override happens after
ConvertOpenAIRequest(...)and only wheninfo.ChannelSetting.SystemPrompt != "". In the responses-compat path, behavior depends entirely onapplySystemPromptIfNeeded(...). Please verify it matches the existing rules (prepend vs override +constant.ContextKeySystemPromptOverride) to avoid subtle regressions for channels using system prompts.Also applies to: 116-156
78-97: Early-return path properly handles streaming, include_usage, and status code mapping—no changes needed.Upon verification,
chatCompletionsViaResponses()correctly implements all three concerns:
- Streaming detection (line 138): Detects
text/event-streamresponses and routes to appropriate handler- include_usage semantics (line 183 of chat_via_responses.go): Stream handler respects
info.ShouldIncludeUsageand includes final usage response- Status code mapping parity (lines 135, 141, 148, 156): Applied on all error paths, matching standard path behavior
service/openai_chat_responses_mode.go (1)
1-14: LGTM (thin wrapper is clear and keeps call sites stable).No concerns with the delegation as written.
service/openaicompat/policy.go (1)
5-10: Confirm intended behavior whenenabled=truebutmodel_patternsis empty.Right now,
enabled=true+ channel enabled +model_patternsomitted/empty will always returnfalse(becausematchAnyRegexreturns false on empty patterns). If you intended “all models” in that case, you’ll want an explicit rule (e.g., empty patterns => allow all).setting/model_setting/global.go (2)
17-28: Policy defaults look sane (explicitly disabled by default).Defaulting
Enabled: falseis the safest rollout posture for a routing change like this.Also applies to: 43-47
4-28: No action required. The repository targets Go 1.25.1, which is well above the Go 1.21 minimum requirement for theslicesstdlib package. Theslices.Containsusage is fully compatible and appropriate.Likely an incorrect or invalid review comment.
service/openaicompat/responses_to_chat.go (1)
17-40: No action needed.CompletionTokenDetailsis a value type (not a pointer) in theUsagestruct, so accessing its fields is safe and will never panic. The code is correct as written.service/openaicompat/chat_to_responses.go (1)
13-35: Current implementation is correct—Responses API requiresimage_urlas a string.The OpenAI Responses API specifies that
image_urlmust be a string (a full URL or data URL), not an object with nested fields. The function correctly extracts the URL string from various input formats (map, struct, pointer). Dropping fields likedetailis not lossy; it's the required behavior to conform to the API specification.
| func chatCompletionsViaResponses(c *gin.Context, info *relaycommon.RelayInfo, adaptor channel.Adaptor, request *dto.GeneralOpenAIRequest) (*dto.Usage, *types.NewAPIError) { | ||
| overrideCtx := relaycommon.BuildParamOverrideContext(info) | ||
| chatJSON, err := common.Marshal(request) | ||
| if err != nil { | ||
| return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry()) | ||
| } | ||
|
|
||
| chatJSON, err = relaycommon.RemoveDisabledFields(chatJSON, info.ChannelOtherSettings) | ||
| if err != nil { | ||
| return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry()) | ||
| } | ||
|
|
||
| if len(info.ParamOverride) > 0 { | ||
| chatJSON, err = relaycommon.ApplyParamOverride(chatJSON, info.ParamOverride, overrideCtx) | ||
| if err != nil { | ||
| return nil, types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry()) | ||
| } | ||
| } | ||
|
|
||
| var overriddenChatReq dto.GeneralOpenAIRequest | ||
| if err := common.Unmarshal(chatJSON, &overriddenChatReq); err != nil { | ||
| return nil, types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry()) | ||
| } | ||
|
|
||
| responsesReq, err := service.ChatCompletionsRequestToResponsesRequest(&overriddenChatReq) | ||
| if err != nil { | ||
| return nil, types.NewErrorWithStatusCode(err, types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry()) | ||
| } | ||
|
|
||
| savedRelayMode := info.RelayMode | ||
| savedRequestURLPath := info.RequestURLPath | ||
| defer func() { | ||
| info.RelayMode = savedRelayMode | ||
| info.RequestURLPath = savedRequestURLPath | ||
| }() | ||
|
|
||
| info.RelayMode = relayconstant.RelayModeResponses | ||
| info.RequestURLPath = "/v1/responses" | ||
|
|
||
| convertedRequest, err := adaptor.ConvertOpenAIResponsesRequest(c, info, *responsesReq) | ||
| if err != nil { | ||
| return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry()) | ||
| } | ||
|
|
||
| jsonData, err := common.Marshal(convertedRequest) | ||
| if err != nil { | ||
| return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry()) | ||
| } | ||
|
|
||
| jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings) | ||
| if err != nil { | ||
| return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry()) | ||
| } | ||
|
|
||
| var httpResp *http.Response | ||
| resp, err := adaptor.DoRequest(c, info, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError) | ||
| } | ||
| if resp == nil { | ||
| return nil, types.NewOpenAIError(nil, types.ErrorCodeBadResponse, http.StatusInternalServerError) | ||
| } | ||
|
|
||
| statusCodeMappingStr := c.GetString("status_code_mapping") | ||
|
|
||
| httpResp = resp.(*http.Response) | ||
| info.IsStream = info.IsStream || strings.HasPrefix(httpResp.Header.Get("Content-Type"), "text/event-stream") | ||
| if httpResp.StatusCode != http.StatusOK { | ||
| newApiErr := service.RelayErrorHandler(c.Request.Context(), httpResp, false) | ||
| service.ResetStatusCode(newApiErr, statusCodeMappingStr) | ||
| return nil, newApiErr | ||
| } | ||
|
|
||
| if info.IsStream { | ||
| usage, newApiErr := openaichannel.OaiResponsesToChatStreamHandler(c, info, httpResp) | ||
| if newApiErr != nil { | ||
| service.ResetStatusCode(newApiErr, statusCodeMappingStr) | ||
| return nil, newApiErr | ||
| } | ||
| return usage, nil | ||
| } | ||
|
|
||
| usage, newApiErr := openaichannel.OaiResponsesToChatHandler(c, info, httpResp) | ||
| if newApiErr != nil { | ||
| service.ResetStatusCode(newApiErr, statusCodeMappingStr) | ||
| return nil, newApiErr | ||
| } | ||
| return usage, nil | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# Find the adaptor interface definition and DoRequest method
rg -n --type=go 'type\s+Adaptor\s+interface|func.*DoRequest' relay/channel/Repository: QuantumNous/new-api
Length of output: 6457
🏁 Script executed:
# Find all implementations of DoRequest
rg -n --type=go 'func.*DoRequest.*\{' relay/Repository: QuantumNous/new-api
Length of output: 6404
🏁 Script executed:
# Find the handler functions mentioned
rg -n --type=go 'func.*OaiResponsesToChat(Stream)?Handler' relay/Repository: QuantumNous/new-api
Length of output: 424
🏁 Script executed:
# Check for Body.Close calls
rg -n --type=go '\.Body\.Close\(' relay/ | head -20Repository: QuantumNous/new-api
Length of output: 1320
🏁 Script executed:
# Read the Adaptor interface definition
sed -n '15,30p' relay/channel/adapter.goRepository: QuantumNous/new-api
Length of output: 1320
🏁 Script executed:
# Read the handler implementations
cat -n relay/channel/openai/chat_via_responses.goRepository: QuantumNous/new-api
Length of output: 7649
Fix unsafe type assertion on line 137.
resp.(*http.Response) will panic if an adaptor returns a different concrete type. Use safe type assertion:
Suggested fix
- httpResp = resp.(*http.Response)
+ httpResp, ok := resp.(*http.Response)
+ if !ok || httpResp == nil {
+ return nil, types.NewOpenAIError(nil, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ }The response body closure concern is not applicable—both handler functions (OaiResponsesToChatHandler and OaiResponsesToChatStreamHandler) properly close the response body via deferred calls at the start.
🤖 Prompt for AI Agents
In @relay/chat_completions_via_responses.go around lines 72 - 160, The code
unsafely asserts resp.(*http.Response) in chatCompletionsViaResponses; replace
it with a safe type assertion (e.g., hr, ok := resp.(*http.Response)) and if not
ok return a proper OpenAI error (use types.NewOpenAIError or types.NewError with
types.ErrorCodeBadResponse or ErrorCodeDoRequestFailed and an appropriate HTTP
500) so the function never panics; update subsequent uses to reference the
safely-asserted variable (httpResp/hr) and ensure behavior and status-code
mapping logic remain unchanged.
| usage, newApiErr := chatCompletionsViaResponses(c, info, adaptor, request) | ||
| if newApiErr != nil { | ||
| return newApiErr | ||
| } | ||
|
|
||
| var containAudioTokens = usage.CompletionTokenDetails.AudioTokens > 0 || usage.PromptTokensDetails.AudioTokens > 0 | ||
| var containsAudioRatios = ratio_setting.ContainsAudioRatio(info.OriginModelName) || ratio_setting.ContainsAudioCompletionRatio(info.OriginModelName) | ||
|
|
||
| if containAudioTokens && containsAudioRatios { | ||
| service.PostAudioConsumeQuota(c, info, usage, "") | ||
| } else { | ||
| postConsumeQuota(c, info, usage) | ||
| } |
There was a problem hiding this comment.
Guard against nil/partial usage to avoid panics on token detail access.
This path assumes usage and nested detail fields are always present:
usage.CompletionTokenDetails.AudioTokensusage.PromptTokensDetails.AudioTokens
If chatCompletionsViaResponses can return a nil usage (or a zero-value usage with missing nested structs/pointers depending on DTO definitions), this will panic. Consider a defensive fallback to postConsumeQuota with nil usage (it already has a fallback path) or ensure chatCompletionsViaResponses always returns a fully-populated *dto.Usage.
🤖 Prompt for AI Agents
In @relay/compatible_handler.go around lines 83 - 95, The code reads nested
fields on usage returned by chatCompletionsViaResponses
(usage.CompletionTokenDetails.AudioTokens and
usage.PromptTokensDetails.AudioTokens) without nil checks; guard against a nil
usage or nil/missing nested token detail structs by checking usage != nil and
that CompletionTokenDetails and PromptTokensDetails are non-nil (or provide zero
defaults) before accessing AudioTokens, and if any are missing fall back to
calling postConsumeQuota(c, info, usage) (or pass nil) instead of
PostAudioConsumeQuota; update the branch that computes containAudioTokens to use
these safe checks and keep the existing ratio_setting.ContainsAudioRatio /
ContainsAudioCompletionRatio logic.
| func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*dto.OpenAIResponsesRequest, error) { | ||
| if req == nil { | ||
| return nil, errors.New("request is nil") | ||
| } | ||
| if req.Model == "" { | ||
| return nil, errors.New("model is required") | ||
| } | ||
| if req.N > 1 { | ||
| return nil, fmt.Errorf("n>1 is not supported in responses compatibility mode") | ||
| } | ||
|
|
||
| var instructionsParts []string | ||
| inputItems := make([]map[string]any, 0, len(req.Messages)) | ||
|
|
||
| for _, msg := range req.Messages { | ||
| role := strings.TrimSpace(msg.Role) | ||
| if role == "" { | ||
| continue | ||
| } | ||
|
|
||
| // Prefer mapping system/developer messages into `instructions`. | ||
| if role == "system" || role == "developer" { | ||
| if msg.Content == nil { | ||
| continue | ||
| } | ||
| if msg.IsStringContent() { | ||
| if s := strings.TrimSpace(msg.StringContent()); s != "" { | ||
| instructionsParts = append(instructionsParts, s) | ||
| } | ||
| continue | ||
| } | ||
| parts := msg.ParseContent() | ||
| var sb strings.Builder | ||
| for _, part := range parts { | ||
| if part.Type == dto.ContentTypeText && strings.TrimSpace(part.Text) != "" { | ||
| if sb.Len() > 0 { | ||
| sb.WriteString("\n") | ||
| } | ||
| sb.WriteString(part.Text) | ||
| } | ||
| } | ||
| if s := strings.TrimSpace(sb.String()); s != "" { | ||
| instructionsParts = append(instructionsParts, s) | ||
| } | ||
| continue | ||
| } | ||
|
|
||
| item := map[string]any{ | ||
| "role": role, | ||
| } | ||
|
|
||
| if msg.Content == nil { | ||
| item["content"] = "" | ||
| inputItems = append(inputItems, item) | ||
| continue | ||
| } | ||
|
|
||
| if msg.IsStringContent() { | ||
| item["content"] = msg.StringContent() | ||
| inputItems = append(inputItems, item) | ||
| continue | ||
| } | ||
|
|
||
| parts := msg.ParseContent() | ||
| contentParts := make([]map[string]any, 0, len(parts)) | ||
| for _, part := range parts { | ||
| switch part.Type { | ||
| case dto.ContentTypeText: | ||
| contentParts = append(contentParts, map[string]any{ | ||
| "type": "input_text", | ||
| "text": part.Text, | ||
| }) | ||
| case dto.ContentTypeImageURL: | ||
| contentParts = append(contentParts, map[string]any{ | ||
| "type": "input_image", | ||
| "image_url": normalizeChatImageURLToString(part.ImageUrl), | ||
| }) | ||
| case dto.ContentTypeInputAudio: | ||
| contentParts = append(contentParts, map[string]any{ | ||
| "type": "input_audio", | ||
| "input_audio": part.InputAudio, | ||
| }) | ||
| case dto.ContentTypeFile: | ||
| contentParts = append(contentParts, map[string]any{ | ||
| "type": "input_file", | ||
| "file": part.File, | ||
| }) | ||
| case dto.ContentTypeVideoUrl: | ||
| contentParts = append(contentParts, map[string]any{ | ||
| "type": "input_video", | ||
| "video_url": part.VideoUrl, | ||
| }) | ||
| default: | ||
| // Best-effort: keep unknown parts as-is to avoid silently dropping context. | ||
| contentParts = append(contentParts, map[string]any{ | ||
| "type": part.Type, | ||
| }) | ||
| } | ||
| } | ||
| item["content"] = contentParts | ||
| inputItems = append(inputItems, item) | ||
| } | ||
|
|
||
| inputRaw, err := common.Marshal(inputItems) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| var instructionsRaw json.RawMessage | ||
| if len(instructionsParts) > 0 { | ||
| instructions := strings.Join(instructionsParts, "\n\n") | ||
| instructionsRaw, _ = common.Marshal(instructions) | ||
| } | ||
|
|
||
| var toolsRaw json.RawMessage | ||
| if req.Tools != nil { | ||
| tools := make([]map[string]any, 0, len(req.Tools)) | ||
| for _, tool := range req.Tools { | ||
| switch tool.Type { | ||
| case "function": | ||
| tools = append(tools, map[string]any{ | ||
| "type": "function", | ||
| "name": tool.Function.Name, | ||
| "description": tool.Function.Description, | ||
| "parameters": tool.Function.Parameters, | ||
| }) | ||
| default: | ||
| // Best-effort: keep original tool shape for unknown types. | ||
| var m map[string]any | ||
| if b, err := common.Marshal(tool); err == nil { | ||
| _ = common.Unmarshal(b, &m) | ||
| } | ||
| if len(m) == 0 { | ||
| m = map[string]any{"type": tool.Type} | ||
| } | ||
| tools = append(tools, m) | ||
| } | ||
| } | ||
| toolsRaw, _ = common.Marshal(tools) | ||
| } | ||
|
|
||
| var toolChoiceRaw json.RawMessage | ||
| if req.ToolChoice != nil { | ||
| switch v := req.ToolChoice.(type) { | ||
| case string: | ||
| toolChoiceRaw, _ = common.Marshal(v) | ||
| default: | ||
| var m map[string]any | ||
| if b, err := common.Marshal(v); err == nil { | ||
| _ = common.Unmarshal(b, &m) | ||
| } | ||
| if m == nil { | ||
| toolChoiceRaw, _ = common.Marshal(v) | ||
| } else if t, _ := m["type"].(string); t == "function" { | ||
| // Chat: {"type":"function","function":{"name":"..."}} | ||
| // Responses: {"type":"function","name":"..."} | ||
| if name, ok := m["name"].(string); ok && name != "" { | ||
| toolChoiceRaw, _ = common.Marshal(map[string]any{ | ||
| "type": "function", | ||
| "name": name, | ||
| }) | ||
| } else if fn, ok := m["function"].(map[string]any); ok { | ||
| if name, ok := fn["name"].(string); ok && name != "" { | ||
| toolChoiceRaw, _ = common.Marshal(map[string]any{ | ||
| "type": "function", | ||
| "name": name, | ||
| }) | ||
| } else { | ||
| toolChoiceRaw, _ = common.Marshal(v) | ||
| } | ||
| } else { | ||
| toolChoiceRaw, _ = common.Marshal(v) | ||
| } | ||
| } else { | ||
| toolChoiceRaw, _ = common.Marshal(v) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| var parallelToolCallsRaw json.RawMessage | ||
| if req.ParallelTooCalls != nil { | ||
| parallelToolCallsRaw, _ = common.Marshal(*req.ParallelTooCalls) | ||
| } | ||
|
|
||
| var textRaw json.RawMessage | ||
| if req.ResponseFormat != nil && req.ResponseFormat.Type != "" { | ||
| textRaw, _ = common.Marshal(map[string]any{ | ||
| "format": req.ResponseFormat, | ||
| }) | ||
| } | ||
|
|
||
| maxOutputTokens := req.MaxTokens | ||
| if req.MaxCompletionTokens > maxOutputTokens { | ||
| maxOutputTokens = req.MaxCompletionTokens | ||
| } | ||
|
|
||
| var topP *float64 | ||
| if req.TopP != 0 { | ||
| topP = common.GetPointer(req.TopP) | ||
| } | ||
|
|
||
| out := &dto.OpenAIResponsesRequest{ | ||
| Model: req.Model, | ||
| Input: inputRaw, | ||
| Instructions: instructionsRaw, | ||
| MaxOutputTokens: maxOutputTokens, | ||
| Stream: req.Stream, | ||
| Temperature: req.Temperature, | ||
| Text: textRaw, | ||
| ToolChoice: toolChoiceRaw, | ||
| Tools: toolsRaw, | ||
| TopP: topP, | ||
| User: req.User, | ||
| ParallelToolCalls: parallelToolCallsRaw, | ||
| Store: req.Store, | ||
| Metadata: req.Metadata, | ||
| } | ||
|
|
||
| if req.ReasoningEffort != "" && req.ReasoningEffort != "none" { | ||
| out.Reasoning = &dto.Reasoning{ | ||
| Effort: req.ReasoningEffort, | ||
| } | ||
| } | ||
|
|
||
| return out, nil | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# Find DTO definitions and Tool structure
find . -name "*.go" -path "*/dto/*" | head -20Repository: QuantumNous/new-api
Length of output: 434
🏁 Script executed:
# Check the DTO file for OpenAIResponsesRequest and Tool definitions
rg -n "type\s+(Tool|OpenAIResponsesRequest|GeneralOpenAIRequest)" --type=go -A 15 | head -100Repository: QuantumNous/new-api
Length of output: 6778
🏁 Script executed:
# Check for ParallelTooCalls vs ParallelToolCalls usage
rg -n "ParallelToo|ParallelTool" --type=goRepository: QuantumNous/new-api
Length of output: 1088
🏁 Script executed:
# Look at the Tool struct specifically and its Function field
rg -n "type.*Tool.*struct|Function\s+\*" --type=go -B 2 -A 10 | head -80Repository: QuantumNous/new-api
Length of output: 4150
🏁 Script executed:
# Check if tool.Function can be nil by looking at type definition
rg -n "type.*Tool\b" --type=go -A 20 | grep -E "(Tool|Function)" | head -30Repository: QuantumNous/new-api
Length of output: 933
🏁 Script executed:
# Get the full GeneralOpenAIRequest definition
rg -n "type GeneralOpenAIRequest struct" --type=go -A 60 dto/openai_request.goRepository: QuantumNous/new-api
Length of output: 4094
🏁 Script executed:
# Search for where Tools is defined in the request types
rg -n "Tools\s*\[\]|Tools\s+\[" --type=go dto/ | head -20Repository: QuantumNous/new-api
Length of output: 419
🏁 Script executed:
# Check how common.Marshal is used elsewhere and if errors are typically handled
rg -n "common\.Marshal" --type=go service/ | head -30Repository: QuantumNous/new-api
Length of output: 1447
🏁 Script executed:
# Look at the context of how marshal errors are handled in similar conversion functions
rg -n "common\.Marshal.*err\s*=" --type=go -B 2 -A 2 service/openaicompat/ | head -50Repository: QuantumNous/new-api
Length of output: 825
🏁 Script executed:
# Check if there are tests or documentation about the Responses API input format
find . -name "*responses*" -type f | grep -E "\.(go|md)" | head -20Repository: QuantumNous/new-api
Length of output: 390
🏁 Script executed:
# Check the relay responses implementation to understand the input schema
cat -n relay/channel/openai/chat_via_responses.go | head -100Repository: QuantumNous/new-api
Length of output: 4005
🏁 Script executed:
# Look at responses_handler to see what the expected input format is
rg -n "input|content" relay/responses_handler.go -B 2 -A 2 | head -60Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
# Check comments or examples about input structure
rg -n "input.*content|content.*string|content.*array" --type=go service/openaicompat/ relay/Repository: QuantumNous/new-api
Length of output: 1899
🏁 Script executed:
# Check if there are any tests or examples of the responses request structure
find . -name "*test*" -o -name "*example*" | xargs grep -l "OpenAIResponsesRequest\|chat_to_responses" 2>/dev/null | head -10Repository: QuantumNous/new-api
Length of output: 91
🏁 Script executed:
# Look at the full code around line 95 and 136 to see content assignment patterns
sed -n '85,140p' service/openaicompat/chat_to_responses.goRepository: QuantumNous/new-api
Length of output: 1581
🏁 Script executed:
# Check the channel-test.go file for usage examples
cat -n controller/channel-test.go | grep -A 20 -B 5 "OpenAIResponsesRequest\|chat_to_responses"Repository: QuantumNous/new-api
Length of output: 3015
🏁 Script executed:
# Look at the responses_to_chat conversion to understand the inverse operation
cat -n service/openaicompat/responses_to_chat.go | head -80Repository: QuantumNous/new-api
Length of output: 2740
🏁 Script executed:
# While we wait, let's check if there are any comments or documentation in the responses files
rg -n "content|input" service/openaicompat/chat_to_responses.go -B 1 -A 1 | grep -E "^[0-9]+[-:].*//|^[0-9]+[-:].*\/\*" | head -20Repository: QuantumNous/new-api
Length of output: 147
🏁 Script executed:
# Check how other handlers deal with potential marshal failures
rg -n "common\.Marshal.*error|err.*common\.Marshal" service/ --type=go -B 1 -A 3 | head -40Repository: QuantumNous/new-api
Length of output: 1105
🏁 Script executed:
# Check ToolCallRequest more carefully to see if Function can be zero-valued
rg -n "type ToolCallRequest\|type FunctionRequest" --type=go -A 10 dto/openai_request.goRepository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
# Verify the exact line where tool.Function is accessed in the code
sed -n '155,165p' service/openaicompat/chat_to_responses.goRepository: QuantumNous/new-api
Length of output: 419
🏁 Script executed:
# Check if tool can be nil by looking for any nil checks in the loop
sed -n '150,175p' service/openaicompat/chat_to_responses.goRepository: QuantumNous/new-api
Length of output: 798
🏁 Script executed:
# Look for FunctionRequest definition again more carefully
cat -n dto/openai_request.go | sed -n '242,254p'Repository: QuantumNous/new-api
Length of output: 596
Propagate marshal errors and validate tool function names.
Several marshal operations silently ignore errors (instructionsRaw, toolsRaw, toolChoiceRaw, parallelToolCallsRaw, textRaw), risking partial requests without error reporting. Only inputRaw at line 140 properly checks and returns the error. Additionally, tool.Function.Name (a required field per FunctionRequest definition) should be validated as non-empty before use.
Proposed change (propagate marshal errors + validate tool.Function.Name)
var instructionsRaw json.RawMessage
if len(instructionsParts) > 0 {
instructions := strings.Join(instructionsParts, "\n\n")
- instructionsRaw, _ = common.Marshal(instructions)
+ instructionsRaw, err = common.Marshal(instructions)
+ if err != nil {
+ return nil, err
+ }
}
@@
if req.Tools != nil {
tools := make([]map[string]any, 0, len(req.Tools))
for _, tool := range req.Tools {
switch tool.Type {
case "function":
+ if strings.TrimSpace(tool.Function.Name) == "" {
+ return nil, fmt.Errorf("tool function name is required")
+ }
tools = append(tools, map[string]any{
"type": "function",
"name": tool.Function.Name,
"description": tool.Function.Description,
"parameters": tool.Function.Parameters,
})
@@
- toolsRaw, _ = common.Marshal(tools)
+ toolsRaw, err = common.Marshal(tools)
+ if err != nil {
+ return nil, err
+ }
}
@@
var toolChoiceRaw json.RawMessage
if req.ToolChoice != nil {
switch v := req.ToolChoice.(type) {
case string:
- toolChoiceRaw, _ = common.Marshal(v)
+ toolChoiceRaw, err = common.Marshal(v)
+ if err != nil {
+ return nil, err
+ }
default:
var m map[string]any
if b, err := common.Marshal(v); err == nil {
_ = common.Unmarshal(b, &m)
}
if m == nil {
- toolChoiceRaw, _ = common.Marshal(v)
+ toolChoiceRaw, err = common.Marshal(v)
+ if err != nil {
+ return nil, err
+ }🤖 Prompt for AI Agents
In @service/openaicompat/chat_to_responses.go around lines 37 - 262, Summary:
ChatCompletionsRequestToResponsesRequest currently swallows marshal errors for
instructionsRaw, toolsRaw, toolChoiceRaw, parallelToolCallsRaw, and textRaw and
uses tool.Function.Name without validating it. Fix: for each place where
common.Marshal is called without checking the error (instructionsRaw, toolsRaw,
toolChoiceRaw, parallelToolCallsRaw, textRaw) propagate and return marshal
errors instead of ignoring them, mirroring the existing inputRaw error pattern
in ChatCompletionsRequestToResponsesRequest; additionally validate that each
tool in req.Tools with Type "function" has a non-empty tool.Function.Name and
return a clear error if missing before building toolsRaw. Ensure the toolChoice
handling also checks marshal/unmarshal errors and returns them instead of
discarding, and keep references to the symbols
ChatCompletionsRequestToResponsesRequest, req.Tools, tool.Function.Name,
instructionsRaw, toolsRaw, toolChoiceRaw, parallelToolCallsRaw, and textRaw to
locate the changes.
| var compiledRegexCache sync.Map // map[string]*regexp.Regexp | ||
|
|
||
| func matchAnyRegex(patterns []string, s string) bool { | ||
| if len(patterns) == 0 || s == "" { | ||
| return false | ||
| } | ||
| for _, pattern := range patterns { | ||
| if pattern == "" { | ||
| continue | ||
| } | ||
| re, ok := compiledRegexCache.Load(pattern) | ||
| if !ok { | ||
| compiled, err := regexp.Compile(pattern) | ||
| if err != nil { | ||
| // Treat invalid patterns as non-matching to avoid breaking runtime traffic. | ||
| continue | ||
| } | ||
| re = compiled | ||
| compiledRegexCache.Store(pattern, re) | ||
| } | ||
| if re.(*regexp.Regexp).MatchString(s) { | ||
| return true | ||
| } | ||
| } |
There was a problem hiding this comment.
Avoid unsafe type assertions + simplify caching via LoadOrStore.
re.(*regexp.Regexp) will panic if anything other than *regexp.Regexp is ever stored (now or in future refactors). Also Load+Store can compile the same pattern concurrently.
Proposed fix
var compiledRegexCache sync.Map // map[string]*regexp.Regexp
func matchAnyRegex(patterns []string, s string) bool {
@@
for _, pattern := range patterns {
@@
- re, ok := compiledRegexCache.Load(pattern)
- if !ok {
- compiled, err := regexp.Compile(pattern)
- if err != nil {
- // Treat invalid patterns as non-matching to avoid breaking runtime traffic.
- continue
- }
- re = compiled
- compiledRegexCache.Store(pattern, re)
- }
- if re.(*regexp.Regexp).MatchString(s) {
+ if v, ok := compiledRegexCache.Load(pattern); ok {
+ if re, ok := v.(*regexp.Regexp); ok && re.MatchString(s) {
+ return true
+ }
+ continue
+ }
+
+ compiled, err := regexp.Compile(pattern)
+ if err != nil {
+ // Treat invalid patterns as non-matching to avoid breaking runtime traffic.
+ continue
+ }
+ v, _ := compiledRegexCache.LoadOrStore(pattern, compiled)
+ if re, ok := v.(*regexp.Regexp); ok && re.MatchString(s) {
return true
}
}
return false
}🤖 Prompt for AI Agents
In @service/openaicompat/regex.go around lines 8 - 31, The matchAnyRegex
function currently uses compiledRegexCache.Load then Store and an unchecked type
assertion re.(*regexp.Regexp), which can panic and allows duplicate compilation
under concurrency; change it to first attempt Load, and if missing compile the
pattern then call compiledRegexCache.LoadOrStore(pattern, compiled) to avoid a
race, then retrieve the stored value and perform a safe type assertion (val, ok
:= storedVal.(*regexp.Regexp)) and skip the pattern if the assertion fails;
update references in matchAnyRegex and keep compiledRegexCache as the sync.Map
key, using regexp.Compile for compilation and LoadOrStore to ensure only one
compiled regexp is stored.
| var toolCalls []dto.ToolCallResponse | ||
| if text == "" && len(resp.Output) > 0 { | ||
| for _, out := range resp.Output { | ||
| if out.Type != "function_call" { | ||
| continue | ||
| } | ||
| name := strings.TrimSpace(out.Name) | ||
| if name == "" { | ||
| continue | ||
| } | ||
| callId := strings.TrimSpace(out.CallId) | ||
| if callId == "" { | ||
| callId = strings.TrimSpace(out.ID) | ||
| } | ||
| toolCalls = append(toolCalls, dto.ToolCallResponse{ | ||
| ID: callId, | ||
| Type: "function", | ||
| Function: dto.FunctionResponse{ | ||
| Name: name, | ||
| Arguments: out.Arguments, | ||
| }, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| finishReason := "stop" | ||
| if len(toolCalls) > 0 { | ||
| finishReason = "tool_calls" | ||
| } | ||
|
|
||
| msg := dto.Message{ | ||
| Role: "assistant", | ||
| Content: text, | ||
| } | ||
| if len(toolCalls) > 0 { | ||
| msg.SetToolCalls(toolCalls) | ||
| msg.Content = "" | ||
| } |
There was a problem hiding this comment.
Bug: tool calls are dropped when there is any extracted text.
toolCalls are only extracted when text == "". If the upstream returns both a message output and one/more function_call outputs in the same response, this will incorrectly map to a plain "stop" chat completion without tool_calls.
Proposed fix (extract tool calls independently of text + ensure non-empty IDs)
package openaicompat
import (
"errors"
+ "fmt"
"strings"
"github.com/QuantumNous/new-api/dto"
)
@@
created := resp.CreatedAt
var toolCalls []dto.ToolCallResponse
- if text == "" && len(resp.Output) > 0 {
- for _, out := range resp.Output {
+ if len(resp.Output) > 0 {
+ for i, out := range resp.Output {
if out.Type != "function_call" {
continue
}
name := strings.TrimSpace(out.Name)
if name == "" {
continue
}
callId := strings.TrimSpace(out.CallId)
if callId == "" {
callId = strings.TrimSpace(out.ID)
}
+ if callId == "" {
+ callId = fmt.Sprintf("call_%d", i)
+ }
toolCalls = append(toolCalls, dto.ToolCallResponse{
ID: callId,
Type: "function",
Function: dto.FunctionResponse{
Name: name,
Arguments: out.Arguments,
},
})
}
}
@@
msg := dto.Message{
Role: "assistant",
Content: text,
}
if len(toolCalls) > 0 {
msg.SetToolCalls(toolCalls)
- msg.Content = ""
}🤖 Prompt for AI Agents
In @service/openaicompat/responses_to_chat.go around lines 44 - 81, The current
logic only builds toolCalls when text == "", so function_call outputs in
resp.Output are ignored whenever any extracted text exists; change the code that
iterates resp.Output to always extract function_call entries into toolCalls
regardless of text, ensure you normalize/validate callId (use out.CallId or
out.ID and skip entries with empty IDs), then set finishReason to "tool_calls"
when toolCalls is non-empty and attach them via msg.SetToolCalls(toolCalls)
while clearing msg.Content only if toolCalls exist; update references to
variables toolCalls, text, resp.Output, callId, finishReason, and
Message.SetToolCalls accordingly.
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Fix all issues with AI agents
In @relay/channel/openai/chat_via_responses.go:
- Around line 162-168: The code reads
streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens without
ensuring CompletionTokenDetails is non-nil; add a nil check similar to the
existing one for InputTokensDetails so you only assign
usage.CompletionTokenDetails.ReasoningTokens when
streamResp.Response.Usage.CompletionTokenDetails != nil (and likewise guard any
other fields on CompletionTokenDetails before dereferencing them), keeping the
same assignment to usage.CompletionTokenDetails.ReasoningTokens.
- Around line 199-200: The streaming handler in chat_via_responses.go currently
ignores "response.output_item.added" and "response.output_item.done" but must
mirror relay_responses.go: when those events occur extract tool-call info from
streamResponse.Item and append/populate the ResponsesOutput fields (CallId,
Name, Arguments) so tool calls are accumulated during streaming; then emit/send
those tool-call chunks (same format relay_responses.go uses) before handling
"response.completed". Update the case for
"response.output_item.added"/"response.output_item.done" to parse
streamResponse.Item, populate ResponsesOutput.Tool call fields, and send the
chunk to the client just like in relay_responses.go.
In @web/src/i18n/locales/ja.json:
- Around line 2583-2587: Update the Japanese strings for consistency: replace
the ASCII colon in the translation for "提示:该功能为测试版..." currently "注意:" with a
fullwidth colon "注意:"; change "格式化 JSON": "JSON を整形" to remove the extra space
"JSONを整形"; and change both "填充模板(指定渠道)" and "填充模板(全渠道)" translations from
"テンプレートを入力(指定チャネル)" / "テンプレートを入力(全チャネル)" to a more natural phrasing like
"テンプレートを適用(指定チャネル)" and "テンプレートを適用(全チャネル)" respectively so wording and
typography match the rest of the locale file.
In @web/src/i18n/locales/zh.json:
- Around line 2572-2576: The translation key used in the UI
t('ChatCompletions→Responses 兼容配置') doesn't match the locale files which only
define 'ChatCompletions→Responses 兼容配置(Beta)', and the UI also renders a
hardcoded "Alpha" tag causing inconsistent labels; fix by either adding the
non‑Beta key 'ChatCompletions→Responses 兼容配置' with appropriate translations to
all locale files (en.json, zh.json, vi.json, ru.json, fr.json, ja.json) or
update the UI in SettingGlobalModel.jsx to call t('ChatCompletions→Responses
兼容配置(Beta)') and replace the hardcoded "Alpha" tag with a translated "(Beta)"
label (or pull the label from i18n) so keys and displayed badge text are
consistent across locales.
In @web/src/pages/Setting/Model/SettingGlobalModel.jsx:
- Around line 219-340: The UI shows a hardcoded Tag "Alpha" while locales use
"(Beta)"—make the tag text consistent (use the localized string instead of
hardcoded 'Alpha' or update all locales); additionally add client-side JSON
validation in onSubmit() before calling UpdateOption(): parse and validate
'global.chat_completions_to_responses_policy' (must be valid JSON
object/expected structure) and 'global.thinking_model_blacklist' (must be a JSON
array), reject submission and call showError(...) when parsing/structure
validation fails (normalizeValueBeforeSave() should still handle empty strings
but not replace explicit parsing/validation here), so invalid JSON never reaches
UpdateOption().
🧹 Nitpick comments (5)
relay/channel/openai/chat_via_responses.go (2)
148-170: Consider extracting usage mapping to a shared helper.The usage extraction logic here duplicates the mapping in
service/openaicompat/responses_to_chat.go(lines 13-34). Consolidating this into a reusable helper function would reduce duplication and improve maintainability.♻️ Refactor suggestion
Create a helper function in a shared location (e.g., in
service/openaicompat/responses_to_chat.go):func MapResponseUsageToDTO(respUsage *dto.ResponseUsage) *dto.Usage { if respUsage == nil { return &dto.Usage{} } usage := &dto.Usage{} if respUsage.InputTokens != 0 { usage.PromptTokens = respUsage.InputTokens usage.InputTokens = respUsage.InputTokens } if respUsage.OutputTokens != 0 { usage.CompletionTokens = respUsage.OutputTokens usage.OutputTokens = respUsage.OutputTokens } if respUsage.TotalTokens != 0 { usage.TotalTokens = respUsage.TotalTokens } else { usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens } if respUsage.InputTokensDetails != nil { usage.PromptTokensDetails.CachedTokens = respUsage.InputTokensDetails.CachedTokens usage.PromptTokensDetails.ImageTokens = respUsage.InputTokensDetails.ImageTokens usage.PromptTokensDetails.AudioTokens = respUsage.InputTokensDetails.AudioTokens } if respUsage.CompletionTokenDetails != nil && respUsage.CompletionTokenDetails.ReasoningTokens != 0 { usage.CompletionTokenDetails.ReasoningTokens = respUsage.CompletionTokenDetails.ReasoningTokens } return usage }Then replace lines 148-170 with:
- if streamResp.Response.Usage != nil { - if streamResp.Response.Usage.InputTokens != 0 { - usage.PromptTokens = streamResp.Response.Usage.InputTokens - usage.InputTokens = streamResp.Response.Usage.InputTokens - } - if streamResp.Response.Usage.OutputTokens != 0 { - usage.CompletionTokens = streamResp.Response.Usage.OutputTokens - usage.OutputTokens = streamResp.Response.Usage.OutputTokens - } - if streamResp.Response.Usage.TotalTokens != 0 { - usage.TotalTokens = streamResp.Response.Usage.TotalTokens - } else { - usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens - } - if streamResp.Response.Usage.InputTokensDetails != nil { - usage.PromptTokensDetails.CachedTokens = streamResp.Response.Usage.InputTokensDetails.CachedTokens - usage.PromptTokensDetails.ImageTokens = streamResp.Response.Usage.InputTokensDetails.ImageTokens - usage.PromptTokensDetails.AudioTokens = streamResp.Response.Usage.InputTokensDetails.AudioTokens - } - if streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens != 0 { - usage.CompletionTokenDetails.ReasoningTokens = streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens - } - } + if streamResp.Response.Usage != nil { + usage = service.MapResponseUsageToDTO(streamResp.Response.Usage) + }
91-95: Consider failing fast on unmarshal errors.When unmarshaling the stream event fails (line 92), the code logs the error but continues processing (returns
true). Depending on requirements, it might be better to fail fast and return an error to the client rather than potentially missing critical events.Alternative approach
var streamResp dto.ResponsesStreamResponse if err := common.UnmarshalJsonStr(data, &streamResp); err != nil { - logger.LogError(c, "failed to unmarshal responses stream event: "+err.Error()) - return true + logger.LogError(c, "failed to unmarshal responses stream event: "+err.Error()) + streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) + return false }web/src/components/settings/ModelSetting.jsx (1)
56-80: Consider normalizing empty JSON option values on load (keep{}/[]), not just on save.Right now, if the API returns
''forglobal.chat_completions_to_responses_policy/global.thinking_model_blacklist, you keep it as''(no formatting), which can surface as a blank editor even though defaults exist elsewhere.A small tweak is to treat blank/whitespace as
{}/[]while buildingnewInputs, similar to the save-time normalization.Proposed patch (load-time normalization)
@@ - if ( + if ( item.key === 'gemini.safety_settings' || item.key === 'gemini.version_settings' || item.key === 'claude.model_headers_settings' || item.key === 'claude.default_max_tokens' || item.key === 'gemini.supported_imagine_models' || item.key === 'global.thinking_model_blacklist' || item.key === 'global.chat_completions_to_responses_policy' ) { - if (item.value !== '') { + const trimmed = item.value == null ? '' : String(item.value).trim(); + if (trimmed !== '') { try { - item.value = JSON.stringify(JSON.parse(item.value), null, 2); + item.value = JSON.stringify(JSON.parse(trimmed), null, 2); } catch (e) { // Keep raw value so user can fix it, and avoid crashing the page. console.error(`Invalid JSON for option ${item.key}:`, e); } + } else if (item.key === 'global.thinking_model_blacklist') { + item.value = '[]'; + } else if (item.key === 'global.chat_completions_to_responses_policy') { + item.value = '{}'; } }web/src/pages/Setting/Model/SettingGlobalModel.jsx (2)
38-57: Template examples look sane; consider documentingchannel_idsvsall_channelsprecedence.Not blocking, but adding a one-liner note near the templates (or in
extraText) about precedence/behavior would reduce misconfiguration.
122-158: Don’t hide invalid stored JSON on load; preserve raw so admins can fix it.In the
global.chat_completions_to_responses_policyload path, a JSON parse failure currently forces the field back to'{}', which makes the UI look “fine” but prevents users from seeing (and correcting) the bad stored value.Proposed patch (preserve raw value on parse errors)
@@ if (key === 'global.chat_completions_to_responses_policy') { try { value = value && String(value).trim() !== '' ? JSON.stringify(JSON.parse(value), null, 2) : defaultGlobalSettingInputs[key]; } catch (error) { - value = defaultGlobalSettingInputs[key]; + // Preserve raw so the user can fix it. + value = String(props.options[key] ?? ''); } }
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
relay/channel/openai/chat_via_responses.goweb/src/components/settings/ModelSetting.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.jsonweb/src/pages/Setting/Model/SettingGlobalModel.jsx
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-08T17:12:43.157Z
Learnt from: RedwindA
Repo: QuantumNous/new-api PR: 1537
File: relay/gemini_handler.go:330-342
Timestamp: 2025-08-08T17:12:43.157Z
Learning: In the new-api repository, the `GeminiEmbeddingHandler` function in `relay/gemini_handler.go` is designed specifically for native Gemini embedding requests and therefore does not require the `ConvertGeminiRequest` step that is used in the chat handler. The embedding requests are already in the native Gemini format and don't need conversion.
Applied to files:
relay/channel/openai/chat_via_responses.go
🧬 Code graph analysis (2)
web/src/pages/Setting/Model/SettingGlobalModel.jsx (1)
web/src/components/settings/ModelSetting.jsx (1)
inputs(31-47)
relay/channel/openai/chat_via_responses.go (5)
dto/openai_response.go (6)
Usage(222-240)OpenAIResponsesResponse(266-289)ResponsesStreamResponse(370-375)ChatCompletionsStreamResponse(141-149)ChatCompletionsStreamResponseChoice(80-85)ChatCompletionsStreamResponseChoiceDelta(87-93)service/http.go (1)
CloseResponseBodyGracefully(15-23)relay/helper/common.go (5)
GetResponseID(158-161)ObjectData(109-118)GenerateStartEmptyResponse(168-184)GenerateStopResponse(186-199)GenerateFinalUsageResponse(201-211)service/openaicompat/responses_to_chat.go (2)
ResponsesResponseToChatCompletionsResponse(10-99)ExtractOutputTextFromResponses(101-133)relay/helper/stream_scanner.go (1)
StreamScannerHandler(37-272)
🔇 Additional comments (7)
web/src/i18n/locales/fr.json (1)
2600-2604: LGTM! French translations for beta feature are well-done.The five new French translation entries for the ChatCompletions→Responses compatibility feature are accurate and follow proper conventions:
- Technical API terms appropriately preserved in English
- French grammatical conventions correctly applied (e.g., "bêta" with accent)
- Consistent terminology with existing translations in the file
- Valid JSON syntax maintained
web/src/i18n/locales/ru.json (1)
2613-2617: LGTM! Russian translations added for ChatCompletions→Responses compatibility feature.The new translation entries are properly formatted and follow the existing pattern in the file. The JSON syntax is valid, and the translations appear to cover the beta feature UI elements mentioned in the PR summary.
Note: While the structure and format are correct, consider having a native Russian speaker verify the translation accuracy and idiomaticity, particularly for:
- The beta warning message (line 2614)
- The technical terminology used in "ChatCompletions→Responses" (line 2613)
For consistency verification, you may want to check that these same keys exist with appropriate translations in the other locale files (en.json, fr.json, ja.json, vi.json, zh.json) mentioned in the AI summary.
relay/channel/openai/chat_via_responses.go (2)
21-65: LGTM! Well-structured non-streaming handler.The function correctly handles the conversion from OpenAI Responses API to chat completions format with proper error handling, DoS protection via body size limits, and fallback usage estimation.
211-230: LGTM! Proper fallback and event completion handling.The code correctly handles fallback usage calculation and ensures that start/stop events are always sent, even if the upstream didn't provide them. The conditional final usage event emission based on
info.ShouldIncludeUsageis a good compatibility pattern.web/src/components/settings/ModelSetting.jsx (1)
31-47: Default{}forglobal.chat_completions_to_responses_policylooks good.Nice to have this initialized explicitly so the global settings UI can treat it as JSON consistently.
web/src/pages/Setting/Model/SettingGlobalModel.jsx (1)
75-85: Save-time normalization for empty policy =>{}is good.Keeps the stored value JSON-shaped and avoids downstream JSON parse failures on empty strings.
web/src/i18n/locales/en.json (1)
2586-2596: LGTM! Translation additions are clear and well-written.The new English translations for the ChatCompletions→Responses compatibility feature are grammatically correct, clear, and consistent with the existing translation patterns in the file. The beta warning appropriately cautions users about production usage, and the action labels ("Fill template", "Format JSON") are concise and descriptive.
| if streamResp.Response.Usage.InputTokensDetails != nil { | ||
| usage.PromptTokensDetails.CachedTokens = streamResp.Response.Usage.InputTokensDetails.CachedTokens | ||
| usage.PromptTokensDetails.ImageTokens = streamResp.Response.Usage.InputTokensDetails.ImageTokens | ||
| usage.PromptTokensDetails.AudioTokens = streamResp.Response.Usage.InputTokensDetails.AudioTokens | ||
| } | ||
| if streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens != 0 { | ||
| usage.CompletionTokenDetails.ReasoningTokens = streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens |
There was a problem hiding this comment.
Add nil check before accessing nested usage details.
Line 162 accesses streamResp.Response.Usage.InputTokensDetails without verifying it's non-nil. If the field is nil, this will cause a panic.
🛡️ Proposed fix
if streamResp.Response.Usage.TotalTokens != 0 {
usage.TotalTokens = streamResp.Response.Usage.TotalTokens
} else {
usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens
}
- if streamResp.Response.Usage.InputTokensDetails != nil {
+ if streamResp.Response.Usage.InputTokensDetails != nil {
usage.PromptTokensDetails.CachedTokens = streamResp.Response.Usage.InputTokensDetails.CachedTokens
usage.PromptTokensDetails.ImageTokens = streamResp.Response.Usage.InputTokensDetails.ImageTokens
usage.PromptTokensDetails.AudioTokens = streamResp.Response.Usage.InputTokensDetails.AudioTokens
}
- if streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens != 0 {
+ if streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens != 0 {
usage.CompletionTokenDetails.ReasoningTokens = streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens
}Wait, I see the nil check is already there at line 162. But there's no nil check for CompletionTokenDetails at line 167. Let me correct this:
if streamResp.Response.Usage.InputTokensDetails != nil {
usage.PromptTokensDetails.CachedTokens = streamResp.Response.Usage.InputTokensDetails.CachedTokens
usage.PromptTokensDetails.ImageTokens = streamResp.Response.Usage.InputTokensDetails.ImageTokens
usage.PromptTokensDetails.AudioTokens = streamResp.Response.Usage.InputTokensDetails.AudioTokens
}
- if streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens != 0 {
+ if streamResp.Response.Usage.CompletionTokenDetails != nil && streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens != 0 {
usage.CompletionTokenDetails.ReasoningTokens = streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens
}🤖 Prompt for AI Agents
In @relay/channel/openai/chat_via_responses.go around lines 162 - 168, The code
reads streamResp.Response.Usage.CompletionTokenDetails.ReasoningTokens without
ensuring CompletionTokenDetails is non-nil; add a nil check similar to the
existing one for InputTokensDetails so you only assign
usage.CompletionTokenDetails.ReasoningTokens when
streamResp.Response.Usage.CompletionTokenDetails != nil (and likewise guard any
other fields on CompletionTokenDetails before dereferencing them), keeping the
same assignment to usage.CompletionTokenDetails.ReasoningTokens.
| case "response.output_item.added", "response.output_item.done": | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for tool call handling in streaming contexts
echo "=== Searching for output_item event handling ==="
rg -n -A5 -B5 'output_item' --type=go
echo -e "\n=== Searching for function_call handling in streaming ==="
rg -n -A5 -B5 'function_call' --type=go
echo -e "\n=== Searching for streaming tool calls in tests ==="
rg -n -A10 'ResponsesStreamResponse|streaming.*tool' --type=goRepository: QuantumNous/new-api
Length of output: 8667
🏁 Script executed:
#!/bin/bash
echo "=== Check ResponsesOutput structure ==="
rg -n -A15 'type ResponsesOutput' --type=go
echo -e "\n=== Check OpenAIResponsesResponse structure ==="
rg -n -A20 'type OpenAIResponsesResponse struct' --type=go
echo -e "\n=== Check how Item field is used in streaming ==="
rg -n 'streamResp\.Item' --type=go
echo -e "\n=== Full context of chat_via_responses.go switch statement ==="
sed -n '97,210p' relay/channel/openai/chat_via_responses.go | cat -nRepository: QuantumNous/new-api
Length of output: 8510
🏁 Script executed:
#!/bin/bash
echo "=== Check relay_responses.go output_item handling ==="
sed -n '80,150p' relay/channel/openai/relay_responses.go | cat -n
echo -e "\n=== Search for any output_item event processing ==="
rg -n -B5 -A10 'output_item' relay/channel/openai/ --type=go
echo -e "\n=== Check if output_item events should be collected ==="
rg -n -B3 -A8 'response.output_item' --type=goRepository: QuantumNous/new-api
Length of output: 6024
🏁 Script executed:
#!/bin/bash
echo "=== Check how tool calls are sent in non-streaming context ==="
rg -n -B5 -A10 'ToolCalls|tool_calls' relay/channel/openai/chat_via_responses.go --type=go
echo -e "\n=== Check ResponsesOutput processing in responses_to_chat.go ==="
sed -n '41,70p' service/openaicompat/responses_to_chat.go | cat -nRepository: QuantumNous/new-api
Length of output: 1037
Process tool calls from output_item events in streaming mode.
The code correctly ignores the empty cases for "response.output_item.added" and "response.output_item.done" events, but this is a gap: relay_responses.go actively processes these events to extract tool calls from streamResponse.Item (lines 35–46), whereas chat_via_responses.go drops this data entirely. The ResponsesOutput struct carries tool call information (CallId, Name, Arguments) that should be accumulated during streaming and sent as tool call chunks before response.completed arrives. Without this, tool uses are lost in streaming mode.
🤖 Prompt for AI Agents
In @relay/channel/openai/chat_via_responses.go around lines 199 - 200, The
streaming handler in chat_via_responses.go currently ignores
"response.output_item.added" and "response.output_item.done" but must mirror
relay_responses.go: when those events occur extract tool-call info from
streamResponse.Item and append/populate the ResponsesOutput fields (CallId,
Name, Arguments) so tool calls are accumulated during streaming; then emit/send
those tool-call chunks (same format relay_responses.go uses) before handling
"response.completed". Update the case for
"response.output_item.added"/"response.output_item.done" to parse
streamResponse.Item, populate ResponsesOutput.Tool call fields, and send the
chunk to the client just like in relay_responses.go.
| "ChatCompletions→Responses 兼容配置(Beta)": "ChatCompletions→Responses 互換設定(ベータ)", | ||
| "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "注意: この機能はベータ版です。今後、設定構造や挙動が変更される可能性があります。本番環境では使用しないでください。", | ||
| "填充模板(指定渠道)": "テンプレートを入力(指定チャネル)", | ||
| "填充模板(全渠道)": "テンプレートを入力(全チャネル)", | ||
| "格式化 JSON": "JSON を整形", |
There was a problem hiding this comment.
Polish JA wording/typography for consistency (“注意:”, “JSONを整形”, “填充模板”)
Current translations are understandable, but the ASCII colon (注意:) and the extra space (JSON を整形) look inconsistent with the rest of the file, and “填充模板” likely reads more naturally as “テンプレートを適用/挿入” than “入力”.
Proposed tweak (wording/typography)
- "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "注意: この機能はベータ版です。今後、設定構造や挙動が変更される可能性があります。本番環境では使用しないでください。",
- "填充模板(指定渠道)": "テンプレートを入力(指定チャネル)",
- "填充模板(全渠道)": "テンプレートを入力(全チャネル)",
- "格式化 JSON": "JSON を整形",
+ "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "注意:この機能はベータ版です。今後、設定構造や挙動が変更される可能性があります。本番環境では使用しないでください。",
+ "填充模板(指定渠道)": "テンプレートを適用(指定チャネル)",
+ "填充模板(全渠道)": "テンプレートを適用(全チャネル)",
+ "格式化 JSON": "JSONを整形",📝 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.
| "ChatCompletions→Responses 兼容配置(Beta)": "ChatCompletions→Responses 互換設定(ベータ)", | |
| "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "注意: この機能はベータ版です。今後、設定構造や挙動が変更される可能性があります。本番環境では使用しないでください。", | |
| "填充模板(指定渠道)": "テンプレートを入力(指定チャネル)", | |
| "填充模板(全渠道)": "テンプレートを入力(全チャネル)", | |
| "格式化 JSON": "JSON を整形", | |
| "ChatCompletions→Responses 兼容配置(Beta)": "ChatCompletions→Responses 互換設定(ベータ)", | |
| "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "注意:この機能はベータ版です。今後、設定構造や挙動が変更される可能性があります。本番環境では使用しないでください。", | |
| "填充模板(指定渠道)": "テンプレートを適用(指定チャネル)", | |
| "填充模板(全渠道)": "テンプレートを適用(全チャネル)", | |
| "格式化 JSON": "JSONを整形", |
🤖 Prompt for AI Agents
In @web/src/i18n/locales/ja.json around lines 2583 - 2587, Update the Japanese
strings for consistency: replace the ASCII colon in the translation for
"提示:该功能为测试版..." currently "注意:" with a fullwidth colon "注意:"; change "格式化 JSON":
"JSON を整形" to remove the extra space "JSONを整形"; and change both "填充模板(指定渠道)" and
"填充模板(全渠道)" translations from "テンプレートを入力(指定チャネル)" / "テンプレートを入力(全チャネル)" to a more
natural phrasing like "テンプレートを適用(指定チャネル)" and "テンプレートを適用(全チャネル)" respectively so
wording and typography match the rest of the locale file.
| "ChatCompletions→Responses 兼容配置(Beta)": "Tương thích ChatCompletions→Responses (Beta)", | ||
| "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "Lưu ý: Đây là tính năng beta. Cấu trúc cấu hình và hành vi có thể thay đổi trong tương lai. Không dùng trong môi trường production.", | ||
| "填充模板(指定渠道)": "Điền mẫu (kênh được chọn)", | ||
| "填充模板(全渠道)": "Điền mẫu (tất cả kênh)", | ||
| "格式化 JSON": "Định dạng JSON", |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let's run the verification script provided to find key references
rg -n "ChatCompletions→Responses 兼容配置(Beta)" -S web/srcRepository: QuantumNous/new-api
Length of output: 807
🏁 Script executed:
# Also check for the key without the (Beta) suffix
rg -n "ChatCompletions→Responses 兼容配置" -S web/srcRepository: QuantumNous/new-api
Length of output: 1054
🏁 Script executed:
# Check the Chinese translation file at similar lines for comparison
sed -n '3160,3170p' web/src/i18n/locales/zh.jsonRepository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
# Look for the "Tương thích" translation in UI code to see actual usage
rg -n "Tương thích|ChatCompletions" -S web/src --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" -B2 -A2Repository: QuantumNous/new-api
Length of output: 504
🏁 Script executed:
# Let me check the actual UI code in SettingGlobalModel.jsx to understand the context better
sed -n '215,230p' web/src/pages/Setting/Model/SettingGlobalModel.jsxRepository: QuantumNous/new-api
Length of output: 603
🏁 Script executed:
# Also search for any other references that might use the (Beta) variant
rg -n "兼容配置" -S web/srcRepository: QuantumNous/new-api
Length of output: 1054
Critical: i18n key mismatch prevents translation lookups.
The UI code calls t('ChatCompletions→Responses 兼容配置') (without the "(Beta)" suffix), but all i18n locale files define the key as "ChatCompletions→Responses 兼配置(Beta)" (with the suffix). This mismatch across all six language files will cause translation lookups to fail and display the untranslated key instead of the intended translation. Align either the UI code or all i18n keys.
Additionally, in the Vietnamese translation at line 3165, replace the English word "production" with "môi trường sản xuất" for consistency:
"提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "Lưu ý: Đây là tính năng beta. Cấu trúc cấu hình và hành vi có thể thay đổi trong tương lai. Không dùng trong môi trường sản xuất.",
| "ChatCompletions→Responses 兼容配置(Beta)": "ChatCompletions→Responses 兼容配置(Beta)", | ||
| "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。": "提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。", | ||
| "填充模板(指定渠道)": "填充模板(指定渠道)", | ||
| "填充模板(全渠道)": "填充模板(全渠道)", | ||
| "格式化 JSON": "格式化 JSON", |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify which translation keys are actually used in the web UI
rg -n "ChatCompletions→Responses 兼容配置" -S web/src --max-count=20Repository: QuantumNous/new-api
Length of output: 1054
🏁 Script executed:
#!/bin/bash
# Check for the Beta variant
rg -n "ChatCompletions→Responses 兼容配置(Beta)" -S web/src --max-count=20Repository: QuantumNous/new-api
Length of output: 807
🏁 Script executed:
#!/bin/bash
# Search for the other keys mentioned
rg -n "填充模板(指定渠道)|填充模板(全渠道)|格式化 JSON" -S web/src --max-count=20Repository: QuantumNous/new-api
Length of output: 1707
🏁 Script executed:
#!/bin/bash
# Check if there's an "Alpha" tag or badge rendered in the UI component
sed -n '210,280p' web/src/pages/Setting/Model/SettingGlobalModel.jsx | cat -nRepository: QuantumNous/new-api
Length of output: 3072
i18n key mismatch breaks translations in non-Chinese locales.
The UI code uses t('ChatCompletions→Responses 兼容配置') without the "(Beta)" suffix, but all locale files define only 'ChatCompletions→Responses 兼容配置(Beta)'. This causes the translation key to fail in all non-Chinese languages and displays the untranslated key string instead.
Additionally, the UI renders a hardcoded "Alpha" tag (line 218) while the i18n keys reference "Beta", creating inconsistent labeling.
Fix by either:
- Adding the non-Beta key variant to all locale files with appropriate translations, or
- Updating the UI code to use the existing "(Beta)" key and unify "Alpha/Beta" terminology.
Code snippet
web/src/pages/Setting/Model/SettingGlobalModel.jsx:219
<Form.Section text={t('ChatCompletions→Responses 兼容配置')}>
All locale files (en.json, zh.json, vi.json, ru.json, fr.json, ja.json) define the key with "(Beta)" suffix only.
🤖 Prompt for AI Agents
In @web/src/i18n/locales/zh.json around lines 2572 - 2576, The translation key
used in the UI t('ChatCompletions→Responses 兼容配置') doesn't match the locale
files which only define 'ChatCompletions→Responses 兼容配置(Beta)', and the UI also
renders a hardcoded "Alpha" tag causing inconsistent labels; fix by either
adding the non‑Beta key 'ChatCompletions→Responses 兼容配置' with appropriate
translations to all locale files (en.json, zh.json, vi.json, ru.json, fr.json,
ja.json) or update the UI in SettingGlobalModel.jsx to call
t('ChatCompletions→Responses 兼容配置(Beta)') and replace the hardcoded "Alpha" tag
with a translated "(Beta)" label (or pull the label from i18n) so keys and
displayed badge text are consistent across locales.
| <Form.Section text={t('ChatCompletions→Responses 兼容配置')}> | ||
| <Row style={{ marginTop: 10 }}> | ||
| <Col span={24}> | ||
| <Banner | ||
| type='warning' | ||
| title={ | ||
| <span> | ||
| {t('ChatCompletions→Responses 兼容配置')}{' '} | ||
| <Tag color='red' size='small'> | ||
| Alpha | ||
| </Tag> | ||
| </span> | ||
| } | ||
| description={t( | ||
| '提示:该功能为测试版,未来配置结构与功能行为可能发生变更,请勿在生产环境使用。', | ||
| )} | ||
| /> | ||
| </Col> | ||
| </Row> | ||
|
|
||
| <Row style={{ marginTop: 10 }}> | ||
| <Col span={24}> | ||
| <div | ||
| style={{ | ||
| display: 'flex', | ||
| gap: 8, | ||
| flexWrap: 'wrap', | ||
| alignItems: 'center', | ||
| }} | ||
| > | ||
| <Button | ||
| type='secondary' | ||
| size='small' | ||
| onClick={() => | ||
| setInputs({ | ||
| ...inputs, | ||
| 'global.chat_completions_to_responses_policy': | ||
| chatCompletionsToResponsesPolicyExample, | ||
| }) | ||
| } | ||
| > | ||
| {t('填充模板(指定渠道)')} | ||
| </Button> | ||
| <Button | ||
| type='secondary' | ||
| size='small' | ||
| onClick={() => | ||
| setInputs({ | ||
| ...inputs, | ||
| 'global.chat_completions_to_responses_policy': | ||
| chatCompletionsToResponsesPolicyAllChannelsExample, | ||
| }) | ||
| } | ||
| > | ||
| {t('填充模板(全渠道)')} | ||
| </Button> | ||
| <Button | ||
| type='secondary' | ||
| size='small' | ||
| onClick={() => { | ||
| const raw = | ||
| inputs['global.chat_completions_to_responses_policy']; | ||
| if (!raw || String(raw).trim() === '') return; | ||
| try { | ||
| const formatted = JSON.stringify( | ||
| JSON.parse(raw), | ||
| null, | ||
| 2, | ||
| ); | ||
| setInputs({ | ||
| ...inputs, | ||
| 'global.chat_completions_to_responses_policy': | ||
| formatted, | ||
| }); | ||
| } catch (error) { | ||
| showError(t('不是合法的 JSON 字符串')); | ||
| } | ||
| }} | ||
| > | ||
| {t('格式化 JSON')} | ||
| </Button> | ||
| </div> | ||
| </Col> | ||
| </Row> | ||
|
|
||
| <Row style={{ marginTop: 10 }}> | ||
| <Col span={24}> | ||
| <Form.TextArea | ||
| label={t('配置 JSON')} | ||
| field={'global.chat_completions_to_responses_policy'} | ||
| placeholder={ | ||
| t('例如(指定渠道):') + | ||
| '\n' + | ||
| chatCompletionsToResponsesPolicyExample + | ||
| '\n\n' + | ||
| t('例如(全渠道):') + | ||
| '\n' + | ||
| chatCompletionsToResponsesPolicyAllChannelsExample | ||
| } | ||
| rows={8} | ||
| rules={[ | ||
| { | ||
| validator: (rule, value) => { | ||
| if (!value || value.trim() === '') return true; | ||
| return verifyJSON(value); | ||
| }, | ||
| message: t('不是合法的 JSON 字符串'), | ||
| }, | ||
| ]} | ||
| extraText={t( | ||
| '当客户端调用 /v1/chat/completions 且 model 命中 model_patterns 时,自动改走上游 /v1/responses,并把响应转换回 /v1/chat/completions 结构', | ||
| )} | ||
| onChange={(value) => | ||
| setInputs({ | ||
| ...inputs, | ||
| 'global.chat_completions_to_responses_policy': value, | ||
| }) | ||
| } | ||
| /> | ||
| </Col> | ||
| </Row> | ||
| </Form.Section> |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check backend validation and usage of the new setting key
rg -n "chat_completions_to_responses_policy" -S .Repository: QuantumNous/new-api
Length of output: 1592
🏁 Script executed:
#!/bin/bash
# Find the verifyJSON function and examine JSON validation
rg -n "verifyJSON|JSON\.parse" -S web/src/pages/Setting/Model/SettingGlobalModel.jsx -A 2Repository: QuantumNous/new-api
Length of output: 885
🏁 Script executed:
#!/bin/bash
# Check for onSubmit handler in the settings file
rg -n "onSubmit|handleSubmit" -S web/src/pages/Setting/Model/SettingGlobalModel.jsx -A 5Repository: QuantumNous/new-api
Length of output: 551
🏁 Script executed:
#!/bin/bash
# Check locale files for Alpha/Beta terminology
fd -e json -e js web/src/locales | head -20Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
#!/bin/bash
# Check the normalizeValueBeforeSave function
rg -n "normalizeValueBeforeSave" -S web/src/pages/Setting/Model/SettingGlobalModel.jsx -B 2 -A 15Repository: QuantumNous/new-api
Length of output: 1280
🏁 Script executed:
#!/bin/bash
# Check backend validation for the setting
cat -n setting/model_setting/global.go | head -100Repository: QuantumNous/new-api
Length of output: 2435
🏁 Script executed:
#!/bin/bash
# Search for locale files with Alpha/Beta terminology
find web/src/locales -type f -name "*.js" -o -name "*.json" 2>/dev/null | head -20Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
#!/bin/bash
# Check if there's validation in the request handler
rg -n "ChatCompletionsToResponsesPolicy" -S setting/model_setting/global.go -B 3 -A 10Repository: QuantumNous/new-api
Length of output: 1498
🏁 Script executed:
#!/bin/bash
# Find the API endpoint handler for option updates
rg -n "\/api\/option" -S --type go -B 2 -A 10Repository: QuantumNous/new-api
Length of output: 142
🏁 Script executed:
#!/bin/bash
# Check for locale files differently
find web/src -type d -name locales -o -name i18nRepository: QuantumNous/new-api
Length of output: 96
🏁 Script executed:
#!/bin/bash
# Search for Alpha/Beta labels in the codebase
rg -n "Alpha|Beta|测试版" -S web/src --type js --type jsx | head -30Repository: QuantumNous/new-api
Length of output: 90
🏁 Script executed:
#!/bin/bash
# Check Arco Design Form behavior - look at imports and Form usage
rg -n "Form\\.TextArea|Form\\.Section" -S web/src/pages/Setting/Model/SettingGlobalModel.jsx -B 5 -A 8 | head -50Repository: QuantumNous/new-api
Length of output: 1769
🏁 Script executed:
#!/bin/bash
# Search for API endpoint handler - fix regex
rg -n "api/option" -S --type go -B 2 -A 10Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
#!/bin/bash
# List locale files to find translations
ls -la web/src/i18n/locales/Repository: QuantumNous/new-api
Length of output: 534
🏁 Script executed:
#!/bin/bash
# Search for option route handler in backend
rg -n "option.*PUT|PUT.*option" -S --type go -B 2 -A 15Repository: QuantumNous/new-api
Length of output: 1287
🏁 Script executed:
#!/bin/bash
# Check if Arco Form validation blocks submit - look at form validation examples
rg -n "rules.*validator|validator.*function" -S web/src/pages/Setting/Model/SettingGlobalModel.jsx -B 1 -A 3Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
#!/bin/bash
# Find the UpdateOption controller function
rg -n "func.*UpdateOption" -S --type go -A 30Repository: QuantumNous/new-api
Length of output: 3238
🏁 Script executed:
#!/bin/bash
# Check locale files for Alpha/Beta terminology and translation consistency
rg -n "Alpha|Beta|测试版" -S web/src/i18n/locales/Repository: QuantumNous/new-api
Length of output: 1950
🏁 Script executed:
#!/bin/bash
# Check if there's JSON validation in the option update handler
rg -n "json.Unmarshal|json.Decode|JSON.parse" -S --type go web/src/i18n/locales/ | head -20Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
#!/bin/bash
# Look at the actual handler implementation more directly
fd -n "*.go" | xargs grep -l "UpdateOption" | head -5Repository: QuantumNous/new-api
Length of output: 293
🏁 Script executed:
#!/bin/bash
# Check the handleConfigUpdate function to see if it validates JSON
rg -n "func handleConfigUpdate" -S --type go -A 40Repository: QuantumNous/new-api
Length of output: 942
🏁 Script executed:
#!/bin/bash
# Check for any JSON validation on the specific keys
rg -n "chat_completions_to_responses_policy|thinking_model_blacklist" -S --type go -B 2 -A 5Repository: QuantumNous/new-api
Length of output: 815
Fix Alpha/Beta inconsistency and add client-side JSON validation before saving.
-
The UI renders a hardcoded
<Tag>Alpha</Tag>, but all six locale files (en.json, zh.json, ja.json, fr.json, ru.json, vi.json) define the key as"ChatCompletions→Responses 兼容配置(Beta)". Update the tag text or unify the terminology across all locales. -
Form
ruleswithverifyJSON()provide validation feedback, butnormalizeValueBeforeSave()only handles empty strings—it does not validate JSON structure. More critically,onSubmit()calls the API without validating invalid JSON first. The controller'sUpdateOption()has no validation forchat_completions_to_responses_policy, and the raw value is saved to the database. Add explicit JSON validation inonSubmit()for both:
global.thinking_model_blacklist(array validation)global.chat_completions_to_responses_policy(object structure validation)
Fail the submission and show an error if JSON parsing fails, preventing invalid configurations from being saved.
🤖 Prompt for AI Agents
In @web/src/pages/Setting/Model/SettingGlobalModel.jsx around lines 219 - 340,
The UI shows a hardcoded Tag "Alpha" while locales use "(Beta)"—make the tag
text consistent (use the localized string instead of hardcoded 'Alpha' or update
all locales); additionally add client-side JSON validation in onSubmit() before
calling UpdateOption(): parse and validate
'global.chat_completions_to_responses_policy' (must be valid JSON
object/expected structure) and 'global.thinking_model_blacklist' (must be a JSON
array), reject submission and call showError(...) when parsing/structure
validation fails (normalizeValueBeforeSave() should still handle empty strings
but not replace explicit parsing/validation here), so invalid JSON never reaches
UpdateOption().
* feat: /v1/chat/completion -> /v1/response
…up (#4265) * feat: add parameter coverage for the operations: copy, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, and regex_replace * fix: CrossGroupRetry default false 移除gorm:"default:false",避免每次 AutoMigrate时都执行ALTER TABLE `tokens` MODIFY COLUMN `cross_group_retry` boolean DEFAULT false 且bool默认false不影响原有功能 * feat: check-in feature integrates Turnstile security check * feat: add support for Doubao /v1/responses (#2567) * feat: add support for Doubao /v1/responses * fix: fix model deployment style issues, lint problems, and i18n gaps. (#2556) * fix: fix model deployment style issues, lint problems, and i18n gaps. * fix: adjust the key not to be displayed on the frontend, tested via the backend. * fix: adjust the sidebar configuration logic to use the default configuration items if they are not defined. * feat: add plans directory to .gitignore * fix: 修复 gemini 文件类型不支持 image/jpg * fix: fix the proxyURL is empty, not using the default HTTP client configuration && the AWS calling side did not apply the relay timeout. * fix: batch add key backend deduplication * Merge pull request #2582 from seefs001/fix/tips fix: add tips for model management and channel testing * fix(gin): update request body size check to allow zero limit * feat: add regex pattern to mask API keys in sensitive information * fix(task): 修复使用 auto 分组时 Task Relay 不记录日志和不扣费的问题 问题描述: - 使用 auto 分组的令牌调用 /v1/videos 等 Task 接口时,虽然任务能成功创建, 但使用日志不显示记录,且不会扣费 根本原因: - Distribute 中间件在选择渠道后,会将实际选中的分组存储在 ContextKeyAutoGroup 中 - 但 RelayTaskSubmit 函数没有从 context 中读取这个值来更新 info.UsingGroup - 导致 info.UsingGroup 始终是 "auto" 而不是实际选中的分组(如 "sora2逆") - 当 auto 分组的倍率配置为 0 时,quota 计算结果为 0 - 日志记录条件 "if quota != 0" 不满足,导致日志不记录、不扣费 修复方案: - 在 RelayTaskSubmit 函数中计算分组倍率之前,添加从 ContextKeyAutoGroup 获取实际分组的逻辑 - 使用安全的类型断言,避免潜在的 panic 风险 影响范围: - 仅影响 Task Relay 流程(/v1/videos, /suno, /kling 等接口) - 不影响使用具体分组令牌的调用 - 不影响其他 Relay 类型(chat/completions 等已有类似处理逻辑) * 🚀 feat(web): port legacy v2 frontend changes into new UI (deployments, check-in, ollama) + align APIs Bring over the key frontend functionality introduced in merge `efa3301` and integrate it cleanly into the new `web/src` architecture and design system. - **Model deployments (io.net)** - Align frontend endpoints and payloads with backend deployment routes (`/api/deployments/*`) - Add missing deployment operations: details, logs (container-aware), update config, rename, extend duration - Improve create-deployment flow (proper request shape, name availability check, price estimation parity) - **System settings** - Enhance io.net deployment settings: allow testing connection with an unsaved API key and add “how to get API key” guidance - **Channels / Ollama** - Improve Ollama model management: live fetch via base_url with fallback to channel fetch, selection + apply flows, delete confirmation - Refactor for feature-layer consistency: extract Ollama parsing/normalization utilities into `features/channels/lib` - **Quality** - Ensure TypeScript typecheck passes after refactor and new dialogs/components integration * Merge pull request #2590 from xyfacai/fix/max-body-limit fix: 设置默认max req body 为128MB * docs: update readme * i18n: add missing translations * fix(gemini): fetch model list via native v1beta/models endpoint Use the native Gemini Models API (/v1beta/models) instead of the OpenAI-compatible path when listing models for Gemini channels, improving compatibility with third-party Gemini-format providers that don't implement OpenAI routes. - Add paginated model listing with timeout and optional proxy support - Select an enabled key for multi-key Gemini channels * refactor(gemini): 更新 GeminiModelsResponse 以使用 dto.GeminiModel 类型 * fix: remove Minimax from FETCHABLE channels * fix(minimax): 添加 MiniMax-M2 系列模型到 ModelList * feat: add doubao video 1.5 * 🤢 chore: remove useless file * feat: /v1/chat/completion -> /v1/response (#2629) * feat: /v1/chat/completion -> /v1/response * fix: clean propertyNames for gemini function * fix: support snake_case fields in GeminiChatGenerationConfig * chore: update dependencies and lockfile for improved compatibility - Updated @clerk/clerk-react to version 5.59.3 - Updated @hookform/resolvers to version 5.2.2 - Updated @lobehub/icons to version 2.48.0 - Updated various Radix UI components to their latest versions - Updated @tanstack/react-query and related packages for better performance - Updated axios, i18next, and other libraries for security and feature enhancements - Updated lockfile to include configVersion and ensure consistency across environments * Merge pull request #2647 from seefs001/feature/status-code-auto-disable feat: status code auto-disable configuration * fix: chat2response setting ui (#2643) * fix: setting ui * fix: rm global.chat_completions_to_responses_policy * fix: rm global.chat_completions_to_responses_policy * Merge pull request #2627 from seefs001/feature/channel-test-param-override feat: channel testing supports parameter overriding * chore: update dependencies and lockfile for improved compatibility - Updated @lobehub/icons to version 4.0.3 - Updated ai to version 6.0.27 - Updated various libraries including axios, react-day-picker, and streamdown for security and feature enhancements - Updated devDependencies for eslint, prettier, and typescript for better performance and compatibility - Updated lockfile to ensure consistency across environments * chore: update lockfile and Vite configuration for improved build process - Updated lockfile to version 1 for better compatibility and consistency - Enhanced Vite configuration to support production optimizations, including code minification and chunking for dependencies - Added environment-specific console and debugger removal for production builds * chore: migrate from Vite to Rsbuild for build process - Added Rsbuild configuration for development and production builds - Updated package.json scripts to use Rsbuild instead of Vite - Replaced @tailwindcss/vite with @tailwindcss/postcss in dependencies - Introduced postcss.config.mjs for Tailwind CSS integration - Updated TypeScript configuration to include Rsbuild config - Removed Vite configuration file to streamline the build process * refactor: optimize user data handling and API calls - Replaced direct API calls to get user data with cached user information from auth-store in ModelsFilter and SummaryCards components. - Improved session management in RootComponent and Authenticated route to utilize localStorage for user authentication status, reducing unnecessary API requests. - Added caching for setup status checks to enhance performance during navigation. * feat: enhance session validation in authenticated route - Implemented session verification to check user authentication status via API call only once per session. - Updated beforeLoad logic to redirect users to the login page if session validation fails or if no user information is available in localStorage. - Improved user data handling by updating the auth store with fresh user information upon successful session verification. * refactor: improve useMediaQuery hook for better SSR handling - Enhanced the useMediaQuery hook to check for window availability before accessing matchMedia, preventing errors during server-side rendering. - Simplified state initialization and change handling by using a dedicated function to determine initial matches. - Updated event listener management for improved performance and clarity. * feat(hooks): export useMediaQuery from hooks index * refactor: update useMediaQuery imports to use unified hooks index * fix(rsbuild): fix loadEnv API usage and removeConsole type * feat: customizable automatic retry status codes * refactor(hooks): use useSyncExternalStore for better SSR handling in useMediaQuery * refactor: simplify embedded file structure in main.go - Updated the embedded file directive to include the entire web/dist directory instead of individual assets, streamlining the build process. * refactor: replace DropdownMenu with Sheet component in ProfileDropdown - Updated the ProfileDropdown component to use a Sheet for user interactions instead of a DropdownMenu. - Enhanced user info display with improved layout and styling. - Added navigation links and sign-out functionality within the Sheet. * refactor: streamline ProfileDropdown layout and improve user info display - Removed unused Badge component and secondary text from user display. - Enhanced styling for user info section and navigation links. - Updated sign-out functionality to use a button for better accessibility. * feat: add System Settings link for super admin in ProfileDropdown - Introduced a new link to System Settings in the ProfileDropdown, visible only to users with the SUPER_ADMIN role. - Updated imports to include the Settings icon and adjusted the component logic accordingly. - Removed the Settings entry from the sidebar data to streamline navigation. * feat: codex channel (#2652) * feat: codex channel * feat: codex channel * feat: codex oauth flow * feat: codex refresh cred * feat: codex usage * fix: codex err message detail * fix: codex setting ui * feat: codex refresh cred task * fix: import err * fix: codex store must be false * fix: chat -> responses tool call * fix: chat -> responses tool call * feat(i18n): add missing translations * fix(i18n): restore missing translations for "360" and add "User Menu" in multiple locales - Reintroduced the translation for "360" in English, French, Japanese, Russian, Vietnamese, and Chinese locales. - Added the "User Menu" translation in the same languages to enhance user interface consistency. * fix: openAI function to gemini function field adjusted to whitelist mode * feat: TLS_INSECURE_SKIP_VERIFY env * fix: for chat-based calls to the Claude model, tagging is required. Using Claude's rendering logs, the two approaches handle input rendering differently. * refactor(system-settings): restructure settings sections and navigation - Replaced SettingsAccordion with a unified SettingsSection component across various settings sections for consistency. - Introduced a section registry to manage general settings sections dynamically. - Updated navigation items in the system settings sidebar to utilize the new section registry. - Enhanced the GeneralSettings component to support section-based content rendering based on user selection. * fix(system-settings): remove type assertion for quotaDisplayType in GeneralSettings - Eliminated the type assertion for quotaDisplayType in the GeneralSettings component to improve type inference and maintain cleaner code. * refactor(system-settings): update zod import syntax in general settings - Changed the import statement for zod from a default import to a namespace import for better clarity and consistency in the codebase. * fix: the login method cannot be displayed under the aff link. * feat(system-settings): implement generic settings page and enhance navigation - Added a new generic SettingsPage component to handle loading states, data fetching, and section rendering. - Integrated section registry for general and authentication settings to streamline navigation and content management. - Updated URL utility functions to improve query parameter handling for active navigation states. - Enhanced the system settings sidebar to include authentication section items dynamically. * refactor(system-settings): replace SettingsAccordion with SettingsSection across authentication settings - Updated BasicAuthSection, BotProtectionSection, OAuthSection, and PasskeySection to use the new SettingsSection component for consistency. - Introduced a section registry to manage authentication settings dynamically, enhancing navigation and content rendering. * feat(system-settings): enhance request limits settings with new section and unified component - Added a new Request Limits section to the system settings sidebar, integrating it with the section registry for improved navigation. - Replaced SettingsAccordion with SettingsSection in RateLimitSection, SensitiveWordsSection, and SSRFSection for consistency. - Updated RequestLimitsSettings to utilize the new SettingsPage component for better data handling and rendering. - Implemented a search schema for request limits to streamline navigation and section management. * feat(system-settings): integrate content settings sections with unified component and registry - Added a new Content section to the system settings sidebar, incorporating it into the section registry for improved navigation. - Replaced SettingsAccordion with SettingsSection in multiple content-related components for consistency. - Created a section registry to manage content settings dynamically, enhancing the rendering and navigation experience. - Updated the ContentSettings component to utilize the new section registry and streamline content display. * feat(system-settings): enhance integrations settings with unified section registry and components - Introduced a new section registry for integrations settings, consolidating various settings components for better organization and navigation. - Replaced SettingsAccordion with SettingsSection in multiple integration-related components for consistency. - Updated IntegrationSettings to utilize the new SettingsPage component, improving data handling and rendering. - Added a new integrations section to the system settings sidebar, enhancing user experience and accessibility. * feat(system-settings): unify model settings with new section registry and components - Introduced a section registry for model settings, consolidating various model-related components for improved organization and navigation. - Replaced SettingsAccordion with SettingsSection in multiple model settings components for consistency. - Updated ModelSettings to utilize the new SettingsPage component, enhancing data handling and rendering. - Added a new Models section to the system settings sidebar, improving user experience and accessibility. * feat(system-settings): enhance maintenance settings with unified section registry and components - Introduced a new section registry for maintenance settings, consolidating various maintenance-related components for improved organization and navigation. - Replaced SettingsAccordion with SettingsSection in multiple maintenance components for consistency. - Updated MaintenanceSettings to utilize the new section registry, enhancing data handling and rendering. - Added a new Maintenance section to the system settings sidebar, improving user experience and accessibility. * feat(system-settings): update section titles for improved clarity and consistency - Renamed various section titles across content, integrations, maintenance, models, and request limits to enhance clarity and better reflect their functionalities. - Adjusted titles such as 'Dashboard' to 'Data Dashboard', 'API Info' to 'API Addresses', and 'Update Checker' to 'System maintenance' for improved user understanding. - Ensured consistency in naming conventions across all settings sections to streamline user experience and navigation. * feat(nav-group): enhance collapsible menu behavior and URL matching logic - Added controlled state management for collapsible menu items to automatically expand based on active sub-item paths. - Updated the URL matching logic in checkIsActive to improve handling of query parameters and ensure accurate navigation state detection. - Refactored the collapsible component to utilize the new state management, enhancing user experience in the sidebar navigation. * feat(system-settings): update system settings navigation and redirect logic - Changed the link in the profile dropdown to point directly to the general section of system settings with a search parameter for section identification. - Implemented a redirect in the general settings route to ensure users are directed to the default section if no section parameter is provided, enhancing navigation consistency. * feat(system-settings): unify route configuration for settings sections - Refactored route configuration for various system settings sections (auth, content, general, integrations, maintenance, models, request limits) to utilize a new `createSettingsRouteConfig` function. - This change consolidates the repetitive logic of creating search schemas and handling redirects, improving code maintainability and readability. - Enhanced navigation by ensuring default sections are loaded when no section parameter is provided. * feat(url-utils): enhance URL handling and matching logic - Introduced a new utility function `urlToString` to convert various URL formats (string and object) into a standardized string format. - Updated the `checkIsActive` function to utilize `urlToString`, improving the accuracy of URL matching and handling of query parameters. - Refactored URL comparison logic to ensure consistent behavior across different URL types, enhancing navigation state detection. * feat(system-settings): validate DataExportDefaultTime for improved data handling - Introduced a new function `validateDataExportDefaultTime` to ensure the `DataExportDefaultTime` value is either 'week', 'hour', or 'day', defaulting to 'hour' for unexpected values. - Updated the `DataExportDefaultTime` assignment in the settings section to utilize this validation function, enhancing data integrity and user experience. * perf(system-settings): Improve the i18n of system settings content - Changed button labels in various sections to use consistent capitalization and translation functions, enhancing user experience. - Updated validation messages in schemas to utilize translation functions for improved internationalization support. - Ensured all user-facing strings are properly translated, improving accessibility for non-English users. * fix(system-settings): update ApiInfoFormValues type inference for improved schema validation - Changed the type inference for ApiInfoFormValues to utilize ReturnType of createApiInfoSchema, ensuring accurate type representation and enhancing type safety in the API info section. * fix(chat-settings): improve validation logic for chat settings schema - Updated the validation logic to ensure that null values are correctly handled and that only objects are accepted as valid items in the chat settings schema. - Simplified error handling by removing the error message from the catch block, providing a consistent user-facing message for invalid JSON strings. * fix(system-settings): enhance validation error handling in uptime-kuma schema - Updated the validation logic for category name, URL, and slug fields to use an object format for error messages, improving clarity and consistency in user feedback. - Ensured that all validation messages are properly structured to enhance internationalization support. * fix(i18n): add translations for Uptime Kuma group management - Added English, French, Japanese, Russian, Vietnamese, and Chinese translations for "Add Uptime Kuma Group" and "Edit Uptime Kuma Group" to enhance internationalization support. - Included validation messages for category name and slug fields across multiple languages to improve user feedback and accessibility. * fix(system-settings): improve validation error message structure for SystemName - Updated the validation logic for the SystemName field to use an object format for error messages, enhancing clarity and consistency in user feedback. - This change aligns with recent improvements in internationalization support across the system settings schemas. * perf(i18n): add new validation error message translations - Added translations for the new validation error message "Invalid JSON format or values out of allowed range" in English, French, Japanese, Russian, Vietnamese, and Chinese. - This update enhances internationalization support by ensuring users receive clear feedback across multiple languages. * fix(i18n): update Japanese translation for payment method configuration message - Corrected the Japanese translation for the message regarding payment methods configuration to use the term "メソッド" instead of "方法" for improved accuracy and consistency in user feedback. - This change enhances the clarity of the message for Japanese-speaking users. * fix(i18n): remove unnecessary loading messages from French translations - Removed the French translations for "Loading settings...", "Loading maintenance settings...", and "Loading content settings..." to streamline the localization file. - This change improves the clarity and relevance of the translations provided to users. * fix(i18n): add translations for Uptime Kuma group management in multiple languages - Added French, Japanese, Russian, Vietnamese, and Chinese translations for "Add Uptime Kuma Group" and "Edit Uptime Kuma Group" to enhance internationalization support. - This update improves user experience by providing clear and consistent messaging across different languages. * fix(validation): enhance pricing schema error messages and add translations - Updated the pricing schema to include localized error messages for validation, ensuring users receive clear feedback when input values are invalid. - Added new translations for "Exchange rate is required" and "Exchange rate must be greater than 0" in English, French, Japanese, and Chinese to improve internationalization support. - This change enhances user experience by providing accurate and contextually relevant messages across multiple languages. * fix: codex Unsupported parameter: max_output_tokens * fix(model-mapping-editor): simplify JSON parsing logic in useEffect * fix: jimeng i2v support multi image by metadata * refactor(models): restructure models section handling and improve UI components - Replaced tab-based navigation with section-based navigation for better clarity and organization. - Introduced a new section registry to manage model sections, including 'metadata' and 'deployments'. - Updated the ModelsContent component to reflect the new section structure and added a Create Deployment button. - Removed the ModelsTabs component as it was no longer needed. - Enhanced internationalization support by adding new translations for section descriptions and management tasks. - Adjusted sidebar configuration to accommodate the new section structure. * fix: update warning threshold label from '5$' to '2$' * fix: video content api Priority use url field * fix: update abortWithOpenAiMessage function to use types.ErrorCode * feat(deployment): introduce CreateDeploymentDrawer component and update dialog references - Replaced the CreateDeploymentDialog with a new CreateDeploymentDrawer component for improved user experience. - Added comprehensive form handling for deployment creation, including validation and price estimation features. - Updated internationalization files to include new translations for UI elements and descriptions related to deployment configuration. - Enhanced the ModelsContent component to integrate the new drawer for creating deployments. * perf(i18n): enhance internationalization for models table and columns - Updated labels and titles in the ModelsTable and useModelsColumns components to utilize translation functions for improved localization. - Changed static text for vendor and sync status to dynamic translations, enhancing user experience for non-English speakers. - Updated empty state messages in the ModelsTable to support internationalization, ensuring clarity for all users. * fix: fix email send * fix: issue where consecutive calls to multiple tools in gemini all returned an index of 0 * fix: replace Alibaba's Claude-compatible interface with the new interface * fix: Only models with the "qwen" designation can use the Claude-compatible interface; others require conversion. * feat: log shows request conversion * feat: optimized display * feat: optimized display * feat: optimized display * fix: codex rm Temperature * Revert "fix: video content api Priority use url field" * feat: requestId time string use UTC * feat(qwen): support qwen image sync image model config * feat: sync old ui * feat: more ui sync * feat: replace theme * fix build * refactor(web): revert theme colors and variables in CSS Updated color variables for light and dark themes to improve consistency and visual appeal. * feat(deployment): enhance deployment access guard and model deployment settings - Introduced loading phase management in the DeploymentAccessGuard component to provide better user feedback during connection checks. - Updated the ModelsContent component to prefetch the deployments list while checking connection status, improving data readiness. - Implemented a caching mechanism for connection status in useModelDeploymentSettings to optimize performance and reduce unnecessary API calls. - Enhanced loading states and error handling for improved user experience during deployment settings retrieval and connection testing. * feat(i18n): add new translations for connection and loading states across multiple languages - Introduced translations for "Checking connection" and "Loading configuration" in English, French, Japanese, Russian, Vietnamese, and Chinese. - This update enhances the internationalization support, providing clearer user feedback during connection checks and loading phases. * refactor(pagination): adjust layout and styling for pagination component - Updated the pagination component to improve layout by removing unnecessary width constraints and enhancing responsiveness. - Increased minimum width for pagination text to ensure better visibility and alignment across different screen sizes. * feat(i18n): implement translations for various UI elements across multiple components - Updated several components to utilize the translation function for titles and placeholders, enhancing internationalization support. - Added new translation entries for "Filter by name or key..." and "Log Type" in English, French, Japanese, Russian, Vietnamese, and Chinese. - This update improves user experience by providing localized text in the ChannelsTable, SummaryCards, ApiKeysTable, RedemptionsTable, UsageLogsTable, and UsersTable components. * feat(i18n): integrate translation support in SummaryCards component - Added the useTranslation hook to the SummaryCards component to enhance internationalization. - This update allows for localized text rendering, improving user experience for diverse language speakers. * feat(dashboard): refactor dashboard structure and introduce section-based navigation - Removed the tab navigation in favor of a section-based approach, enhancing user experience by providing clearer context for the dashboard content. - Introduced a new section registry to manage dashboard sections, allowing for easier expansion and maintenance. - Updated sidebar configuration to reflect the new section structure, ensuring proper navigation links are displayed. - Added translations for new section titles and descriptions to support internationalization. * feat(i18n): update time range labels and enhance translation support - Changed time range labels from shorthand (e.g., '1D') to full text (e.g., '1 Day') for better clarity. - Updated various components to utilize the translation function for time range labels, improving internationalization. - Added new translation entries for time ranges in English, French, Japanese, Russian, Vietnamese, and Chinese, enhancing user experience across languages. * feat(dashboard): enhance type safety and improve component structure - Updated the Dashboard component to use specific types for model data and filters, enhancing type safety. - Introduced new types for announcements and FAQs, improving clarity and maintainability. - Refactored LogStatCards and UptimePanel components to utilize AbortController for better data fetching management. - Optimized the rendering of announcements and FAQs by using unique keys based on item IDs. - Improved theme management in ModelCharts by caching the ThemeManager import to reduce dynamic imports. * feat(agents): add comprehensive guidelines for React and Next.js development - Introduced a new set of best practices and optimization techniques for React and Next.js applications, aimed at enhancing performance and maintainability. - Included detailed rules covering various aspects such as event handling, API routes, rendering strategies, and state management. - Added extensive documentation in AGENTS.md and SKILL.md to support developers in adhering to these practices. - This update serves as a foundational resource for improving code quality and efficiency in React-based projects. * chore(web): update package.json dependencies - Removed outdated dependencies including @base-ui/react, @clerk/clerk-react, and others to streamline the project. - Updated remaining dependencies to their latest versions for improved performance and security. - This cleanup enhances the overall maintainability of the project. * feat(usage-logs): implement section-based navigation and enhance log management - Introduced a section registry for usage logs, allowing for better organization and navigation between different log categories (common, drawing, task). - Updated the UsageLogsContent component to dynamically render titles and descriptions based on the selected section. - Refactored UsageLogsTable and UsageLogsPrimaryButtons components to accept the active log category as a prop, improving modularity. - Enhanced sidebar configuration to support new section navigation, ensuring users can easily access different log types. - Updated routing to redirect to the default section if none is specified, improving user experience. * feat(i18n): enhance internationalization across usage logs components - Integrated the useTranslation hook in various components related to usage logs, including CommonLogsStats, UsageLogsTable, and column helpers. - Updated labels, titles, and messages to utilize translation functions, improving localization support. - Added new translation entries for log-related terms in English, French, Japanese, Russian, Vietnamese, and Chinese, enhancing user experience for diverse language speakers. * feat(datetime-picker): integrate dayjs for date formatting - Added dayjs as a dependency to the project for improved date handling. - Updated the DateTimePicker component to use dayjs for formatting dates, enhancing consistency and readability of date displays. * feat(date-handling): replace date-fns with dayjs for improved date management - Updated the project to use dayjs instead of date-fns for date formatting and manipulation, enhancing consistency across components. - Refactored DatePicker, DateTimePicker, and other components to utilize dayjs for date-related functionalities. - Added a new dayjs configuration file to extend its capabilities with relative time support. - Updated AGENTS.md to reflect the new technology stack, emphasizing the use of dayjs for date handling. * refactor(agents): streamline front-end development guidelines and update technology stack - Revised AGENTS.md to condense front-end development standards and best practices, making it more accessible for developers and AI assistants. - Updated the technology stack section to reflect current dependencies, emphasizing the use of Bun, React 19, TypeScript, and other key libraries. - Enhanced the document structure with a new table format for better readability and navigation, including a comprehensive table of contents for quick access to sections. * feat(i18n): enhance date picker and datetime picker localization support - Integrated internationalization support in DatePicker and DateTimePicker components by adding locale handling for multiple languages (English, French, Japanese, Russian, Vietnamese, Chinese). - Updated the calendar component to accept a locale prop, ensuring proper localization of month and weekday labels. - Improved user experience by allowing date selection to adapt based on the user's language preference. * feat(layout): add SectionPageLayout component for structured page layouts - Introduced a new SectionPageLayout component to facilitate structured layouts for pages with sections, enhancing the organization of content. - Added subcomponents for Title, Description, Actions, and Content to improve clarity and maintainability of page structures. - Updated AGENTS.md to include guidelines on avoiding unnecessary destructuring of props for better code readability. * feat(layout): refactor components to use SectionPageLayout for improved structure - Replaced AppHeader and Main components with SectionPageLayout across multiple features including Channels, Dashboard, ApiKeys, Models, Redemption Codes, Usage Logs, Users, and Wallet. - Enhanced page organization by utilizing SectionPageLayout's Title, Description, Actions, and Content subcomponents, improving clarity and maintainability. - This update standardizes the layout structure across the application, facilitating a more cohesive user experience. * feat(usage-logs): enhance URL state management and redirection logic - Added useEffect to synchronize column filters with URL search changes, preventing infinite loops caused by inline references. - Improved redirection logic in usage logs to clear 'type' from the URL when the section is not 'common', enhancing user experience and URL cleanliness. * fix(usage-logs): disable global filter and update DataTableToolbar props - Disabled the global filter in the UsageLogsTable component to streamline the user interface. - Updated the DataTableToolbar component to accept a null customSearch prop, enhancing flexibility in toolbar configuration. * feat(routes): implement section-based routing for system settings and dashboard - Introduced section-based routing for system settings and dashboard features, enhancing navigation and organization. - Updated route definitions to include dynamic sections, allowing for more granular access to settings and dashboard components. - Refactored existing routes to redirect to default sections when no specific section is provided, improving user experience. - Added new section routes for models, usage logs, and system settings, ensuring consistency across the application. - Removed deprecated routes to streamline the routing structure and improve maintainability. * refactor(usage-logs): update column helper functions to require config parameter - Modified createFailReasonColumn and createProgressColumn functions to require a config parameter instead of allowing it to be optional. - Simplified destructuring of config to enhance clarity and ensure necessary properties are always provided, improving code reliability. * refactor(usage-logs): improve section ID validation and routing logic - Introduced a type guard function, isUsageLogsSectionId, to validate section IDs, enhancing type safety and reducing the need for casting. - Updated UsageLogsContent to utilize the new validation function for determining the active category, improving clarity and reliability. - Refactored routing logic to use isUsageLogsSectionId for section validation, ensuring proper redirection to the default section when necessary. * refactor(calendar): update locale documentation for i18n support - Revised the locale prop documentation in the Calendar component to specify the use of react-day-picker for internationalization, clarifying the expected locale setup for users. * chore(i18n): remove redundant user information description from locale files - Removed the user information description from English, French, Japanese, Russian, Vietnamese, and Chinese locale files to streamline translations and improve clarity. * chore(i18n): streamline locale files by removing redundant entries - Removed unnecessary entries from English, French, Japanese, Russian, Vietnamese, and Chinese locale files to enhance clarity and reduce clutter. - Adjusted translations for consistency and improved user experience across multiple languages. * chore(sidebar): remove deprecated usage logs route from sidebar config - Eliminated the '/usage-logs' entry from the sidebar configuration to streamline navigation and improve clarity in the sidebar structure. * refactor(redemption-codes): enhance internationalization support and improve UI consistency - Updated various components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages. - Added meta labels for table columns to improve accessibility and clarity. - Revised confirmation and action texts in dialogs and tooltips to leverage translation, enhancing user experience. - Updated locale files to include new translations for improved clarity and consistency. * feat(masked-value-display): add MaskedValueDisplay component for sensitive data handling - Introduced a new MaskedValueDisplay component to display masked values with a popover for full value visibility and a copy button for easy access. - Updated api-keys-columns and redemptions-columns to utilize the new component, enhancing code reusability and UI consistency. - Revised translation keys in locale files to remove colons for improved clarity. * refactor(url-utils): simplify query parameter matching logic in checkIsActive function - Updated the checkIsActive function to streamline the logic for matching URLs with and without query parameters. - Removed unnecessary checks for query parameters when matching base paths, improving clarity and maintainability of the code. * fix(channels-table): update group filter label to use translation function - Replaced hardcoded 'All Groups' label with a translation function call to enhance internationalization support in the ChannelsTable component. * chore(api-keys): remove deprecated API key action messages and related exports - Deleted the api-key-actions.ts file, which contained action messages for enabling, disabling, and deleting API keys. - Updated index.ts to remove the export of getApiKeyActionMessage, streamlining the codebase by eliminating unused functionality. * refactor(i18n): enhance internationalization support across various components - Updated multiple components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages. - Revised constants and labels in the channels and redemption codes features to use i18n keys, improving maintainability and clarity. - Ensured that success and error messages leverage translation functions, enhancing user experience and accessibility. - Streamlined the handling of i18n keys in the constants files for better organization and clarity. * refactor(i18n): enhance translation support across various components - Updated multiple components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages. - Revised pagination and status labels to use i18n keys, improving maintainability and clarity. - Enhanced response time formatting to support internationalization, allowing for localized display of time values. - Updated locale files to include new translations for improved clarity and consistency. * docs(AGENTS): add type checking requirement for TypeScript changes - Included a new guideline stating that type checks must be executed after modifying TypeScript or TSX code, ensuring no type errors are left unresolved. - Updated the document to reflect this addition in the relevant section for better clarity on coding standards. * feat(combobox-input): add ComboboxInput component for enhanced token selection - Introduced a new ComboboxInput component to facilitate token name selection with search and filtering capabilities. - Integrated the ComboboxInput into the UsageLogsFilterDialog for improved user experience when filtering by token name. - Updated locale files to include new translations for user-facing strings related to token filtering. * feat(combobox): integrate translation support for custom value prompt - Added translation functionality to the Combobox component, replacing hardcoded text with a translatable string for the custom value prompt. - Utilized the useTranslation hook from react-i18next to enhance internationalization support, ensuring a consistent user experience across different languages. * refactor(i18n): improve Chinese translations for consistency and clarity - Adjusted spacing in various Chinese translations to enhance readability and maintain consistency across the locale file. - Updated multiple user-facing strings to ensure proper formatting and alignment with localization standards. * feat(calendar): add CalendarDropdown component for enhanced dropdown functionality - Introduced a new CalendarDropdown component to improve user interaction with dropdown selections in the calendar. - Implemented state management for dropdown visibility and selection handling, enhancing the overall user experience. - Updated styling for dropdown elements to ensure consistency and better alignment with the UI design. * fix(balance-query-dialog): handle null currentRow and improve usage query logic - Updated the BalanceQueryDialog component to safely access currentRow properties using optional chaining. - Added a check to ensure currentRow is not null before proceeding with usage queries, preventing potential runtime errors. - Refactored the handleQueryCodexUsage function to use a local variable for currentRow, enhancing code clarity. * feat(i18n): add new translations for batch creation and channel updates - Added new translation strings for batch creation instructions across multiple languages, enhancing user guidance. - Included translations for the "Update Channel" prompt to improve clarity in channel configuration settings. - Ensured consistency in terminology across locale files for better user experience. * feat(channel-mutate-drawer): improve API key input handling and update translations - Refactored the API key input logic in the ChannelMutateDrawer component to enhance readability and maintainability. - Added new placeholder translations for batch creation and existing key prompts in multiple languages, improving user guidance. - Ensured consistency in translation strings across locale files for better user experience. * feat(fetch-models-dialog): implement sorting for model categories - Added a new function to sort model categories alphabetically, placing 'Other' at the end for easier navigation. - Updated the rendering logic in the FetchModelsDialog component to utilize the new sorting function for both new and existing models, enhancing user experience. * refactor(wallet-stats-card): standardize props usage and improve layout consistency Standardizes props usage and improves layout consistency in wallet stats card Refactors the wallet stats card component to: - Use props directly instead of destructuring for consistency - Add min-w-0 to prevent content overflow - Adjust text sizing with break-all for proper wrapping - Implement responsive font sizes (3xl on mobile, 4xl on larger screens) - Improve leading and tracking for better readability Refactor wallet stats card for consistency and layout Standardizes props usage and improves layout consistency in wallet stats card - Uses props directly instead of destructuring for consistency - Adds min-w-0 to prevent content overflow - Adjusts text sizing with break-all for proper wrapping - Implements responsive font sizes (3xl on mobile, 4xl on larger screens) - Improves leading and tracking for better readability * feat(web): add subscription management and admin settings UI * feat(web): add subscription management and admin settings UI - Add subscription management module (plans, pricing, toggle status, and related dialogs/tables with Stripe/Creem integration notes) - Add channel affinity (rules and cache stats), Waffo integration, performance, and Grok model sections to system settings, with extended types and section registry - Add status code mapping validation/risk warnings, upstream update hooks, and utilities for channels; add available models and sidebar module cards to user profile - Add chat2link route and useMinimumLoadingTime, useTableCompactMode shared hooks Made-with: Cursor * fix: remove duplicate GenerateOAuthCode and add missing TaskBulkUpdate - remove duplicate GenerateOAuthCode from github.go since oauth.go already has the generic version. - add model.TaskBulkUpdate for bulk update by upstream task_id strings, fixing task_video.go build failure. * feat(router): add chat2link and subscriptions routes - register /chat2link page route under authenticated layout. - register /subscriptions/ page route under authenticated layout. - update auto-generated routeTree type definitions and route mappings. * feat(docker): add development environment setup with Docker Compose - Introduced docker-compose.dev.yml for local development, including services for new-api, Redis, and PostgreSQL. - Created Dockerfile.dev for backend-only builds, optimizing the development workflow. - Updated makefile to include new commands for starting backend services and frontend development. * feat(web): complete i18n coverage for setup wizard and add language switcher - wrap all hardcoded English strings in setup-wizard, database-step, usage-mode-step, and complete-step with t() calls, covering step titles, descriptions, form validation messages, and fallback strings. - add LanguageSwitcher component to the top-right corner of the setup page so users can switch language during initial setup. - register 25 dynamic i18n keys in static-keys.ts and provide full translations for zh/en/ja/fr/ru/vi. * feat(i18n): internationalize default version text in workspace-switcher - remove hardcoded 'Unknown version' default, use t('Unknown version') for i18n fallback - add "Unknown version" translation entries across all 6 locale files (zh/en/fr/ru/ja/vi) * feat(i18n): add full i18n coverage for channel-affinity settings page - replace Chinese t() keys with English keys across three channel-affinity components to align with new frontend i18n conventions. - add 51 translation entries to all 6 locale files (en/zh/ja/fr/ru/vi) covering main page, rule editor, and cache stats dialog. - register section-registry dynamic keys in static-keys.ts. * feat(i18n): add full i18n coverage for Waffo payment settings page - replace Chinese i18n keys with English keys in waffo-settings-section.tsx for consistency. - wrap previously hardcoded labels (Pay Method Type / Pay Method Name) with t(). - add 26 Waffo-related translation entries across all 6 locale files (en/zh/fr/ru/ja/vi). * feat(i18n): add missing translations for global model settings page - add all 6 locale translations for 3 missing t() keys in global-settings-card. - register dynamically used 'Grok' key in static-keys.ts for i18n scanner coverage. * feat(i18n): add full i18n coverage for Grok model settings page - add translations in all 6 locales (en/zh/fr/ja/ru/vi) for grok-settings-card t() calls. - cover violation fee toggle, amount input, and official docs link labels. - include section-registry descriptionKey translation entries. * feat(i18n): add full i18n coverage for performance settings page - migrate all t() keys from Chinese to English to align with project conventions. - add translations for all 6 locales (en/zh/ja/fr/ru/vi) covering disk cache, system monitoring, log management, and stats dashboard sections. - remove 71 obsolete Chinese-keyed entries from every locale file. * fix(i18n): add 116 missing English translation keys across all locales - scan all t() calls to identify English keys used in code but absent from locale files. - add translations for zh/en/fr/ja/ru/vi, keeping key sets and sort order consistent. - covers system-settings, channels, models, auth, wallet and other modules. * fix(i18n): add missing translations for log cleanup quick-select and confirm dialog - wrap quick-select button labels (24 hours ago / 7 days ago / 30 days ago) with t(). - replace hardcoded English strings in purge confirm dialog with t() calls and date interpolation. - add 5 new translation keys across all 6 locale files (zh/en/fr/ja/ru/vi). * refactor(web): unify all time display with dayjs formatting - replace all toLocaleString/toLocaleDateString/toLocaleTimeString and manual padStart concatenation with dayjs.format(). - standardize output: datetime as YYYY-MM-DD HH:mm:ss, date as YYYY-MM-DD, time as HH:mm:ss. - add formatDateTimeStr, formatDateStr, formatTimeStr dayjs-based helpers in lib/format.ts. - update 12 files across core utils and feature components. * refactor(web): replace native datetime-local input with DateTimePicker in announcements - swap browser-native datetime-local for the project's DateTimePicker component to match the UI used in log cleanup and other pages. - convert between Date objects and ISO strings to bridge the form's string-based schema. * refactor(web): replace native HTML elements with design system components - replace ~35 native <button> with <Button> across pricing, profile, channels modules - replace native <input>/<textarea>/<label> with <Input>/<Textarea>/<Label> for consistent form styling - replace native <table> with <Table> components, <details>/<summary> with <Collapsible> - replace decorative <hr> with <Separator> to ensure global UI consistency * refactor(web): enhance profile components with design system consistency - update ProfileSecurityCard to use buttons for security actions, improving accessibility and styling. - modify AccountBindingsTab layout to a grid for better responsiveness and visual alignment. - refactor NotificationTab to utilize icons for notification methods, enhancing user experience and clarity. * fix(i18n): complete i18n coverage for profile page components - wrap passkey card status badges (enabled/disabled, backup state) and last-used text with t() - fix hardcoded button labels in security dialogs (change password, access token, delete account) - internationalize all 2FA dialog strings (setup, disable, backup codes) - fix email bind dialog description and button state text missing i18n - wrap remaining hardcoded strings in notification tab and checkin calendar - add all missing translation entries to zh.json and en.json * fix(i18n): enhance error messages with translations for deployment access and settings - wrap connection error messages in DeploymentAccessGuard and IoNetDeploymentSettingsSection with t() for internationalization. - add missing translation key for "io.net model deployment is not enabled or api key missing" in all locale files (en, fr, ja, ru, vi, zh). * 🧹 chore(web): resolve all ESLint errors and warnings Align the Vite/React frontend with the current ESLint flat config and React Compiler–related rules by fixing violations instead of broad suppression where practical. - Replace `any` with concrete types (`unknown`, `Record<string, unknown>`, domain types) where upstream/API shapes allow - Fix duplicate imports, unused bindings, `no-console`, and empty blocks - Address react-hooks issues: reorder declarations, memoize unstable callbacks (`useCallback`), extend dependency arrays, and use targeted disables only where sync-from-props in `useEffect` is intentional - Refactor `motion.create` usage in ai-elements shimmer to avoid creating components during render (static-components) - Stabilize TanStack Query/Mutation hook usage (query keys, `mutate` in deps) and add narrowly scoped rule disables where the linter conflicts with library patterns - Disable `react-hooks/incompatible-library` in ESLint config for TanStack Table / RHF false positives - Add file-level `react-refresh/only-export-components` disables for registry/provider/column modules that intentionally mix exports `bun lint` completes with 0 errors and 0 warnings. * ✨ feat(web): add subscription management to sidebar and align drawer with project conventions - Register "Subscription Management" nav item in the admin sidebar group with CreditCard icon pointing to /subscriptions - Add subscription module to sidebar config defaults and URL mapping so it integrates with the admin sidebar modules toggle in system settings - Add subscription entry to sidebar-modules-section moduleMeta for the maintenance settings UI - Refactor SubscriptionsMutateDrawer to follow the same patterns used by users, redemption-codes, and other mutate drawers: - Use shadcn Form/FormField/FormItem/FormControl/FormLabel/FormMessage instead of raw register() + Label + manual error display - Move SheetFooter outside the form with form attribute association - Use SheetClose for the cancel button - Reset form state on drawer close - Align SheetContent width (sm:max-w-[600px]) and spacing conventions * ✨ feat(web): overhaul UI/UX with Vercel Geist design alignment Refactor the entire frontend UI/UX to align with Vercel/OpenAI design principles, covering layout, animations, skeleton loading, and overall visual polish. Motion & Page Transitions: - Add centralized motion system (lib/motion.ts) with Vercel-style transition presets, stagger variants for tables, cards, and sidebars - Implement AnimatedOutlet for route-level page enter animations using TanStack Router pathname keying - Add PageTransition, StaggerContainer, StaggerItem, CardStagger, and TableStagger wrapper components for progressive reveal effects Skeleton Loading — Vercel Geist Style: - Replace shadcn default `animate-pulse` with Geist-style shimmer sweep animation (linear-gradient + background-position keyframes) - Add `--skeleton-base` / `--skeleton-highlight` CSS variables tuned for both light and dark themes with neutral oklch tones - Override auto-skeleton-react inline styles via CSS to unify all skeleton elements under the same shimmer effect - Update TableSkeleton with varied column widths for a natural feel - Add ContentSkeleton and QuerySkeleton wrappers for auto-skeleton integration with React Query error/loading states - Respect prefers-reduced-motion: disable shimmer for accessibility Layout & Sidebar: - Upgrade sidebar expand/collapse transitions to cubic-bezier easing - Add hover micro-interactions (background-color, color, transform) to sidebar menu buttons with smooth 150ms transitions - Fix oklch color compatibility in sidebar outline variant - Integrate AnimatedOutlet into AuthenticatedLayout for unified route-level animations Theme & CSS: - Streamline theme.css with cleaner oklch color definitions - Add CSS table row stagger-in animations with nth-child delays - Fix hover-scrollbar color bug (hsl → color-mix for oklch compat) - Add content-auto utility for long list rendering optimization Cleanup: - Remove deprecated skeleton-wrapper.tsx - Remove unused imports and dead code across components - Add empty-state, error-state, and loading-state utility components * 🐛 fix(docker): track bun.lock to fix Docker build failure Remove `web/bun.lock` from `.gitignore` so the lock file is committed to version control. The Dockerfile `COPY web/bun.lock .` instruction requires this file to be present in the build context, and ignoring it caused the build to fail with a "not found" error. * ⬆️ chore(web): upgrade dependencies and fix all type/lint errors Upgrade all frontend dependencies to latest stable versions: - lucide-react 0.562 → 1.7 (major: brand icons removed) - shiki 3.x → 4.x, eslint 9.x → 10.x, knip 5.x → 6.x - @rsbuild/core 1.3 → 1.7, @types/node 24 → 25 - tailwindcss/postcss 4.1 → 4.2, motion 12.25 → 12.38 - @tanstack/react-query 5.90 → 5.95, zod 4.3.5 → 4.3.6 - react 19.2.3 → 19.2.4, axios 1.13.2 → 1.13.6 - prettier 3.7 → 3.8, typescript-eslint 8.52 → 8.57 - Add missing optional deps: @xyflow/react, embla-carousel-react Resolve all TypeScript compilation errors introduced by upgrades: - Replace lucide-react brand icons (Github) with react-icons/si - Fix react-hook-form Control/Resolver generics for zod v4 - Fix Record<string, unknown> type constraints across API utils - Fix axios interceptor return types in lib/api.ts - Add type assertions for useSettings/useStatus hook returns - Resolve Badge variant, spread type, and route path mismatches Resolve all ESLint 10 errors: - preserve-caught-error: attach cause to re-thrown errors - no-useless-assignment: refactor redundant variable assignments - prefer-as-const: use `as const` over literal type assertions - no-unused-vars: prefix type-only schemas with underscore Update tsconfig lib from ES2020 to ES2022 for Error.cause support. * 🐛 fix(web): stop pricing model row from centering its content Wrapping the row in shadcn <Button variant='ghost'> inherits `justify-center`, and the inner flex container had no width, so `justify-between` collapsed and the row appeared centered. * feat: add Waffo payment integration and related UI components - Introduced Waffo payment method with support for custom icons and settings. - Updated payment settings section to include Waffo settings. - Added Waffo payment request handling in the wallet API. - Enhanced wallet recharge form to support Waffo payment methods. - Implemented hooks for Waffo payment processing. - Updated localization files for new Waffo-related strings. - Added new payment type and icon for Waffo in constants and UI components. - Refactored topup info handling to include Waffo payment methods and configurations. * feat(profile): add admin-only upstream model update notification setting * fix(web): make sidebar module user settings actually take effect Previously, saving sidebar module preferences in profile had no effect because the client ignored user-level sidebar_modules entirely. This fix wires user config into useSidebarConfig so the sidebar updates immediately without a page refresh. Changes: - Add UserPermissions type with sidebar_settings/sidebar_modules fields - Refactor useSidebarConfig to merge admin × user config with AND logic - Sync sidebar_modules to auth store on save for immediate UI updates - Conditionally render SidebarModulesCard based on user permissions - Treat null/empty user config as "do not narrow" for legacy users * feat(web): add custom OAuth provider CRUD and login button support Migrate custom OAuth from v1 to v2: - Admin CRUD UI with provider table, form dialog, preset templates, and OIDC discovery - Login page renders dynamic buttons for custom OAuth providers - Fix account bindings display showing "Not bound" text when already bound * feat(web): add ServerAddress, SMTPForceAuthLogin, CreateCacheRatio and group special usable settings Migrate missing v1 system settings to v2: - ServerAddress input in General > System Information - SMTPForceAuthLogin toggle in Integrations > Email - CreateCacheRatio JSON editor in Models > Ratio - Group special usable group rules editor in Models > Ratio * feat(web): wire user subscriptions dialog to users table row actions The UserSubscriptionsDialog component already existed but had no entry point in the users table dropdown menu. Add "Manage Subscriptions" menu item. * chore(web): update i18n translations for new settings and custom OAuth * 💎 refactor(web): redesign pricing page with flat, typography-driven layout * 🌐 chore(i18n): complete missing translations and normalize project config - Add 425+ missing translations across fr, ja, ru, zh, vi locales for subscription management, sidebar navigation, Grok settings, upstream model updates, pricing page, and other UI components - Add 37 missing i18n keys used in t() calls but absent from locale files (pricing filters, display options, audio/cache labels, etc.) - Fix stale tech stack info in CLAUDE.md, AGENTS.md, and project.mdc: React 18 → 19, Vite → Rsbuild, Semi Design → Radix UI + Tailwind - Fix i18n key format description: "Chinese source strings" → English - Deduplicate .cursor/rules/project.mdc to avoid triple-loading the same rules already present in root CLAUDE.md and AGENTS.md - Add i18n-translate Cursor skill for repeatable translation workflow * 🎨 refactor(web): redesign dashboard with flat, typography-driven layout Replace Card-based dashboard components with a flat, border-driven design system consistent with the pricing page, following the ui-style.mdc conventions. Overview section: - StatCard: replace Card wrapper with flat flex layout, monospace tabular values, uppercase tracking-wider labels, layered opacity hierarchy - PanelWrapper: replace Card/CardHeader/CardContent with rounded-lg border container and border-b header - SummaryCards: merge three stat cards into a single bordered container with divide-x separators; decouple border from stagger animation to prevent border deformation during entrance transitions - ApiInfoPanel/Item: full-width list rows with border-b separators, monospace route names, layered opacity for URLs and descriptions - AnnouncementsPanel: native button rows with hover:bg-muted/40, i18n for "Click for details" hint - FAQPanel: lighter border-border/60 accordion dividers, muted answer text - UptimePanel: uppercase tracking-wider group headers with bg-muted/30 background, monospace uptime percentages, fine-grained border opacity Models section: - LogStatCards: replace Card with rounded-lg border + divide-x grid, fix react-hooks/exhaustive-deps by destructuring props before useEffect - ModelCharts: replace Card+Tabs with bordered container + custom segmented control matching ui-style spec - Suspense fallbacks: match new flat skeleton layout with accurate column structure Animation: - Wrap models section in FadeIn with staggered delay - Keep CardStagger for overview panel grid (each panel has own border) Other: - Add ui-style.mdc cursor rule documenting the design language - Disable react-refresh/only-export-components for src/routes/** in eslint config (TanStack Router route files always export Route objects) - Fix zh.json: "Token-based" translation "基于令牌的" → "按量计费" * ✨ refactor(web): adopt flat dot-and-text design for all status badges Replace the bordered/colored-background StatusBadge and Badge components across the entire frontend with a minimal flat design: a small colored dot followed by colored text, eliminating visual noise from heavy borders, backgrounds, and rounded pill shapes. Key changes: - Redesign StatusBadge to use dot + text instead of bordered pill style, removing cva-based background/border variants in favor of exported dotColorMap and textColorMap lookup tables - Add children prop support to StatusBadge for flexible content rendering alongside the existing label prop - Migrate all Badge usages (except pricing page) to StatusBadge with appropriate variant mappings (default→info, secondary→neutral, outline→neutral, destructive→danger) - Consolidate adjacent multi-badge groups into single-dot layouts with dot separators (·) to reduce visual clutter in: - Channel balance columns (used + remaining) - Channel type column (type + IO.NET indicator) - User invite info column (invited + revenue + inviter) - Usage log stats bar (usage + RPM + TPM) - Usage log time/FRT column (time + FRT + stream status) - Subscription plan counts (active + expired) - Channel affinity scope/regex/key-source columns - Prefill group card headers (type + ID) - Export dotColorMap and textColorMap for direct use in custom inline layouts that need consistent status colors without the full component * ✨ refactor(web): redesign public layout and landing page with modern UI Overhaul the public-facing layout, header, and homepage to deliver a polished, animation-rich landing experience inspired by contemporary SaaS design patterns. Header: - Replace sticky header with fixed floating navbar that compacts into a pill-shaped glass-morphism bar on scroll (backdrop-blur + ring) - Add smooth 700ms cubic-bezier transitions for scroll-based shrinking - Build full-screen mobile menu overlay with staggered entry animations - Remove background color from logo container, show logo image directly Homepage sections: - Hero: gradient text title, radial gradient + grid pattern background, interactive terminal demo showcasing API request/response - Terminal demo: auto-cycles through gpt-4o, claude-sonnet-4-20250514, gemini-2.5-pro, deepseek-chat with smooth cross-fade transitions, clickable model badges, dual theme support (light/dark), fixed height - Stats: animated co…
…up (#4265)
* feat: add parameter coverage for the operations: copy, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, and regex_replace
* fix: CrossGroupRetry default false
移除gorm:"default:false",避免每次 AutoMigrate时都执行ALTER TABLE `tokens` MODIFY COLUMN `cross_group_retry` boolean DEFAULT false
且bool默认false不影响原有功能
* feat: check-in feature integrates Turnstile security check
* feat: add support for Doubao /v1/responses (#2567)
* feat: add support for Doubao /v1/responses
* fix: fix model deployment style issues, lint problems, and i18n gaps. (#2556)
* fix: fix model deployment style issues, lint problems, and i18n gaps.
* fix: adjust the key not to be displayed on the frontend, tested via the backend.
* fix: adjust the sidebar configuration logic to use the default configuration items if they are not defined.
* feat: add plans directory to .gitignore
* fix: 修复 gemini 文件类型不支持 image/jpg
* fix: fix the proxyURL is empty, not using the default HTTP client configuration && the AWS calling side did not apply the relay timeout.
* fix: batch add key backend deduplication
* Merge pull request #2582 from seefs001/fix/tips
fix: add tips for model management and channel testing
* fix(gin): update request body size check to allow zero limit
* feat: add regex pattern to mask API keys in sensitive information
* fix(task): 修复使用 auto 分组时 Task Relay 不记录日志和不扣费的问题
问题描述:
- 使用 auto 分组的令牌调用 /v1/videos 等 Task 接口时,虽然任务能成功创建,
但使用日志不显示记录,且不会扣费
根本原因:
- Distribute 中间件在选择渠道后,会将实际选中的分组存储在 ContextKeyAutoGroup 中
- 但 RelayTaskSubmit 函数没有从 context 中读取这个值来更新 info.UsingGroup
- 导致 info.UsingGroup 始终是 "auto" 而不是实际选中的分组(如 "sora2逆")
- 当 auto 分组的倍率配置为 0 时,quota 计算结果为 0
- 日志记录条件 "if quota != 0" 不满足,导致日志不记录、不扣费
修复方案:
- 在 RelayTaskSubmit 函数中计算分组倍率之前,添加从 ContextKeyAutoGroup
获取实际分组的逻辑
- 使用安全的类型断言,避免潜在的 panic 风险
影响范围:
- 仅影响 Task Relay 流程(/v1/videos, /suno, /kling 等接口)
- 不影响使用具体分组令牌的调用
- 不影响其他 Relay 类型(chat/completions 等已有类似处理逻辑)
* 🚀 feat(web): port legacy v2 frontend changes into new UI (deployments, check-in, ollama) + align APIs
Bring over the key frontend functionality introduced in merge `efa3301` and integrate it cleanly into the new `web/src` architecture and design system.
- **Model deployments (io.net)**
- Align frontend endpoints and payloads with backend deployment routes (`/api/deployments/*`)
- Add missing deployment operations: details, logs (container-aware), update config, rename, extend duration
- Improve create-deployment flow (proper request shape, name availability check, price estimation parity)
- **System settings**
- Enhance io.net deployment settings: allow testing connection with an unsaved API key and add “how to get API key” guidance
- **Channels / Ollama**
- Improve Ollama model management: live fetch via base_url with fallback to channel fetch, selection + apply flows, delete confirmation
- Refactor for feature-layer consistency: extract Ollama parsing/normalization utilities into `features/channels/lib`
- **Quality**
- Ensure TypeScript typecheck passes after refactor and new dialogs/components integration
* Merge pull request #2590 from xyfacai/fix/max-body-limit
fix: 设置默认max req body 为128MB
* docs: update readme
* i18n: add missing translations
* fix(gemini): fetch model list via native v1beta/models endpoint
Use the native Gemini Models API (/v1beta/models) instead of the OpenAI-compatible
path when listing models for Gemini channels, improving compatibility with
third-party Gemini-format providers that don't implement OpenAI routes.
- Add paginated model listing with timeout and optional proxy support
- Select an enabled key for multi-key Gemini channels
* refactor(gemini): 更新 GeminiModelsResponse 以使用 dto.GeminiModel 类型
* fix: remove Minimax from FETCHABLE channels
* fix(minimax): 添加 MiniMax-M2 系列模型到 ModelList
* feat: add doubao video 1.5
* 🤢 chore: remove useless file
* feat: /v1/chat/completion -> /v1/response (#2629)
* feat: /v1/chat/completion -> /v1/response
* fix: clean propertyNames for gemini function
* fix: support snake_case fields in GeminiChatGenerationConfig
* chore: update dependencies and lockfile for improved compatibility
- Updated @clerk/clerk-react to version 5.59.3
- Updated @hookform/resolvers to version 5.2.2
- Updated @lobehub/icons to version 2.48.0
- Updated various Radix UI components to their latest versions
- Updated @tanstack/react-query and related packages for better performance
- Updated axios, i18next, and other libraries for security and feature enhancements
- Updated lockfile to include configVersion and ensure consistency across environments
* Merge pull request #2647 from seefs001/feature/status-code-auto-disable
feat: status code auto-disable configuration
* fix: chat2response setting ui (#2643)
* fix: setting ui
* fix: rm global.chat_completions_to_responses_policy
* fix: rm global.chat_completions_to_responses_policy
* Merge pull request #2627 from seefs001/feature/channel-test-param-override
feat: channel testing supports parameter overriding
* chore: update dependencies and lockfile for improved compatibility
- Updated @lobehub/icons to version 4.0.3
- Updated ai to version 6.0.27
- Updated various libraries including axios, react-day-picker, and streamdown for security and feature enhancements
- Updated devDependencies for eslint, prettier, and typescript for better performance and compatibility
- Updated lockfile to ensure consistency across environments
* chore: update lockfile and Vite configuration for improved build process
- Updated lockfile to version 1 for better compatibility and consistency
- Enhanced Vite configuration to support production optimizations, including code minification and chunking for dependencies
- Added environment-specific console and debugger removal for production builds
* chore: migrate from Vite to Rsbuild for build process
- Added Rsbuild configuration for development and production builds
- Updated package.json scripts to use Rsbuild instead of Vite
- Replaced @tailwindcss/vite with @tailwindcss/postcss in dependencies
- Introduced postcss.config.mjs for Tailwind CSS integration
- Updated TypeScript configuration to include Rsbuild config
- Removed Vite configuration file to streamline the build process
* refactor: optimize user data handling and API calls
- Replaced direct API calls to get user data with cached user information from auth-store in ModelsFilter and SummaryCards components.
- Improved session management in RootComponent and Authenticated route to utilize localStorage for user authentication status, reducing unnecessary API requests.
- Added caching for setup status checks to enhance performance during navigation.
* feat: enhance session validation in authenticated route
- Implemented session verification to check user authentication status via API call only once per session.
- Updated beforeLoad logic to redirect users to the login page if session validation fails or if no user information is available in localStorage.
- Improved user data handling by updating the auth store with fresh user information upon successful session verification.
* refactor: improve useMediaQuery hook for better SSR handling
- Enhanced the useMediaQuery hook to check for window availability before accessing matchMedia, preventing errors during server-side rendering.
- Simplified state initialization and change handling by using a dedicated function to determine initial matches.
- Updated event listener management for improved performance and clarity.
* feat(hooks): export useMediaQuery from hooks index
* refactor: update useMediaQuery imports to use unified hooks index
* fix(rsbuild): fix loadEnv API usage and removeConsole type
* feat: customizable automatic retry status codes
* refactor(hooks): use useSyncExternalStore for better SSR handling in useMediaQuery
* refactor: simplify embedded file structure in main.go
- Updated the embedded file directive to include the entire web/dist directory instead of individual assets, streamlining the build process.
* refactor: replace DropdownMenu with Sheet component in ProfileDropdown
- Updated the ProfileDropdown component to use a Sheet for user interactions instead of a DropdownMenu.
- Enhanced user info display with improved layout and styling.
- Added navigation links and sign-out functionality within the Sheet.
* refactor: streamline ProfileDropdown layout and improve user info display
- Removed unused Badge component and secondary text from user display.
- Enhanced styling for user info section and navigation links.
- Updated sign-out functionality to use a button for better accessibility.
* feat: add System Settings link for super admin in ProfileDropdown
- Introduced a new link to System Settings in the ProfileDropdown, visible only to users with the SUPER_ADMIN role.
- Updated imports to include the Settings icon and adjusted the component logic accordingly.
- Removed the Settings entry from the sidebar data to streamline navigation.
* feat: codex channel (#2652)
* feat: codex channel
* feat: codex channel
* feat: codex oauth flow
* feat: codex refresh cred
* feat: codex usage
* fix: codex err message detail
* fix: codex setting ui
* feat: codex refresh cred task
* fix: import err
* fix: codex store must be false
* fix: chat -> responses tool call
* fix: chat -> responses tool call
* feat(i18n): add missing translations
* fix(i18n): restore missing translations for "360" and add "User Menu" in multiple locales
- Reintroduced the translation for "360" in English, French, Japanese, Russian, Vietnamese, and Chinese locales.
- Added the "User Menu" translation in the same languages to enhance user interface consistency.
* fix: openAI function to gemini function field adjusted to whitelist mode
* feat: TLS_INSECURE_SKIP_VERIFY env
* fix: for chat-based calls to the Claude model, tagging is required. Using Claude's rendering logs, the two approaches handle input rendering differently.
* refactor(system-settings): restructure settings sections and navigation
- Replaced SettingsAccordion with a unified SettingsSection component across various settings sections for consistency.
- Introduced a section registry to manage general settings sections dynamically.
- Updated navigation items in the system settings sidebar to utilize the new section registry.
- Enhanced the GeneralSettings component to support section-based content rendering based on user selection.
* fix(system-settings): remove type assertion for quotaDisplayType in GeneralSettings
- Eliminated the type assertion for quotaDisplayType in the GeneralSettings component to improve type inference and maintain cleaner code.
* refactor(system-settings): update zod import syntax in general settings
- Changed the import statement for zod from a default import to a namespace import for better clarity and consistency in the codebase.
* fix: the login method cannot be displayed under the aff link.
* feat(system-settings): implement generic settings page and enhance navigation
- Added a new generic SettingsPage component to handle loading states, data fetching, and section rendering.
- Integrated section registry for general and authentication settings to streamline navigation and content management.
- Updated URL utility functions to improve query parameter handling for active navigation states.
- Enhanced the system settings sidebar to include authentication section items dynamically.
* refactor(system-settings): replace SettingsAccordion with SettingsSection across authentication settings
- Updated BasicAuthSection, BotProtectionSection, OAuthSection, and PasskeySection to use the new SettingsSection component for consistency.
- Introduced a section registry to manage authentication settings dynamically, enhancing navigation and content rendering.
* feat(system-settings): enhance request limits settings with new section and unified component
- Added a new Request Limits section to the system settings sidebar, integrating it with the section registry for improved navigation.
- Replaced SettingsAccordion with SettingsSection in RateLimitSection, SensitiveWordsSection, and SSRFSection for consistency.
- Updated RequestLimitsSettings to utilize the new SettingsPage component for better data handling and rendering.
- Implemented a search schema for request limits to streamline navigation and section management.
* feat(system-settings): integrate content settings sections with unified component and registry
- Added a new Content section to the system settings sidebar, incorporating it into the section registry for improved navigation.
- Replaced SettingsAccordion with SettingsSection in multiple content-related components for consistency.
- Created a section registry to manage content settings dynamically, enhancing the rendering and navigation experience.
- Updated the ContentSettings component to utilize the new section registry and streamline content display.
* feat(system-settings): enhance integrations settings with unified section registry and components
- Introduced a new section registry for integrations settings, consolidating various settings components for better organization and navigation.
- Replaced SettingsAccordion with SettingsSection in multiple integration-related components for consistency.
- Updated IntegrationSettings to utilize the new SettingsPage component, improving data handling and rendering.
- Added a new integrations section to the system settings sidebar, enhancing user experience and accessibility.
* feat(system-settings): unify model settings with new section registry and components
- Introduced a section registry for model settings, consolidating various model-related components for improved organization and navigation.
- Replaced SettingsAccordion with SettingsSection in multiple model settings components for consistency.
- Updated ModelSettings to utilize the new SettingsPage component, enhancing data handling and rendering.
- Added a new Models section to the system settings sidebar, improving user experience and accessibility.
* feat(system-settings): enhance maintenance settings with unified section registry and components
- Introduced a new section registry for maintenance settings, consolidating various maintenance-related components for improved organization and navigation.
- Replaced SettingsAccordion with SettingsSection in multiple maintenance components for consistency.
- Updated MaintenanceSettings to utilize the new section registry, enhancing data handling and rendering.
- Added a new Maintenance section to the system settings sidebar, improving user experience and accessibility.
* feat(system-settings): update section titles for improved clarity and consistency
- Renamed various section titles across content, integrations, maintenance, models, and request limits to enhance clarity and better reflect their functionalities.
- Adjusted titles such as 'Dashboard' to 'Data Dashboard', 'API Info' to 'API Addresses', and 'Update Checker' to 'System maintenance' for improved user understanding.
- Ensured consistency in naming conventions across all settings sections to streamline user experience and navigation.
* feat(nav-group): enhance collapsible menu behavior and URL matching logic
- Added controlled state management for collapsible menu items to automatically expand based on active sub-item paths.
- Updated the URL matching logic in checkIsActive to improve handling of query parameters and ensure accurate navigation state detection.
- Refactored the collapsible component to utilize the new state management, enhancing user experience in the sidebar navigation.
* feat(system-settings): update system settings navigation and redirect logic
- Changed the link in the profile dropdown to point directly to the general section of system settings with a search parameter for section identification.
- Implemented a redirect in the general settings route to ensure users are directed to the default section if no section parameter is provided, enhancing navigation consistency.
* feat(system-settings): unify route configuration for settings sections
- Refactored route configuration for various system settings sections (auth, content, general, integrations, maintenance, models, request limits) to utilize a new `createSettingsRouteConfig` function.
- This change consolidates the repetitive logic of creating search schemas and handling redirects, improving code maintainability and readability.
- Enhanced navigation by ensuring default sections are loaded when no section parameter is provided.
* feat(url-utils): enhance URL handling and matching logic
- Introduced a new utility function `urlToString` to convert various URL formats (string and object) into a standardized string format.
- Updated the `checkIsActive` function to utilize `urlToString`, improving the accuracy of URL matching and handling of query parameters.
- Refactored URL comparison logic to ensure consistent behavior across different URL types, enhancing navigation state detection.
* feat(system-settings): validate DataExportDefaultTime for improved data handling
- Introduced a new function `validateDataExportDefaultTime` to ensure the `DataExportDefaultTime` value is either 'week', 'hour', or 'day', defaulting to 'hour' for unexpected values.
- Updated the `DataExportDefaultTime` assignment in the settings section to utilize this validation function, enhancing data integrity and user experience.
* perf(system-settings): Improve the i18n of system settings content
- Changed button labels in various sections to use consistent capitalization and translation functions, enhancing user experience.
- Updated validation messages in schemas to utilize translation functions for improved internationalization support.
- Ensured all user-facing strings are properly translated, improving accessibility for non-English users.
* fix(system-settings): update ApiInfoFormValues type inference for improved schema validation
- Changed the type inference for ApiInfoFormValues to utilize ReturnType of createApiInfoSchema, ensuring accurate type representation and enhancing type safety in the API info section.
* fix(chat-settings): improve validation logic for chat settings schema
- Updated the validation logic to ensure that null values are correctly handled and that only objects are accepted as valid items in the chat settings schema.
- Simplified error handling by removing the error message from the catch block, providing a consistent user-facing message for invalid JSON strings.
* fix(system-settings): enhance validation error handling in uptime-kuma schema
- Updated the validation logic for category name, URL, and slug fields to use an object format for error messages, improving clarity and consistency in user feedback.
- Ensured that all validation messages are properly structured to enhance internationalization support.
* fix(i18n): add translations for Uptime Kuma group management
- Added English, French, Japanese, Russian, Vietnamese, and Chinese translations for "Add Uptime Kuma Group" and "Edit Uptime Kuma Group" to enhance internationalization support.
- Included validation messages for category name and slug fields across multiple languages to improve user feedback and accessibility.
* fix(system-settings): improve validation error message structure for SystemName
- Updated the validation logic for the SystemName field to use an object format for error messages, enhancing clarity and consistency in user feedback.
- This change aligns with recent improvements in internationalization support across the system settings schemas.
* perf(i18n): add new validation error message translations
- Added translations for the new validation error message "Invalid JSON format or values out of allowed range" in English, French, Japanese, Russian, Vietnamese, and Chinese.
- This update enhances internationalization support by ensuring users receive clear feedback across multiple languages.
* fix(i18n): update Japanese translation for payment method configuration message
- Corrected the Japanese translation for the message regarding payment methods configuration to use the term "メソッド" instead of "方法" for improved accuracy and consistency in user feedback.
- This change enhances the clarity of the message for Japanese-speaking users.
* fix(i18n): remove unnecessary loading messages from French translations
- Removed the French translations for "Loading settings...", "Loading maintenance settings...", and "Loading content settings..." to streamline the localization file.
- This change improves the clarity and relevance of the translations provided to users.
* fix(i18n): add translations for Uptime Kuma group management in multiple languages
- Added French, Japanese, Russian, Vietnamese, and Chinese translations for "Add Uptime Kuma Group" and "Edit Uptime Kuma Group" to enhance internationalization support.
- This update improves user experience by providing clear and consistent messaging across different languages.
* fix(validation): enhance pricing schema error messages and add translations
- Updated the pricing schema to include localized error messages for validation, ensuring users receive clear feedback when input values are invalid.
- Added new translations for "Exchange rate is required" and "Exchange rate must be greater than 0" in English, French, Japanese, and Chinese to improve internationalization support.
- This change enhances user experience by providing accurate and contextually relevant messages across multiple languages.
* fix: codex Unsupported parameter: max_output_tokens
* fix(model-mapping-editor): simplify JSON parsing logic in useEffect
* fix: jimeng i2v support multi image by metadata
* refactor(models): restructure models section handling and improve UI components
- Replaced tab-based navigation with section-based navigation for better clarity and organization.
- Introduced a new section registry to manage model sections, including 'metadata' and 'deployments'.
- Updated the ModelsContent component to reflect the new section structure and added a Create Deployment button.
- Removed the ModelsTabs component as it was no longer needed.
- Enhanced internationalization support by adding new translations for section descriptions and management tasks.
- Adjusted sidebar configuration to accommodate the new section structure.
* fix: update warning threshold label from '5$' to '2$'
* fix: video content api Priority use url field
* fix: update abortWithOpenAiMessage function to use types.ErrorCode
* feat(deployment): introduce CreateDeploymentDrawer component and update dialog references
- Replaced the CreateDeploymentDialog with a new CreateDeploymentDrawer component for improved user experience.
- Added comprehensive form handling for deployment creation, including validation and price estimation features.
- Updated internationalization files to include new translations for UI elements and descriptions related to deployment configuration.
- Enhanced the ModelsContent component to integrate the new drawer for creating deployments.
* perf(i18n): enhance internationalization for models table and columns
- Updated labels and titles in the ModelsTable and useModelsColumns components to utilize translation functions for improved localization.
- Changed static text for vendor and sync status to dynamic translations, enhancing user experience for non-English speakers.
- Updated empty state messages in the ModelsTable to support internationalization, ensuring clarity for all users.
* fix: fix email send
* fix: issue where consecutive calls to multiple tools in gemini all returned an index of 0
* fix: replace Alibaba's Claude-compatible interface with the new interface
* fix: Only models with the "qwen" designation can use the Claude-compatible interface; others require conversion.
* feat: log shows request conversion
* feat: optimized display
* feat: optimized display
* feat: optimized display
* fix: codex rm Temperature
* Revert "fix: video content api Priority use url field"
* feat: requestId time string use UTC
* feat(qwen): support qwen image sync image model config
* feat: sync old ui
* feat: more ui sync
* feat: replace theme
* fix build
* refactor(web): revert theme colors and variables in CSS
Updated color variables for light and dark themes to improve consistency and visual appeal.
* feat(deployment): enhance deployment access guard and model deployment settings
- Introduced loading phase management in the DeploymentAccessGuard component to provide better user feedback during connection checks.
- Updated the ModelsContent component to prefetch the deployments list while checking connection status, improving data readiness.
- Implemented a caching mechanism for connection status in useModelDeploymentSettings to optimize performance and reduce unnecessary API calls.
- Enhanced loading states and error handling for improved user experience during deployment settings retrieval and connection testing.
* feat(i18n): add new translations for connection and loading states across multiple languages
- Introduced translations for "Checking connection" and "Loading configuration" in English, French, Japanese, Russian, Vietnamese, and Chinese.
- This update enhances the internationalization support, providing clearer user feedback during connection checks and loading phases.
* refactor(pagination): adjust layout and styling for pagination component
- Updated the pagination component to improve layout by removing unnecessary width constraints and enhancing responsiveness.
- Increased minimum width for pagination text to ensure better visibility and alignment across different screen sizes.
* feat(i18n): implement translations for various UI elements across multiple components
- Updated several components to utilize the translation function for titles and placeholders, enhancing internationalization support.
- Added new translation entries for "Filter by name or key..." and "Log Type" in English, French, Japanese, Russian, Vietnamese, and Chinese.
- This update improves user experience by providing localized text in the ChannelsTable, SummaryCards, ApiKeysTable, RedemptionsTable, UsageLogsTable, and UsersTable components.
* feat(i18n): integrate translation support in SummaryCards component
- Added the useTranslation hook to the SummaryCards component to enhance internationalization.
- This update allows for localized text rendering, improving user experience for diverse language speakers.
* feat(dashboard): refactor dashboard structure and introduce section-based navigation
- Removed the tab navigation in favor of a section-based approach, enhancing user experience by providing clearer context for the dashboard content.
- Introduced a new section registry to manage dashboard sections, allowing for easier expansion and maintenance.
- Updated sidebar configuration to reflect the new section structure, ensuring proper navigation links are displayed.
- Added translations for new section titles and descriptions to support internationalization.
* feat(i18n): update time range labels and enhance translation support
- Changed time range labels from shorthand (e.g., '1D') to full text (e.g., '1 Day') for better clarity.
- Updated various components to utilize the translation function for time range labels, improving internationalization.
- Added new translation entries for time ranges in English, French, Japanese, Russian, Vietnamese, and Chinese, enhancing user experience across languages.
* feat(dashboard): enhance type safety and improve component structure
- Updated the Dashboard component to use specific types for model data and filters, enhancing type safety.
- Introduced new types for announcements and FAQs, improving clarity and maintainability.
- Refactored LogStatCards and UptimePanel components to utilize AbortController for better data fetching management.
- Optimized the rendering of announcements and FAQs by using unique keys based on item IDs.
- Improved theme management in ModelCharts by caching the ThemeManager import to reduce dynamic imports.
* feat(agents): add comprehensive guidelines for React and Next.js development
- Introduced a new set of best practices and optimization techniques for React and Next.js applications, aimed at enhancing performance and maintainability.
- Included detailed rules covering various aspects such as event handling, API routes, rendering strategies, and state management.
- Added extensive documentation in AGENTS.md and SKILL.md to support developers in adhering to these practices.
- This update serves as a foundational resource for improving code quality and efficiency in React-based projects.
* chore(web): update package.json dependencies
- Removed outdated dependencies including @base-ui/react, @clerk/clerk-react, and others to streamline the project.
- Updated remaining dependencies to their latest versions for improved performance and security.
- This cleanup enhances the overall maintainability of the project.
* feat(usage-logs): implement section-based navigation and enhance log management
- Introduced a section registry for usage logs, allowing for better organization and navigation between different log categories (common, drawing, task).
- Updated the UsageLogsContent component to dynamically render titles and descriptions based on the selected section.
- Refactored UsageLogsTable and UsageLogsPrimaryButtons components to accept the active log category as a prop, improving modularity.
- Enhanced sidebar configuration to support new section navigation, ensuring users can easily access different log types.
- Updated routing to redirect to the default section if none is specified, improving user experience.
* feat(i18n): enhance internationalization across usage logs components
- Integrated the useTranslation hook in various components related to usage logs, including CommonLogsStats, UsageLogsTable, and column helpers.
- Updated labels, titles, and messages to utilize translation functions, improving localization support.
- Added new translation entries for log-related terms in English, French, Japanese, Russian, Vietnamese, and Chinese, enhancing user experience for diverse language speakers.
* feat(datetime-picker): integrate dayjs for date formatting
- Added dayjs as a dependency to the project for improved date handling.
- Updated the DateTimePicker component to use dayjs for formatting dates, enhancing consistency and readability of date displays.
* feat(date-handling): replace date-fns with dayjs for improved date management
- Updated the project to use dayjs instead of date-fns for date formatting and manipulation, enhancing consistency across components.
- Refactored DatePicker, DateTimePicker, and other components to utilize dayjs for date-related functionalities.
- Added a new dayjs configuration file to extend its capabilities with relative time support.
- Updated AGENTS.md to reflect the new technology stack, emphasizing the use of dayjs for date handling.
* refactor(agents): streamline front-end development guidelines and update technology stack
- Revised AGENTS.md to condense front-end development standards and best practices, making it more accessible for developers and AI assistants.
- Updated the technology stack section to reflect current dependencies, emphasizing the use of Bun, React 19, TypeScript, and other key libraries.
- Enhanced the document structure with a new table format for better readability and navigation, including a comprehensive table of contents for quick access to sections.
* feat(i18n): enhance date picker and datetime picker localization support
- Integrated internationalization support in DatePicker and DateTimePicker components by adding locale handling for multiple languages (English, French, Japanese, Russian, Vietnamese, Chinese).
- Updated the calendar component to accept a locale prop, ensuring proper localization of month and weekday labels.
- Improved user experience by allowing date selection to adapt based on the user's language preference.
* feat(layout): add SectionPageLayout component for structured page layouts
- Introduced a new SectionPageLayout component to facilitate structured layouts for pages with sections, enhancing the organization of content.
- Added subcomponents for Title, Description, Actions, and Content to improve clarity and maintainability of page structures.
- Updated AGENTS.md to include guidelines on avoiding unnecessary destructuring of props for better code readability.
* feat(layout): refactor components to use SectionPageLayout for improved structure
- Replaced AppHeader and Main components with SectionPageLayout across multiple features including Channels, Dashboard, ApiKeys, Models, Redemption Codes, Usage Logs, Users, and Wallet.
- Enhanced page organization by utilizing SectionPageLayout's Title, Description, Actions, and Content subcomponents, improving clarity and maintainability.
- This update standardizes the layout structure across the application, facilitating a more cohesive user experience.
* feat(usage-logs): enhance URL state management and redirection logic
- Added useEffect to synchronize column filters with URL search changes, preventing infinite loops caused by inline references.
- Improved redirection logic in usage logs to clear 'type' from the URL when the section is not 'common', enhancing user experience and URL cleanliness.
* fix(usage-logs): disable global filter and update DataTableToolbar props
- Disabled the global filter in the UsageLogsTable component to streamline the user interface.
- Updated the DataTableToolbar component to accept a null customSearch prop, enhancing flexibility in toolbar configuration.
* feat(routes): implement section-based routing for system settings and dashboard
- Introduced section-based routing for system settings and dashboard features, enhancing navigation and organization.
- Updated route definitions to include dynamic sections, allowing for more granular access to settings and dashboard components.
- Refactored existing routes to redirect to default sections when no specific section is provided, improving user experience.
- Added new section routes for models, usage logs, and system settings, ensuring consistency across the application.
- Removed deprecated routes to streamline the routing structure and improve maintainability.
* refactor(usage-logs): update column helper functions to require config parameter
- Modified createFailReasonColumn and createProgressColumn functions to require a config parameter instead of allowing it to be optional.
- Simplified destructuring of config to enhance clarity and ensure necessary properties are always provided, improving code reliability.
* refactor(usage-logs): improve section ID validation and routing logic
- Introduced a type guard function, isUsageLogsSectionId, to validate section IDs, enhancing type safety and reducing the need for casting.
- Updated UsageLogsContent to utilize the new validation function for determining the active category, improving clarity and reliability.
- Refactored routing logic to use isUsageLogsSectionId for section validation, ensuring proper redirection to the default section when necessary.
* refactor(calendar): update locale documentation for i18n support
- Revised the locale prop documentation in the Calendar component to specify the use of react-day-picker for internationalization, clarifying the expected locale setup for users.
* chore(i18n): remove redundant user information description from locale files
- Removed the user information description from English, French, Japanese, Russian, Vietnamese, and Chinese locale files to streamline translations and improve clarity.
* chore(i18n): streamline locale files by removing redundant entries
- Removed unnecessary entries from English, French, Japanese, Russian, Vietnamese, and Chinese locale files to enhance clarity and reduce clutter.
- Adjusted translations for consistency and improved user experience across multiple languages.
* chore(sidebar): remove deprecated usage logs route from sidebar config
- Eliminated the '/usage-logs' entry from the sidebar configuration to streamline navigation and improve clarity in the sidebar structure.
* refactor(redemption-codes): enhance internationalization support and improve UI consistency
- Updated various components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages.
- Added meta labels for table columns to improve accessibility and clarity.
- Revised confirmation and action texts in dialogs and tooltips to leverage translation, enhancing user experience.
- Updated locale files to include new translations for improved clarity and consistency.
* feat(masked-value-display): add MaskedValueDisplay component for sensitive data handling
- Introduced a new MaskedValueDisplay component to display masked values with a popover for full value visibility and a copy button for easy access.
- Updated api-keys-columns and redemptions-columns to utilize the new component, enhancing code reusability and UI consistency.
- Revised translation keys in locale files to remove colons for improved clarity.
* refactor(url-utils): simplify query parameter matching logic in checkIsActive function
- Updated the checkIsActive function to streamline the logic for matching URLs with and without query parameters.
- Removed unnecessary checks for query parameters when matching base paths, improving clarity and maintainability of the code.
* fix(channels-table): update group filter label to use translation function
- Replaced hardcoded 'All Groups' label with a translation function call to enhance internationalization support in the ChannelsTable component.
* chore(api-keys): remove deprecated API key action messages and related exports
- Deleted the api-key-actions.ts file, which contained action messages for enabling, disabling, and deleting API keys.
- Updated index.ts to remove the export of getApiKeyActionMessage, streamlining the codebase by eliminating unused functionality.
* refactor(i18n): enhance internationalization support across various components
- Updated multiple components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages.
- Revised constants and labels in the channels and redemption codes features to use i18n keys, improving maintainability and clarity.
- Ensured that success and error messages leverage translation functions, enhancing user experience and accessibility.
- Streamlined the handling of i18n keys in the constants files for better organization and clarity.
* refactor(i18n): enhance translation support across various components
- Updated multiple components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages.
- Revised pagination and status labels to use i18n keys, improving maintainability and clarity.
- Enhanced response time formatting to support internationalization, allowing for localized display of time values.
- Updated locale files to include new translations for improved clarity and consistency.
* docs(AGENTS): add type checking requirement for TypeScript changes
- Included a new guideline stating that type checks must be executed after modifying TypeScript or TSX code, ensuring no type errors are left unresolved.
- Updated the document to reflect this addition in the relevant section for better clarity on coding standards.
* feat(combobox-input): add ComboboxInput component for enhanced token selection
- Introduced a new ComboboxInput component to facilitate token name selection with search and filtering capabilities.
- Integrated the ComboboxInput into the UsageLogsFilterDialog for improved user experience when filtering by token name.
- Updated locale files to include new translations for user-facing strings related to token filtering.
* feat(combobox): integrate translation support for custom value prompt
- Added translation functionality to the Combobox component, replacing hardcoded text with a translatable string for the custom value prompt.
- Utilized the useTranslation hook from react-i18next to enhance internationalization support, ensuring a consistent user experience across different languages.
* refactor(i18n): improve Chinese translations for consistency and clarity
- Adjusted spacing in various Chinese translations to enhance readability and maintain consistency across the locale file.
- Updated multiple user-facing strings to ensure proper formatting and alignment with localization standards.
* feat(calendar): add CalendarDropdown component for enhanced dropdown functionality
- Introduced a new CalendarDropdown component to improve user interaction with dropdown selections in the calendar.
- Implemented state management for dropdown visibility and selection handling, enhancing the overall user experience.
- Updated styling for dropdown elements to ensure consistency and better alignment with the UI design.
* fix(balance-query-dialog): handle null currentRow and improve usage query logic
- Updated the BalanceQueryDialog component to safely access currentRow properties using optional chaining.
- Added a check to ensure currentRow is not null before proceeding with usage queries, preventing potential runtime errors.
- Refactored the handleQueryCodexUsage function to use a local variable for currentRow, enhancing code clarity.
* feat(i18n): add new translations for batch creation and channel updates
- Added new translation strings for batch creation instructions across multiple languages, enhancing user guidance.
- Included translations for the "Update Channel" prompt to improve clarity in channel configuration settings.
- Ensured consistency in terminology across locale files for better user experience.
* feat(channel-mutate-drawer): improve API key input handling and update translations
- Refactored the API key input logic in the ChannelMutateDrawer component to enhance readability and maintainability.
- Added new placeholder translations for batch creation and existing key prompts in multiple languages, improving user guidance.
- Ensured consistency in translation strings across locale files for better user experience.
* feat(fetch-models-dialog): implement sorting for model categories
- Added a new function to sort model categories alphabetically, placing 'Other' at the end for easier navigation.
- Updated the rendering logic in the FetchModelsDialog component to utilize the new sorting function for both new and existing models, enhancing user experience.
* refactor(wallet-stats-card): standardize props usage and improve layout consistency
Standardizes props usage and improves layout consistency in wallet stats card
Refactors the wallet stats card component to:
- Use props directly instead of destructuring for consistency
- Add min-w-0 to prevent content overflow
- Adjust text sizing with break-all for proper wrapping
- Implement responsive font sizes (3xl on mobile, 4xl on larger screens)
- Improve leading and tracking for better readability
Refactor wallet stats card for consistency and layout
Standardizes props usage and improves layout consistency in wallet stats card
- Uses props directly instead of destructuring for consistency
- Adds min-w-0 to prevent content overflow
- Adjusts text sizing with break-all for proper wrapping
- Implements responsive font sizes (3xl on mobile, 4xl on larger screens)
- Improves leading and tracking for better readability
* feat(web): add subscription management and admin settings UI
* feat(web): add subscription management and admin settings UI
- Add subscription management module (plans, pricing, toggle status, and related dialogs/tables with Stripe/Creem integration notes)
- Add channel affinity (rules and cache stats), Waffo integration, performance, and Grok model sections to system settings, with extended types and section registry
- Add status code mapping validation/risk warnings, upstream update hooks, and utilities for channels; add available models and sidebar module cards to user profile
- Add chat2link route and useMinimumLoadingTime, useTableCompactMode shared hooks
Made-with: Cursor
* fix: remove duplicate GenerateOAuthCode and add missing TaskBulkUpdate
- remove duplicate GenerateOAuthCode from github.go since oauth.go already has the generic version.
- add model.TaskBulkUpdate for bulk update by upstream task_id strings, fixing task_video.go build failure.
* feat(router): add chat2link and subscriptions routes
- register /chat2link page route under authenticated layout.
- register /subscriptions/ page route under authenticated layout.
- update auto-generated routeTree type definitions and route mappings.
* feat(docker): add development environment setup with Docker Compose
- Introduced docker-compose.dev.yml for local development, including services for new-api, Redis, and PostgreSQL.
- Created Dockerfile.dev for backend-only builds, optimizing the development workflow.
- Updated makefile to include new commands for starting backend services and frontend development.
* feat(web): complete i18n coverage for setup wizard and add language switcher
- wrap all hardcoded English strings in setup-wizard, database-step, usage-mode-step, and complete-step with t() calls, covering step titles, descriptions, form validation messages, and fallback strings.
- add LanguageSwitcher component to the top-right corner of the setup page so users can switch language during initial setup.
- register 25 dynamic i18n keys in static-keys.ts and provide full translations for zh/en/ja/fr/ru/vi.
* feat(i18n): internationalize default version text in workspace-switcher
- remove hardcoded 'Unknown version' default, use t('Unknown version') for i18n fallback
- add "Unknown version" translation entries across all 6 locale files (zh/en/fr/ru/ja/vi)
* feat(i18n): add full i18n coverage for channel-affinity settings page
- replace Chinese t() keys with English keys across three channel-affinity components to align with new frontend i18n conventions.
- add 51 translation entries to all 6 locale files (en/zh/ja/fr/ru/vi) covering main page, rule editor, and cache stats dialog.
- register section-registry dynamic keys in static-keys.ts.
* feat(i18n): add full i18n coverage for Waffo payment settings page
- replace Chinese i18n keys with English keys in waffo-settings-section.tsx for consistency.
- wrap previously hardcoded labels (Pay Method Type / Pay Method Name) with t().
- add 26 Waffo-related translation entries across all 6 locale files (en/zh/fr/ru/ja/vi).
* feat(i18n): add missing translations for global model settings page
- add all 6 locale translations for 3 missing t() keys in global-settings-card.
- register dynamically used 'Grok' key in static-keys.ts for i18n scanner coverage.
* feat(i18n): add full i18n coverage for Grok model settings page
- add translations in all 6 locales (en/zh/fr/ja/ru/vi) for grok-settings-card t() calls.
- cover violation fee toggle, amount input, and official docs link labels.
- include section-registry descriptionKey translation entries.
* feat(i18n): add full i18n coverage for performance settings page
- migrate all t() keys from Chinese to English to align with project conventions.
- add translations for all 6 locales (en/zh/ja/fr/ru/vi) covering disk cache,
system monitoring, log management, and stats dashboard sections.
- remove 71 obsolete Chinese-keyed entries from every locale file.
* fix(i18n): add 116 missing English translation keys across all locales
- scan all t() calls to identify English keys used in code but absent from locale files.
- add translations for zh/en/fr/ja/ru/vi, keeping key sets and sort order consistent.
- covers system-settings, channels, models, auth, wallet and other modules.
* fix(i18n): add missing translations for log cleanup quick-select and confirm dialog
- wrap quick-select button labels (24 hours ago / 7 days ago / 30 days ago) with t().
- replace hardcoded English strings in purge confirm dialog with t() calls and date interpolation.
- add 5 new translation keys across all 6 locale files (zh/en/fr/ja/ru/vi).
* refactor(web): unify all time display with dayjs formatting
- replace all toLocaleString/toLocaleDateString/toLocaleTimeString and manual padStart concatenation with dayjs.format().
- standardize output: datetime as YYYY-MM-DD HH:mm:ss, date as YYYY-MM-DD, time as HH:mm:ss.
- add formatDateTimeStr, formatDateStr, formatTimeStr dayjs-based helpers in lib/format.ts.
- update 12 files across core utils and feature components.
* refactor(web): replace native datetime-local input with DateTimePicker in announcements
- swap browser-native datetime-local for the project's DateTimePicker component to match the UI used in log cleanup and other pages.
- convert between Date objects and ISO strings to bridge the form's string-based schema.
* refactor(web): replace native HTML elements with design system components
- replace ~35 native <button> with <Button> across pricing, profile, channels modules
- replace native <input>/<textarea>/<label> with <Input>/<Textarea>/<Label> for consistent form styling
- replace native <table> with <Table> components, <details>/<summary> with <Collapsible>
- replace decorative <hr> with <Separator> to ensure global UI consistency
* refactor(web): enhance profile components with design system consistency
- update ProfileSecurityCard to use buttons for security actions, improving accessibility and styling.
- modify AccountBindingsTab layout to a grid for better responsiveness and visual alignment.
- refactor NotificationTab to utilize icons for notification methods, enhancing user experience and clarity.
* fix(i18n): complete i18n coverage for profile page components
- wrap passkey card status badges (enabled/disabled, backup state) and last-used text with t()
- fix hardcoded button labels in security dialogs (change password, access token, delete account)
- internationalize all 2FA dialog strings (setup, disable, backup codes)
- fix email bind dialog description and button state text missing i18n
- wrap remaining hardcoded strings in notification tab and checkin calendar
- add all missing translation entries to zh.json and en.json
* fix(i18n): enhance error messages with translations for deployment access and settings
- wrap connection error messages in DeploymentAccessGuard and IoNetDeploymentSettingsSection with t() for internationalization.
- add missing translation key for "io.net model deployment is not enabled or api key missing" in all locale files (en, fr, ja, ru, vi, zh).
* 🧹 chore(web): resolve all ESLint errors and warnings
Align the Vite/React frontend with the current ESLint flat config and
React Compiler–related rules by fixing violations instead of broad
suppression where practical.
- Replace `any` with concrete types (`unknown`, `Record<string, unknown>`,
domain types) where upstream/API shapes allow
- Fix duplicate imports, unused bindings, `no-console`, and empty blocks
- Address react-hooks issues: reorder declarations, memoize unstable
callbacks (`useCallback`), extend dependency arrays, and use targeted
disables only where sync-from-props in `useEffect` is intentional
- Refactor `motion.create` usage in ai-elements shimmer to avoid creating
components during render (static-components)
- Stabilize TanStack Query/Mutation hook usage (query keys, `mutate` in
deps) and add narrowly scoped rule disables where the linter conflicts
with library patterns
- Disable `react-hooks/incompatible-library` in ESLint config for
TanStack Table / RHF false positives
- Add file-level `react-refresh/only-export-components` disables for
registry/provider/column modules that intentionally mix exports
`bun lint` completes with 0 errors and 0 warnings.
* ✨ feat(web): add subscription management to sidebar and align drawer with project conventions
- Register "Subscription Management" nav item in the admin sidebar group
with CreditCard icon pointing to /subscriptions
- Add subscription module to sidebar config defaults and URL mapping so it
integrates with the admin sidebar modules toggle in system settings
- Add subscription entry to sidebar-modules-section moduleMeta for the
maintenance settings UI
- Refactor SubscriptionsMutateDrawer to follow the same patterns used by
users, redemption-codes, and other mutate drawers:
- Use shadcn Form/FormField/FormItem/FormControl/FormLabel/FormMessage
instead of raw register() + Label + manual error display
- Move SheetFooter outside the form with form attribute association
- Use SheetClose for the cancel button
- Reset form state on drawer close
- Align SheetContent width (sm:max-w-[600px]) and spacing conventions
* ✨ feat(web): overhaul UI/UX with Vercel Geist design alignment
Refactor the entire frontend UI/UX to align with Vercel/OpenAI design
principles, covering layout, animations, skeleton loading, and overall
visual polish.
Motion & Page Transitions:
- Add centralized motion system (lib/motion.ts) with Vercel-style
transition presets, stagger variants for tables, cards, and sidebars
- Implement AnimatedOutlet for route-level page enter animations
using TanStack Router pathname keying
- Add PageTransition, StaggerContainer, StaggerItem, CardStagger,
and TableStagger wrapper components for progressive reveal effects
Skeleton Loading — Vercel Geist Style:
- Replace shadcn default `animate-pulse` with Geist-style shimmer
sweep animation (linear-gradient + background-position keyframes)
- Add `--skeleton-base` / `--skeleton-highlight` CSS variables tuned
for both light and dark themes with neutral oklch tones
- Override auto-skeleton-react inline styles via CSS to unify all
skeleton elements under the same shimmer effect
- Update TableSkeleton with varied column widths for a natural feel
- Add ContentSkeleton and QuerySkeleton wrappers for auto-skeleton
integration with React Query error/loading states
- Respect prefers-reduced-motion: disable shimmer for accessibility
Layout & Sidebar:
- Upgrade sidebar expand/collapse transitions to cubic-bezier easing
- Add hover micro-interactions (background-color, color, transform)
to sidebar menu buttons with smooth 150ms transitions
- Fix oklch color compatibility in sidebar outline variant
- Integrate AnimatedOutlet into AuthenticatedLayout for unified
route-level animations
Theme & CSS:
- Streamline theme.css with cleaner oklch color definitions
- Add CSS table row stagger-in animations with nth-child delays
- Fix hover-scrollbar color bug (hsl → color-mix for oklch compat)
- Add content-auto utility for long list rendering optimization
Cleanup:
- Remove deprecated skeleton-wrapper.tsx
- Remove unused imports and dead code across components
- Add empty-state, error-state, and loading-state utility components
* 🐛 fix(docker): track bun.lock to fix Docker build failure
Remove `web/bun.lock` from `.gitignore` so the lock file is committed
to version control. The Dockerfile `COPY web/bun.lock .` instruction
requires this file to be present in the build context, and ignoring it
caused the build to fail with a "not found" error.
* ⬆️ chore(web): upgrade dependencies and fix all type/lint errors
Upgrade all frontend dependencies to latest stable versions:
- lucide-react 0.562 → 1.7 (major: brand icons removed)
- shiki 3.x → 4.x, eslint 9.x → 10.x, knip 5.x → 6.x
- @rsbuild/core 1.3 → 1.7, @types/node 24 → 25
- tailwindcss/postcss 4.1 → 4.2, motion 12.25 → 12.38
- @tanstack/react-query 5.90 → 5.95, zod 4.3.5 → 4.3.6
- react 19.2.3 → 19.2.4, axios 1.13.2 → 1.13.6
- prettier 3.7 → 3.8, typescript-eslint 8.52 → 8.57
- Add missing optional deps: @xyflow/react, embla-carousel-react
Resolve all TypeScript compilation errors introduced by upgrades:
- Replace lucide-react brand icons (Github) with react-icons/si
- Fix react-hook-form Control/Resolver generics for zod v4
- Fix Record<string, unknown> type constraints across API utils
- Fix axios interceptor return types in lib/api.ts
- Add type assertions for useSettings/useStatus hook returns
- Resolve Badge variant, spread type, and route path mismatches
Resolve all ESLint 10 errors:
- preserve-caught-error: attach cause to re-thrown errors
- no-useless-assignment: refactor redundant variable assignments
- prefer-as-const: use `as const` over literal type assertions
- no-unused-vars: prefix type-only schemas with underscore
Update tsconfig lib from ES2020 to ES2022 for Error.cause support.
* 🐛 fix(web): stop pricing model row from centering its content
Wrapping the row in shadcn <Button variant='ghost'> inherits
`justify-center`, and the inner flex container had no width, so
`justify-between` collapsed and the row appeared centered.
* feat: add Waffo payment integration and related UI components
- Introduced Waffo payment method with support for custom icons and settings.
- Updated payment settings section to include Waffo settings.
- Added Waffo payment request handling in the wallet API.
- Enhanced wallet recharge form to support Waffo payment methods.
- Implemented hooks for Waffo payment processing.
- Updated localization files for new Waffo-related strings.
- Added new payment type and icon for Waffo in constants and UI components.
- Refactored topup info handling to include Waffo payment methods and configurations.
* feat(profile): add admin-only upstream model update notification setting
* fix(web): make sidebar module user settings actually take effect
Previously, saving sidebar module preferences in profile had no effect
because the client ignored user-level sidebar_modules entirely. This
fix wires user config into useSidebarConfig so the sidebar updates
immediately without a page refresh.
Changes:
- Add UserPermissions type with sidebar_settings/sidebar_modules fields
- Refactor useSidebarConfig to merge admin × user config with AND logic
- Sync sidebar_modules to auth store on save for immediate UI updates
- Conditionally render SidebarModulesCard based on user permissions
- Treat null/empty user config as "do not narrow" for legacy users
* feat(web): add custom OAuth provider CRUD and login button support
Migrate custom OAuth from v1 to v2:
- Admin CRUD UI with provider table, form dialog, preset templates, and OIDC discovery
- Login page renders dynamic buttons for custom OAuth providers
- Fix account bindings display showing "Not bound" text when already bound
* feat(web): add ServerAddress, SMTPForceAuthLogin, CreateCacheRatio and group special usable settings
Migrate missing v1 system settings to v2:
- ServerAddress input in General > System Information
- SMTPForceAuthLogin toggle in Integrations > Email
- CreateCacheRatio JSON editor in Models > Ratio
- Group special usable group rules editor in Models > Ratio
* feat(web): wire user subscriptions dialog to users table row actions
The UserSubscriptionsDialog component already existed but had no entry point
in the users table dropdown menu. Add "Manage Subscriptions" menu item.
* chore(web): update i18n translations for new settings and custom OAuth
* 💎 refactor(web): redesign pricing page with flat, typography-driven layout
* 🌐 chore(i18n): complete missing translations and normalize project config
- Add 425+ missing translations across fr, ja, ru, zh, vi locales
for subscription management, sidebar navigation, Grok settings,
upstream model updates, pricing page, and other UI components
- Add 37 missing i18n keys used in t() calls but absent from locale
files (pricing filters, display options, audio/cache labels, etc.)
- Fix stale tech stack info in CLAUDE.md, AGENTS.md, and project.mdc:
React 18 → 19, Vite → Rsbuild, Semi Design → Radix UI + Tailwind
- Fix i18n key format description: "Chinese source strings" → English
- Deduplicate .cursor/rules/project.mdc to avoid triple-loading the
same rules already present in root CLAUDE.md and AGENTS.md
- Add i18n-translate Cursor skill for repeatable translation workflow
* 🎨 refactor(web): redesign dashboard with flat, typography-driven layout
Replace Card-based dashboard components with a flat, border-driven design
system consistent with the pricing page, following the ui-style.mdc conventions.
Overview section:
- StatCard: replace Card wrapper with flat flex layout, monospace tabular
values, uppercase tracking-wider labels, layered opacity hierarchy
- PanelWrapper: replace Card/CardHeader/CardContent with rounded-lg border
container and border-b header
- SummaryCards: merge three stat cards into a single bordered container
with divide-x separators; decouple border from stagger animation to
prevent border deformation during entrance transitions
- ApiInfoPanel/Item: full-width list rows with border-b separators,
monospace route names, layered opacity for URLs and descriptions
- AnnouncementsPanel: native button rows with hover:bg-muted/40, i18n for
"Click for details" hint
- FAQPanel: lighter border-border/60 accordion dividers, muted answer text
- UptimePanel: uppercase tracking-wider group headers with bg-muted/30
background, monospace uptime percentages, fine-grained border opacity
Models section:
- LogStatCards: replace Card with rounded-lg border + divide-x grid,
fix react-hooks/exhaustive-deps by destructuring props before useEffect
- ModelCharts: replace Card+Tabs with bordered container + custom
segmented control matching ui-style spec
- Suspense fallbacks: match new flat skeleton layout with accurate
column structure
Animation:
- Wrap models section in FadeIn with staggered delay
- Keep CardStagger for overview panel grid (each panel has own border)
Other:
- Add ui-style.mdc cursor rule documenting the design language
- Disable react-refresh/only-export-components for src/routes/** in
eslint config (TanStack Router route files always export Route objects)
- Fix zh.json: "Token-based" translation "基于令牌的" → "按量计费"
* ✨ refactor(web): adopt flat dot-and-text design for all status badges
Replace the bordered/colored-background StatusBadge and Badge components
across the entire frontend with a minimal flat design: a small colored
dot followed by colored text, eliminating visual noise from heavy
borders, backgrounds, and rounded pill shapes.
Key changes:
- Redesign StatusBadge to use dot + text instead of bordered pill style,
removing cva-based background/border variants in favor of exported
dotColorMap and textColorMap lookup tables
- Add children prop support to StatusBadge for flexible content rendering
alongside the existing label prop
- Migrate all Badge usages (except pricing page) to StatusBadge with
appropriate variant mappings (default→info, secondary→neutral,
outline→neutral, destructive→danger)
- Consolidate adjacent multi-badge groups into single-dot layouts with
dot separators (·) to reduce visual clutter in:
- Channel balance columns (used + remaining)
- Channel type column (type + IO.NET indicator)
- User invite info column (invited + revenue + inviter)
- Usage log stats bar (usage + RPM + TPM)
- Usage log time/FRT column (time + FRT + stream status)
- Subscription plan counts (active + expired)
- Channel affinity scope/regex/key-source columns
- Prefill group card headers (type + ID)
- Export dotColorMap and textColorMap for direct use in custom inline
layouts that need consistent status colors without the full component
* ✨ refactor(web): redesign public layout and landing page with modern UI
Overhaul the public-facing layout, header, and homepage to deliver a
polished, animation-rich landing experience inspired by contemporary
SaaS design patterns.
Header:
- Replace sticky header with fixed floating navbar that compacts into
a pill-shaped glass-morphism bar on scroll (backdrop-blur + ring)
- Add smooth 700ms cubic-bezier transitions for scroll-based shrinking
- Build full-screen mobile menu overlay with staggered entry animations
- Remove background color from logo container, show logo image directly
Homepage sections:
- Hero: gradient text title, radial gradient + grid pattern background,
interactive terminal demo showcasing API request/response
- Terminal demo: auto-cycles through gpt-4o, claude-sonnet-4-20250514,
gemini-2.5-pro, deepseek-chat with smooth cross-fade transitions,
clickable model badges, dual theme support (light/dark), fixed height
- Stats: animated co…
…up (QuantumNous#4265) * feat: add parameter coverage for the operations: copy, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, and regex_replace * fix: CrossGroupRetry default false 移除gorm:"default:false",避免每次 AutoMigrate时都执行ALTER TABLE `tokens` MODIFY COLUMN `cross_group_retry` boolean DEFAULT false 且bool默认false不影响原有功能 * feat: check-in feature integrates Turnstile security check * feat: add support for Doubao /v1/responses (#2567) * feat: add support for Doubao /v1/responses * fix: fix model deployment style issues, lint problems, and i18n gaps. (#2556) * fix: fix model deployment style issues, lint problems, and i18n gaps. * fix: adjust the key not to be displayed on the frontend, tested via the backend. * fix: adjust the sidebar configuration logic to use the default configuration items if they are not defined. * feat: add plans directory to .gitignore * fix: 修复 gemini 文件类型不支持 image/jpg * fix: fix the proxyURL is empty, not using the default HTTP client configuration && the AWS calling side did not apply the relay timeout. * fix: batch add key backend deduplication * Merge pull request #2582 from seefs001/fix/tips fix: add tips for model management and channel testing * fix(gin): update request body size check to allow zero limit * feat: add regex pattern to mask API keys in sensitive information * fix(task): 修复使用 auto 分组时 Task Relay 不记录日志和不扣费的问题 问题描述: - 使用 auto 分组的令牌调用 /v1/videos 等 Task 接口时,虽然任务能成功创建, 但使用日志不显示记录,且不会扣费 根本原因: - Distribute 中间件在选择渠道后,会将实际选中的分组存储在 ContextKeyAutoGroup 中 - 但 RelayTaskSubmit 函数没有从 context 中读取这个值来更新 info.UsingGroup - 导致 info.UsingGroup 始终是 "auto" 而不是实际选中的分组(如 "sora2逆") - 当 auto 分组的倍率配置为 0 时,quota 计算结果为 0 - 日志记录条件 "if quota != 0" 不满足,导致日志不记录、不扣费 修复方案: - 在 RelayTaskSubmit 函数中计算分组倍率之前,添加从 ContextKeyAutoGroup 获取实际分组的逻辑 - 使用安全的类型断言,避免潜在的 panic 风险 影响范围: - 仅影响 Task Relay 流程(/v1/videos, /suno, /kling 等接口) - 不影响使用具体分组令牌的调用 - 不影响其他 Relay 类型(chat/completions 等已有类似处理逻辑) * 🚀 feat(web): port legacy v2 frontend changes into new UI (deployments, check-in, ollama) + align APIs Bring over the key frontend functionality introduced in merge `efa3301` and integrate it cleanly into the new `web/src` architecture and design system. - **Model deployments (io.net)** - Align frontend endpoints and payloads with backend deployment routes (`/api/deployments/*`) - Add missing deployment operations: details, logs (container-aware), update config, rename, extend duration - Improve create-deployment flow (proper request shape, name availability check, price estimation parity) - **System settings** - Enhance io.net deployment settings: allow testing connection with an unsaved API key and add “how to get API key” guidance - **Channels / Ollama** - Improve Ollama model management: live fetch via base_url with fallback to channel fetch, selection + apply flows, delete confirmation - Refactor for feature-layer consistency: extract Ollama parsing/normalization utilities into `features/channels/lib` - **Quality** - Ensure TypeScript typecheck passes after refactor and new dialogs/components integration * Merge pull request #2590 from xyfacai/fix/max-body-limit fix: 设置默认max req body 为128MB * docs: update readme * i18n: add missing translations * fix(gemini): fetch model list via native v1beta/models endpoint Use the native Gemini Models API (/v1beta/models) instead of the OpenAI-compatible path when listing models for Gemini channels, improving compatibility with third-party Gemini-format providers that don't implement OpenAI routes. - Add paginated model listing with timeout and optional proxy support - Select an enabled key for multi-key Gemini channels * refactor(gemini): 更新 GeminiModelsResponse 以使用 dto.GeminiModel 类型 * fix: remove Minimax from FETCHABLE channels * fix(minimax): 添加 MiniMax-M2 系列模型到 ModelList * feat: add doubao video 1.5 * 🤢 chore: remove useless file * feat: /v1/chat/completion -> /v1/response (#2629) * feat: /v1/chat/completion -> /v1/response * fix: clean propertyNames for gemini function * fix: support snake_case fields in GeminiChatGenerationConfig * chore: update dependencies and lockfile for improved compatibility - Updated @clerk/clerk-react to version 5.59.3 - Updated @hookform/resolvers to version 5.2.2 - Updated @lobehub/icons to version 2.48.0 - Updated various Radix UI components to their latest versions - Updated @tanstack/react-query and related packages for better performance - Updated axios, i18next, and other libraries for security and feature enhancements - Updated lockfile to include configVersion and ensure consistency across environments * Merge pull request #2647 from seefs001/feature/status-code-auto-disable feat: status code auto-disable configuration * fix: chat2response setting ui (#2643) * fix: setting ui * fix: rm global.chat_completions_to_responses_policy * fix: rm global.chat_completions_to_responses_policy * Merge pull request #2627 from seefs001/feature/channel-test-param-override feat: channel testing supports parameter overriding * chore: update dependencies and lockfile for improved compatibility - Updated @lobehub/icons to version 4.0.3 - Updated ai to version 6.0.27 - Updated various libraries including axios, react-day-picker, and streamdown for security and feature enhancements - Updated devDependencies for eslint, prettier, and typescript for better performance and compatibility - Updated lockfile to ensure consistency across environments * chore: update lockfile and Vite configuration for improved build process - Updated lockfile to version 1 for better compatibility and consistency - Enhanced Vite configuration to support production optimizations, including code minification and chunking for dependencies - Added environment-specific console and debugger removal for production builds * chore: migrate from Vite to Rsbuild for build process - Added Rsbuild configuration for development and production builds - Updated package.json scripts to use Rsbuild instead of Vite - Replaced @tailwindcss/vite with @tailwindcss/postcss in dependencies - Introduced postcss.config.mjs for Tailwind CSS integration - Updated TypeScript configuration to include Rsbuild config - Removed Vite configuration file to streamline the build process * refactor: optimize user data handling and API calls - Replaced direct API calls to get user data with cached user information from auth-store in ModelsFilter and SummaryCards components. - Improved session management in RootComponent and Authenticated route to utilize localStorage for user authentication status, reducing unnecessary API requests. - Added caching for setup status checks to enhance performance during navigation. * feat: enhance session validation in authenticated route - Implemented session verification to check user authentication status via API call only once per session. - Updated beforeLoad logic to redirect users to the login page if session validation fails or if no user information is available in localStorage. - Improved user data handling by updating the auth store with fresh user information upon successful session verification. * refactor: improve useMediaQuery hook for better SSR handling - Enhanced the useMediaQuery hook to check for window availability before accessing matchMedia, preventing errors during server-side rendering. - Simplified state initialization and change handling by using a dedicated function to determine initial matches. - Updated event listener management for improved performance and clarity. * feat(hooks): export useMediaQuery from hooks index * refactor: update useMediaQuery imports to use unified hooks index * fix(rsbuild): fix loadEnv API usage and removeConsole type * feat: customizable automatic retry status codes * refactor(hooks): use useSyncExternalStore for better SSR handling in useMediaQuery * refactor: simplify embedded file structure in main.go - Updated the embedded file directive to include the entire web/dist directory instead of individual assets, streamlining the build process. * refactor: replace DropdownMenu with Sheet component in ProfileDropdown - Updated the ProfileDropdown component to use a Sheet for user interactions instead of a DropdownMenu. - Enhanced user info display with improved layout and styling. - Added navigation links and sign-out functionality within the Sheet. * refactor: streamline ProfileDropdown layout and improve user info display - Removed unused Badge component and secondary text from user display. - Enhanced styling for user info section and navigation links. - Updated sign-out functionality to use a button for better accessibility. * feat: add System Settings link for super admin in ProfileDropdown - Introduced a new link to System Settings in the ProfileDropdown, visible only to users with the SUPER_ADMIN role. - Updated imports to include the Settings icon and adjusted the component logic accordingly. - Removed the Settings entry from the sidebar data to streamline navigation. * feat: codex channel (#2652) * feat: codex channel * feat: codex channel * feat: codex oauth flow * feat: codex refresh cred * feat: codex usage * fix: codex err message detail * fix: codex setting ui * feat: codex refresh cred task * fix: import err * fix: codex store must be false * fix: chat -> responses tool call * fix: chat -> responses tool call * feat(i18n): add missing translations * fix(i18n): restore missing translations for "360" and add "User Menu" in multiple locales - Reintroduced the translation for "360" in English, French, Japanese, Russian, Vietnamese, and Chinese locales. - Added the "User Menu" translation in the same languages to enhance user interface consistency. * fix: openAI function to gemini function field adjusted to whitelist mode * feat: TLS_INSECURE_SKIP_VERIFY env * fix: for chat-based calls to the Claude model, tagging is required. Using Claude's rendering logs, the two approaches handle input rendering differently. * refactor(system-settings): restructure settings sections and navigation - Replaced SettingsAccordion with a unified SettingsSection component across various settings sections for consistency. - Introduced a section registry to manage general settings sections dynamically. - Updated navigation items in the system settings sidebar to utilize the new section registry. - Enhanced the GeneralSettings component to support section-based content rendering based on user selection. * fix(system-settings): remove type assertion for quotaDisplayType in GeneralSettings - Eliminated the type assertion for quotaDisplayType in the GeneralSettings component to improve type inference and maintain cleaner code. * refactor(system-settings): update zod import syntax in general settings - Changed the import statement for zod from a default import to a namespace import for better clarity and consistency in the codebase. * fix: the login method cannot be displayed under the aff link. * feat(system-settings): implement generic settings page and enhance navigation - Added a new generic SettingsPage component to handle loading states, data fetching, and section rendering. - Integrated section registry for general and authentication settings to streamline navigation and content management. - Updated URL utility functions to improve query parameter handling for active navigation states. - Enhanced the system settings sidebar to include authentication section items dynamically. * refactor(system-settings): replace SettingsAccordion with SettingsSection across authentication settings - Updated BasicAuthSection, BotProtectionSection, OAuthSection, and PasskeySection to use the new SettingsSection component for consistency. - Introduced a section registry to manage authentication settings dynamically, enhancing navigation and content rendering. * feat(system-settings): enhance request limits settings with new section and unified component - Added a new Request Limits section to the system settings sidebar, integrating it with the section registry for improved navigation. - Replaced SettingsAccordion with SettingsSection in RateLimitSection, SensitiveWordsSection, and SSRFSection for consistency. - Updated RequestLimitsSettings to utilize the new SettingsPage component for better data handling and rendering. - Implemented a search schema for request limits to streamline navigation and section management. * feat(system-settings): integrate content settings sections with unified component and registry - Added a new Content section to the system settings sidebar, incorporating it into the section registry for improved navigation. - Replaced SettingsAccordion with SettingsSection in multiple content-related components for consistency. - Created a section registry to manage content settings dynamically, enhancing the rendering and navigation experience. - Updated the ContentSettings component to utilize the new section registry and streamline content display. * feat(system-settings): enhance integrations settings with unified section registry and components - Introduced a new section registry for integrations settings, consolidating various settings components for better organization and navigation. - Replaced SettingsAccordion with SettingsSection in multiple integration-related components for consistency. - Updated IntegrationSettings to utilize the new SettingsPage component, improving data handling and rendering. - Added a new integrations section to the system settings sidebar, enhancing user experience and accessibility. * feat(system-settings): unify model settings with new section registry and components - Introduced a section registry for model settings, consolidating various model-related components for improved organization and navigation. - Replaced SettingsAccordion with SettingsSection in multiple model settings components for consistency. - Updated ModelSettings to utilize the new SettingsPage component, enhancing data handling and rendering. - Added a new Models section to the system settings sidebar, improving user experience and accessibility. * feat(system-settings): enhance maintenance settings with unified section registry and components - Introduced a new section registry for maintenance settings, consolidating various maintenance-related components for improved organization and navigation. - Replaced SettingsAccordion with SettingsSection in multiple maintenance components for consistency. - Updated MaintenanceSettings to utilize the new section registry, enhancing data handling and rendering. - Added a new Maintenance section to the system settings sidebar, improving user experience and accessibility. * feat(system-settings): update section titles for improved clarity and consistency - Renamed various section titles across content, integrations, maintenance, models, and request limits to enhance clarity and better reflect their functionalities. - Adjusted titles such as 'Dashboard' to 'Data Dashboard', 'API Info' to 'API Addresses', and 'Update Checker' to 'System maintenance' for improved user understanding. - Ensured consistency in naming conventions across all settings sections to streamline user experience and navigation. * feat(nav-group): enhance collapsible menu behavior and URL matching logic - Added controlled state management for collapsible menu items to automatically expand based on active sub-item paths. - Updated the URL matching logic in checkIsActive to improve handling of query parameters and ensure accurate navigation state detection. - Refactored the collapsible component to utilize the new state management, enhancing user experience in the sidebar navigation. * feat(system-settings): update system settings navigation and redirect logic - Changed the link in the profile dropdown to point directly to the general section of system settings with a search parameter for section identification. - Implemented a redirect in the general settings route to ensure users are directed to the default section if no section parameter is provided, enhancing navigation consistency. * feat(system-settings): unify route configuration for settings sections - Refactored route configuration for various system settings sections (auth, content, general, integrations, maintenance, models, request limits) to utilize a new `createSettingsRouteConfig` function. - This change consolidates the repetitive logic of creating search schemas and handling redirects, improving code maintainability and readability. - Enhanced navigation by ensuring default sections are loaded when no section parameter is provided. * feat(url-utils): enhance URL handling and matching logic - Introduced a new utility function `urlToString` to convert various URL formats (string and object) into a standardized string format. - Updated the `checkIsActive` function to utilize `urlToString`, improving the accuracy of URL matching and handling of query parameters. - Refactored URL comparison logic to ensure consistent behavior across different URL types, enhancing navigation state detection. * feat(system-settings): validate DataExportDefaultTime for improved data handling - Introduced a new function `validateDataExportDefaultTime` to ensure the `DataExportDefaultTime` value is either 'week', 'hour', or 'day', defaulting to 'hour' for unexpected values. - Updated the `DataExportDefaultTime` assignment in the settings section to utilize this validation function, enhancing data integrity and user experience. * perf(system-settings): Improve the i18n of system settings content - Changed button labels in various sections to use consistent capitalization and translation functions, enhancing user experience. - Updated validation messages in schemas to utilize translation functions for improved internationalization support. - Ensured all user-facing strings are properly translated, improving accessibility for non-English users. * fix(system-settings): update ApiInfoFormValues type inference for improved schema validation - Changed the type inference for ApiInfoFormValues to utilize ReturnType of createApiInfoSchema, ensuring accurate type representation and enhancing type safety in the API info section. * fix(chat-settings): improve validation logic for chat settings schema - Updated the validation logic to ensure that null values are correctly handled and that only objects are accepted as valid items in the chat settings schema. - Simplified error handling by removing the error message from the catch block, providing a consistent user-facing message for invalid JSON strings. * fix(system-settings): enhance validation error handling in uptime-kuma schema - Updated the validation logic for category name, URL, and slug fields to use an object format for error messages, improving clarity and consistency in user feedback. - Ensured that all validation messages are properly structured to enhance internationalization support. * fix(i18n): add translations for Uptime Kuma group management - Added English, French, Japanese, Russian, Vietnamese, and Chinese translations for "Add Uptime Kuma Group" and "Edit Uptime Kuma Group" to enhance internationalization support. - Included validation messages for category name and slug fields across multiple languages to improve user feedback and accessibility. * fix(system-settings): improve validation error message structure for SystemName - Updated the validation logic for the SystemName field to use an object format for error messages, enhancing clarity and consistency in user feedback. - This change aligns with recent improvements in internationalization support across the system settings schemas. * perf(i18n): add new validation error message translations - Added translations for the new validation error message "Invalid JSON format or values out of allowed range" in English, French, Japanese, Russian, Vietnamese, and Chinese. - This update enhances internationalization support by ensuring users receive clear feedback across multiple languages. * fix(i18n): update Japanese translation for payment method configuration message - Corrected the Japanese translation for the message regarding payment methods configuration to use the term "メソッド" instead of "方法" for improved accuracy and consistency in user feedback. - This change enhances the clarity of the message for Japanese-speaking users. * fix(i18n): remove unnecessary loading messages from French translations - Removed the French translations for "Loading settings...", "Loading maintenance settings...", and "Loading content settings..." to streamline the localization file. - This change improves the clarity and relevance of the translations provided to users. * fix(i18n): add translations for Uptime Kuma group management in multiple languages - Added French, Japanese, Russian, Vietnamese, and Chinese translations for "Add Uptime Kuma Group" and "Edit Uptime Kuma Group" to enhance internationalization support. - This update improves user experience by providing clear and consistent messaging across different languages. * fix(validation): enhance pricing schema error messages and add translations - Updated the pricing schema to include localized error messages for validation, ensuring users receive clear feedback when input values are invalid. - Added new translations for "Exchange rate is required" and "Exchange rate must be greater than 0" in English, French, Japanese, and Chinese to improve internationalization support. - This change enhances user experience by providing accurate and contextually relevant messages across multiple languages. * fix: codex Unsupported parameter: max_output_tokens * fix(model-mapping-editor): simplify JSON parsing logic in useEffect * fix: jimeng i2v support multi image by metadata * refactor(models): restructure models section handling and improve UI components - Replaced tab-based navigation with section-based navigation for better clarity and organization. - Introduced a new section registry to manage model sections, including 'metadata' and 'deployments'. - Updated the ModelsContent component to reflect the new section structure and added a Create Deployment button. - Removed the ModelsTabs component as it was no longer needed. - Enhanced internationalization support by adding new translations for section descriptions and management tasks. - Adjusted sidebar configuration to accommodate the new section structure. * fix: update warning threshold label from '5$' to '2$' * fix: video content api Priority use url field * fix: update abortWithOpenAiMessage function to use types.ErrorCode * feat(deployment): introduce CreateDeploymentDrawer component and update dialog references - Replaced the CreateDeploymentDialog with a new CreateDeploymentDrawer component for improved user experience. - Added comprehensive form handling for deployment creation, including validation and price estimation features. - Updated internationalization files to include new translations for UI elements and descriptions related to deployment configuration. - Enhanced the ModelsContent component to integrate the new drawer for creating deployments. * perf(i18n): enhance internationalization for models table and columns - Updated labels and titles in the ModelsTable and useModelsColumns components to utilize translation functions for improved localization. - Changed static text for vendor and sync status to dynamic translations, enhancing user experience for non-English speakers. - Updated empty state messages in the ModelsTable to support internationalization, ensuring clarity for all users. * fix: fix email send * fix: issue where consecutive calls to multiple tools in gemini all returned an index of 0 * fix: replace Alibaba's Claude-compatible interface with the new interface * fix: Only models with the "qwen" designation can use the Claude-compatible interface; others require conversion. * feat: log shows request conversion * feat: optimized display * feat: optimized display * feat: optimized display * fix: codex rm Temperature * Revert "fix: video content api Priority use url field" * feat: requestId time string use UTC * feat(qwen): support qwen image sync image model config * feat: sync old ui * feat: more ui sync * feat: replace theme * fix build * refactor(web): revert theme colors and variables in CSS Updated color variables for light and dark themes to improve consistency and visual appeal. * feat(deployment): enhance deployment access guard and model deployment settings - Introduced loading phase management in the DeploymentAccessGuard component to provide better user feedback during connection checks. - Updated the ModelsContent component to prefetch the deployments list while checking connection status, improving data readiness. - Implemented a caching mechanism for connection status in useModelDeploymentSettings to optimize performance and reduce unnecessary API calls. - Enhanced loading states and error handling for improved user experience during deployment settings retrieval and connection testing. * feat(i18n): add new translations for connection and loading states across multiple languages - Introduced translations for "Checking connection" and "Loading configuration" in English, French, Japanese, Russian, Vietnamese, and Chinese. - This update enhances the internationalization support, providing clearer user feedback during connection checks and loading phases. * refactor(pagination): adjust layout and styling for pagination component - Updated the pagination component to improve layout by removing unnecessary width constraints and enhancing responsiveness. - Increased minimum width for pagination text to ensure better visibility and alignment across different screen sizes. * feat(i18n): implement translations for various UI elements across multiple components - Updated several components to utilize the translation function for titles and placeholders, enhancing internationalization support. - Added new translation entries for "Filter by name or key..." and "Log Type" in English, French, Japanese, Russian, Vietnamese, and Chinese. - This update improves user experience by providing localized text in the ChannelsTable, SummaryCards, ApiKeysTable, RedemptionsTable, UsageLogsTable, and UsersTable components. * feat(i18n): integrate translation support in SummaryCards component - Added the useTranslation hook to the SummaryCards component to enhance internationalization. - This update allows for localized text rendering, improving user experience for diverse language speakers. * feat(dashboard): refactor dashboard structure and introduce section-based navigation - Removed the tab navigation in favor of a section-based approach, enhancing user experience by providing clearer context for the dashboard content. - Introduced a new section registry to manage dashboard sections, allowing for easier expansion and maintenance. - Updated sidebar configuration to reflect the new section structure, ensuring proper navigation links are displayed. - Added translations for new section titles and descriptions to support internationalization. * feat(i18n): update time range labels and enhance translation support - Changed time range labels from shorthand (e.g., '1D') to full text (e.g., '1 Day') for better clarity. - Updated various components to utilize the translation function for time range labels, improving internationalization. - Added new translation entries for time ranges in English, French, Japanese, Russian, Vietnamese, and Chinese, enhancing user experience across languages. * feat(dashboard): enhance type safety and improve component structure - Updated the Dashboard component to use specific types for model data and filters, enhancing type safety. - Introduced new types for announcements and FAQs, improving clarity and maintainability. - Refactored LogStatCards and UptimePanel components to utilize AbortController for better data fetching management. - Optimized the rendering of announcements and FAQs by using unique keys based on item IDs. - Improved theme management in ModelCharts by caching the ThemeManager import to reduce dynamic imports. * feat(agents): add comprehensive guidelines for React and Next.js development - Introduced a new set of best practices and optimization techniques for React and Next.js applications, aimed at enhancing performance and maintainability. - Included detailed rules covering various aspects such as event handling, API routes, rendering strategies, and state management. - Added extensive documentation in AGENTS.md and SKILL.md to support developers in adhering to these practices. - This update serves as a foundational resource for improving code quality and efficiency in React-based projects. * chore(web): update package.json dependencies - Removed outdated dependencies including @base-ui/react, @clerk/clerk-react, and others to streamline the project. - Updated remaining dependencies to their latest versions for improved performance and security. - This cleanup enhances the overall maintainability of the project. * feat(usage-logs): implement section-based navigation and enhance log management - Introduced a section registry for usage logs, allowing for better organization and navigation between different log categories (common, drawing, task). - Updated the UsageLogsContent component to dynamically render titles and descriptions based on the selected section. - Refactored UsageLogsTable and UsageLogsPrimaryButtons components to accept the active log category as a prop, improving modularity. - Enhanced sidebar configuration to support new section navigation, ensuring users can easily access different log types. - Updated routing to redirect to the default section if none is specified, improving user experience. * feat(i18n): enhance internationalization across usage logs components - Integrated the useTranslation hook in various components related to usage logs, including CommonLogsStats, UsageLogsTable, and column helpers. - Updated labels, titles, and messages to utilize translation functions, improving localization support. - Added new translation entries for log-related terms in English, French, Japanese, Russian, Vietnamese, and Chinese, enhancing user experience for diverse language speakers. * feat(datetime-picker): integrate dayjs for date formatting - Added dayjs as a dependency to the project for improved date handling. - Updated the DateTimePicker component to use dayjs for formatting dates, enhancing consistency and readability of date displays. * feat(date-handling): replace date-fns with dayjs for improved date management - Updated the project to use dayjs instead of date-fns for date formatting and manipulation, enhancing consistency across components. - Refactored DatePicker, DateTimePicker, and other components to utilize dayjs for date-related functionalities. - Added a new dayjs configuration file to extend its capabilities with relative time support. - Updated AGENTS.md to reflect the new technology stack, emphasizing the use of dayjs for date handling. * refactor(agents): streamline front-end development guidelines and update technology stack - Revised AGENTS.md to condense front-end development standards and best practices, making it more accessible for developers and AI assistants. - Updated the technology stack section to reflect current dependencies, emphasizing the use of Bun, React 19, TypeScript, and other key libraries. - Enhanced the document structure with a new table format for better readability and navigation, including a comprehensive table of contents for quick access to sections. * feat(i18n): enhance date picker and datetime picker localization support - Integrated internationalization support in DatePicker and DateTimePicker components by adding locale handling for multiple languages (English, French, Japanese, Russian, Vietnamese, Chinese). - Updated the calendar component to accept a locale prop, ensuring proper localization of month and weekday labels. - Improved user experience by allowing date selection to adapt based on the user's language preference. * feat(layout): add SectionPageLayout component for structured page layouts - Introduced a new SectionPageLayout component to facilitate structured layouts for pages with sections, enhancing the organization of content. - Added subcomponents for Title, Description, Actions, and Content to improve clarity and maintainability of page structures. - Updated AGENTS.md to include guidelines on avoiding unnecessary destructuring of props for better code readability. * feat(layout): refactor components to use SectionPageLayout for improved structure - Replaced AppHeader and Main components with SectionPageLayout across multiple features including Channels, Dashboard, ApiKeys, Models, Redemption Codes, Usage Logs, Users, and Wallet. - Enhanced page organization by utilizing SectionPageLayout's Title, Description, Actions, and Content subcomponents, improving clarity and maintainability. - This update standardizes the layout structure across the application, facilitating a more cohesive user experience. * feat(usage-logs): enhance URL state management and redirection logic - Added useEffect to synchronize column filters with URL search changes, preventing infinite loops caused by inline references. - Improved redirection logic in usage logs to clear 'type' from the URL when the section is not 'common', enhancing user experience and URL cleanliness. * fix(usage-logs): disable global filter and update DataTableToolbar props - Disabled the global filter in the UsageLogsTable component to streamline the user interface. - Updated the DataTableToolbar component to accept a null customSearch prop, enhancing flexibility in toolbar configuration. * feat(routes): implement section-based routing for system settings and dashboard - Introduced section-based routing for system settings and dashboard features, enhancing navigation and organization. - Updated route definitions to include dynamic sections, allowing for more granular access to settings and dashboard components. - Refactored existing routes to redirect to default sections when no specific section is provided, improving user experience. - Added new section routes for models, usage logs, and system settings, ensuring consistency across the application. - Removed deprecated routes to streamline the routing structure and improve maintainability. * refactor(usage-logs): update column helper functions to require config parameter - Modified createFailReasonColumn and createProgressColumn functions to require a config parameter instead of allowing it to be optional. - Simplified destructuring of config to enhance clarity and ensure necessary properties are always provided, improving code reliability. * refactor(usage-logs): improve section ID validation and routing logic - Introduced a type guard function, isUsageLogsSectionId, to validate section IDs, enhancing type safety and reducing the need for casting. - Updated UsageLogsContent to utilize the new validation function for determining the active category, improving clarity and reliability. - Refactored routing logic to use isUsageLogsSectionId for section validation, ensuring proper redirection to the default section when necessary. * refactor(calendar): update locale documentation for i18n support - Revised the locale prop documentation in the Calendar component to specify the use of react-day-picker for internationalization, clarifying the expected locale setup for users. * chore(i18n): remove redundant user information description from locale files - Removed the user information description from English, French, Japanese, Russian, Vietnamese, and Chinese locale files to streamline translations and improve clarity. * chore(i18n): streamline locale files by removing redundant entries - Removed unnecessary entries from English, French, Japanese, Russian, Vietnamese, and Chinese locale files to enhance clarity and reduce clutter. - Adjusted translations for consistency and improved user experience across multiple languages. * chore(sidebar): remove deprecated usage logs route from sidebar config - Eliminated the '/usage-logs' entry from the sidebar configuration to streamline navigation and improve clarity in the sidebar structure. * refactor(redemption-codes): enhance internationalization support and improve UI consistency - Updated various components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages. - Added meta labels for table columns to improve accessibility and clarity. - Revised confirmation and action texts in dialogs and tooltips to leverage translation, enhancing user experience. - Updated locale files to include new translations for improved clarity and consistency. * feat(masked-value-display): add MaskedValueDisplay component for sensitive data handling - Introduced a new MaskedValueDisplay component to display masked values with a popover for full value visibility and a copy button for easy access. - Updated api-keys-columns and redemptions-columns to utilize the new component, enhancing code reusability and UI consistency. - Revised translation keys in locale files to remove colons for improved clarity. * refactor(url-utils): simplify query parameter matching logic in checkIsActive function - Updated the checkIsActive function to streamline the logic for matching URLs with and without query parameters. - Removed unnecessary checks for query parameters when matching base paths, improving clarity and maintainability of the code. * fix(channels-table): update group filter label to use translation function - Replaced hardcoded 'All Groups' label with a translation function call to enhance internationalization support in the ChannelsTable component. * chore(api-keys): remove deprecated API key action messages and related exports - Deleted the api-key-actions.ts file, which contained action messages for enabling, disabling, and deleting API keys. - Updated index.ts to remove the export of getApiKeyActionMessage, streamlining the codebase by eliminating unused functionality. * refactor(i18n): enhance internationalization support across various components - Updated multiple components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages. - Revised constants and labels in the channels and redemption codes features to use i18n keys, improving maintainability and clarity. - Ensured that success and error messages leverage translation functions, enhancing user experience and accessibility. - Streamlined the handling of i18n keys in the constants files for better organization and clarity. * refactor(i18n): enhance translation support across various components - Updated multiple components to utilize translation functions for user-facing strings, ensuring a consistent experience across different languages. - Revised pagination and status labels to use i18n keys, improving maintainability and clarity. - Enhanced response time formatting to support internationalization, allowing for localized display of time values. - Updated locale files to include new translations for improved clarity and consistency. * docs(AGENTS): add type checking requirement for TypeScript changes - Included a new guideline stating that type checks must be executed after modifying TypeScript or TSX code, ensuring no type errors are left unresolved. - Updated the document to reflect this addition in the relevant section for better clarity on coding standards. * feat(combobox-input): add ComboboxInput component for enhanced token selection - Introduced a new ComboboxInput component to facilitate token name selection with search and filtering capabilities. - Integrated the ComboboxInput into the UsageLogsFilterDialog for improved user experience when filtering by token name. - Updated locale files to include new translations for user-facing strings related to token filtering. * feat(combobox): integrate translation support for custom value prompt - Added translation functionality to the Combobox component, replacing hardcoded text with a translatable string for the custom value prompt. - Utilized the useTranslation hook from react-i18next to enhance internationalization support, ensuring a consistent user experience across different languages. * refactor(i18n): improve Chinese translations for consistency and clarity - Adjusted spacing in various Chinese translations to enhance readability and maintain consistency across the locale file. - Updated multiple user-facing strings to ensure proper formatting and alignment with localization standards. * feat(calendar): add CalendarDropdown component for enhanced dropdown functionality - Introduced a new CalendarDropdown component to improve user interaction with dropdown selections in the calendar. - Implemented state management for dropdown visibility and selection handling, enhancing the overall user experience. - Updated styling for dropdown elements to ensure consistency and better alignment with the UI design. * fix(balance-query-dialog): handle null currentRow and improve usage query logic - Updated the BalanceQueryDialog component to safely access currentRow properties using optional chaining. - Added a check to ensure currentRow is not null before proceeding with usage queries, preventing potential runtime errors. - Refactored the handleQueryCodexUsage function to use a local variable for currentRow, enhancing code clarity. * feat(i18n): add new translations for batch creation and channel updates - Added new translation strings for batch creation instructions across multiple languages, enhancing user guidance. - Included translations for the "Update Channel" prompt to improve clarity in channel configuration settings. - Ensured consistency in terminology across locale files for better user experience. * feat(channel-mutate-drawer): improve API key input handling and update translations - Refactored the API key input logic in the ChannelMutateDrawer component to enhance readability and maintainability. - Added new placeholder translations for batch creation and existing key prompts in multiple languages, improving user guidance. - Ensured consistency in translation strings across locale files for better user experience. * feat(fetch-models-dialog): implement sorting for model categories - Added a new function to sort model categories alphabetically, placing 'Other' at the end for easier navigation. - Updated the rendering logic in the FetchModelsDialog component to utilize the new sorting function for both new and existing models, enhancing user experience. * refactor(wallet-stats-card): standardize props usage and improve layout consistency Standardizes props usage and improves layout consistency in wallet stats card Refactors the wallet stats card component to: - Use props directly instead of destructuring for consistency - Add min-w-0 to prevent content overflow - Adjust text sizing with break-all for proper wrapping - Implement responsive font sizes (3xl on mobile, 4xl on larger screens) - Improve leading and tracking for better readability Refactor wallet stats card for consistency and layout Standardizes props usage and improves layout consistency in wallet stats card - Uses props directly instead of destructuring for consistency - Adds min-w-0 to prevent content overflow - Adjusts text sizing with break-all for proper wrapping - Implements responsive font sizes (3xl on mobile, 4xl on larger screens) - Improves leading and tracking for better readability * feat(web): add subscription management and admin settings UI * feat(web): add subscription management and admin settings UI - Add subscription management module (plans, pricing, toggle status, and related dialogs/tables with Stripe/Creem integration notes) - Add channel affinity (rules and cache stats), Waffo integration, performance, and Grok model sections to system settings, with extended types and section registry - Add status code mapping validation/risk warnings, upstream update hooks, and utilities for channels; add available models and sidebar module cards to user profile - Add chat2link route and useMinimumLoadingTime, useTableCompactMode shared hooks Made-with: Cursor * fix: remove duplicate GenerateOAuthCode and add missing TaskBulkUpdate - remove duplicate GenerateOAuthCode from github.go since oauth.go already has the generic version. - add model.TaskBulkUpdate for bulk update by upstream task_id strings, fixing task_video.go build failure. * feat(router): add chat2link and subscriptions routes - register /chat2link page route under authenticated layout. - register /subscriptions/ page route under authenticated layout. - update auto-generated routeTree type definitions and route mappings. * feat(docker): add development environment setup with Docker Compose - Introduced docker-compose.dev.yml for local development, including services for new-api, Redis, and PostgreSQL. - Created Dockerfile.dev for backend-only builds, optimizing the development workflow. - Updated makefile to include new commands for starting backend services and frontend development. * feat(web): complete i18n coverage for setup wizard and add language switcher - wrap all hardcoded English strings in setup-wizard, database-step, usage-mode-step, and complete-step with t() calls, covering step titles, descriptions, form validation messages, and fallback strings. - add LanguageSwitcher component to the top-right corner of the setup page so users can switch language during initial setup. - register 25 dynamic i18n keys in static-keys.ts and provide full translations for zh/en/ja/fr/ru/vi. * feat(i18n): internationalize default version text in workspace-switcher - remove hardcoded 'Unknown version' default, use t('Unknown version') for i18n fallback - add "Unknown version" translation entries across all 6 locale files (zh/en/fr/ru/ja/vi) * feat(i18n): add full i18n coverage for channel-affinity settings page - replace Chinese t() keys with English keys across three channel-affinity components to align with new frontend i18n conventions. - add 51 translation entries to all 6 locale files (en/zh/ja/fr/ru/vi) covering main page, rule editor, and cache stats dialog. - register section-registry dynamic keys in static-keys.ts. * feat(i18n): add full i18n coverage for Waffo payment settings page - replace Chinese i18n keys with English keys in waffo-settings-section.tsx for consistency. - wrap previously hardcoded labels (Pay Method Type / Pay Method Name) with t(). - add 26 Waffo-related translation entries across all 6 locale files (en/zh/fr/ru/ja/vi). * feat(i18n): add missing translations for global model settings page - add all 6 locale translations for 3 missing t() keys in global-settings-card. - register dynamically used 'Grok' key in static-keys.ts for i18n scanner coverage. * feat(i18n): add full i18n coverage for Grok model settings page - add translations in all 6 locales (en/zh/fr/ja/ru/vi) for grok-settings-card t() calls. - cover violation fee toggle, amount input, and official docs link labels. - include section-registry descriptionKey translation entries. * feat(i18n): add full i18n coverage for performance settings page - migrate all t() keys from Chinese to English to align with project conventions. - add translations for all 6 locales (en/zh/ja/fr/ru/vi) covering disk cache, system monitoring, log management, and stats dashboard sections. - remove 71 obsolete Chinese-keyed entries from every locale file. * fix(i18n): add 116 missing English translation keys across all locales - scan all t() calls to identify English keys used in code but absent from locale files. - add translations for zh/en/fr/ja/ru/vi, keeping key sets and sort order consistent. - covers system-settings, channels, models, auth, wallet and other modules. * fix(i18n): add missing translations for log cleanup quick-select and confirm dialog - wrap quick-select button labels (24 hours ago / 7 days ago / 30 days ago) with t(). - replace hardcoded English strings in purge confirm dialog with t() calls and date interpolation. - add 5 new translation keys across all 6 locale files (zh/en/fr/ja/ru/vi). * refactor(web): unify all time display with dayjs formatting - replace all toLocaleString/toLocaleDateString/toLocaleTimeString and manual padStart concatenation with dayjs.format(). - standardize output: datetime as YYYY-MM-DD HH:mm:ss, date as YYYY-MM-DD, time as HH:mm:ss. - add formatDateTimeStr, formatDateStr, formatTimeStr dayjs-based helpers in lib/format.ts. - update 12 files across core utils and feature components. * refactor(web): replace native datetime-local input with DateTimePicker in announcements - swap browser-native datetime-local for the project's DateTimePicker component to match the UI used in log cleanup and other pages. - convert between Date objects and ISO strings to bridge the form's string-based schema. * refactor(web): replace native HTML elements with design system components - replace ~35 native <button> with <Button> across pricing, profile, channels modules - replace native <input>/<textarea>/<label> with <Input>/<Textarea>/<Label> for consistent form styling - replace native <table> with <Table> components, <details>/<summary> with <Collapsible> - replace decorative <hr> with <Separator> to ensure global UI consistency * refactor(web): enhance profile components with design system consistency - update ProfileSecurityCard to use buttons for security actions, improving accessibility and styling. - modify AccountBindingsTab layout to a grid for better responsiveness and visual alignment. - refactor NotificationTab to utilize icons for notification methods, enhancing user experience and clarity. * fix(i18n): complete i18n coverage for profile page components - wrap passkey card status badges (enabled/disabled, backup state) and last-used text with t() - fix hardcoded button labels in security dialogs (change password, access token, delete account) - internationalize all 2FA dialog strings (setup, disable, backup codes) - fix email bind dialog description and button state text missing i18n - wrap remaining hardcoded strings in notification tab and checkin calendar - add all missing translation entries to zh.json and en.json * fix(i18n): enhance error messages with translations for deployment access and settings - wrap connection error messages in DeploymentAccessGuard and IoNetDeploymentSettingsSection with t() for internationalization. - add missing translation key for "io.net model deployment is not enabled or api key missing" in all locale files (en, fr, ja, ru, vi, zh). * 🧹 chore(web): resolve all ESLint errors and warnings Align the Vite/React frontend with the current ESLint flat config and React Compiler–related rules by fixing violations instead of broad suppression where practical. - Replace `any` with concrete types (`unknown`, `Record<string, unknown>`, domain types) where upstream/API shapes allow - Fix duplicate imports, unused bindings, `no-console`, and empty blocks - Address react-hooks issues: reorder declarations, memoize unstable callbacks (`useCallback`), extend dependency arrays, and use targeted disables only where sync-from-props in `useEffect` is intentional - Refactor `motion.create` usage in ai-elements shimmer to avoid creating components during render (static-components) - Stabilize TanStack Query/Mutation hook usage (query keys, `mutate` in deps) and add narrowly scoped rule disables where the linter conflicts with library patterns - Disable `react-hooks/incompatible-library` in ESLint config for TanStack Table / RHF false positives - Add file-level `react-refresh/only-export-components` disables for registry/provider/column modules that intentionally mix exports `bun lint` completes with 0 errors and 0 warnings. * ✨ feat(web): add subscription management to sidebar and align drawer with project conventions - Register "Subscription Management" nav item in the admin sidebar group with CreditCard icon pointing to /subscriptions - Add subscription module to sidebar config defaults and URL mapping so it integrates with the admin sidebar modules toggle in system settings - Add subscription entry to sidebar-modules-section moduleMeta for the maintenance settings UI - Refactor SubscriptionsMutateDrawer to follow the same patterns used by users, redemption-codes, and other mutate drawers: - Use shadcn Form/FormField/FormItem/FormControl/FormLabel/FormMessage instead of raw register() + Label + manual error display - Move SheetFooter outside the form with form attribute association - Use SheetClose for the cancel button - Reset form state on drawer close - Align SheetContent width (sm:max-w-[600px]) and spacing conventions * ✨ feat(web): overhaul UI/UX with Vercel Geist design alignment Refactor the entire frontend UI/UX to align with Vercel/OpenAI design principles, covering layout, animations, skeleton loading, and overall visual polish. Motion & Page Transitions: - Add centralized motion system (lib/motion.ts) with Vercel-style transition presets, stagger variants for tables, cards, and sidebars - Implement AnimatedOutlet for route-level page enter animations using TanStack Router pathname keying - Add PageTransition, StaggerContainer, StaggerItem, CardStagger, and TableStagger wrapper components for progressive reveal effects Skeleton Loading — Vercel Geist Style: - Replace shadcn default `animate-pulse` with Geist-style shimmer sweep animation (linear-gradient + background-position keyframes) - Add `--skeleton-base` / `--skeleton-highlight` CSS variables tuned for both light and dark themes with neutral oklch tones - Override auto-skeleton-react inline styles via CSS to unify all skeleton elements under the same shimmer effect - Update TableSkeleton with varied column widths for a natural feel - Add ContentSkeleton and QuerySkeleton wrappers for auto-skeleton integration with React Query error/loading states - Respect prefers-reduced-motion: disable shimmer for accessibility Layout & Sidebar: - Upgrade sidebar expand/collapse transitions to cubic-bezier easing - Add hover micro-interactions (background-color, color, transform) to sidebar menu buttons with smooth 150ms transitions - Fix oklch color compatibility in sidebar outline variant - Integrate AnimatedOutlet into AuthenticatedLayout for unified route-level animations Theme & CSS: - Streamline theme.css with cleaner oklch color definitions - Add CSS table row stagger-in animations with nth-child delays - Fix hover-scrollbar color bug (hsl → color-mix for oklch compat) - Add content-auto utility for long list rendering optimization Cleanup: - Remove deprecated skeleton-wrapper.tsx - Remove unused imports and dead code across components - Add empty-state, error-state, and loading-state utility components * 🐛 fix(docker): track bun.lock to fix Docker build failure Remove `web/bun.lock` from `.gitignore` so the lock file is committed to version control. The Dockerfile `COPY web/bun.lock .` instruction requires this file to be present in the build context, and ignoring it caused the build to fail with a "not found" error. * ⬆️ chore(web): upgrade dependencies and fix all type/lint errors Upgrade all frontend dependencies to latest stable versions: - lucide-react 0.562 → 1.7 (major: brand icons removed) - shiki 3.x → 4.x, eslint 9.x → 10.x, knip 5.x → 6.x - @rsbuild/core 1.3 → 1.7, @types/node 24 → 25 - tailwindcss/postcss 4.1 → 4.2, motion 12.25 → 12.38 - @tanstack/react-query 5.90 → 5.95, zod 4.3.5 → 4.3.6 - react 19.2.3 → 19.2.4, axios 1.13.2 → 1.13.6 - prettier 3.7 → 3.8, typescript-eslint 8.52 → 8.57 - Add missing optional deps: @xyflow/react, embla-carousel-react Resolve all TypeScript compilation errors introduced by upgrades: - Replace lucide-react brand icons (Github) with react-icons/si - Fix react-hook-form Control/Resolver generics for zod v4 - Fix Record<string, unknown> type constraints across API utils - Fix axios interceptor return types in lib/api.ts - Add type assertions for useSettings/useStatus hook returns - Resolve Badge variant, spread type, and route path mismatches Resolve all ESLint 10 errors: - preserve-caught-error: attach cause to re-thrown errors - no-useless-assignment: refactor redundant variable assignments - prefer-as-const: use `as const` over literal type assertions - no-unused-vars: prefix type-only schemas with underscore Update tsconfig lib from ES2020 to ES2022 for Error.cause support. * 🐛 fix(web): stop pricing model row from centering its content Wrapping the row in shadcn <Button variant='ghost'> inherits `justify-center`, and the inner flex container had no width, so `justify-between` collapsed and the row appeared centered. * feat: add Waffo payment integration and related UI components - Introduced Waffo payment method with support for custom icons and settings. - Updated payment settings section to include Waffo settings. - Added Waffo payment request handling in the wallet API. - Enhanced wallet recharge form to support Waffo payment methods. - Implemented hooks for Waffo payment processing. - Updated localization files for new Waffo-related strings. - Added new payment type and icon for Waffo in constants and UI components. - Refactored topup info handling to include Waffo payment methods and configurations. * feat(profile): add admin-only upstream model update notification setting * fix(web): make sidebar module user settings actually take effect Previously, saving sidebar module preferences in profile had no effect because the client ignored user-level sidebar_modules entirely. This fix wires user config into useSidebarConfig so the sidebar updates immediately without a page refresh. Changes: - Add UserPermissions type with sidebar_settings/sidebar_modules fields - Refactor useSidebarConfig to merge admin × user config with AND logic - Sync sidebar_modules to auth store on save for immediate UI updates - Conditionally render SidebarModulesCard based on user permissions - Treat null/empty user config as "do not narrow" for legacy users * feat(web): add custom OAuth provider CRUD and login button support Migrate custom OAuth from v1 to v2: - Admin CRUD UI with provider table, form dialog, preset templates, and OIDC discovery - Login page renders dynamic buttons for custom OAuth providers - Fix account bindings display showing "Not bound" text when already bound * feat(web): add ServerAddress, SMTPForceAuthLogin, CreateCacheRatio and group special usable settings Migrate missing v1 system settings to v2: - ServerAddress input in General > System Information - SMTPForceAuthLogin toggle in Integrations > Email - CreateCacheRatio JSON editor in Models > Ratio - Group special usable group rules editor in Models > Ratio * feat(web): wire user subscriptions dialog to users table row actions The UserSubscriptionsDialog component already existed but had no entry point in the users table dropdown menu. Add "Manage Subscriptions" menu item. * chore(web): update i18n translations for new settings and custom OAuth * 💎 refactor(web): redesign pricing page with flat, typography-driven layout * 🌐 chore(i18n): complete missing translations and normalize project config - Add 425+ missing translations across fr, ja, ru, zh, vi locales for subscription management, sidebar navigation, Grok settings, upstream model updates, pricing page, and other UI components - Add 37 missing i18n keys used in t() calls but absent from locale files (pricing filters, display options, audio/cache labels, etc.) - Fix stale tech stack info in CLAUDE.md, AGENTS.md, and project.mdc: React 18 → 19, Vite → Rsbuild, Semi Design → Radix UI + Tailwind - Fix i18n key format description: "Chinese source strings" → English - Deduplicate .cursor/rules/project.mdc to avoid triple-loading the same rules already present in root CLAUDE.md and AGENTS.md - Add i18n-translate Cursor skill for repeatable translation workflow * 🎨 refactor(web): redesign dashboard with flat, typography-driven layout Replace Card-based dashboard components with a flat, border-driven design system consistent with the pricing page, following the ui-style.mdc conventions. Overview section: - StatCard: replace Card wrapper with flat flex layout, monospace tabular values, uppercase tracking-wider labels, layered opacity hierarchy - PanelWrapper: replace Card/CardHeader/CardContent with rounded-lg border container and border-b header - SummaryCards: merge three stat cards into a single bordered container with divide-x separators; decouple border from stagger animation to prevent border deformation during entrance transitions - ApiInfoPanel/Item: full-width list rows with border-b separators, monospace route names, layered opacity for URLs and descriptions - AnnouncementsPanel: native button rows with hover:bg-muted/40, i18n for "Click for details" hint - FAQPanel: lighter border-border/60 accordion dividers, muted answer text - UptimePanel: uppercase tracking-wider group headers with bg-muted/30 background, monospace uptime percentages, fine-grained border opacity Models section: - LogStatCards: replace Card with rounded-lg border + divide-x grid, fix react-hooks/exhaustive-deps by destructuring props before useEffect - ModelCharts: replace Card+Tabs with bordered container + custom segmented control matching ui-style spec - Suspense fallbacks: match new flat skeleton layout with accurate column structure Animation: - Wrap models section in FadeIn with staggered delay - Keep CardStagger for overview panel grid (each panel has own border) Other: - Add ui-style.mdc cursor rule documenting the design language - Disable react-refresh/only-export-components for src/routes/** in eslint config (TanStack Router route files always export Route objects) - Fix zh.json: "Token-based" translation "基于令牌的" → "按量计费" * ✨ refactor(web): adopt flat dot-and-text design for all status badges Replace the bordered/colored-background StatusBadge and Badge components across the entire frontend with a minimal flat design: a small colored dot followed by colored text, eliminating visual noise from heavy borders, backgrounds, and rounded pill shapes. Key changes: - Redesign StatusBadge to use dot + text instead of bordered pill style, removing cva-based background/border variants in favor of exported dotColorMap and textColorMap lookup tables - Add children prop support to StatusBadge for flexible content rendering alongside the existing label prop - Migrate all Badge usages (except pricing page) to StatusBadge with appropriate variant mappings (default→info, secondary→neutral, outline→neutral, destructive→danger) - Consolidate adjacent multi-badge groups into single-dot layouts with dot separators (·) to reduce visual clutter in: - Channel balance columns (used + remaining) - Channel type column (type + IO.NET indicator) - User invite info column (invited + revenue + inviter) - Usage log stats bar (usage + RPM + TPM) - Usage log time/FRT column (time + FRT + stream status) - Subscription plan counts (active + expired) - Channel affinity scope/regex/key-source columns - Prefill group card headers (type + ID) - Export dotColorMap and textColorMap for direct use in custom inline layouts that need consistent status colors without the full component * ✨ refactor(web): redesign public layout and landing page with modern UI Overhaul the public-facing layout, header, and homepage to deliver a polished, animation-rich landing experience inspired by contemporary SaaS design patterns. Header: - Replace sticky header with fixed floating navbar that compacts into a pill-shaped glass-morphism bar on scroll (backdrop-blur + ring) - Add smooth 700ms cubic-bezier transitions for scroll-based shrinking - Build full-screen mobile menu overlay with staggered entry animations - Remove background color from logo container, show logo image directly Homepage sections: - Hero: gradient text title, radial gradient + grid pattern background, interactive terminal demo showcasing API request/response - Terminal demo: auto-cycles through gpt-4o, claude-sonnet-4-20250514, gemini-2.5-pro, deepseek-chat with smooth cross-fade transitions, clickable model badges, dual theme support (light/dark), fixed height - Stats: animated co…
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.