Skip to content

rikkahub默认可查询余额,gemini格式获取模型列表修复 - #5899

Closed
zhaibingye wants to merge 7 commits into
QuantumNous:mainfrom
zhaibingye:main
Closed

rikkahub默认可查询余额,gemini格式获取模型列表修复#5899
zhaibingye wants to merge 7 commits into
QuantumNous:mainfrom
zhaibingye:main

Conversation

@zhaibingye

@zhaibingye zhaibingye commented Jul 4, 2026

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

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

📝 变更描述 / Description

gemini获取模型给了模型名称解决了无法正确拉取模型列表的bug,增加了一个地址,是rikkahub默认获取余额的地址,方便rikkahub用户查询余额

🚀 变更类型 / Type of change

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

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

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

📸 运行证明 / Proof of Work

Screenshot_2026-07-04-14-30-21-390_me rerere rikk Screenshot_2026-07-04-14-30-28-274_me rerere rikk

Summary by CodeRabbit

  • New Features
    • Added GET /v1/credits with OpenAI-style data.total_usage, using the correct remaining-quota source.
    • Enhanced Gemini ListModels to return a more native model payload with supported generation methods.
    • Dashboard chart granularity now supports per-user “default time” with quick switching.
  • Bug Fixes
    • Improved Gemini base /v1/models handling and token-key extraction.
    • Gemini model fetching now skips empty model names; Gemini model JSON serialization is more precise.
  • Tests
    • Added coverage for /v1/credits and Gemini ListModels response shape.
  • Documentation
    • Updated Quick Start, deploy guides, and docker-compose.yml to use the fork’s Docker image tag.
  • Chores
    • Added contributor guidance for CodeGraph and removed several Docker/CI release workflows.

@coderabbitai

coderabbitai Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 16d1ded2-ee76-4139-bd99-08c09994dda8

📥 Commits

Reviewing files that changed from the base of the PR and between ed0de85 and 43f0f1a.

📒 Files selected for processing (1)
  • web/classic/rsbuild.config.ts

Walkthrough

Adds a /v1/credits endpoint, updates Gemini model listing and routing/auth behavior, threads dashboard granularity state through storage and chart loading, and adds fork image publishing plus repository-specific documentation updates.

Changes

Credits endpoint

Layer / File(s) Summary
Credits response types
controller/channel-billing.go
Adds response structs for data.total_usage.
GetCredits handler and route
controller/billing.go, router/dashboard.go
Implements quota lookup and display conversion in GetCredits, then registers GET /v1/credits.
Handler tests
controller/billing_test.go
Adds DB setup, request helper, and tests for token-quota and user-quota paths.

Gemini model listing

Layer / File(s) Summary
GeminiModel typing
dto/pricing.go
Changes GeminiModel fields to typed optional JSON values.
Model list construction
controller/model.go
Adds buildGeminiModel, uses it in ListModels, and returns an empty nextPageToken.
Routing and auth for /v1/models
router/relay-router.go, middleware/auth.go
Routes Gemini /v1/models requests to ListModels and extends auth matching to the exact path.
FetchGeminiModels parsing
relay/channel/gemini/relay-gemini.go
Trims whitespace from model names and skips empty entries.
Model list tests
controller/model_list_test.go
Adds Gemini response helpers and a test for the native response shape.

Dashboard time granularity

Layer / File(s) Summary
Dashboard time storage helpers
web/classic/src/helpers/dashboard.jsx
Adds per-user default-time storage, validation, and timestamp derivation helpers.
Dashboard state and quota flow
web/classic/src/hooks/dashboard/useDashboardData.js
Derives a storage key from the current user, initializes and persists time granularity from that key, refreshes quota queries with an overrideable default time, and resets timestamps when the user key changes.
Dashboard chart updates
web/classic/src/hooks/dashboard/useDashboardCharts.jsx
Threads the selected default time through chart and user-chart data processing.
Dashboard granularity UI
web/classic/src/components/dashboard/DashboardHeader.jsx, web/classic/src/components/dashboard/index.jsx
Passes time options into the dashboard header and adds granularity actions for refresh, search, and quick changes.

Fork image publishing and docs

Layer / File(s) Summary
Publish workflow
.github/workflows/docker-hub-user.yml
Creates the multi-arch Docker Hub publish workflow for the user image.
Fork references and image updates
docker-compose.yml, docs/installation/BT.md, README*.md
Updates the compose image, installation notes, README quick-start sections, and star-history embeds to point at the fork repository and image.
Agent guidance
AGENTS.md
Adds a CodeGraph usage rule.

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

Possibly related PRs

Suggested reviewers: Calcium-Ion, seefs001, creamlike1024

Poem

A rabbit hops through credits bright,
Gemini models now line up just right 🥕
Granularity ticks by time,
Fork docs sparkle, image tags shine,
Thump-thump — the build runs smooth tonight.

🚥 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 标题准确概括了本次变更的两个核心点:默认余额查询接口和 Gemini 模型列表修复。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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: 3

🧹 Nitpick comments (2)
controller/billing.go (1)

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

Extract shared quota-display conversion logic.

This switch statement is duplicated verbatim in GetUsage (lines 94-101) and GetSubscription (lines 48-55). A shared helper (e.g. convertQuotaToDisplayAmount(quota int) float64) would prevent the three copies from drifting when a new display type or conversion rule is added.

♻️ Proposed refactor
+func convertQuotaToDisplayAmount(quota int) float64 {
+	amount := float64(quota)
+	switch operation_setting.GetQuotaDisplayType() {
+	case operation_setting.QuotaDisplayTypeCNY:
+		amount = amount / common.QuotaPerUnit * operation_setting.USDExchangeRate
+	case operation_setting.QuotaDisplayTypeTokens:
+		// tokens 保持原值
+	default:
+		amount = amount / common.QuotaPerUnit
+	}
+	return amount
+}
+
 func GetCredits(c *gin.Context) {
 	...
-	amount := float64(quota)
-	switch operation_setting.GetQuotaDisplayType() {
-	case operation_setting.QuotaDisplayTypeCNY:
-		amount = amount / common.QuotaPerUnit * operation_setting.USDExchangeRate
-	case operation_setting.QuotaDisplayTypeTokens:
-		// tokens 保持原值
-	default:
-		amount = amount / common.QuotaPerUnit
-	}
+	amount := convertQuotaToDisplayAmount(quota)
🤖 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/billing.go` around lines 134 - 142, The quota display conversion
switch is duplicated in controller billing logic and should be centralized to
avoid drift. Extract the shared amount conversion from GetUsage,
GetSubscription, and the current billing flow into a helper such as
convertQuotaToDisplayAmount that uses operation_setting.GetQuotaDisplayType,
common.QuotaPerUnit, and operation_setting.USDExchangeRate, then have each
caller use that helper instead of repeating the switch.
controller/billing_test.go (1)

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

Consider covering UnlimitedQuota and the error path.

Current tests only exercise the plain token/user quota branches. GetCredits has two other billing-relevant behaviors not covered here: the UnlimitedQuota override (amount = 100000000) and the JSON error response when the token/user lookup fails. Since this endpoint reports account balance, these are worth locking in as regression tests.

As per path instructions, "Backend tests must protect real behavior, API contracts, billing/accounting invariants, data 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 `@controller/billing_test.go` around lines 78 - 115, Add coverage in GetCredits
tests for the remaining billing branches: verify that the credits calculation
honors the UnlimitedQuota override, and add a negative test for the lookup
failure path that returns the JSON error response. Use the existing
TestGetCreditsUsesTokenRemainingQuotaWhenTokenStatsEnabled,
TestGetCreditsUsesUserQuotaWhenTokenStatsDisabled, and requestCredits helpers to
locate the behavior, and assert the expected TotalUsage or error payload for the
token/user fetch failures.

Source: Path instructions

🤖 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 @.github/workflows/docker-hub-user.yml:
- Around line 4-7: The Docker Hub publish workflow is pushing the wrong image
target for main branch builds. Update the workflow in docker-hub-user to publish
the documented deployment image used by the repo docs and compose examples, and
make sure the build/push job in the workflow points to the same repository/name
as the deployed image rather than yeranshuanghua/shuanghua-api; if this workflow
is intended only as a personal mirror, remove the main branch push trigger and
keep it manual or fork-scoped. Also verify the related build/push steps later in
the workflow stay consistent with this image name.
- Around line 17-18: The checkout step in the docker-hub-user workflow is
leaving GitHub credentials in the workspace, which can get copied into the
Docker build context. Update the existing actions/checkout usage in the checkout
step to disable persisted credentials so no token remains after checkout,
keeping the workspace clean before the Docker build runs.

In `@controller/model.go`:
- Around line 172-189: The Gemini model mapping in buildGeminiModel only
recognizes a narrow set of embedding prefixes, so some embedding variants are
incorrectly marked as chat models. Update the prefix detection logic in
buildGeminiModel to classify all configured embedding model names, including
newer Gemini embedding variants like gemini-embedding-exp-03-07 and other
text-embedding-* forms, so SupportedGenerationMethods is set to
embedContent/batchEmbedContents instead of generateContent/countTokens.

---

Nitpick comments:
In `@controller/billing_test.go`:
- Around line 78-115: Add coverage in GetCredits tests for the remaining billing
branches: verify that the credits calculation honors the UnlimitedQuota
override, and add a negative test for the lookup failure path that returns the
JSON error response. Use the existing
TestGetCreditsUsesTokenRemainingQuotaWhenTokenStatsEnabled,
TestGetCreditsUsesUserQuotaWhenTokenStatsDisabled, and requestCredits helpers to
locate the behavior, and assert the expected TotalUsage or error payload for the
token/user fetch failures.

In `@controller/billing.go`:
- Around line 134-142: The quota display conversion switch is duplicated in
controller billing logic and should be centralized to avoid drift. Extract the
shared amount conversion from GetUsage, GetSubscription, and the current billing
flow into a helper such as convertQuotaToDisplayAmount that uses
operation_setting.GetQuotaDisplayType, common.QuotaPerUnit, and
operation_setting.USDExchangeRate, then have each caller use that helper instead
of repeating the switch.
🪄 Autofix (Beta)

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

Run ID: 222952e3-1773-4fdb-9a0e-315abee9f5f2

📥 Commits

Reviewing files that changed from the base of the PR and between 722d036 and 12b3f9a.

📒 Files selected for processing (11)
  • .github/workflows/docker-hub-user.yml
  • controller/billing.go
  • controller/billing_test.go
  • controller/channel-billing.go
  • controller/model.go
  • controller/model_list_test.go
  • dto/pricing.go
  • middleware/auth.go
  • relay/channel/gemini/relay-gemini.go
  • router/dashboard.go
  • router/relay-router.go

Comment on lines +4 to +7
push:
branches:
- main
workflow_dispatch:

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

Align the pushed Docker image with the documented deployment image.

The repo docs and compose examples consume calciumion/new-api:latest, but this push-on-main workflow only publishes yeranshuanghua/shuanghua-api. Main builds will not update the image users are instructed to deploy; if this is only a personal mirror, make it manual/fork-scoped instead.

Proposed fix if this workflow is meant to publish the documented image
           username: yeranshuanghua
           password: ${{ secrets.DOCKER_HUB }}
@@
           tags: |
-            yeranshuanghua/shuanghua-api:latest
-            yeranshuanghua/shuanghua-api:${{ github.sha }}
+            calciumion/new-api:latest
+            calciumion/new-api:${{ github.sha }}

Also applies to: 29-44

🤖 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 @.github/workflows/docker-hub-user.yml around lines 4 - 7, The Docker Hub
publish workflow is pushing the wrong image target for main branch builds.
Update the workflow in docker-hub-user to publish the documented deployment
image used by the repo docs and compose examples, and make sure the build/push
job in the workflow points to the same repository/name as the deployed image
rather than yeranshuanghua/shuanghua-api; if this workflow is intended only as a
personal mirror, remove the main branch push trigger and keep it manual or
fork-scoped. Also verify the related build/push steps later in the workflow stay
consistent with this image name.

Comment on lines +17 to +18
- name: Check out
uses: actions/checkout@v4

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Disable persisted checkout credentials before building the Docker context.

actions/checkout persists the GitHub token by default, and this job does not need git credentials after checkout. Keep the token out of the workspace used for the Docker build.

Proposed fix
       - name: Check out
         uses: actions/checkout@v4
+        with:
+          persist-credentials: false
📝 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
- name: Check out
uses: actions/checkout@v4
- name: Check out
uses: actions/checkout@v4
with:
persist-credentials: false
🧰 Tools
🪛 zizmor (1.26.1)

[warning] 17-18: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)

🤖 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 @.github/workflows/docker-hub-user.yml around lines 17 - 18, The checkout
step in the docker-hub-user workflow is leaving GitHub credentials in the
workspace, which can get copied into the Docker build context. Update the
existing actions/checkout usage in the checkout step to disable persisted
credentials so no token remains after checkout, keeping the workspace clean
before the Docker build runs.

Source: Linters/SAST tools

Comment thread controller/model.go
@zhaibingye zhaibingye closed this Jul 6, 2026
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