Skip to content

h3 - #6662

Open
guanguan669 wants to merge 9 commits into
QuantumNous:mainfrom
guanguan669:feat/kuocai-channel
Open

h3#6662
guanguan669 wants to merge 9 commits into
QuantumNous:mainfrom
guanguan669:feat/kuocai-channel

Conversation

@guanguan669

@guanguan669 guanguan669 commented Aug 5, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

Summary by CodeRabbit

  • New Features

    • Added Kuocai as a supported video-generation channel.
    • Added Kuocai configuration options to the channel management interface.
    • Added video request submission, progress tracking, and completed video retrieval.
    • Added OpenAI-compatible video responses, model discovery, model mapping, metadata, and default settings.
  • Bug Fixes

    • Improved handling of task statuses, result URLs, invalid task IDs, and API errors.
  • Tests

    • Added coverage for request conversion, response parsing, model discovery, and validation.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This change adds Kuocai as channel 61. It registers OpenAI-compatible video mappings, discovers video models from /health, implements task submission and polling, converts results to OpenAI video responses, wires relay dispatch, adds tests, and exposes the channel in the frontend.

Changes

Kuocai video channel

Layer / File(s) Summary
Channel registration and compatibility mappings
common/api_type.go, common/endpoint_type.go, constant/channel.go, web/src/features/channels/constants.ts
Registers Kuocai as channel 61 with its base URL, display name, OpenAI API type, OpenAI video endpoint, and frontend display order.
Kuocai model discovery
controller/channel_upstream_update.go, controller/channel_upstream_update_test.go
Queries /health, filters non-empty video model keys, normalizes model names, and validates response errors.
Request construction and task submission
relay/channel/task/kuocai/adaptor.go, relay/channel/task/kuocai/adaptor_test.go
Defines Kuocai request and response structures, applies defaults and model validation, submits authenticated tasks, and returns pending OpenAI-compatible video data.
Task polling, result conversion, and relay wiring
relay/channel/task/kuocai/adaptor.go, relay/relay_adaptor.go, relay/channel/task/kuocai/adaptor_test.go
Polls task status, parses alternate response shapes, normalizes progress and status values, serializes completed videos, dispatches channel 61 to the adaptor, and validates result parsing.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant RelayAdaptor
  participant TaskAdaptor
  participant KuocaiAPI

  Client->>RelayAdaptor: Submit video request
  RelayAdaptor->>TaskAdaptor: Build and send Kuocai task
  TaskAdaptor->>KuocaiAPI: Authenticated task submission
  KuocaiAPI-->>TaskAdaptor: Task ID and pending status
  TaskAdaptor-->>Client: OpenAI-compatible pending video

  Client->>TaskAdaptor: Fetch task by task ID
  TaskAdaptor->>KuocaiAPI: Authenticated task polling request
  KuocaiAPI-->>TaskAdaptor: Status, progress, and result URL
  TaskAdaptor-->>Client: OpenAI-compatible video result
Loading

Possibly related PRs

Suggested reviewers: calcium-ion

Poem

A rabbit maps channel sixty-one,
Then sends a video task to run.
It polls the task and tracks the flow,
Finds the URL when results show.
OpenAI-shaped data hops in view. 🐇

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title "h3" does not describe the Kuocai channel implementation or any other change in the pull request. Replace "h3" with a concise title that identifies the addition of Kuocai channel support.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

Inline comments:
In `@relay/channel/task/kuocai/adaptor_test.go`:
- Around line 18-30: The TestConvertRequestUsesConfiguredNumericModelID test
should include metadata containing model_id set to 39 while the configured model
mapping remains "51", then assert body.ModelID is still 51 after convertRequest.
Keep the existing assertions for duration, count, and resolution unchanged.

In `@relay/channel/task/kuocai/adaptor.go`:
- Around line 35-48: Update the request struct containing ModelID, Size,
Seconds, Resolution, and Count so optional scalar fields use pointer types with
omitempty, preserving explicit zero and empty-string values during
common.Marshal; keep pointers nil only when metadata is absent. Apply the same
treatment to any other optional scalar fields in this struct, while retaining
existing non-scalar fields and tags.
🪄 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: b6659591-dbc2-43db-8fde-d826f4fad617

📥 Commits

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

📒 Files selected for processing (7)
  • common/api_type.go
  • common/endpoint_type.go
  • constant/channel.go
  • relay/channel/task/kuocai/adaptor.go
  • relay/channel/task/kuocai/adaptor_test.go
  • relay/relay_adaptor.go
  • web/src/features/channels/constants.ts

