Skip to content

fix(deepseek): declare Responses and Anthropic endpoints - #88

Merged
mergify[bot] merged 1 commit into
suanova:mainfrom
skeeey:fix/deepseek-endpoint-types
Sep 16, 2026
Merged

mergify[bot] merged 1 commit into
suanova:mainfrom
skeeey:fix/deepseek-endpoint-types

Conversation

@skeeey

@skeeey skeeey commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Agent

  • Tool: Claude Code
  • Tool version: 2.1.263
  • Model (full id): deepseek-v4-flash[1m]
  • Host (CLI / IDE / GitHub coding agent / other): CLI
  • Date (UTC): 2026-09-15

Links

  • Closes #
  • Related:

无关联 issue。本 PR 由仓库维护者在本地核对 DeepSeek 渠道端点声明时发现,未先开 issue。

User request

(原话)

看下 deepseek 的渠道,这个渠道应该是 chat/response/message 都支持的吧?

但是这个渠道默认的端点只有 chat?

加

OK,我们先把 deepseek 的那个 fix 提个 pr 吧,注意用新分支哈

Out of scope — refuse

  • Matched: no
  • If yes, what was told to the user (stop here; do not open a PR):

不适用。这是既有端点声明表(渠道类型 → 端点类型)的一处遗漏,不属于 Coding Plan / 逆向渠道 / 第三方包装 / Codex / 纯透传 / 第三方托管 / 使用配置咨询。

Kind

  • Bug fix
  • New feature
  • Performance / refactor
  • Docs
  • Other:

Issue facts

无关联 issue,以下事实来自本次排查(代码定位 + 本地实例实测)。

  • Actual behavior: common.GetEndpointTypesByChannelType 没有 ChannelTypeDeepSeek(渠道类型 43)分支,落到 default(common/endpoint_type.go:61-66),因此所有 deepseek-* 模型声明的 supported_endpoint_types 只有 ["openai"]。而 relay/channel/deepseek/adaptor.go:59-77 的 GetRequestURL 已经按格式分别拼出三个上游地址:{base}/v1/chat/completions、{base}/responses、{base}/anthropic/v1/messages。
  • Impact: 模型广场的端点类型筛选把 DeepSeek 模型只归到 Chat;模型卡片/详情的「端点」只显示 openai;后台模型元信息页 endpoints 默认值同此;GET /v1/models 返回的 supported_endpoint_types 同样只有 openai,读该字段决定用哪个协议调的客户端会认为 Responses / Messages 不可用。注意该表不参与路由:选渠道仍按 model + group,格式由客户端请求路径决定,因此这是声明与实际能力不一致,不是转发失败。
  • Frequency: 100%。渠道类型 43 上的所有模型恒定如此,与模型名、分组无关。
  • Evidence that the problem is in new-api rather than the client or upstream:
    • 同仓库中形态相同的渠道都已登记:ChannelTypeXai → [openai, openai-response]、ChannelTypeAnthropic → [anthropic, openai](common/endpoint_type.go:19-30),仅 DeepSeek 缺失。
    • 该表是唯一来源,且被 /v1/models(controller/model.go:178)与模型元信息页(controller/model_meta.go:203)直接消费。
    • 本地实例实测(见 Verification):打完补丁后 GET /api/pricing 对该模型返回 ["openai","openai-response","anthropic"],模型广场端点筛选随之变成 Chat 1 / Response 1 / Anthropic 1,说明差异确实产生在本仓库的这张表里。
  • Applicable types and their fields (relay / billing / frontend / deployment; write "not applicable" otherwise):
    • relay:不适用。该表不参与转发决策,GetEndpointTypesByChannelType 在 relay 路径下无调用点(全仓引用见 Research)。
    • billing:不适用。计费按模型倍率与 usage 计算,与端点声明无关。
    • frontend:适用。模型广场的端点筛选(web/src/features/pricing/lib/filters.ts:104、components/pricing-sidebar.tsx:255)、模型卡片(model-card.tsx:70)、模型详情(model-details.tsx:519)、列表列(pricing-columns.tsx:411),以及后台模型页 endpoints 默认值。
    • deployment:不适用。

Change

common/endpoint_type.go 增加 DeepSeek 分支:

case constant.ChannelTypeDeepSeek:
	// DeepSeek 同时提供 OpenAI chat、Responses 与 Anthropic messages 端点,
	// 见 relay/channel/deepseek/adaptor.go 的 GetRequestURL。
	endpointTypes = []constant.EndpointType{
		constant.EndpointTypeOpenAI,
		constant.EndpointTypeOpenAIResponse,
		constant.EndpointTypeAnthropic,
	}

openai 放第一位:model/pricing.go:277 的注释与实现都以「第一个端点是优先使用端点」为前提,而 chat 是 DeepSeek 的原生端点。

没有走「在模型表里给 deepseek-* 配 endpoints」的绕行方案,原因见 Research/Alternatives。

relaykit 未改动:EndpointType 的常量定义在 relaykit/types,但本 PR 只增加 host 侧 common 包的分支,不触碰 relaykit 的公开 API。

Research

Duplicate / prior art

  • Search queries (issues, PRs):
    • gh search prs --repo suanova/cuberouter "endpoint type"
    • gh search issues --repo suanova/cuberouter "supported_endpoint_types"
    • gh search prs --repo suanova/cuberouter "deepseek"
    • git log --oneline -- common/endpoint_type.go
  • What already existed and why this is not a duplicate: 以上检索均无命中同类改动。common/endpoint_type.go 的历次改动只有 AstraFlow 多模型端点(3682cca、676fabc)与渠道拆分,均为别的渠道类型,DeepSeek 分支从未存在。

Docs and code

Open them. Do not write "already checked" without sources.

  • https://docs.newapi.ai/ : 未取到正文。 WebFetch 返回「Unable to verify if domain docs.newapi.ai is safe to fetch」,域名策略拦截,未能核对。本仓库文档(README*.md、docs/)中也没有端点类型表的说明。
  • https://deepwiki.com/QuantumNous/new-api : 未取到正文。 同上,域名策略拦截。
  • README / repo docs: 无相关章节。仓库内该表的唯一权威来源即 common/endpoint_type.go 本身,配套测试在同目录 endpoint_type_test.go,其中已有 TestAstraFlowChannelRegistration、TestDoubaoVideoChannelRegistration、TestAstraFlowEndpointTypeDiffersFromOpenAIVideo 等逐渠道契约测试,说明这张表是被维护的契约而非随手填的展示数据。
  • Code paths and what they imply for this change:
    • common/GetEndpointTypesByChannelType(common/endpoint_type.go:6):声明表本体,本 PR 改动点。
    • model/pricing.go:115-123 getPricingEndpointTypesForAbility → model/pricing.go:278-320 汇总进 modelSupportEndpointTypes → model/pricing.go:368 写入 Pricing.SupportedEndpointTypes。
    • controller/model.go:178:/v1/models 的 supported_endpoint_types。
    • controller/model_meta.go:203、:249:模型元信息页 endpoints 字段的默认值与规则模型并集。
    • 全仓检索 modelSupportEndpointTypes / SupportedEndpointTypes / EndpointTypeOpenAIResponse 等常量后确认:relay 侧没有任何调用点会依据该表放行或拒绝请求,唯一在 relay 相关代码里的用法是 controller/channel-test.go 的端点下拉与默认值(与渠道类型无关)。

Alternatives considered

  • Option A: 不改代码,在模型表里给 deepseek-* 配 endpoints。model/pricing.go:295-310 的自定义端点是追加到推断结果、不裁剪渠道真实能力,所以技术上可行。但每个渠道的每个模型都要手工维护,新模型持续漏配,且 default 分支的推断结果本来就与实际能力不符——治标不治本。
  • Option B: 让 default 分支直接返回全部端点类型。一行改动,但会让所有未登记的渠道(含只支持 chat 的第三方中转)都宣称支持 Responses / Anthropic,影响面远大于本问题。
  • Why this approach: 渠道分支是该表既有的组织方式(xai / anthropic / astraflow / codex 都这么写),作用域精确限定在渠道类型 43,且能配一条稳定的契约测试。改动 8 行 + 12 行测试。

Files

Path Why
common/endpoint_type.go 增加 ChannelTypeDeepSeek 分支,声明三种端点类型
common/endpoint_type_test.go 新增 TestDeepSeekChannelRegistration,锁定渠道 43 → 三种端点的契约

