Skip to content

feat: add native Fire Ark API channel - #6648

Closed
ENCHIGO wants to merge 6 commits into
QuantumNous:mainfrom
ENCHIGO:feat/volc-native-adapter
Closed

ENCHIGO wants to merge 6 commits into
QuantumNous:mainfrom
ENCHIGO:feat/volc-native-adapter

Conversation

@ENCHIGO

@ENCHIGO ENCHIGO commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes #4705\n\n- add a separate Volc Native channel for Fire Ark /api/v3 endpoints\n- preserve native image and async task request fields\n- keep OpenAI-compatible VolcEngine routing isolated\n- scope task list, fetch, and cancel operations to the authenticated user\n- add coverage for native route isolation and upstream task ID masking

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Volc Native channel support with image generation and asynchronous task management capabilities.
    • New image generation endpoint at /api/v3/images/generations.
    • Task management endpoints for creation, retrieval, listing, and deletion.
  • UI & Branding

    • System name updated and branding refreshed.
    • Added new "Dasheng" theme variant with updated color scheme.
  • Chores

    • Updated Docker build configuration for improved package installation.
    • Updated application metadata and descriptions across web frontends and desktop app.

ENCHIGO added 6 commits July 2, 2026 15:26
- Replace favicon/logo (web/default + web/classic) and Electron icons with 大晟 AI assets
- Append dasheng theme preset (web/default) and Semi brand colors (web/classic), opt-in / non-default
- Update HTML title/meta/theme-color, DEFAULT_SYSTEM_NAME, default SiteSettings.SystemName,
  SystemBrand fallback, Electron productName/description/window title, startup log → 大晟 AI

Runtime rebrand only. All upstream project/org attribution preserved:
go.mod module path & imports (github.com/QuantumNous/new-api), LICENSE, NOTICE,
.go copyright headers, README attribution, electron author/repository — untouched.

AI-assisted change (committer is not an upstream core maintainer).
oven/bun:1 image ships a newer bun than the committed web/bun.lock,
so --frozen-lockfile fails on a clean build. Relax to plain bun install
for both default and classic frontend stages. Version ldflag and all
QuantumNous/new-api attribution untouched.
Build host is in mainland China and cannot reach proxy.golang.org.
Set GOPROXY=https://goproxy.cn,direct in the Go build stage.
GOSUMDB=off skips the remote transparency log only; committed go.sum
still enforces module hash verification locally.
Version ldflag and QuantumNous/new-api attribution untouched.
Backend /api/status serves SystemName (default was 'New API'), which the
frontend prefers over its own fallback. Set default to 大晟 AI so a fresh
instance is branded out-of-the-box without admin config. Runtime default
only; license header, module path, Version ldflag untouched.
Rename the custom runtime brand from 大晟 AI to 晟枢|统一模型服务网关 across
the backend default, both frontends, and the Electron app:
- backend: common.SystemName default + startup log line
- default theme: <title>/meta title/description, DEFAULT_SYSTEM_NAME,
  SiteSettings default, SystemBrand fallback
- classic theme: <title> + generator meta
- electron: productName + description + window title

Runtime rebrand only. All upstream project/org attribution preserved:
go.mod module path & imports (github.com/QuantumNous/new-api), LICENSE, NOTICE,
.go copyright headers, README attribution, electron author/repository — untouched.

AI-assisted change (committer is not an upstream core maintainer).
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The change adds Fire Ark Volc Native channel support for image and asynchronous content generation, including routing, adaptors, task lifecycle handling, billing, and polling. It also updates application branding, frontend themes, and Docker build settings.

Changes

Volc Native API support

Layer / File(s) Summary
Channel contracts and adaptor registration
constant/..., common/..., relay/..., web/default/src/features/channels/...
Registers channel and API type 59 across backend relay infrastructure and frontend channel configuration.
Native request and task adaptors
relay/channel/volcnative/..., relay/channel/task/volcnative/...
Validates and forwards native requests, preserves response fields, and replaces upstream task IDs with public IDs.
Native routes and channel selection
router/..., middleware/..., model/..., controller/channel-test.go
Adds native generation routes and restricts Volc Native channels to supported /api/v3 paths.
Task relay and polling lifecycle
controller/volc_native.go, controller/volc_native_test.go, service/task_polling.go
Implements image relay, task retrieval, listing, cancellation, billing settlement, response shaping, tests, and polling key selection.

Application branding

Layer / File(s) Summary
Branding defaults and presentation
common/constants.go, main.go, electron/..., web/classic/..., web/default/..., newapi品牌替换分析.md
Replaces default New API branding with 晟枢|统一模型服务网关 and adds cyan light and dark themes.

Build environment

