Repository navigation
Conversation
Add an admin-only "Cost Attribution" tab to the dashboard that attributes spend across user/token/model dimensions with one-level drill-down (e.g. a token's per-model composition) and a daily VChart cost trend. - backend: cross-DB aggregation endpoints /api/log/attribution[/trend] over the logs table (LogTypeConsume), guarded by AdminAuth - frontend: new dashboard section reusing chart/theme conventions - i18n: 6 locales; docs: requirements + tech design Co-authored-by: Cursor <cursoragent@cursor.com>
WalkthroughAdds an admin-only cost attribution feature: backend types and aggregation queries for consume logs, API handlers and routes, frontend types and API functions, chart spec and UI components (ranking, drill-down, trend), docs, tests, and i18n updates. ChangesCost Attribution Dashboard Implementation
Sequence DiagramsequenceDiagram
participant Admin as Admin User
participant DashUI as Dashboard UI
participant React as React Query
participant API as /api/log/attribution
participant Handler as Controller.GetLogAttribution
participant Model as model.GetLogAttribution
participant DB as Database
Admin->>DashUI: Select dimension/time/top & trigger query
DashUI->>React: Run query with params
React->>API: GET /api/log/attribution?<br/>dimension=...&start=...&end=...
API->>Handler: parse filter params
Handler->>Model: GetLogAttribution(filter)
Model->>DB: Aggregate consume logs (GROUP BY dimension, filtered)
DB-->>Model: totals & grouped rows
Model-->>Handler: AttributionTotal + rows
Handler-->>API: JSON response
API-->>React: { dimension, total, rows }
React-->>DashUI: Render totals, ranking, trend
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~75 minutes Suggested Reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (5)
web/default/src/features/dashboard/lib/attribution-chart.ts (1)
23-24: ⚡ Quick winAvoid introducing
anyinVChartSpec.Please switch
Record<string, any>toRecord<string, unknown>(or a concrete chart spec type) to keep type safety consistent with project rules.As per coding guidelines, “Avoid
anytype in TypeScript; prefer specific types orunknown.”🤖 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/dashboard/lib/attribution-chart.ts` around lines 23 - 24, The VChartSpec type currently uses Record<string, any>, which introduces `any`; change the alias `type VChartSpec` to use `Record<string, unknown>` (or replace with a concrete chart-spec interface if available) to restore type safety; update any usages of VChartSpec accordingly so callers narrow/validate values rather than relying on `any`.Source: Coding guidelines
web/default/src/features/dashboard/components/attribution/attribution-charts.tsx (1)
273-278: ⚡ Quick winMark decorative icons as hidden from assistive tech.
ChevronRight,TrendingUp, and the loading spinner are decorative here; addaria-hidden="true"to avoid noisy announcements.As per coding guidelines, “add
aria-hidden="true"to decorative icons.”Also applies to: 363-363, 521-521
🤖 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/dashboard/components/attribution/attribution-charts.tsx` around lines 273 - 278, The decorative icons ChevronRight, TrendingUp, and the loading spinner should be hidden from assistive tech: add aria-hidden="true" to each icon component instance (e.g., the ChevronRight usage shown, the TrendingUp instance, and the Spinner/loading icon) so they don't produce noisy announcements; ensure you don't add conflicting aria-label/role props on those same icon elements and keep the accessible label on the surrounding interactive element (if any).Source: Coding guidelines
docs/features/cost-attribution-tech-design.md (2)
47-49: 💤 Low valueAdd language specifier to code block.
The fenced code block lacks a language identifier. Adding
httportextimproves rendering and satisfies markdown linting.📝 Suggested fix
-``` +```http GET /api/log/attribution</details> <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.In
@docs/features/cost-attribution-tech-design.mdaround lines 47 - 49, The
fenced code block containing "GET /api/log/attribution" is missing a language
specifier; update that markdown block (the triple-backtick fence around GET
/api/log/attribution) to include a language like "http" (i.e., change ``` to
88-90: 💤 Low valueAdd language specifier to code block.
Same issue as line 47: the fenced code block should specify a language identifier for better rendering.
📝 Suggested fix
-``` +```http GET /api/log/attribution/trend</details> <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.In
@docs/features/cost-attribution-tech-design.mdaround lines 88 - 90, The
fenced code block containing "GET /api/log/attribution/trend" needs a language
specifier for proper rendering; update the triple-backtick fence to include
"http" (i.e., ```http) around the block that contains GET
/api/log/attribution/trend so it matches the other examples (same fix as around
the earlier GET example).</details> <!-- cr-comment:v1:7a4d7ce7e8ddbeafcf69bf61 --> </blockquote></details> <details> <summary>model/log_attribution_test.go (1)</summary><blockquote> `33-115`: _⚡ Quick win_ **Add negative-case tests for filter validation paths.** Please add cases for invalid `Dimension`, invalid `Sub`, and non-numeric `ParentId` (for `user`/`token` drill) so error contracts in `GetLogAttribution`/`GetLogAttributionTrend` don’t regress. <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@model/log_attribution_test.go` around lines 33 - 115, The test suite is missing negative-case tests for filter validation paths in GetLogAttribution and GetLogAttributionTrend; add new tests in model/log_attribution_test.go that call GetLogAttribution and GetLogAttributionTrend with (a) an invalid Dimension value and assert an error, (b) an invalid Sub value (e.g., unsupported drill-down) and assert an error, and (c) a non-numeric ParentId when Dimension/Sub expect numeric IDs (user/token drill) and assert an error; ensure each new test (e.g., TestGetLogAttribution_InvalidDimension, TestGetLogAttribution_InvalidSub, TestGetLogAttribution_InvalidParentId and equivalents for GetLogAttributionTrend) uses truncateTables/seedAttributionLogs as needed and verifies the functions return the expected error contract rather than nil results. ``` </details> <!-- cr-comment:v1:7854eedff9dea34919d033af --> </blockquote></details> </blockquote></details> <details> <summary>🤖 Prompt for all review comments with AI agents</summary>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@docs/features/cost-attribution-tech-design.md:
- Line 13: The doc incorrectly references the feature path
web/default/src/features/usage-logs; update both occurrences in this document
to the correct pathweb/default/src/features/dashboardand ensure the text
refers to the "数据看板" (Data Dashboard) location. Search for the literal string
web/default/src/features/usage-logsand replace it with
web/default/src/features/dashboard, and verify the section heading and any
related sentences match the companion requirements (cost-attribution.md) and PR
intent describing an admin-only "成本归因" tab on the dashboard.In
@docs/features/cost-attribution.md:
- Line 3: The status line "状态:需求已确认,待实现" is outdated; update that markdown
to reflect the implemented feature (e.g., "状态:已实现" or "状态:实现中") so docs
match the PR which includes backend aggregation, API handlers, React UI
components, and tests—locate and edit the exact line containing 状态:需求已确认,待实现
in docs/features/cost-attribution.md.In
@model/log.go:
- Around line 633-657: The attribution query currently leaves Start/End unset
and Top uncapped, causing full-table scans; update attributionBase to enforce
safe defaults and a hard Top cap: define a MAX_ATTRIBUTION_TOP constant (e.g.,
- and a default time window (e.g., defaultWindow = 30 days), and if f.Start
== 0 set f.Start = now - defaultWindow, if f.End == 0 set f.End = now, and if
f.Top > MAX_ATTRIBUTION_TOP set f.Top = MAX_ATTRIBUTION_TOP (or if f.Top == 0
set a sensible default like 100); apply the same defaulting/capping logic
wherever similar predicates are constructed (the other blocks noted around lines
712-715 and 736-738) so functions using AttributionFilter (including
attributionBase and the related totals/ranking/trend query builders) always add
bounded time WHERE clauses and a capped TOP.In
@web/default/src/features/dashboard/index.tsx:
- Around line 312-318: The attribution render branch currently checks only
activeSection and can be mounted via deep-link; modify the conditional to
enforce the admin guard by also checking isAdmin (e.g., change the branch from
activeSection === 'attribution' to activeSection === 'attribution' && isAdmin)
or, if not isAdmin, programmatically redirect/set activeSection to an allowed
section; apply this change around the LazyAttributionCharts/FadeIn/Suspense
block so only admins can mount LazyAttributionCharts.
Nitpick comments:
In@docs/features/cost-attribution-tech-design.md:
- Around line 47-49: The fenced code block containing "GET /api/log/attribution"
is missing a language specifier; update that markdown block (the triple-backtick
fence around GET /api/log/attribution) to include a language like "http" (i.e.,
changetohttp) so the snippet renders and satisfies markdown linting.- Around line 88-90: The fenced code block containing "GET
/api/log/attribution/trend" needs a language specifier for proper rendering;
update the triple-backtick fence to include "http" (i.e., ```http) around the
block that contains GET /api/log/attribution/trend so it matches the other
examples (same fix as around the earlier GET example).In
@model/log_attribution_test.go:
- Around line 33-115: The test suite is missing negative-case tests for filter
validation paths in GetLogAttribution and GetLogAttributionTrend; add new tests
in model/log_attribution_test.go that call GetLogAttribution and
GetLogAttributionTrend with (a) an invalid Dimension value and assert an error,
(b) an invalid Sub value (e.g., unsupported drill-down) and assert an error, and
(c) a non-numeric ParentId when Dimension/Sub expect numeric IDs (user/token
drill) and assert an error; ensure each new test (e.g.,
TestGetLogAttribution_InvalidDimension, TestGetLogAttribution_InvalidSub,
TestGetLogAttribution_InvalidParentId and equivalents for
GetLogAttributionTrend) uses truncateTables/seedAttributionLogs as needed and
verifies the functions return the expected error contract rather than nil
results.In
@web/default/src/features/dashboard/components/attribution/attribution-charts.tsx:
- Around line 273-278: The decorative icons ChevronRight, TrendingUp, and the
loading spinner should be hidden from assistive tech: add aria-hidden="true" to
each icon component instance (e.g., the ChevronRight usage shown, the TrendingUp
instance, and the Spinner/loading icon) so they don't produce noisy
announcements; ensure you don't add conflicting aria-label/role props on those
same icon elements and keep the accessible label on the surrounding interactive
element (if any).In
@web/default/src/features/dashboard/lib/attribution-chart.ts:
- Around line 23-24: The VChartSpec type currently uses Record<string, any>,
which introducesany; change the aliastype VChartSpecto use
Record<string, unknown>(or replace with a concrete chart-spec interface if
available) to restore type safety; update any usages of VChartSpec accordingly
so callers narrow/validate values rather than relying onany.</details> <details> <summary>🪄 Autofix (Beta)</summary> Fix all unresolved CodeRabbit comments on this PR: - [ ] <!-- {"checkboxId": "4b0d0e0a-96d7-4f10-b296-3a18ea78f0b9"} --> Push a commit to this branch (recommended) - [ ] <!-- {"checkboxId": "ff5b1114-7d8c-49e6-8ac1-43f82af23a33"} --> Create a new PR with the fixes </details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Organization UI **Review profile**: CHILL **Plan**: Pro **Run ID**: `944ce20c-6c7c-46d1-81f7-755881b394af` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 6f415428d3e6ac7d136f44808fc76e0f3aebab1e and fc3c1b6983ad40389d237a44a3abb568acae1842. </details> <details> <summary>📒 Files selected for processing (18)</summary> * `controller/log.go` * `docs/features/cost-attribution-tech-design.md` * `docs/features/cost-attribution.md` * `model/log.go` * `model/log_attribution_test.go` * `router/api-router.go` * `web/default/src/features/dashboard/api.ts` * `web/default/src/features/dashboard/components/attribution/attribution-charts.tsx` * `web/default/src/features/dashboard/index.tsx` * `web/default/src/features/dashboard/lib/attribution-chart.ts` * `web/default/src/features/dashboard/section-registry.tsx` * `web/default/src/features/dashboard/types.ts` * `web/default/src/i18n/locales/en.json` * `web/default/src/i18n/locales/fr.json` * `web/default/src/i18n/locales/ja.json` * `web/default/src/i18n/locales/ru.json` * `web/default/src/i18n/locales/vi.json` * `web/default/src/i18n/locales/zh.json` </details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
- model: bound attribution queries with a hard Top cap (200) and a default 30-day time window when no start timestamp is provided, to avoid full consume-log history scans; cover with unit tests - web: gate the dashboard attribution render path with isAdmin (not just tab visibility) and make drill-down rows keyboard-accessible (tabIndex/role/aria-expanded/Enter+Space) - docs: correct feature location (usage-logs -> dashboard) and mark the requirements doc as implemented Co-authored-by: Cursor <cursoragent@cursor.com>
Move the default lower time-window bound from the public entry functions into attributionBase so every query path (totals/ranking/drill/trend) is always bounded at the data-access layer, regardless of caller. normalize now only hard-caps Top. Addresses CodeRabbit: unbounded full-history scan. Co-authored-by: Cursor <cursoragent@cursor.com>
51fdfc5 to
2b6f1df
Compare
Persist authenticated stable-principal cost attribution and scoped reports; regression tests and Verify CI passed. Refs: QuantumNous/new-api#5431 QuantumNous/new-api#5431 Refs: QuantumNous/new-api#4329 QuantumNous/new-api#4329 Refs: QuantumNous/new-api#4328 QuantumNous/new-api#4328
Preserve principal cost report translations and the complete reviewed model import interface translations. Refs: QuantumNous/new-api#5431 Refs: QuantumNous/new-api#7953
docs: finalize community improvement batches and validation Document eight implemented capabilities, review fixes, exact commits, CI evidence and upstream correspondence. Preserve identity, Redis and evaluation boundaries, and provide the model governance lifecycle/API guide. All functional PRs were reviewed and merged after successful regression tests and Verify CI. The running checkout and services were not changed. Refs: QuantumNous/new-api issue #1730 QuantumNous/new-api#1730 Refs: QuantumNous/new-api issue #2841 QuantumNous/new-api#2841 Refs: QuantumNous/new-api issue #3240 QuantumNous/new-api#3240 Refs: QuantumNous/new-api PR #3345 QuantumNous/new-api#3345 Refs: QuantumNous/new-api issue #4328 QuantumNous/new-api#4328 Refs: QuantumNous/new-api PR #4329 QuantumNous/new-api#4329 Refs: QuantumNous/new-api PR #4492 QuantumNous/new-api#4492 Refs: QuantumNous/new-api PR #5431 QuantumNous/new-api#5431 Refs: QuantumNous/new-api PR #5791 QuantumNous/new-api#5791 Refs: QuantumNous/new-api PR #6264 QuantumNous/new-api#6264 Refs: QuantumNous/new-api PR #6583 QuantumNous/new-api#6583 Refs: QuantumNous/new-api PR #6620 QuantumNous/new-api#6620 Refs: QuantumNous/new-api PR #6673 QuantumNous/new-api#6673 Refs: QuantumNous/new-api issue #6972 QuantumNous/new-api#6972 Refs: QuantumNous/new-api PR #7028 QuantumNous/new-api#7028 Refs: QuantumNous/new-api issue #7951 QuantumNous/new-api#7951 Refs: QuantumNous/new-api issue #7952 QuantumNous/new-api#7952 Refs: QuantumNous/new-api PR #7953 QuantumNous/new-api#7953 Refs: QuantumNous/new-api PR #7955 QuantumNous/new-api#7955 Refs: QuantumNous/new-api issue #8034 QuantumNous/new-api#8034 Refs: QuantumNous/new-api PR #8076 QuantumNous/new-api#8076 Refs: QuantumNous/new-api issue #8123 QuantumNous/new-api#8123 Refs: QuantumNous/new-api PR #8124 QuantumNous/new-api#8124 Refs: QuantumNous/new-api issue #8232 QuantumNous/new-api#8232 Refs: QuantumNous/new-api PR #8233 QuantumNous/new-api#8233 Refs: QuantumNous/new-api issue #8295 QuantumNous/new-api#8295 Refs: QuantumNous/new-api PR #8296 QuantumNous/new-api#8296 Refs: QuantumNous/new-api PR #8350 QuantumNous/new-api#8350 Refs: QuantumNous/new-api PR #8357 QuantumNous/new-api#8357 Refs: QuantumNous/new-api PR #8363 QuantumNous/new-api#8363 Refs: #99 #99 Refs: #100 #100 Refs: #101 #101 Refs: #102 #102 Refs: #103 #103 Refs: #104 #104 Refs: #105 #105 Refs: #106 #106 Refs: #107 #107 Refs: #108 #108 Refs: #109 #109 Documentation Verify CI passed: https://github.com/soulteary/yunqi/actions/runs/45003986698
📝 变更描述 / Description
在「数据看板」新增一个仅管理员可见的「成本归因」Tab,用来回答"钱花在谁/哪个 key/哪个模型上"。
🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
✅ 提交前检查项 / Checklist
go build ./...、go test ./model/ -run TestGetLogAttribution、前端tsc -b,并手动验证看板效果。AdminAuth(),无敏感凭据,符合项目规范。📸 运行证明 / Proof of Work
看板「成本归因」Tab(模型维度示例:总费用 / 调用次数 / 输入输出 token + 每日趋势 + 排行表):
Summary by CodeRabbit
New Features
Documentation
Tests
Internationalization