Behavior

  • Before: 渠道类型 43 上的模型 supported_endpoint_types = ["openai"]。
  • After: ["openai","openai-response","anthropic"];/v1/models、模型广场端点筛选/卡片/详情、后台模型页 endpoints 默认值同步显示三种。
  • Explicit non-goals / leftover work: 不改转发行为(该表不参与路由);不改 DeepSeek 适配器的三个 URL 与请求/响应转换;不处理阿里百炼(17)、星图(59)等其它渠道的同类型声明缺口——排查中发现它们同样与实际能力不一致(百炼实际支持 responses / messages / embeddings / rerank / 生图,星图实际支持 messages),但那两个的声明需要模型级条件判断,适合另开 PR。

Verification

Only what was actually run.

  • Commands and results:
    • go build ./... → 通过
    • go test ./common/ -count=1 → ok github.com/QuantumNous/new-api/common(含新增用例与同文件既有的 AstraFlow / DoubaoVideo / Sora 契约测试全部通过)
    • go test ./common/ -run 'TestDeepSeekChannelRegistration|TestAstraFlow|TestDoubaoVideo|TestVideoOnly' -count=1 -v → 全部 PASS
    • cd relaykit && GOWORK=off go build ./... → 通过(relaykit 未改动,仅做独立可构建性确认)
  • Manual steps and observed result: 本地起了一个实例做实测,使用独立 SQLite 库(/tmp/cuberouter-run/one-api.db,未触碰仓库内的 one-api.db)。新建渠道 type=43、base_url=https://api.deepseek.com、key 为假值,models=deepseek-v4-flash;随后 GET /api/pricing 返回 "supported_endpoint_types":["openai","openai-response","anthropic"]。该调用链路由 model/pricing.go 的推断路径产生,未依赖任何模型表 endpoints 配置。
  • UI: screenshot or recording (or why none): 有截图(模型广场 → deepseek-v4-flash → 详情,「端点」一栏显示 openai openai-response anthropic 三个 chip;左侧端点类型筛选同时变为 Chat 1 / Response 1 / Anthropic 1)。截图保存在本地排查目录,未随 PR 附件上传。
  • Tests added or updated, or why none: 新增 TestDeepSeekChannelRegistration(common/endpoint_type_test.go),锁定渠道 43 → [openai, openai-response, anthropic] 的映射,沿用了同文件 AstraFlow / DoubaoVideo 的注册契约测试写法。
  • Databases / providers / platforms exercised: SQLite(本地实例)。本改动不涉及模型、迁移、约束、raw SQL 或 GORM 行为,故未跑三库矩阵;MySQL / PostgreSQL 未验证。
  • Not verified: 未用真实 DeepSeek key 端到端调用过三个端点。 本地渠道的 key 是假值,只验证了声明与展示链路。因此这两点仍属未验证:① 上游确实在 {base}/responses(注意该路径没有 /v1 前缀)与 {base}/anthropic/v1/messages 提供服务;② DeepSeek 的 Anthropic 兼容端点是否需要 anthropic-version 头——relay/channel/deepseek/adaptor.go:79-83 只发 Authorization: Bearer,不带 x-api-key 与 anthropic-version。

Risks

  • Failure modes: 若上游实际未提供 Responses 或 Anthropic 端点,本次声明属于「声明超出能力」。由于该表不参与路由,影响限于展示与客户端选择(客户端可能据 /v1/models 用 messages 调 DeepSeek)。如需回退,删除该分支即可,无数据迁移。
  • Billing / quota / auth impact: 无。不涉及计费路径、配额换算、鉴权头或凭证处理。
  • Follow-ups: ① 用真实 DeepSeek key 验证 /responses 与 /anthropic/v1/messages 两条路径,并确认是否需要补 anthropic-version;② 阿里百炼(17)与星图(59)的端点声明同样与实际能力不一致,可另开 PR(需要按模型名分支,且百炼的 anthropic 判定函数在 relay/channel/ali 内,common 反向引用会成环,需先定口径)。

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex): no

Summary by CodeRabbit

  • New Features

    • DeepSeek integrations now support OpenAI chat, OpenAI Responses, and Anthropic Messages endpoint types.
  • Bug Fixes

    • Corrected endpoint capability detection so DeepSeek models expose all supported request formats.