Layer / File(s) Summary
Docker build settings
Dockerfile
Uses non-frozen Bun installs and configures the Go module proxy and checksum settings.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant NativeRouter
  participant Distributor
  participant Controller
  participant FireArkAPI
  participant TaskStore
  Client->>NativeRouter: Submit native image or task request
  NativeRouter->>Distributor: Authenticate, rate-limit, and select channel
  Distributor->>Controller: Dispatch supported native route
  Controller->>FireArkAPI: Forward request with channel credentials
  FireArkAPI-->>Controller: Return image or task response
  Controller->>TaskStore: Persist task and billing state
  Controller-->>Client: Return native-shaped response
Loading

Possibly related PRs

Suggested reviewers: calcium-ion

Poem

A rabbit checks the native gate,
Fire Ark tasks now route and wait.
IDs stay neat, fields pass through,
Cyan themes brighten every view.
“晟枢” blooms in logs and screen—
Hop, build, and ship the change serene!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.68% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add native Fire Ark API channel' accurately summarizes the main feature addition—introducing a new dedicated channel type for Fire Ark native API endpoints alongside the existing VolcEngine channel.
Linked Issues check ✅ Passed All primary objectives from issue #4705 are met: new native channel (ChannelTypeVolcNative) is added, native endpoints (/api/v3/contents/generations/tasks* and /api/v3/images/generations) are supported with transparent request/response proxying, private fields are preserved, existing VolcEngine behavior is unchanged, and tiered-expression quota charging is implemented.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the native Fire Ark API channel. Branding updates (constants, UI, Electron, web pages) are consistent supporting changes for unified rebranding; Docker and Go proxy configuration changes are infrastructure improvements required for build consistency.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch feat/volc-native-adapter
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@ENCHIGO ENCHIGO closed this Aug 4, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Nitpick comments (6)
controller/volc_native.go (1)

239-239: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the "cancelled" sentinel into a named constant.

RelayVolcNativeTaskDelete writes the literal "cancelled" into task.FailReason, and volcNativeTaskStatus compares against the same literal to map the status. A typo in either place silently downgrades a cancelled task to failed. Declare one constant, for example volcNativeCancelledReason, and use it at both sites.

Also applies to: 320-334

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/volc_native.go` at line 239, Define a named constant for the
"cancelled" failure reason and replace the literal in both
RelayVolcNativeTaskDelete and volcNativeTaskStatus, preserving the existing
cancellation status mapping.
middleware/distributor.go (2)

442-445: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The Volc Native route allowlist is defined three times. Each of the three channel-selection layers encodes the same two /api/v3 prefixes. Adding a native endpoint requires three synchronized edits, and any miss lets a channel be selected for a path it cannot serve or blocks a path it can.

  • middleware/distributor.go#L442-L445: replace isVolcNativePath with a call to one exported helper, for example constant.IsVolcNativeRequestPath.
  • model/channel_cache.go#L239-L242: delete isVolcNativeRequestPath and call the shared helper from filterChannelsByRequestPath.
  • model/ability.go#L187-L192: replace the inline strings.HasPrefix pair with the shared helper.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@middleware/distributor.go` around lines 442 - 445, The Volc Native route
allowlist is duplicated across three channel-selection layers; centralize it in
one exported helper and have all callers reuse it. In middleware/distributor.go
lines 442-445, replace isVolcNativePath with the shared helper; in
model/channel_cache.go lines 239-242, remove isVolcNativeRequestPath and call
the shared helper from filterChannelsByRequestPath; in model/ability.go lines
187-192, replace the inline prefix checks with the shared helper while
preserving both existing /api/v3 prefixes.

163-166: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use i18n.T for the new abort message.

Every other abortWithOpenAiMessage call in Distribute passes a translated message from the i18n catalog. This new message is a hard-coded English string, so clients receive an untranslated error for this one failure mode. Add a message key such as MsgDistributorPathNotSupported and use it here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@middleware/distributor.go` around lines 163 - 166, The abortWithOpenAiMessage
call in the channel path validation block uses a hard-coded English string
instead of translating it. Add a new message key to the i18n catalog such as
MsgDistributorPathNotSupported, then replace the hard-coded string with an
i18n.T call using that key to match the pattern of other abortWithOpenAiMessage
calls throughout the Distribute function.
service/task_polling.go (1)

446-461: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Select the channel key only when the task has no private key.

task.PrivateData.Key overrides the selected key at line 460, but GetNextEnabledKey already ran. In MultiKeyModePolling that call advances MultiKeyPollingIndex and takes the per-channel lock for a key that is then discarded, which skews rotation across polls. Check the private key first.

♻️ Proposed refactor
-	key := ch.Key
-	// Volc Native tasks use the channel's key selector for every poll. This
-	// avoids handing a newline-delimited multi-key bundle to Fire Ark and keeps
-	// credentials in the channel store rather than task payloads.
-	if ch.Type == constant.ChannelTypeVolcNative {
-		selectedKey, _, keyErr := ch.GetNextEnabledKey()
-		if keyErr != nil {
-			return fmt.Errorf("select key for task %s failed: %w", taskId, keyErr)
-		}
-		key = selectedKey
-	}
-
-	privateData := task.PrivateData
-	if privateData.Key != "" {
-		key = privateData.Key
-	}
+	key := ch.Key
+	if privateKey := task.PrivateData.Key; privateKey != "" {
+		key = privateKey
+	} else if ch.Type == constant.ChannelTypeVolcNative {
+		// Volc Native tasks use the channel's key selector so Fire Ark never
+		// receives a newline-delimited multi-key bundle.
+		selectedKey, _, keyErr := ch.GetNextEnabledKey()
+		if keyErr != nil {
+			return fmt.Errorf("select key for task %s failed: %w", taskId, keyErr)
+		}
+		key = selectedKey
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/task_polling.go` around lines 446 - 461, Update the key-selection
flow around GetNextEnabledKey and task.PrivateData.Key so channel key selection
occurs only when the task has no private key. Preserve the private key as the
highest-priority value, and avoid calling GetNextEnabledKey for tasks that
already provide one.
router/video-router.go (1)

43-45: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove middleware.Distribute() from the read-only task routes, or confirm it is required.

getModelRequest returns shouldSelectChannel = false for non-POST /api/v3/contents/generations/tasks requests, so Distribute selects no channel. RelayVolcNativeTaskList, RelayVolcNativeTaskFetch, and RelayVolcNativeTaskDelete read the task from the database and resolve the channel with model.CacheGetChannel. The middleware therefore adds body parsing and context setup with no effect. Dropping it keeps the route definitions honest about their dependencies.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@router/video-router.go` around lines 43 - 45, Remove middleware.Distribute()
from the GET routes for RelayVolcNativeTaskList and RelayVolcNativeTaskFetch,
since these handlers resolve channels from the database and do not select a
channel through the middleware. Leave the DELETE route unchanged unless its
handler has the same read-only behavior and does not depend on Distribute.
main.go (1)

59-59: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse common.SystemName in the startup log.

The startup log duplicates the value from common/constants.go Line 17. Use common.SystemName so future branding changes cannot leave the log stale.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@main.go` at line 59, Update the startup log statement in main to use
common.SystemName instead of the duplicated hardcoded product name, while
preserving the existing version and started message formatting.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@common/constants.go`:
- Line 17: Update the email sender construction in the code that formats the
From header to apply mime.QEncoding.Encode to SystemName before inserting it
into the display name. Preserve the existing sender address and subject
behavior, and use the encoded value when composing the From header.

In `@controller/volc_native_test.go`:
- Line 21: Strengthen the watermark check in the test around
buildVolcNativeTaskResponse so it verifies the watermark field exists rather
than relying on Bool() returning false for a missing key. Assert key existence
directly, or change the fixture to use true and compare against true, while
preserving the intended response validation.

In `@controller/volc_native.go`:
- Around line 104-113: Update the HTTP client setup used by
GetHttpClientWithProxy and the subsequent client.Do(req) call to enforce a
default upstream timeout when RELAY_TIMEOUT/common.RelayTimeout is unset,
covering both non-proxy and SOCKS5 proxy paths. Preserve explicitly configured
timeout values and ensure requests cannot hang indefinitely.
- Around line 236-258: Update the cancellation flow around the task.Status
assignment and buildVolcNativeTaskResponse so task.Data is rewritten when
cancellation succeeds, rather than retaining the polled upstream status. Ensure
the cached payload reflects the local cancelled/failure state for both the
immediate response and later RelayVolcNativeTaskFetch responses, while
preserving the existing durable-state refresh path when won is false.

In `@newapi品牌替换分析.md`:
- Line 57: Update the table entry describing the fallback in the row referencing
system-brand.tsx so the literal || does not create extra Markdown table cells;
escape the pipe characters or rewrite the operator example in prose, while
preserving the documented fallback behavior and ensuring the document passes
MD056.
- Around line 1-5: Update the branding replacement report to reflect the final
shipped product branding. Replace all references to "New API" that appear in
Line 28 and Lines 45-57 with "晟枢|统一模型服务网关" to match the actual delivered
product. Ensure the "Current value" column and any example references throughout
the document accurately represent what was shipped rather than the
pre-replacement baseline, so the report serves as an accurate post-change
documentation of the branding migration.

In `@relay/channel/task/volcnative/adaptor.go`:
- Around line 79-83: In the response-handling function, defer closing resp.Body
immediately after the nil-response check and before io.ReadAll, ensuring both
successful and failed read paths release the body; remove the later explicit
close if it becomes redundant.

In `@web/default/src/features/channels/constants.ts`:
- Line 80: Replace all user-facing string literals with translation keys to
comply with i18n requirements. In web/default/src/features/channels/constants.ts
at line 80, replace the literal 'Volc Native' with an appropriate translation
key constant (e.g., 'channels.volcNative'). In
web/default/src/features/channels/lib/channel-type-config.ts at lines 149-155,
replace the channel name and setup hints literals with their corresponding
translation keys. Store these translation keys as constants and resolve them
with t() at each display site where the user-facing text is rendered, following
the established i18n pattern in the codebase.

In `@web/default/src/features/channels/lib/channel-type-config.ts`:
- Line 151: Update the defaultBaseUrl configuration in the channel type config
to read from the VITE_VOLC_NATIVE_BASE_URL environment variable instead of
hardcoding the endpoint. Add the variable to .env with the existing default URL
and preserve the current URL as the fallback if the environment value is
unavailable.

In `@web/default/src/styles/theme-presets.css`:
- Around line 745-749: Update the light preset’s --primary-foreground to a dark
color that provides at least 4.5:1 contrast against --primary, and verify the
selected foreground also meets the contrast requirement for --primary-hover and
--primary-active while leaving the existing primary colors unchanged.

---

Nitpick comments:
In `@controller/volc_native.go`:
- Line 239: Define a named constant for the "cancelled" failure reason and
replace the literal in both RelayVolcNativeTaskDelete and volcNativeTaskStatus,
preserving the existing cancellation status mapping.

In `@main.go`:
- Line 59: Update the startup log statement in main to use common.SystemName
instead of the duplicated hardcoded product name, while preserving the existing
version and started message formatting.

In `@middleware/distributor.go`:
- Around line 442-445: The Volc Native route allowlist is duplicated across
three channel-selection layers; centralize it in one exported helper and have
all callers reuse it. In middleware/distributor.go lines 442-445, replace
isVolcNativePath with the shared helper; in model/channel_cache.go lines
239-242, remove isVolcNativeRequestPath and call the shared helper from
filterChannelsByRequestPath; in model/ability.go lines 187-192, replace the
inline prefix checks with the shared helper while preserving both existing
/api/v3 prefixes.
- Around line 163-166: The abortWithOpenAiMessage call in the channel path
validation block uses a hard-coded English string instead of translating it. Add
a new message key to the i18n catalog such as MsgDistributorPathNotSupported,
then replace the hard-coded string with an i18n.T call using that key to match
the pattern of other abortWithOpenAiMessage calls throughout the Distribute
function.

In `@router/video-router.go`:
- Around line 43-45: Remove middleware.Distribute() from the GET routes for
RelayVolcNativeTaskList and RelayVolcNativeTaskFetch, since these handlers
resolve channels from the database and do not select a channel through the
middleware. Leave the DELETE route unchanged unless its handler has the same
read-only behavior and does not depend on Distribute.

In `@service/task_polling.go`:
- Around line 446-461: Update the key-selection flow around GetNextEnabledKey
and task.PrivateData.Key so channel key selection occurs only when the task has
no private key. Preserve the private key as the highest-priority value, and
avoid calling GetNextEnabledKey for tasks that already provide one.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4b5dfa10-63a6-490d-9d3c-1765829e5cff

📥 Commits

Reviewing files that changed from the base of the PR and between 0ab0202 and a03c202.

⛔ Files ignored due to path filters (8)
  • electron/icon.png is excluded by !**/*.png
  • electron/tray-icon-windows.png is excluded by !**/*.png
  • electron/tray-iconTemplate.png is excluded by !**/*.png
  • electron/[email protected] is excluded by !**/*.png
  • web/classic/public/favicon.ico is excluded by !**/*.ico
  • web/classic/public/logo.png is excluded by !**/*.png
  • web/default/public/favicon.ico is excluded by !**/*.ico
  • web/default/public/logo.png is excluded by !**/*.png
📒 Files selected for processing (33)
  • Dockerfile
  • common/api_type.go
  • common/constants.go
  • constant/api_type.go
  • constant/channel.go
  • controller/channel-test.go
  • controller/volc_native.go
  • controller/volc_native_test.go
  • electron/main.js
  • electron/package.json
  • main.go
  • middleware/distributor.go
  • middleware/volc_native_test.go
  • model/ability.go
  • model/channel_cache.go
  • newapi品牌替换分析.md
  • relay/channel/task/volcnative/adaptor.go
  • relay/channel/task/volcnative/adaptor_test.go
  • relay/channel/volcnative/adaptor.go
  • relay/relay_adaptor.go
  • router/relay-router.go
  • router/video-router.go
  • service/task_polling.go
  • web/classic/index.html
  • web/classic/src/index.css
  • web/default/index.html
  • web/default/src/components/layout/components/system-brand.tsx
  • web/default/src/features/channels/constants.ts
  • web/default/src/features/channels/lib/channel-type-config.ts
  • web/default/src/features/channels/lib/channel-utils.ts
  • web/default/src/features/system-settings/site/index.tsx
  • web/default/src/lib/constants.ts
  • web/default/src/styles/theme-presets.css

Comment thread common/constants.go
var StartTime = time.Now().Unix() // unit: second
var Version = "v0.0.0" // this hard coding will be replaced automatically when building, no need to manually change
var SystemName = "New API"
var SystemName = "晟枢|统一模型服务网关"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Files matching constants.go and email.go:\n'
fd -a '^(constants|email)\.go$' . || true

printf '\nRelevant Go files:\n'
for f in $(fd '^constants\.go$|email\.go$' .); do
  echo "--- $f"
  wc -l "$f"
done

printf '\nconstants.go:\n'
for f in $(fd '^constants\.go$' .); do
  sed -n '1,80p' "$f"
done

printf '\nemail.go outline/snippet:\n'
for f in $(fd '^email\.go$' .); do
  echo "--- $f"
  ast-grep outline "$f" --view compact || true
  sed -n '70,125p' "$f"
done

printf '\nSearch for SystemName and MIME encoding usage:\n'
rg -n 'SystemName|mime\.|QEncoder|BEncoder|EncodeWord|Headers|From:\\s*%s|Subject' .

Repository: QuantumNous/new-api

Length of output: 50375


Encode SystemName before placing it in the email sender name.

common/constants.go:17 sets a non-ASCII display name, and common/email.go:96 writes it directly into From: %s <%s>. Only the subject uses a MIME encoded-word. Use mime.QEncoding.Encode for SystemName, or configure SMTPUTF8 support, before sending email.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/constants.go` at line 17, Update the email sender construction in the
code that formats the From header to apply mime.QEncoding.Encode to SystemName
before inserting it into the display name. Preserve the existing sender address
and subject behavior, and use the encoded value when composing the From header.


