Skip to content

Dev 1.0.3 - #5023

Closed
jianghu918 wants to merge 9 commits into
QuantumNous:mainfrom
jianghu918:dev-1.0.3
Closed

jianghu918 wants to merge 9 commits into
QuantumNous:mainfrom
jianghu918:dev-1.0.3

Conversation

@jianghu918

@jianghu918 jianghu918 commented May 21, 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 Token Statistics page for monitoring token consumption by user with date range and username filters
    • Configurable user registration toggle for administrators
    • Improved MIME type detection for file handling
  • Dashboard

    • New token consumption visualization chart displaying per-user metrics
  • UI Updates

    • Added "Token Statistics" navigation item to sidebar
  • Internationalization

    • Added token statistics translations in English, French, Japanese, Russian, Vietnamese, and Chinese
  • Documentation

    • New local development startup guide

Review Change Stack

功能 1:用户使用日志显示请求内容
- 修改 common-logs-columns.tsx,对于消费日志(type=2)直接显示 content 字段

功能 2:新增 Token 统计菜单
- 后端:controller/log.go 添加 GetTokenStats API
- 后端:model/log.go 添加 TokenStat 结构和查询函数
- 路由:/api/log/token_stats
- 前端:features/token-stats/ 组件,支持时间范围和用户筛选
- 前端:按用户统计输入/输出 Token,单位为 m(百万)
- 侧边栏添加菜单入口
- 国际化:中英文翻译
功能更新:
1. 系统设置菜单(管理员专用)
   - 系统名称、Logo 配置
   - 公告管理(dashboard/overview 显示)
   - 常见问答管理(FAQ)
   - 运行时间监控(Uptime Kuma)
   - 权限控制:role >= 10 可访问

2. 用户请求日志增强
   - Content 字段只对管理员显示
   - 日志详情弹窗同样限制
   - 保存用户发送的 prompt 内容

3. 版本号修复
   - 创建 VERSION 文件
   - 修复前端显示"未知版本"问题

修改文件:
- service/quota.go: 添加 extractUserPrompt 函数
- service/text_quota.go: 保存用户 prompt
- web/default/src/hooks/use-sidebar-data.ts: 添加系统设置菜单
- web/default/src/routes/_authenticated/system-settings/route.tsx: 权限控制
- web/default/src/features/usage-logs/components/columns/common-logs-columns.tsx: Content 列权限
- web/default/src/features/usage-logs/components/dialogs/details-dialog.tsx: 详情弹窗权限
- VERSION: 版本号 dev-1.0.2
- 新增 TokenStatItem 类型定义
- 新增 getTokenStats API 调用
- 新增 processTokenChartData 堆叠柱状图处理函数
- 新增 TokenCharts 组件,展示输入/输出 Token 排行
- 集成到 users 页面,显示在用户消耗趋势下方
- 堆叠柱状图显示:X轴用户名,Y轴Token数(k),蓝色输入+绿色输出
- 支持时间范围选择和 Top N 筛选
- refactor: Move GetMimeTypeByExtension to common package, remove duplicate
- feat: Add text file decoding for Claude media messages
- feat: Add MIME type sniffing for base64 files
- feat: Add Claude request support for quota user prompt extraction
- fix: Reduce Log.Content column from longtext to text
- fix: Various web component fixes (token charts, api keys, logs)
- fix: Add MIME type support for OpenAI file sources
@jianghu918

Copy link
Copy Markdown
Author

marge

@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f6bb7497-d999-44a0-acc9-2c601e369aa5

📥 Commits

Reviewing files that changed from the base of the PR and between 006e801 and e4102c1.

📒 Files selected for processing (51)
  • Dockerfile.local
  • VERSION
  • build-and-deploy.sh
  • common/constants.go
  • common/mime.go
  • controller/log.go
  • controller/oauth.go
  • controller/user.go
  • docker-compose.dev.yml
  • docker-compose.yml
  • dto/openai_request.go
  • i18n/locales/en.yaml
  • i18n/locales/zh-CN.yaml
  • i18n/locales/zh-TW.yaml
  • migration-1.0.3.sql
  • model/log.go
  • model/option.go
  • relay/channel/claude/relay-claude.go
  • router/api-router.go
  • service/file_decoder.go
  • service/file_service.go
  • service/quota.go
  • service/text_quota.go
  • web/default/src/features/dashboard/api.ts
  • web/default/src/features/dashboard/components/users/token-charts.tsx
  • web/default/src/features/dashboard/index.tsx
  • web/default/src/features/dashboard/lib/charts.ts
  • web/default/src/features/dashboard/lib/index.ts
  • web/default/src/features/dashboard/types.ts
  • web/default/src/features/keys/components/api-keys-dialogs.tsx
  • web/default/src/features/token-stats/api.ts
  • web/default/src/features/token-stats/components/token-stats-table.tsx
  • web/default/src/features/token-stats/index.tsx
  • web/default/src/features/token-stats/section-registry.tsx
  • web/default/src/features/token-stats/types.ts
  • web/default/src/features/usage-logs/components/columns/common-logs-columns.tsx
  • web/default/src/features/usage-logs/components/common-logs-filter-bar.tsx
  • web/default/src/features/usage-logs/components/dialogs/details-dialog.tsx
  • web/default/src/hooks/use-sidebar-config.ts
  • web/default/src/hooks/use-sidebar-data.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
  • web/default/src/routeTree.gen.ts
  • web/default/src/routes/_authenticated/system-settings/route.tsx
  • web/default/src/routes/_authenticated/token-stats/$section.tsx
  • web/default/src/routes/_authenticated/token-stats/index.tsx
  • 本地开发启动.md

Walkthrough

This PR introduces a comprehensive token statistics feature with backend aggregation and frontend dashboards, centralizes MIME type detection across services, adds a user registration toggle flag, enhances usage logs UI with admin-only content visibility, and improves local development setup through Docker automation and documentation.

Changes

Token Statistics Backend & Frontend

Layer / File(s) Summary
Token statistics backend (model, controller, router)
model/log.go, controller/log.go, router/api-router.go, i18n/locales/*
Aggregates per-username token consumption from logs with optional filters (time range, username, model, channel, group), exposes /api/log/token_stats endpoint protected by AdminAuth(), includes localized error messages for query failures.
Token statistics frontend types and API
web/default/src/features/token-stats/types.ts, web/default/src/features/token-stats/api.ts, web/default/src/features/dashboard/types.ts, web/default/src/features/dashboard/api.ts
Defines TokenStat schema with Zod validation, API client functions for querying token stats with optional filters, and TokenStatItem type for dashboard integration.
Token statistics page, routes, and navigation
web/default/src/features/token-stats/index.tsx, web/default/src/features/token-stats/section-registry.tsx, web/default/src/routes/_authenticated/token-stats/*, web/default/src/routeTree.gen.ts
TanStack Router routes with section-based navigation, default section redirect, and route tree generation with proper type augmentations.
Token statistics table UI component
web/default/src/features/token-stats/components/token-stats-table.tsx
Interactive table with date range and optional admin-only username filters, fetches aggregated token stats on query submission, displays loading/empty states, formats tokens as millions (m) suffix, computes and shows aggregate totals.
Dashboard token consumption charts
web/default/src/features/dashboard/components/users/token-charts.tsx, web/default/src/features/dashboard/lib/charts.ts
Stacked bar chart component with time range presets and top-user limit controls, lazy theme loading via VisActor ThemeManager, React Query integration, chart data processing with user sorting and tooltip configuration.

User Registration Toggle and Auth Changes

Layer / File(s) Summary
User registration enable/disable flag and guards
common/constants.go, controller/oauth.go, controller/user.go, model/option.go
Adds global UserRegistrationEnabled flag (default true) with early-exit guards in OAuth and standard registration flows, synchronized via the option map database.
System settings route authorization update
web/default/src/routes/_authenticated/system-settings/route.tsx
Relaxes authorization from requiring exactly ROLE.SUPER_ADMIN to allowing ROLE.ADMIN and above.

MIME Type Centralization and Media Handling

Layer / File(s) Summary
Centralized MIME type detection utility
common/mime.go
New exported utility function that normalizes file extensions and maps them to MIME types, with fallback to application/octet-stream for unknown extensions.
Consolidate MIME detection across services
service/file_decoder.go, service/file_service.go, dto/openai_request.go
Remove duplicate GetMimeTypeByExtension from file_decoder, update file_service to use centralized common utility and add fallback http.DetectContentType sniff for base64 data, update DTO to derive MIME types from file extensions.
Enhanced Claude media message handling
relay/channel/claude/relay-claude.go
Special-case text/* MIME types by base64-decoding and emitting as text content; explicitly classify document/image media with proper base64 source field initialization (Type, MediaType, Data).

Prompt Extraction and Consumption Logging

Layer / File(s) Summary
Prompt extraction helpers for OpenAI and Claude formats
service/quota.go
New helpers that safely extract the last user message text from OpenAI-style and Claude-style request payloads, returning empty string on missing/unparseable content.
Integrate prompt extraction into quota endpoints
service/quota.go, service/text_quota.go
WebSocket, audio, and text quota endpoints now log extracted user prompts as primary log content when available.

Usage Logs UI Refinements

Layer / File(s) Summary
Usage logs column definition and admin-only content
web/default/src/features/usage-logs/components/columns/common-logs-columns.tsx
Rename Details column to Content, restrict log.content display to admins viewing consume logs only.
Usage logs filter bar state refactoring
web/default/src/features/usage-logs/components/common-logs-filter-bar.tsx
Convert filter state initialization from useEffect-based sync to useState initializers with searchParams directly.
Details dialog conditional content rendering
web/default/src/features/usage-logs/components/dialogs/details-dialog.tsx
Gate Content section visibility to admins viewing consume logs with non-empty details.

Sidebar Navigation and Frontend Routes

Layer / File(s) Summary
Sidebar navigation items and configuration
web/default/src/hooks/use-sidebar-data.ts, web/default/src/hooks/use-sidebar-config.ts
Add "Token Statistics" (BarChart3 icon) and "System Settings" navigation items; map /token-stats route to existing console.log module enablement checks.
TanStack Router tree generation for token-stats routes
web/default/src/routeTree.gen.ts
Generated additions for authenticated token-stats index and section routes with corresponding type mappings, FileRoutesByPath, FileRoutesByFullPath, and module augmentations.

Docker and Local Development Setup

Layer / File(s) Summary
Multi-stage Dockerfile and version configuration
Dockerfile.local, VERSION
Two-stage build: builder compiles Go binary with prebuilt frontend assets and mirrors them across themes; runtime stage uses slim Debian with minimal dependencies and configures port 3000 and /data working directory.
Docker Compose configurations for dev and production
docker-compose.yml, docker-compose.dev.yml
Update production image tag to new-api:dev-1.0.1; reconfigure dev environment to connect PostgreSQL and Redis via host.docker.internal without in-Compose service dependencies.
End-to-end build and deploy automation script
build-and-deploy.sh
Bash script automating frontend build with Bun, Docker image build, container lifecycle management (stop/remove/run), environment variable configuration (SQL_DSN, Redis, timezone), and local deployment messaging.
Local development startup guide
本地开发启动.md
Documentation describing frontend build workflow and Docker container rebuild/run procedure with all required environment variables and volume mounts.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • QuantumNous/new-api#2455: Both PRs modify French UI translation file with token/label wording updates.
  • QuantumNous/new-api#2669: The retrieved PR implements channel-affinity backend that injects data consumed by the main PR's usage logs UI tag rendering.

Suggested labels

ready to merge

Suggested reviewers

  • Calcium-Ion
  • seefs001

Poem

🐰 A token tally tale, now bold and bright,
With charts that dance and stats in sight,
Admins control who joins the fray,
As MIME types find their rightful way.
From Docker's build to dev's delight! 📊

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch dev-1.0.3

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 and usage tips.

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