GetEndpointTypesByChannelType had no DeepSeek branch, so channel type 43
fell through to the default case and every deepseek-* model declared
["openai"] as its supported endpoint types. The DeepSeek adaptor already
serves three protocols, each with its own upstream URL built in
GetRequestURL: /v1/chat/completions, /responses, and
/anthropic/v1/messages.

That declaration is metadata. It feeds the /v1/models response, the
endpoints default on the model meta page, and the pricing page's endpoint
filter, cards and detail view. It does not gate relay routing, which picks
a channel by model and group and takes the format from the client's
request path. The visible effect was a pricing page listing deepseek
models under Chat only, and clients reading /v1/models concluding that
Responses and Messages were unavailable.

The channel now declares the three endpoint types, matching xai's
[openai, openai-response] and anthropic's [anthropic, openai]. OpenAI
stays first because pricing treats the first entry as the preferred
endpoint.

Co-authored-by: Wei Liu <[email protected]>
Co-Authored-By: Claude Code <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 7e8d806f-4b82-49b6-8618-e6f8027a4c27

📥 Commits

Reviewing files that changed from the base of the PR and between 7805f33 and 96f3629.

📒 Files selected for processing (2)
  • common/endpoint_type.go
  • common/endpoint_type_test.go

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

DeepSeek channel registration now returns OpenAI, OpenAI Responses, and Anthropic endpoint types. A test verifies this mapping for deepseek-v4-pro.

Changes

DeepSeek endpoint registration

Layer / File(s) Summary
Endpoint mapping and validation
common/endpoint_type.go, common/endpoint_type_test.go
DeepSeek now maps to EndpointTypeOpenAI, EndpointTypeOpenAIResponse, and EndpointTypeAnthropic. The test verifies the exact mapping.

Priority: ⬇️ Low

Estimated code review effort: 1 (Trivial) | ~5 minutes

Change: Bug fix

Suggested reviewers: clyang82

Merge Risk: ⚪ Minimal · up to 96f36

The metadata-only registration correctly exposes DeepSeek's supported endpoints without introducing a concrete merge-blocking risk.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding DeepSeek support declarations for Responses and Anthropic endpoints.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files.
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.

@mergify
mergify Bot merged commit c304b77 into suanova:main Sep 16, 2026
7 checks passed
@mergify

mergify Bot commented Sep 16, 2026

Copy link
Copy Markdown

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

mergify Bot pushed a commit that referenced this pull request Sep 24, 2026
* Port from develop 9525343+3fc95ec: aggregated API create-user remark support

Port the remark field for the aggregated create-user API from the
searouter-isuanova develop branch:

- 9525343 feat(#88): 聚合API创建用户支持 remark 字段
- 3fc95ec fix(#89): remark 拼接超长时截断为 255 字符

- AggregatedCreateUserRequest: new remark field (max 255 chars,
  TrimSpace'd); written to User.Remark at insert time
- buildCreateUserRemark: combines user remark with user_validity as
  "remark;账户有效期至 YYYY-MM-DD" without overwriting user remark
- capRemarkRunes: truncates the combined value to 255 runes so the
  varchar(255) column is never exceeded (#89, decision: truncate,
  do not reject)
- Ported unit tests (controller/aggregated_api_remark_test.go)
- Swagger artifacts regenerated (docs.go/swagger.json/swagger.yaml)

Verified with go build + controller tests (TestBuildCreateUserRemark,
swagger gate tests).

Co-Authored-By: Claude <[email protected]>

* Port from develop 43ef0df: unify username/email 50-char limit with per-layer checks

Port Issue #91 from the searouter-isuanova develop branch:

- AggregatedCreateUser: reject username/email over 50 chars
- SendEmailVerification / SendPasswordResetEmail: email max=50 with
  user.email_too_long i18n error (adapting to this repo's
  NormalizeEmail + ApiErrorI18n style)
- EmailBind: length check before verification-code validation
- Frontend: maxLength={50} on sign-up email, forgot-password email,
  email-bind dialog email, and admin user create/edit username inputs

The model-layer validate:"max=50" baseline already exists in this
repo (User.Username/User.Email); this commit adds the controller-layer
early rejection and the frontend input constraints.

Verified with go build + controller tests + tsgo typecheck.

Co-Authored-By: Claude <[email protected]>

* Port from develop 4233420: token quota input uses native quota directly

Port Issue #96 from the searouter-isuanova develop branch: the API key
create/edit quota input now takes the native quota number directly
instead of a currency amount converted client-side.

- api-key-form.ts: form field remain_quota_dollars -> remain_quota
  (non-negative integer, default 0); payload sends the raw value
  (backend already accepts native remain_quota); edit-mode prefill
  reads apiKey.remain_quota as-is; removed parseQuotaFromDollars /
  quotaUnitsToDollars conversion
- api-keys-mutate-drawer.tsx: quota label/placeholder/description
  switched to native-token wording, input min=0 step=1; removed the
  currency display logic
- i18n: added native-quota keys to en/zh/zh-TW (obfuscated
  footer.newapi attribution key untouched)

Related items from the same source batch verified as already covered
in this codebase, no changes needed:
- #82 (dd740a8, no converted-amount hint under the quota input): this
  drawer never rendered such a hint
- #87 (7877fc3, hide group selector, token defaults to user group):
  SHOW_KEY_GROUP_SELECTOR is already false with DEFAULT_GROUP = '',
  and the token auth middleware falls back to the account group when
  token.Group is empty

Verified with tsgo typecheck + keys feature tests (29 passed).

Co-Authored-By: Claude <[email protected]>

* Port from develop 954b714: billing report API user param username -> user_id

Port the breaking API change from the searouter-isuanova develop branch:
GET /data/billing and GET /ops/data/billing now take ?user_id=<bigint>
instead of ?username=<string>.

- parseBillingUserId helper: empty/non-integer/non-positive -> 400
- GetUserBillingReport / GetOpsBillingReport: resolve the user by ID
  (primary-key lookup); ops permission check (inviter only) unchanged
- GetUserBillingAgg: filter logs by user_id instead of username
  (index-friendly; avoids same-username ambiguity)
- Ported model test (in-memory SQLite): same-username-different-ID
  filtering and invalid-ID cases; adapted to this repo's Log model
  (no CacheTokens column, matching the existing 0 AS cache_tokens
  select)

BREAKING CHANGE: callers must switch ?username=xxx to ?user_id=123

Verified with go build + model billing tests.

Co-Authored-By: Claude <[email protected]>

* Port from develop 0fb2d5d: ops read-only access to user management and logs (backend)

Port the backend half of the ops-readonly feature from the
searouter-isuanova develop branch:

- User management routes split into a read group (OpsAuth) and a
  write group (AdminAuth): ops can list/search/view users, topups,
  columns, invitees, quota-dates, oauth bindings and 2FA stats;
  create/manage/update/delete/export/2FA-disable remain admin-only
- Log read routes (GET /, /stat, /channel_affinity_usage_cache)
  opened to OpsAuth for read-only ops auditing; /search stays
  admin-only (this repo has no log DELETE route; log cleanup goes
  through the performance route)

Frontend half (route guard, read-only users page, sidebar entry,
usage-logs full-data mode for ops) to follow in a separate commit.

Verified with go build + router/middleware tests.

Co-Authored-By: Claude <[email protected]>

* Port from develop 3eb59a8: dashboard model consumption charts use native quota, drop statistical-quota card

Source commit: 3eb59a8 (searouter-isuanova develop, feat(#84): 数据看板改为原生额度显示并移除统计额度卡片)

Changes in this shadcn codebase:
- New hook useSubscriptionNativeQuota (dashboard/hooks): sums
  remain/used native quota over ACTIVE subscriptions; self endpoint
  (/api/subscription/self) vs admin endpoint
  (/api/subscription/admin/users/:id/subscriptions). Exported for
  subscription-quota display and the upcoming summary revamp.
- lib/charts.ts processChartData: model consumption distribution
  bar/area charts now plot raw quota values (y-axis, tooltips and the
  total header use thousands-separated native numbers); the currency
  conversion for these charts is removed. processUserChartData keeps
  its currency display (out of scope, unchanged).
- use-dashboard-config: removed the "Total Quota" (统计额度) stat card
  from the model analytics stat row (5 -> 4 cards); log-stat-cards and
  the index.tsx fallback grid follow (grid-cols-5 -> grid-cols-4).

Notes:
- The source commit also switched the account-data cards (当前余额/
  历史消耗) to native quota; that intermediate state was reverted by
  #95 (ff211b1) back to wallet-amount display. The target SummaryCards
  already display wallet quota via formatQuota (amount), so no
  account-card change is made here (see the #95 port commit).
- The source commit's UserDataDashboard isViewingOtherUser wiring has
  no counterpart in the target dashboard architecture (there is no
  per-user data-dashboard section); the hook covers the admin path via
  its userId parameter.

Co-Authored-By: Claude <[email protected]>

* Port from develop 7d8bf54: dashboard current-balance card topup button — already equivalent, no change

Source commit: 7d8bf54 (searouter-isuanova develop, fix: 数据看板当前余额项移除充值按钮 (#85))

The source commit removed the 充值 (top-up) Tag rendered next to the
当前余额 card in StatsCards, plus its navigation to /console/topup and
the now-unused showTopupAction prop.

Already equivalently covered in the target: the redesigned dashboard's
balance surfaces (overview SummaryCards / Credit remaining panel) never
had a top-up action — the only nearby control is the "Wallet" link
button, a section link rather than a top-up CTA. No code change.

Co-Authored-By: Claude <[email protected]>

* Port from develop ff211b1: dashboard account-data amount display + resource-consumption subscription cards — already equivalent / not applicable

Source commit: ff211b1 (searouter-isuanova develop, feat(#95): 数据看板账户数据改按金额显示,资源消耗新增订阅原生额度卡片)

- Account data (当前余额/历史消耗) switched to the user's wallet quota
  (quota/used_quota) converted to money via renderQuota: already
  equivalent in the target — the overview SummaryCards render wallet
  quota/used via formatQuota, the project-standard currency conversion
  honoring display_in_currency. No change.
- Resource-consumption section: the source added two subscription
  native-quota cards (当前余额/历史消耗, raw numbers from
  useSubscriptionNativeQuota). Not applicable to the target
  architecture: the redesigned dashboard has no resource-consumption
  block (account surfaces live in the overview SummaryCards), and the
  source itself removed that block entirely in the later adec8c7
  revamp, replacing it with the 订阅余额 (converted value) card. The
  subscription data is available via useSubscriptionNativeQuota
  (ported in 5fb530f, extended in the adec8c7 hook port below) for
  the future summary revamp. No change.

Co-Authored-By: Claude <[email protected]>

* Port from develop adec8c7: subscription native quota hook adds plan-price remaining value

Source commit: adec8c7 (searouter-isuanova develop, feat: 模型价格支持缓存命中价设置,订阅余额按套餐价折算展示) — dashboard data-layer part only:
the useSubscriptionNativeQuota remainValue aggregation (套餐现价 × 剩余/总量).
The rest of the source commit (cache-hit pricing UI, dashboard layout
revamp, topup page, docs page) is out of scope for this port.

useSubscriptionNativeQuota now additionally returns:
- totalQuota: sum of amount_total over active finite-quota subscriptions
- remainValue: sum of planPrice x (remain / total) over those
  subscriptions (USD), i.e. the subscription balance converted at the
  plan's current price
- hasActive: whether the user has any active subscription

Implementation note (target adaptation): the source backend attaches
plan_price_amount to each SubscriptionSummary (adec8c7 backend change in
model/subscription.go). The target's SubscriptionSummary does not carry
the plan price and the backend is owned by another workstream, so the
hook resolves current plan prices client-side from
GET /api/subscription/plans (enabled plans, UserAuth) and joins by
plan_id. Edge-case difference: subscriptions whose plan is disabled no
longer appear in /api/subscription/plans, so their remaining value
contributes 0 (source would still resolve the disabled plan's price).

Co-Authored-By: Claude <[email protected]>

* Port from develop fbdf945 5ad7ee0: subscription overdraw + pre-consume audit trail (backend)

Port the subscription overdraw feature and the pre-consume
calculation audit trail from the searouter-isuanova develop branch
(#98):

Overdraw (fbdf945):
- PostConsumeUserSubscriptionDelta no longer rejects settle deltas
  that push amount_used above amount_total; the excess is recorded as
  a negative balance (remain = total - used < 0) and the pre-consume
  check naturally blocks further requests on that subscription
- Refund path keeps the used >= 0 clamp
- Consumption logs record subscription_remain as a true negative
  (no more clamp to 0)

Pre-consume audit trail (fbdf945):
- PriceData gains PreConsumeDetail (estimated prompt tokens, floor,
  request max_tokens, model/group ratios, final quota) filled by
  ModelPriceHelper
- Token estimation records a breakdown (text tokens, message/tool/
  name overhead, base overhead, media tokens, method); the relay
  handler attaches it to the detail; GenerateTextOtherInfo emits
  other["pre_consume_detail"] so logs can trace how the
  pre-consumed quota was derived
- New service/token_estimate_breakdown.go with the last-estimate
  record (mutex-guarded, returned by copy)

Adaptations: the breakdown recording lives in CountRequestToken
(develop had it in EstimateRequestToken); tests adapted to this
repo's package layout (relaykit/types alias, local SQLite test DB
helper).

Verified with go build + full model/service/relay-helper test suites.

Co-Authored-By: Claude <[email protected]>

* Port from develop 0fb2d5d: ops read-only access to user management and logs (web, part 1)

Frontend half of the ops-readonly feature, first batch:

- /users route guard: ops (and above) may now open the user
  management page (was admin-only); the page-level read-only
  treatment of actions/buttons follows in part 2
- usage-logs view scope: ops may view all users' logs (full-data
  branch: endpoint, columns, filters, detail fields); the log table
  has no write actions so the access is read-only by construction
- Sidebar ops section: new Users entry (/users, ops and above); the
  existing invite-history entry is relabeled Invite History to match
  its page title (previously mislabeled User Management)

Verified with usage-logs tests (23 passed) + tsgo typecheck.

Co-Authored-By: Claude <[email protected]>

* Port from develop 51b3f79 58cf985 2c55d2e f951584 9df4a57: user list quota columns switch to effective-subscription basis

User list (admin) and ops invitee list quota columns now use the
effective-subscription token basis instead of the wallet quota.

- model/user.go: non-persistent User fields (subscription_total_quota /
  subscription_remain_quota / subscription_used_quota /
  subscription_unlimited / subscription_remain_value) plus
  FillUsersSubscriptionQuotaStats, a single GROUP BY (user_id, plan_id)
  aggregate over user_subscriptions (status=active AND end_time > now):
  remain = SUM(max(0, amount_total-amount_used)) for amount_total>0 only,
  used = SUM(amount_used) (includes unlimited-subscription usage), total =
  SUM(amount_total) for amount_total>0 only, unlimited = any
  amount_total<=0 active sub, remain value = SUM(plan price x remain/total)
  with plan prices batch-fetched through the getSubscriptionPlanByIdTx
  cache (same source as the plan_price_amount summary field).
- controller/user.go: GetAllUsers/SearchUsers fill the stats before
  responding (51b3f79/#86).
- controller/user_ops.go: invitee list/search/CSV export fill the stats;
  CSV total/used quota columns output the subscription basis, unlimited
  total renders the localized string (new i18n key ops.export.unlimited in
  en/zh-CN/zh-TW).
- controller/user_columns.go + ops_user_columns.go: column metadata final
  state (58cf985/#94, 2c55d2e) — quota relabeled Remaining/Total Quota,
  new money_balance column Subscription Balance (plan-price-converted
  remaining value), the standalone ops used_quota column removed (used
  quota moves into the quota column tooltip), no history-money column.
- web users/ops-users: UserQuotaCell now renders the subscription basis
  (total is the subscription total - remain is clamped per subscription so
  used+remaining is not the total) with Unlimited support; new
  SubscriptionBalanceCell renders the plan-price-converted remaining value
  (USD) plus remaining percentage, '-' without an active subscription,
  Unlimited for unlimited subs, tooltip with the token breakdown;
  User/OpsUser types gain the 5 optional subscription stats fields.
- i18n: Remaining/Total Quota + Subscription Balance added to en/zh/zh-TW
  in place (zero reordering).
- Tests: FillUsersSubscriptionQuotaStats (no-active / single / mixed /
  empty, plus opt-in PostgreSQL dialect check gated on TEST_PG_DSN) and
  column metadata order/label tests for both tables.

Note: the aggregate uses CAST(... AS FLOAT8), valid on PostgreSQL/SQLite;
on MySQL the query errors and the function silently degrades to zero
values (same behavior as the source, kept as-is). The admin user CSV
export keeps the wallet basis, matching the source.

Co-Authored-By: Claude <[email protected]>

* Port from develop fbdf945 5ad7ee0: subscription overdraw (web)

Frontend half of the #98 overdraw port:

- Log details: subscription settlement now shows a single
  Final Consumed row (develop 5ad7ee0: only the final deduction is
  shown, pre-consume/post-delta stay log-only for auditing); falls
  back to pre-consume + post-delta for old logs missing
  subscription_consumed. The pre-consume detail / estimate
  breakdown recorded in the log (backend commit) are intentionally
  not rendered (develop: stored for auditing, not shown in UI)
- Subscription plans card: remaining amount no longer clamped at
  zero, so overdrawn subscriptions show a true negative balance
  (Usage percent text may exceed 100%, matching develop)

Verified with usage-logs + wallet tests (28 passed) + tsgo typecheck.

Co-Authored-By: Claude <[email protected]>

* Port from develop adec8c7: dashboard subscription balance card

Port the display half of adec8c7 (subscription remaining value at
plan price): the overview "Usage at a glance" panel gains a
Subscription balance cell under the wallet credit block, fed by the
useSubscriptionNativeQuota hook (added with the #84 port):

- no active subscription -> None; any unlimited active
  subscription -> Unlimited; otherwise the remaining value
  (sum of plan price x remain/total over active subscriptions, USD)
  formatted in the display currency (or native quota when currency
  display is disabled)
- sub-value: remaining percent (remain/total over finite
  subscriptions), matching the develop dashboard
- i18n: Subscription balance key in en/zh/zh-TW (obfuscated
  footer.newapi attribution key untouched)

Verified with tsgo typecheck + dashboard tests (39 passed).

Co-Authored-By: Claude <[email protected]>

* Port from develop 0fb2d5d: ops read-only access to user management and logs (web, part 2)

Users management page read-only treatment for ops viewers:

- Primary buttons (Add User / Export All): hidden for ops
- Bulk actions toolbar (export selected): hidden for ops
- Row actions (edit / enable / disable / promote / demote / 2FA
  reset / passkey / delete): not rendered for ops

Read data (user list, search, detail, columns) stays fully
available; the backend enforces the same split (write endpoints
admin-only, see the backend half of this port).

Verified with tsgo typecheck + users feature tests.

Co-Authored-By: Claude <[email protected]>

* Address CodeRabbit review comments on PR #110

- model/log_billing.go: format the dayKey calendar date in UTC — west-of-UTC
  time zones no longer shift the billing day back one day (Major, outside diff)
- controller/user.go: EmailBind counts Unicode characters instead of bytes,
  consistent with the aggregated create-user entry point
- model/user.go: portable (amount_total - amount_used) * 1.0 / amount_total
  division replaces the PG/SQLite-only FLOAT8 cast; valid on SQLite/MySQL/PG
- controller: GetUser and GetUserOAuthBindingsByAdmin read scope decoupled
  from the canManageTargetRole write policy — ops may read any user detail
  and OAuth bindings, consistent with GetAllUsers; write checks unchanged
- service/token_estimate_breakdown: request-scoped via gin context
  (constant.ContextKeyTokenEstimateBreakdown) instead of a package-level
  last-estimate; concurrent requests no longer overwrite each other and
  requests that skip counting cannot reuse another request's breakdown
- tests: converted 10 test files to testify require/assert per repository
  guidelines (require for setup/fatal/type assertions, assert for value
  checks; RedisEnabled saved and restored via t.Cleanup)
- web: api-key quota default 5,000,000 (the former $10 default in native
  units) instead of 0; "Native Quota" wording without token units + locales;
  explicit ids on the ops-users subscription columns so column-visibility
  metadata resolves; usage-logs scope is category-aware (ops pinned to the
  self tier on drawing/task views whose read endpoints are AdminAuth);
  username 50-codepoint schema refine (HTML maxLength counts UTF-16 units)

Verified: go build ./... + go test (controller/model/service/relay/helper),
billing date tests under TZ=America/New_York and TZ=Asia/Shanghai, tsgo
typecheck, 138 web test files / 1080 tests.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
@skeeey
skeeey deleted the fix/deepseek-endpoint-types branch September 26, 2026 12:01
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.

2 participants