require.Equal(t, "task_public_id", gjson.GetBytes(body, "id").String())
require.NotContains(t, string(body), "upstream-task-id")
require.Equal(t, false, gjson.GetBytes(body, "watermark").Bool())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Strengthen the watermark assertion.

gjson.GetBytes(body, "watermark").Bool() returns false when the key is absent, so this assertion also passes if buildVolcNativeTaskResponse drops watermark entirely. Assert existence, or use true in the fixture so the comparison detects a dropped field.

💚 Proposed fix
-	require.Equal(t, false, gjson.GetBytes(body, "watermark").Bool())
+	watermark := gjson.GetBytes(body, "watermark")
+	require.True(t, watermark.Exists())
+	require.False(t, watermark.Bool())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
require.Equal(t, false, gjson.GetBytes(body, "watermark").Bool())
watermark := gjson.GetBytes(body, "watermark")
require.True(t, watermark.Exists())
require.False(t, watermark.Bool())
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/volc_native_test.go` at line 21, Strengthen the watermark check in
the test around buildVolcNativeTaskResponse so it verifies the watermark field
exists rather than relying on Bool() returning false for a missing key. Assert
key existence directly, or change the fixture to use true and compare against
true, while preserving the intended response validation.

Comment thread controller/volc_native.go
Comment on lines +104 to +113
client, err := service.GetHttpClientWithProxy(info.ChannelSetting.Proxy)
if err != nil {
respondVolcNativeError(c, http.StatusInternalServerError, "http_client_failed", "failed to initialise upstream client")
return
}
resp, err := client.Do(req)
if err != nil {
respondVolcNativeError(c, http.StatusBadGateway, "upstream_request_failed", "upstream request failed")
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect GetHttpClientWithProxy for a configured timeout.
rg -n 'func GetHttpClientWithProxy' -A 40 --type=go service
rg -n 'Timeout' --type=go service/http_client*.go 2>/dev/null

Repository: QuantumNous/new-api

Length of output: 2738


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== http_client.go relevant sections =="
sed -n '1,180p' service/http_client.go | cat -n

echo
echo "== relay timeout constants/config references =="
rg -n 'RelayTimeout|RelayIdleConnTimeout' --type=go

echo
echo "== volc_native.go relevant sections =="
sed -n '80,235p' controller/volc_native.go | cat -n

Repository: QuantumNous/new-api

Length of output: 6355


🏁 Script executed:

#!/bin/bash
set -u

echo "== relay timeout references, all types =="
rg -n 'RelayTimeout|RelayIdleConnTimeout|RelayMaxIdleConns' . || true

echo
echo "== GetHttpClientWithProxy call sites =="
rg -n 'GetHttpClientWithProxy\s*\(' --type=go controller service || true

echo
echo "== volc_native.go controller sections =="
sed -n '90,125p' controller/volc_native.go | cat -n
sed -n '200,225p' controller/volc_native.go | cat -n

Repository: QuantumNous/new-api

Length of output: 6041


🏁 Script executed:

#!/bin/bash
set -u

echo "== common.InitHttpClient call sites =="
rg -n 'InitHttpClient\s*\(' --type=go . || true

echo
echo "== server/init context around common.InitHttpClient =="
sed -n '80,125p' common/init.go | cat -n

Repository: QuantumNous/new-api

Length of output: 3051


🏁 Script executed:

#!/bin/bash
set -u

echo "== service.InitHttpClient call sites =="
rg -n 'service\.InitHttpClient\s*\(' --type=go . || true

echo
echo "== InitHttpClient implementation if present =="
rg -n 'func InitHttpClient\s*\(' --type=go service . || true

echo
echo "== service/http_client.go InitHttpClient reference =="
sed -n '36,60p' service/http_client.go | cat -n

Repository: QuantumNous/new-api

Length of output: 1392


Set a default upstream timeout for RELAY_TIMEOUT.

GetHttpClientWithProxy only applies common.RelayTimeout when it is explicitly set; the non-proxy client path creates a client without Timeout, and the SOCKS5 proxy client path does the same. If RELAY_TIMEOUT is unset in production, these client.Do(req) calls can hang outside the request context. Set a fallback relay timeout or add per-call timeout context.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/volc_native.go` around lines 104 - 113, Update the HTTP client
setup used by GetHttpClientWithProxy and the subsequent client.Do(req) call to
enforce a default upstream timeout when RELAY_TIMEOUT/common.RelayTimeout is
unset, covering both non-proxy and SOCKS5 proxy paths. Preserve explicitly
configured timeout values and ensure requests cannot hang indefinitely.

Comment thread controller/volc_native.go
Comment on lines +236 to +258
previousStatus := task.Status
task.Status = model.TaskStatusFailure
task.Progress = "100%"
task.FailReason = "cancelled"
task.FinishTime = time.Now().Unix()
won, err := task.UpdateWithStatus(previousStatus)
if err != nil {
respondVolcNativeError(c, http.StatusInternalServerError, "task_update_failed", "failed to update local task")
return
}
if won {
service.RefundTaskQuota(c.Request.Context(), task, "cancelled")
} else {
// A concurrent poll completed the task. Return the durable state and do
// not perform a second refund.
refreshed, exists, refreshErr := model.GetByTaskId(c.GetInt("id"), task.TaskID)
if refreshErr != nil || !exists || refreshed == nil {
respondVolcNativeError(c, http.StatusInternalServerError, "task_refresh_failed", "failed to refresh local task")
return
}
task = refreshed
}
c.Data(http.StatusOK, "application/json", buildVolcNativeTaskResponse(task))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Cancellation returns a stale upstream status.

buildVolcNativeTaskResponse prefers task.Data whenever that payload has a status field (lines 294-299). service/task_polling.go line 495 fills task.Data with the redacted upstream body on every poll, so a running task holds {"status":"running",...}. This handler updates task.Status, task.Progress, and task.FailReason, but leaves task.Data untouched. The cancel response and every later RelayVolcNativeTaskFetch response therefore report running after a successful cancellation.

Rewrite the cached payload when the local status changes.

🐛 Proposed fix
 	previousStatus := task.Status
 	task.Status = model.TaskStatusFailure
 	task.Progress = "100%"
 	task.FailReason = "cancelled"
 	task.FinishTime = time.Now().Unix()
+	if len(task.Data) > 0 && gjson.GetBytes(task.Data, "status").Exists() {
+		if updated, setErr := sjson.SetBytes(task.Data, "status", "cancelled"); setErr == nil {
+			task.Data = updated
+		}
+	}
 	won, err := task.UpdateWithStatus(previousStatus)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
previousStatus := task.Status
task.Status = model.TaskStatusFailure
task.Progress = "100%"
task.FailReason = "cancelled"
task.FinishTime = time.Now().Unix()
won, err := task.UpdateWithStatus(previousStatus)
if err != nil {
respondVolcNativeError(c, http.StatusInternalServerError, "task_update_failed", "failed to update local task")
return
}
if won {
service.RefundTaskQuota(c.Request.Context(), task, "cancelled")
} else {
// A concurrent poll completed the task. Return the durable state and do
// not perform a second refund.
refreshed, exists, refreshErr := model.GetByTaskId(c.GetInt("id"), task.TaskID)
if refreshErr != nil || !exists || refreshed == nil {
respondVolcNativeError(c, http.StatusInternalServerError, "task_refresh_failed", "failed to refresh local task")
return
}
task = refreshed
}
c.Data(http.StatusOK, "application/json", buildVolcNativeTaskResponse(task))
previousStatus := task.Status
task.Status = model.TaskStatusFailure
task.Progress = "100%"
task.FailReason = "cancelled"
task.FinishTime = time.Now().Unix()
if len(task.Data) > 0 && gjson.GetBytes(task.Data, "status").Exists() {
if updated, setErr := sjson.SetBytes(task.Data, "status", "cancelled"); setErr == nil {
task.Data = updated
}
}
won, err := task.UpdateWithStatus(previousStatus)
if err != nil {
respondVolcNativeError(c, http.StatusInternalServerError, "task_update_failed", "failed to update local task")
return
}
if won {
service.RefundTaskQuota(c.Request.Context(), task, "cancelled")
} else {
// A concurrent poll completed the task. Return the durable state and do
// not perform a second refund.
refreshed, exists, refreshErr := model.GetByTaskId(c.GetInt("id"), task.TaskID)
if refreshErr != nil || !exists || refreshed == nil {
respondVolcNativeError(c, http.StatusInternalServerError, "task_refresh_failed", "failed to refresh local task")
return
}
task = refreshed
}
c.Data(http.StatusOK, "application/json", buildVolcNativeTaskResponse(task))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/volc_native.go` around lines 236 - 258, Update the cancellation
flow around the task.Status assignment and buildVolcNativeTaskResponse so
task.Data is rewritten when cancellation succeeds, rather than retaining the
polled upstream status. Ensure the cached payload reflects the local
cancelled/failure state for both the immediate response and later
RelayVolcNativeTaskFetch responses, while preserving the existing durable-state
refresh path when won is false.

Comment on lines +1 to +5
# new-api 品牌替换为「数科 / 大晟」交付报告

> 适用对象:产品经理 / UI / 前后端开发 / 运维
> 分析范围:整仓库静态资源与品牌元素
> 核心原则:**只换"运行时系统标识 + 可定制资源",绝不动"源码层项目 / 组织署名"**

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Refresh the report to match the final branding.

The report targets 数科 / 大晟 and lists New API as current values, including Line 28 and Lines 45-57. This PR ships 晟枢|统一模型服务网关. Update the report before merge, or label it explicitly as a pre-change baseline.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@newapi品牌替换分析.md` around lines 1 - 5, Update the branding replacement report
to reflect the final shipped product branding. Replace all references to "New
API" that appear in Line 28 and Lines 45-57 with "晟枢|统一模型服务网关" to match the
actual delivered product. Ensure the "Current value" column and any example
references throughout the document accurately represent what was shipped rather
than the pre-replacement baseline, so the report serves as an accurate
post-change documentation of the branding migration.

| `web/default/src/lib/constants.ts:24` | `DEFAULT_SYSTEM_NAME = 'New API'` |
| `web/default/src/lib/constants.ts:25` | `DEFAULT_LOGO = '/logo.png'`(保留路径,换文件即可) |
| `web/default/src/features/system-settings/site/index.tsx:30` | 表单默认 `SystemName: 'New API'` |
| `web/default/src/components/layout/components/system-brand.tsx:53` | 末级 fallback `... || 'New API'` |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Make the fallback operator table-safe.

Line 57 contains || inside a two-column table row. markdownlint-cli2 reports four cells. Escape the pipes or rewrite the example in prose so the document passes MD056.

🧰 Tools
🪛 markdownlint-cli2 (0.23.1)

[warning] 57-57: Table column count
Expected: 2; Actual: 4; Too many cells, extra data will be missing

(MD056, table-column-count)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@newapi品牌替换分析.md` at line 57, Update the table entry describing the fallback
in the row referencing system-brand.tsx so the literal || does not create extra
Markdown table cells; escape the pipe characters or rewrite the operator example
in prose, while preserving the documented fallback behavior and ensuring the
document passes MD056.

Source: Linters/SAST tools

Comment on lines +79 to +83
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, taskError(err, "read_response_body_failed", http.StatusInternalServerError)
}
_ = resp.Body.Close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Close resp.Body on every read path.

If io.ReadAll fails, this function returns before Line 83 closes resp.Body. Defer the close immediately after the nil-response check.

Proposed fix
+	defer resp.Body.Close()
 	body, err := io.ReadAll(resp.Body)
 	if err != nil {
 		return "", nil, taskError(err, "read_response_body_failed", http.StatusInternalServerError)
 	}
-	_ = resp.Body.Close()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, taskError(err, "read_response_body_failed", http.StatusInternalServerError)
}
_ = resp.Body.Close()
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, taskError(err, "read_response_body_failed", http.StatusInternalServerError)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@relay/channel/task/volcnative/adaptor.go` around lines 79 - 83, In the
response-handling function, defer closing resp.Body immediately after the
nil-response check and before io.ReadAll, ensuring both successful and failed
read paths release the body; remove the later explicit close if it becomes
redundant.