Comment on lines +18 to +30
func TestConvertRequestUsesConfiguredNumericModelID(t *testing.T) {
body, err := convertRequest(relaycommon.TaskSubmitReq{
Prompt: "A sunset over the sea",
Size: "16:9",
Duration: 8,
Metadata: map[string]interface{}{"resolution": "720P", "count": 2},
}, "51")
require.NoError(t, err)
require.Equal(t, 51, body.ModelID)
require.Equal(t, 8, body.Seconds)
require.Equal(t, 2, body.Count)
require.Equal(t, "720P", body.Resolution)
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Test metadata cannot override the configured model ID.

Add a case with metadata model_id: 39 and configured model mapping "51". Assert that body.ModelID remains 51.

This protects the configured upstream model selection after metadata unmarshaling.

As per coding guidelines, “Backend tests must protect real behavior, API contracts, billing/accounting invariants, compatibility, or regression paths.”

🤖 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/kuocai/adaptor_test.go` around lines 18 - 30, The
TestConvertRequestUsesConfiguredNumericModelID test should include metadata
containing model_id set to 39 while the configured model mapping remains "51",
then assert body.ModelID is still 51 after convertRequest. Keep the existing
assertions for duration, count, and resolution unchanged.

Source: Coding guidelines

Comment on lines +35 to +48
ModelID int `json:"model_id,omitempty"`
Prompt string `json:"prompt"`
Size string `json:"size,omitempty"`
Seconds int `json:"seconds,omitempty"`
Resolution string `json:"resolution,omitempty"`
Count int `json:"count,omitempty"`
ReferenceImage string `json:"reference_image,omitempty"`
ReferenceImages []string `json:"reference_images,omitempty"`
FrameStart string `json:"frame_start,omitempty"`
FrameEnd string `json:"frame_end,omitempty"`
ReferenceAudio string `json:"reference_audio,omitempty"`
ReferenceAudios []string `json:"reference_audios,omitempty"`
ReferenceVideo string `json:"reference_video,omitempty"`
ReferenceVideos []string `json:"reference_videos,omitempty"`

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

Preserve explicit optional scalar values.

These fields combine non-pointer scalar types with omitempty. An explicit metadata value such as count: 0, seconds: 0, or resolution: "" is dropped when common.Marshal creates the upstream request.

Use pointer types for optional scalar fields. Set nil only when the field is absent. Remove omitempty from fields that must always be sent.

As per coding guidelines, “Optional scalar fields in client-parsed and upstream-remarshaled request structs must use pointer types with omitempty.”

🤖 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/kuocai/adaptor.go` around lines 35 - 48, Update the
request struct containing ModelID, Size, Seconds, Resolution, and Count so
optional scalar fields use pointer types with omitempty, preserving explicit
zero and empty-string values during common.Marshal; keep pointers nil only when
metadata is absent. Apply the same treatment to any other optional scalar fields
in this struct, while retaining existing non-scalar fields and tags.

Source: Coding guidelines

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
controller/channel_upstream_update_test.go (1)

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

Strengthen the Kuocai discovery contract test.

Initialize the channel setting explicitly before calling fetchChannelUpstreamModelIDs; this path reaches channel.GetSetting().Proxy. Also assert r.Method == http.MethodGet and add deterministic cases for malformed JSON, non-200 HTTP or application status, no video models, and non-positive model_id values. The current test covers only the successful response.

As per coding guidelines, backend tests must initialize settings explicitly and protect real behavior with deterministic contract coverage.

🤖 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/channel_upstream_update_test.go` around lines 411 - 437,
Strengthen TestFetchKuocaiModelsUsesHealthAndExcludesImages by initializing the
channel’s setting before calling fetchChannelUpstreamModelIDs, and assert the
health request uses http.MethodGet. Add deterministic table-driven coverage for
malformed JSON, non-200 HTTP/application status, no video models, and
non-positive model_id values, verifying the expected error or empty result for
each case.

Source: Coding guidelines

🤖 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 `@controller/channel_upstream_update.go`:
- Around line 433-443: Bound the Kuocai health request in
fetchKuocaiUpstreamModelIDs so it cannot stall indefinitely, using a
timeout-aware request/client path for getFetchModelsResponseBody. Before
common.Unmarshal processes the response, cap the readable body size and reject
oversized payloads rather than loading the full response into memory. Preserve
the existing error propagation for request and decoding failures.

---

Nitpick comments:
In `@controller/channel_upstream_update_test.go`:
- Around line 411-437: Strengthen
TestFetchKuocaiModelsUsesHealthAndExcludesImages by initializing the channel’s
setting before calling fetchChannelUpstreamModelIDs, and assert the health
request uses http.MethodGet. Add deterministic table-driven coverage for
malformed JSON, non-200 HTTP/application status, no video models, and
non-positive model_id values, verifying the expected error or empty result for
each case.
🪄 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: 52db11f1-ca0d-4139-b478-4babba569486

📥 Commits

Reviewing files that changed from the base of the PR and between ef6c6b0 and 5a53af4.

📒 Files selected for processing (2)
  • controller/channel_upstream_update.go
  • controller/channel_upstream_update_test.go

Comment on lines +433 to +443
func fetchKuocaiUpstreamModelIDs(channel *model.Channel, baseURL string) ([]string, error) {
body, err := getFetchModelsResponseBody(
http.MethodGet,
strings.TrimRight(baseURL, "/")+"/health",
channel,
http.Header{},
)
if err != nil {
return nil, err
}

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
set -euo pipefail

rg -n -C 10 'func NewProxyHttpClient|NewProxyHttpClient|io\.ReadAll' --glob '*.go'

Repository: QuantumNous/new-api

Length of output: 157


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Go files matching likely names:\n'
fd -e go . | sed -n '1,120p'

printf '\nFind file:\n'
fd 'channel_upstream_update\.go$|.*channel.*upstream.*\.go$|.*proxy.*http.*\.go$|.*service.*\.go$' . -d 4

printf '\nSearch exact symbols and request helpers:\n'
rg -n -C 8 'fetchKuocaiUpstreamModelIDs|getFetchModelsResponseBody|FetchUpstreamModels|ReadAll|NewClient|Timeout|context\.Deadline|context\.WithTimeout|http\.Request' --glob '*.go' | sed -n '1,240p'

Repository: QuantumNous/new-api

Length of output: 3300


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'channel_upstream_update outline:\n'
ast-grep outline controller/channel_upstream_update.go --view compact || true

printf '\nRelevant controller sections:\n'
rg -n -C 15 'fetchKuocaiUpstreamModelIDs|getFetchModelsResponseBody|FetchUpstreamModels|service\.NewProxyHttpClient|NewProxyHttpClient|ReadAll|NewRequestWithContext|Timeout|context\.WithTimeout' controller/channel_upstream_update.go common service relay --glob '*.go' | sed -n '1,320p'

printf '\nRead target file length and focused sections:\n'
wc -l controller/channel_upstream_update.go
sed -n '1,140p' controller/channel_upstream_update.go
sed -n '380,490p' controller/channel_upstream_update.go
sed -n '490,540p' controller/channel_upstream_update.go

Repository: QuantumNous/new-api

Length of output: 28339


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'service.go files:\n'
fd -e go . | rg '/service/|/service' || true

printf '\nSearch NewProxyHttpClient in all tracked files:\n'
git ls-files | xargs rg -n -C 12 'func NewProxyHttpClient|NewProxyHttpClient|ProxyHttpClient'\
  | sed -n '1,260p'

printf '\nSearch response body limits in channel_upstream_update and common:\n'
rg -n -C 8 'ReadAll|LimitReader|max.*response|response.*limit|ReadCloser|NewProxyHttpClient|context\.WithTimeout|context\.Deadline' --glob '*.go' controller/common | sed -n '1,320p'

Repository: QuantumNous/new-api

Length of output: 4811


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'service/http_client relevant sections:\n'
wc -l service/http_client.go
sed -n '1,180p' service/http_client.go
sed -n '360,455p' service/http_client.go

printf '\nGetHttpClientWithProxy and transport policy callers:\n'
rg -n -C 8 'func GetHttpClientWithProxy|defaultHTTPTransportPolicy|HTTPTimeout|Timeout|IdleConnTimeout|MaxIdleConnsPerHost|MaxConnsPerHost' service relay controller --glob '*.go' | sed -n '1,400p'

Repository: QuantumNous/new-api

Length of output: 34370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'service/http_client.go mid-section:\n'
sed -n '180,355p' service/http_client.go

printf '\nservice/http_client.go later sections:\n'
sed -n '355,446p' service/http_client.go

printf '\nFetch models endpoint for Kuocai /health:\n'
rg -n -C 6 'ChannelTypeKuocai|kuocai|/health|fetchKuocaiUpstreamModelIDs|FetchUpstreamModels' controller/common service relay --glob '*.go' | sed -n '1,260p'

printf '\nRelevant controller test references:\n'
rg -n -C 8 'Kuocai|fetchKuocaiUpstreamModelIDs|health|FetchUpstreamModels' controller/channel_upstream_update_test.go --glob '*.go' | sed -n '1,220p'

Repository: QuantumNous/new-api

Length of output: 13294


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'http transport/policy definitions:\n'
rg -n -C 12 'type HTTPTransportPolicy|defaultHTTPTransportPolicy|NormalizeHTTPTransportPolicy|HTTPTimeout|ClientTimeout|Timeout|RespBodyLimit|applyHTTPTransportPolicy' --glob '*.go' service common relaykit setting constant --glob '*.go' | sed -n '1,320p'

printf '\nAll response body reader helper patterns:\n'
rg -n -C 8 'ReadAll|io\.LimitReader|RespBodyLimit|Max.*Response|response.*size|body.*limit|ReadCloser' --glob '*.go' controller service relaykit relay common constant setting | sed -n '1,400p'

printf '\nFetchUpstreamModels callers:\n'
rg -n -C 12 'FetchUpstreamModels|ctx, cancel := context\.WithTimeout|time\.After|go\s+collect' --glob '*.go' controller service relaykit relay common | sed -n '1,260p'

Repository: QuantumNous/new-api

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'http transport policy struct and implementation:\n'
rg -n -C 16 'type HTTPTransportPolicy struct|HTTPTimeout|ClientTimeout|ApplyHTTPTransportPolicy|applyHTTPTransportPolicy|ResetTimeout|DialContext|TLSHandshakeTimeout' service/http_client.go --glob '*.go' | sed -n '1,320p'

printf '\nRelevant service/http_client.go ranges around transport factory implementation:\n'
wc -l service/http_client.go
sed -n '230,330p' service/http_client.go
sed -n '360,425p' service/http_client.go

printf '\ncontroller/channel_upstream_update.go relevant handler range:\n'
sed -n '540,740p' controller/channel_upstream_update.go

Repository: QuantumNous/new-api

Length of output: 17141


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'http_client.go top-level imports and policy-related symbols:\n'
sed -n '1,85p' service/http_client.go
rg -n -C 10 'type HTTPTransportPolicy struct|HTTPHTTP1|HTTP2|HTTP3|HTTPS|Timeout|ResponseHeaderTimeout|DisableCompression|MaxIdleConns|EnableCompression|ResetTimeout|ResetIdleConnTimeout|Dialer|context\.WithTimeout|DialContext' service/http_client.go --glob '*.go' | sed -n '1,420p'

printf '\nSearch for transport policy file or DTO:\n'
fd -e go . | rg 'http_client|transport|policy|dto' | sed -n '1,120p'
rg -n -C 8 'DefaultHTTPTimeout|HTTPTimeout|MaxIdleConnTimeout|HTTPIdleConnTimeout|HTTP2|HTTP3|HTTP1' --glob '*.go' | sed -n '1,320p'

Repository: QuantumNous/new-api

Length of output: 7220


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'service/http_transport_policy.go:\n'
sed -n '1,240p' service/http_transport_policy.go

printf '\nservice/http_transport_sharded.go relevant range:\n'
sed -n '1,220p' service/http_transport_sharded.go

printf '\nchannel_upstream_update FetchUpstreamModels exact section:\n'
rg -n -C 20 'func FetchUpstreamModels|runChannelUpstreamModelUpdateTaskOnce|collectPendingUpstreamModelChanges|FetchUpstreamModels' controller/channel_upstream_update.go | sed -n '1,260p'

printf '\ncontroller/channel_upstream_update_test Kuocai/model fetch tests:\n'
rg -n -C 20 'kuocai|Kuocai|health|FetchUpstreamModels|upstream model' controller/channel_upstream_update_test.go | sed -n '1,260p'

Repository: QuantumNous/new-api

Length of output: 14963


Bound the Kuocai health response before unmarshaling.

getFetchModelsResponseBody uses a client with no configured Timeout, so the synchronous Cuocai /health request can stall indefinitely. Also, line 333 reads the full response.Body into memory; use a response-size limit before common.Unmarshal.

🤖 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/channel_upstream_update.go` around lines 433 - 443, Bound the
Kuocai health request in fetchKuocaiUpstreamModelIDs so it cannot stall
indefinitely, using a timeout-aware request/client path for
getFetchModelsResponseBody. Before common.Unmarshal processes the response, cap
the readable body size and reject oversized payloads rather than loading the
full response into memory. Preserve the existing error propagation for request
and decoding failures.

@coderabbitai coderabbitai Bot mentioned this pull request Aug 5, 2026
@Calcium-Ion
Calcium-Ion force-pushed the main branch 2 times, most recently from 51fdfc5 to 2b6f1df Compare August 30, 2026 15:03

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant