Repository navigation
Conversation
Add a lightweight active-subscription check to skip subscription pre-consume when none exist, reducing unnecessary transactions and locks. In the subscription UI, disable subscription-first options when no active plan is available, show the effective fallback to wallet with a clear notice, and distinguish “invalidated” from “expired” states. Update i18n strings across supported locales to reflect the new messages and status labels.
Aligns the error variable types in the subscription-first path so that quota fallback checks use the correct NewAPIError. This prevents build failures and preserves the intended wallet fallback when subscription pre-consume returns an insufficient quota error.
Routes quota alerts through a subscription-specific check when billing from subscriptions, preventing wallet-based thresholds from triggering false warnings. Updates the notification settings description and localization keys to clarify that both wallet and subscription balances are monitored.
…n-quota-notify 🔔 feat: Add subscription-aware quota notifications and update UI copy
…-preference-fallback ✨ chore: Improve subscription billing fallback and UI states
…tumNous#2881) 当上游为 AWS Bedrock 时,message_delta 的 usage 可能缺少 input_tokens、 cache_creation_input_tokens、cache_read_input_tokens 等字段,导致与原生 Anthropic 格式不一致。从 message_start 积累的 claudeInfo 中补全这些字段后 重新序列化,确保客户端收到一致的 usage 格式。
Modified the formatUserLogs function to include a startIdx parameter, allowing for more flexible log ID assignment. Updated calls to this function in GetLogByTokenId and GetUserLogs to pass the appropriate starting index.
feat: add Codex channel disclaimer (i18n, OpenAI terms)
feat: Force beta=true parameter for Anthropic channel
feat(oauth): implement custom OAuth provider
fix: Claude stream block index/type transitions
fix: add paragraph breaks between reasoning summary chunks
# Conflicts: # service/openaicompat/chat_to_responses.go
…t-stream feat: channel test with stream=true
…fo-input-token fix: 使用openai兼容接口调用部分渠道在最终端点为claude原生端点下还是走了openai扣减input_token的逻辑
fix: 补全 streaming message_delta 事件缺失的 input_tokens 和 cache 相关字段
…sponses feat: /v1/messages -> /v1/responses
…ion-configurable feat: make 5m cache-creation ratio configurable
fix: 如果模型管理有自定义配置则不合并默认配置
fix: 修复模型管理"参与官方同步"与"状态"开关无法保存的问题
- Add display_name field to Log model (read-only from users table) - Update GetAllLogs to fetch display_name via bulk query - Update frontend to show display_name instead of username - Add grouping dropdown with User/Hour/Model options - Implement grouping logic with aggregated stats Co-authored-by: gmij <22893579+gmij@users.noreply.github.com>
The grouping feature was querying the logs table and doing client-side aggregation, but the system has a dedicated quota_data table for aggregated statistics. Removed: - Grouping dropdown UI from filters - Client-side grouping logic (getProcessedLogs) - Grouping state management - Group summary rendering in columns The logs page is now focused on viewing detailed log records. For aggregated statistics and grouping by user/model/time, users should use the existing Data Dashboard (/api/data endpoints) which properly leverages the quota_data table. This aligns with the system architecture where: - logs table = detailed per-request records - quota_data table = hourly aggregated statistics Co-authored-by: gmij <22893579+gmij@users.noreply.github.com>
Co-authored-by: gmij <22893579+gmij@users.noreply.github.com>
…ropdown feat: add top users consumption ranking to dashboard
WalkthroughAdds an admin-only API and DB query to return top users by quota, enriches logs with display names via bulk user lookup, and introduces frontend hooks, chart spec, UI tab, and i18n to display an admin-only user consumption ranking. Changes
Sequence Diagram(s)sequenceDiagram
participant Frontend as "Frontend\n(Dashboard)"
participant Router as "Router\n(api-router)"
participant Controller as "Controller\nGetTopUsersByQuota"
participant Model as "Model\nGetTopUsersByQuota"
participant DB as "Database"
Frontend->>Router: GET /api/data/top-users?start_timestamp&end_timestamp&limit
Router->>Controller: invoke GetTopUsersByQuota(c)
Controller->>Controller: parse & validate params (start,end,limit)
Controller->>Model: GetTopUsersByQuota(start,end,limit)
Model->>DB: SELECT user_id, username, SUM(quota), COUNT(*), SUM(token_used) ... GROUP BY user_id ORDER BY SUM(quota) DESC LIMIT N
DB-->>Model: rows
Model-->>Controller: []*QuotaData
Controller-->>Frontend: JSON {success:true, message:"", data: [...]}
Frontend->>Frontend: map data -> spec_user_rank_bar then render chart
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
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: 4
🧹 Nitpick comments (3)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx (1)
444-459: Use the same identity source for avatar text and color.Right now the avatar character uses
displayText, but color still hashestext(username). Using one source avoids subtle mismatch.♻️ Optional consistency tweak
render: (text, record, index) => { const displayText = record.display_name || text; + const colorSeed = displayText || text; return isAdminUser ? ( <div> <Avatar size='extra-small' - color={stringToColor(text)} + color={stringToColor(colorSeed)} style={{ marginRight: 4 }} onClick={(event) => { event.stopPropagation(); showUserInfoFunc(record.user_id); }}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx` around lines 444 - 459, The avatar uses displayText for the visible character but still hashes the original text for color, causing mismatches; update the Avatar usage in the render block (component Avatar inside UsageLogsColumnDefs) to call stringToColor with the same source as the avatar text (displayText derived from record.display_name || text) so both the character and color are computed from the same value, and keep the onClick handler (showUserInfoFunc) and trimming logic (displayText.slice(0,1)) unchanged.web/src/components/dashboard/ChartsPanel.jsx (1)
59-82: NormalizeactiveChartTabwhen admin permission is not present.If the state is
'5'andisAdminUserbecomes false, this component can render an empty chart area.♻️ Suggested guard
const ChartsPanel = ({ @@ t, }) => { + React.useEffect(() => { + if (!isAdminUser && activeChartTab === '5') { + setActiveChartTab('1'); + } + }, [isAdminUser, activeChartTab, setActiveChartTab]); + return (🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/dashboard/ChartsPanel.jsx` around lines 59 - 82, When isAdminUser flips to false while activeChartTab === '5' the panel can render nothing; add a guard in the ChartsPanel component to normalize activeChartTab when permissions change: inside the component (where activeChartTab and setActiveChartTab are defined) add an effect that watches isAdminUser and activeChartTab and, if isAdminUser is false and activeChartTab === '5', call setActiveChartTab to a valid fallback (e.g. '1' or the current first visible tab). This ensures the conditional render blocks (checks of activeChartTab and isAdminUser for spec_user_rank_bar) always have a valid tab selected.web/src/hooks/dashboard/useDashboardData.js (1)
254-259: Consider parallelizing independent refresh calls.
loadUptimeDataandloadTopUsersDatadon’t depend on quota response, so running them concurrently can reduce refresh latency.⚡ Suggested refactor
const refresh = useCallback(async () => { - const data = await loadQuotaData(); - await loadUptimeData(); - await loadTopUsersData(); + const [data] = await Promise.all([ + loadQuotaData(), + loadUptimeData(), + loadTopUsersData(), + ]); return data; }, [loadQuotaData, loadUptimeData, loadTopUsersData]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/hooks/dashboard/useDashboardData.js` around lines 254 - 259, The refresh function currently awaits loadQuotaData, then sequentially awaits loadUptimeData and loadTopUsersData; kick off loadUptimeData and loadTopUsersData concurrently (e.g. call them to get promises first) and then await those promises together with Promise.all (or Promise.allSettled) while still awaiting loadQuotaData to return its value; update the refresh implementation (function name refresh, and calls to loadQuotaData, loadUptimeData, loadTopUsersData) to start the two independent calls in parallel and await them together to reduce latency.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@controller/usedata.go`:
- Around line 59-61: The current check resets limit to 10 for any non-positive
or overly large value; change this to clamp properly by keeping the default of
10 only when limit <= 0 and otherwise capping values > 100 to 100 — e.g. replace
the single if (limit <= 0 || limit > 100) { limit = 10 } with two checks: if
limit <= 0 { limit = 10 } else if limit > 100 { limit = 100 }; update the code
that uses the variable limit accordingly (look for the variable named "limit" in
controller/usedata.go).
In `@model/usedata.go`:
- Around line 133-137: The query currently groups by both user_id and username
(see DB.Table("quota_data") Select(...) and Group("user_id, username")) which
causes the same user to be split across rows when their username changes; change
the Group call to group only by "user_id" (Group("user_id")) and, if you still
need a username column in the Select, replace the raw username select with an
aggregated expression such as MAX(username) AS username (or similar) so the
SELECT and GROUP clauses remain consistent.
In `@web/src/components/dashboard/index.jsx`:
- Around line 144-163: The effect currently only updates the user-rank chart
when dashboardData.topUsersData has length > 0, which leaves stale chart data
when it becomes an empty array; change the logic around
dashboardData.topUsersData so it runs whenever topUsersData is defined (e.g.,
Array.isArray(dashboardData.topUsersData)), compute userRankData =
dashboardData.topUsersData.map(...) (will be [] when empty), and always call
dashboardCharts.setSpecUserRankBar to set data to the new values array and
update title.subtext to reflect the current count (userRankData.length),
ensuring the chart is cleared and subtitle shows zero when topUsersData is [].
In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 220-243: When loading top users in loadTopUsersData, ensure stale
results are cleared on non-success and error paths by calling
setTopUsersData([]) whenever the API response is not successful (inside the else
branch) and also in the catch block; keep setTopUsersLoading(false) in finally
as-is and keep references to inputs and isAdminUser unchanged.
---
Nitpick comments:
In `@web/src/components/dashboard/ChartsPanel.jsx`:
- Around line 59-82: When isAdminUser flips to false while activeChartTab ===
'5' the panel can render nothing; add a guard in the ChartsPanel component to
normalize activeChartTab when permissions change: inside the component (where
activeChartTab and setActiveChartTab are defined) add an effect that watches
isAdminUser and activeChartTab and, if isAdminUser is false and activeChartTab
=== '5', call setActiveChartTab to a valid fallback (e.g. '1' or the current
first visible tab). This ensures the conditional render blocks (checks of
activeChartTab and isAdminUser for spec_user_rank_bar) always have a valid tab
selected.
In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx`:
- Around line 444-459: The avatar uses displayText for the visible character but
still hashes the original text for color, causing mismatches; update the Avatar
usage in the render block (component Avatar inside UsageLogsColumnDefs) to call
stringToColor with the same source as the avatar text (displayText derived from
record.display_name || text) so both the character and color are computed from
the same value, and keep the onClick handler (showUserInfoFunc) and trimming
logic (displayText.slice(0,1)) unchanged.
In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 254-259: The refresh function currently awaits loadQuotaData, then
sequentially awaits loadUptimeData and loadTopUsersData; kick off loadUptimeData
and loadTopUsersData concurrently (e.g. call them to get promises first) and
then await those promises together with Promise.all (or Promise.allSettled)
while still awaiting loadQuotaData to return its value; update the refresh
implementation (function name refresh, and calls to loadQuotaData,
loadUptimeData, loadTopUsersData) to start the two independent calls in parallel
and await them together to reduce latency.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e2f6b9d2-856f-447e-ac95-e98420d0e279
📒 Files selected for processing (10)
controller/usedata.gomodel/log.gomodel/usedata.gorouter/api-router.goweb/src/components/dashboard/ChartsPanel.jsxweb/src/components/dashboard/index.jsxweb/src/components/table/usage-logs/UsageLogsColumnDefs.jsxweb/src/hooks/dashboard/useDashboardCharts.jsxweb/src/hooks/dashboard/useDashboardData.jsweb/src/i18n/locales/en.json
…tion links and submission checks
Round remaining balance
enhance channel key viewing
Prevent stale “top users” chart when result is empty.
There was a problem hiding this comment.
♻️ Duplicate comments (1)
web/src/components/dashboard/index.jsx (1)
144-164:⚠️ Potential issue | 🟠 MajorFix stale “用户消耗排行” chart when data becomes empty.
Line 144 still blocks updates for
[], so old bars/subtitle can persist. This issue appears unresolved from the earlier review.🔧 Suggested fix
- useEffect(() => { - if (dashboardData.topUsersData && dashboardData.topUsersData.length > 0) { - const userRankData = (dashboardData.topUsersData || []).map((item) => ({ - username: item.username, - quota: item.quota, - })); - - dashboardCharts.setSpecUserRankBar((prev) => ({ - ...prev, - data: [ - { - id: 'userRankData', - values: userRankData, - }, - ], - title: { - ...prev.title, - subtext: `${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`, - }, - })); - } - }, [dashboardData.topUsersData, dashboardData.t, dashboardCharts.setSpecUserRankBar]); + useEffect(() => { + if (!Array.isArray(dashboardData.topUsersData)) return; + const userRankData = dashboardData.topUsersData.map((item) => ({ + username: item.username, + quota: item.quota, + })); + + dashboardCharts.setSpecUserRankBar((prev) => ({ + ...prev, + data: [ + { + id: 'userRankData', + values: userRankData, + }, + ], + title: { + ...prev.title, + subtext: `${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`, + }, + })); + }, [dashboardData.topUsersData, dashboardData.t, dashboardCharts.setSpecUserRankBar]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/dashboard/index.jsx` around lines 144 - 164, The effect currently skips updates when dashboardData.topUsersData is an empty array, leaving stale bars and subtitle; change the logic in the effect using dashboardData.topUsersData and dashboardCharts.setSpecUserRankBar so it always runs for both non-empty and empty arrays: compute userRankData = (dashboardData.topUsersData || []).map(...) (or just use the fallback empty array), then call dashboardCharts.setSpecUserRankBar to set data to an object with id 'userRankData' and values userRankData (which will be [] when empty) and update the title.subtext to reflect the current count (e.g., `${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`), removing the conditional that requires length > 0 so the chart is cleared when data becomes empty.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@web/src/components/dashboard/index.jsx`:
- Around line 144-164: The effect currently skips updates when
dashboardData.topUsersData is an empty array, leaving stale bars and subtitle;
change the logic in the effect using dashboardData.topUsersData and
dashboardCharts.setSpecUserRankBar so it always runs for both non-empty and
empty arrays: compute userRankData = (dashboardData.topUsersData || []).map(...)
(or just use the fallback empty array), then call
dashboardCharts.setSpecUserRankBar to set data to an object with id
'userRankData' and values userRankData (which will be [] when empty) and update
the title.subtext to reflect the current count (e.g.,
`${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`),
removing the conditional that requires length > 0 so the chart is cleared when
data becomes empty.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ad060448-d5c3-4ccf-ab95-08118a2c736c
📒 Files selected for processing (1)
web/src/components/dashboard/index.jsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
web/src/hooks/dashboard/useDashboardData.js (1)
257-262: Sequential API calls are acceptable, but parallel execution is an option.The
refreshfunction awaits three API calls sequentially. For admin users viewing the dashboard, this means serial latency.♻️ Optional: Parallel data loading for faster refresh
const refresh = useCallback(async () => { - const data = await loadQuotaData(); - await loadUptimeData(); - await loadTopUsersData(); + const [data] = await Promise.all([ + loadQuotaData(), + loadUptimeData(), + loadTopUsersData(), + ]); return data; }, [loadQuotaData, loadUptimeData, loadTopUsersData]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/hooks/dashboard/useDashboardData.js` around lines 257 - 262, The refresh function currently awaits three API calls sequentially (refresh) which increases latency; modify refresh to start all three loads concurrently using Promise.all on loadQuotaData(), loadUptimeData(), and loadTopUsersData() and await them together so they run in parallel, then return the quota result (the resolved value from loadQuotaData) to preserve the existing return shape; locate the refresh function and the loadQuotaData, loadUptimeData, and loadTopUsersData references to implement this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 257-262: The refresh function currently awaits three API calls
sequentially (refresh) which increases latency; modify refresh to start all
three loads concurrently using Promise.all on loadQuotaData(), loadUptimeData(),
and loadTopUsersData() and await them together so they run in parallel, then
return the quota result (the resolved value from loadQuotaData) to preserve the
existing return shape; locate the refresh function and the loadQuotaData,
loadUptimeData, and loadTopUsersData references to implement this change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fb1ee8e5-65f7-49a8-83ce-a0e8d55d17ed
📒 Files selected for processing (3)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsxweb/src/hooks/dashboard/useDashboardData.jsweb/src/i18n/locales/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 239-245: The catch block in useDashboardData's top-users fetch
currently only logs errors; update the catch to surface failures to the UI by
introducing and setting an error state (e.g., add setTopUsersError via useState
or reuse an existing global error handler) instead of only console.error,
clear/initialize that error before the fetch, and optionally trigger a
user-visible notification (e.g., enqueueSnackbar or similar) so components
reading top users (references: setTopUsersData, setTopUsersLoading, and the
top-users fetch function inside useDashboardData) can display an error message;
ensure the finally block still sets setTopUsersLoading(false).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: afeb3503-d2bc-45cd-ae87-ab9ae697567f
📒 Files selected for processing (1)
web/src/hooks/dashboard/useDashboardData.js
| } catch (err) { | ||
| setTopUsersData([]); | ||
| console.error(err); | ||
| } finally { | ||
| setTopUsersLoading(false); | ||
| } | ||
| }, [inputs, isAdminUser]); |
There was a problem hiding this comment.
Surface fetch errors to users in the catch path.
At Line 239, request failures currently only log to console, so ranking silently disappears without feedback.
🔧 Suggested patch
const loadTopUsersData = useCallback(async () => {
@@
} catch (err) {
setTopUsersData([]);
+ const errMsg =
+ err?.response?.data?.message || err?.message || t('加载用户消耗排行失败');
+ showError(errMsg);
console.error(err);
} finally {
setTopUsersLoading(false);
}
- }, [inputs, isAdminUser]);
+ }, [inputs, isAdminUser, t]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/hooks/dashboard/useDashboardData.js` around lines 239 - 245, The
catch block in useDashboardData's top-users fetch currently only logs errors;
update the catch to surface failures to the UI by introducing and setting an
error state (e.g., add setTopUsersError via useState or reuse an existing global
error handler) instead of only console.error, clear/initialize that error before
the fetch, and optionally trigger a user-visible notification (e.g.,
enqueueSnackbar or similar) so components reading top users (references:
setTopUsersData, setTopUsersLoading, and the top-users fetch function inside
useDashboardData) can display an error message; ensure the finally block still
sets setTopUsersLoading(false).
|
@Calcium-Ion ??? 发生了什么?强制回滚了? |
Summary by CodeRabbit
New Features
User Experience
Internationalization