56: 'Replicate',
57: 'ChatGPT Subscription (Codex)',
58: 'Advanced Custom',
59: 'Volc Native',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Replace the new user-facing literals with translation keys.

Store translation keys in channel metadata. Resolve them with t() at each display site.

  • web/default/src/features/channels/constants.ts#L80-L80: replace Volc Native with a channel-type translation key.
  • web/default/src/features/channels/lib/channel-type-config.ts#L149-L155: replace the channel name and setup hints with translation keys.

As per coding guidelines, “面向用户的文案必须使用 i18n” and constants must store translation keys that are resolved through t().

📍 Affects 2 files
  • web/default/src/features/channels/constants.ts#L80-L80 (this comment)
  • web/default/src/features/channels/lib/channel-type-config.ts#L149-L155
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/features/channels/constants.ts` at line 80, Replace all
user-facing string literals with translation keys to comply with i18n
requirements. In web/default/src/features/channels/constants.ts at line 80,
replace the literal 'Volc Native' with an appropriate translation key constant
(e.g., 'channels.volcNative'). In
web/default/src/features/channels/lib/channel-type-config.ts at lines 149-155,
replace the channel name and setup hints literals with their corresponding
translation keys. Store these translation keys as constants and resolve them
with t() at each display site where the user-facing text is rendered, following
the established i18n pattern in the codebase.

Source: Coding guidelines

id: 59,
name: CHANNEL_TYPES[59],
icon: 'volcengine',
defaultBaseUrl: 'https://ark.cn-beijing.volces.com',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Load the default endpoint from a VITE_ environment variable.

defaultBaseUrl hardcodes deployment configuration in the frontend bundle. Define VITE_VOLC_NATIVE_BASE_URL in .env and read that value here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/features/channels/lib/channel-type-config.ts` at line 151,
Update the defaultBaseUrl configuration in the channel type config to read from
the VITE_VOLC_NATIVE_BASE_URL environment variable instead of hardcoding the
endpoint. Add the variable to .env with the existing default URL and preserve
the current URL as the fallback if the environment value is unavailable.

Source: Coding guidelines

Comment on lines +745 to +749
--primary: oklch(76.1% 0.130 197.3); /* #00CACE 大晟品牌青 */
--primary-hover: oklch(86.1% 0.146 197.5); /* #0AEEF3 悬浮 */
--primary-active: oklch(68.4% 0.116 197.0); /* #00AFB2 点击 */
--primary-foreground: oklch(100% 0 0); /* 主色上的文字用白 */
--ring: oklch(76.1% 0.130 197.3);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use a dark foreground for the light preset.

The light preset uses #00CACE with a white --primary-foreground. This contrast is about 2:1, below the required 4.5:1 contrast for normal text on primary controls. Set a dark foreground and recheck the primary, hover, and active states.

Proposed fix
-  --primary-foreground: oklch(100% 0 0);
+  --primary-foreground: oklch(20.8% 0.011 260.7);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
--primary: oklch(76.1% 0.130 197.3); /* #00CACE 大晟品牌青 */
--primary-hover: oklch(86.1% 0.146 197.5); /* #0AEEF3 悬浮 */
--primary-active: oklch(68.4% 0.116 197.0); /* #00AFB2 点击 */
--primary-foreground: oklch(100% 0 0); /* 主色上的文字用白 */
--ring: oklch(76.1% 0.130 197.3);
--primary: oklch(76.1% 0.130 197.3); /* `#00CACE` 大晟品牌青 */
--primary-hover: oklch(86.1% 0.146 197.5); /* `#0AEEF3` 悬浮 */
--primary-active: oklch(68.4% 0.116 197.0); /* `#00AFB2` 点击 */
--primary-foreground: oklch(20.8% 0.011 260.7);
--ring: oklch(76.1% 0.130 197.3);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/styles/theme-presets.css` around lines 745 - 749, Update the
light preset’s --primary-foreground to a dark color that provides at least 4.5:1
contrast against --primary, and verify the selected foreground also meets the
contrast requirement for --primary-hover and --primary-active while leaving the
existing primary colors unchanged.

Source: Coding guidelines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] 新增独立渠道支持火山方舟 /api/v3/* 原生接口透传

1 participant