Enterprise AI Usage Monitoring & Analytics Platform
Real-time GitHub Copilot AI Credits monitoring with automatic data synchronization
中文版 | English
- ✨ Features
- 🛠️ Tech Stack
- 📁 Project Structure
- 🚀 Quick Start
- 📊 Data Source
- 🔌 API Documentation
- 🌐 Internationalization
- 🔒 IP Whitelist
- 📜 Scripts
- 📄 License
| Feature | Description |
|---|---|
| 📊 Monthly Total | Hero card with animated number showing total AI Credits consumed |
| 👥 User Usage | Bar chart by user + model breakdown table with hover effects |
| 🤖 Model Usage | Bar chart + pie chart for model distribution analysis |
| 🔌 GitHub API | Automatic data sync via GitHub Billing API (no manual CSV export) |
| ⚡ Concurrent Fetching | Parallel API calls for fast data loading |
| 💾 Smart Caching | 2-hour TTL cache + aggregated response cache (5 keys) + hourly warm-up |
| 🖥️ SSR Instant Render | Server-side injects first-screen JSON, zero-delay page display |
| 🔄 Stale-While-Revalidate | sessionStorage cache with background refresh, no blank screen on reload |
| 🛡️ singleflight | Prevents duplicate GitHub API calls for the same cache key under concurrent requests |
| Auto-detects GitHub API quota, throttles warming when limit approached | |
| 🎨 Loading Animation | Full-screen overlay with CSS3 ring animation |
| 🌐 i18n Support | Chinese/English toggle with localStorage persistence |
| 🔒 IP Whitelist | Access control with exact IP and CIDR subnet support |
| 📜 Process Management | Start/stop/restart/reload with PID file tracking + graceful shutdown |
| 🔁 CDN Fallback | jQuery/ECharts auto-switch to cdnjs mirror when primary CDN fails |
| Layer | Technology |
|---|---|
| 🖥️ Backend | Go 1.26 + Gin v1.12 |
| ⚙️ Config | Viper v1.21 + TOML |
| 🎨 Frontend | Vanilla HTML/CSS/JS + jQuery 4.0 + ECharts 6.1 |
| 🌐 i18n | Custom implementation with data-i18n attributes |
| 🔌 API | GitHub Billing API (AI Credit usage) |
CopilotLens/
├── main.go # 🚀 Entry point + graceful shutdown + warm-up
│
├── domain/dto/ # 📦 Data Transfer Objects
│ ├── copilot.go # CopilotRecord
│ ├── monthly_total.go # MonthlyTotalResponse
│ ├── monthly_user.go # UserUsage, UserModel, MonthlyUserResponse
│ └── monthly_model.go # ModelUsage, MonthlyModelResponse
│
├── internal/ # 🔧 Internal packages
│ ├── client/ # Data loading utilities
│ │ └── client.go # LoadUsers, LoadUsernameMap, Round2
│ ├── config/ # Configuration (init() auto-load)
│ │ └── config.go # AppConfig + Config() getter
│ ├── github/ # GitHub API client
│ │ ├── client.go # Billing API + singleflight + rate limit
│ │ └── cache.go # CacheManager (2h TTL, RWMutex, LRU 5000)
│ ├── handler/ # HTTP handlers
│ │ ├── common.go # InjectInitialData (SSR JSON injection)
│ │ ├── render.go # renderPage + parseDateOrMonth
│ │ ├── router.go # Route registration + IPWhitelist middleware
│ │ ├── total.go # MonthlyTotal handler
│ │ ├── user.go # MonthlyUser + DailyUser handlers
│ │ └── model.go # MonthlyModel + DailyModel handlers
│ └── service/ # Business logic layer
│ └── usage.go # UsageService: 5 GetXXX + 5 BuildXXX + singleflight
│
├── tasks/ # ⏱️ Background tasks
│ ├── common.go # Init/Stop + task registry
│ ├── cache_clean.go # Cache expiration cleanup (10min)
│ └── cache_warm.go # Hourly cache warm-up + rate limit guard
│
├── web/ # 🎨 Frontend
│ ├── index.html # Homepage with hero banner
│ ├── monthly-total.html # Monthly total with hero card
│ ├── monthly-user.html # User usage charts + table
│ ├── monthly-model.html # Model usage charts
│ └── static/
│ ├── css/style.css # Global styles + loading animation
│ ├── js/common.js # CL module: SSR cache + stale-while-revalidate
│ └── i18n/
│ ├── zh.js # Chinese translations
│ └── en.js # English translations
│
├── data/ # 📊 Data files
│ └── username.csv # Username → display name mapping
│
├── toml/config_template.toml # ⚙️ Config template
├── build.sh / build.ps1 # 🔨 Build scripts
├── run.sh / run.ps1 # ▶️ Process management
├── LICENSE # 📄 MIT License
└── .gitignore
- Go 1.26 or higher
- GitHub Personal Access Token with
copilotscope
# Clone the repository
git clone https://github.com/yuwenlong/CopilotLens.git
cd CopilotLens
# Build (choose your platform)
# Windows
.\build.ps1
# Linux/macOS
chmod +x build.sh
./build.sh# Edit config file
vim bin/conf/config.toml[server]
port = "8880"
whitelist = [] # Empty = allow all IPs
[github]
token = "" # GitHub PAT (or set GITHUB_TOKEN env var)
org = "your-org" # GitHub organization name# Windows
.\run.ps1 start
# Linux/macOS
chmod +x run.sh
./run.sh startOpen your browser and visit: http://localhost:8880
CopilotLens automatically fetches AI Credits usage data from the GitHub Billing API:
- Authentication: Uses GitHub Personal Access Token with
copilotscope - Data Source:
GET /organizations/{org}/settings/billing/ai_credit/usage - Two-tier Caching: Raw data cache (
monthly:,daily:,user_monthly:,user_daily:) + aggregated response cache (resp:monthly_total,resp:monthly_user, etc.) with 2-hour TTL - singleflight: Concurrent requests for the same key share one GitHub API call, preventing thundering herd
- SSR Instant Render: Server injects pre-built JSON into HTML (
{{.InitialData}}), page renders immediately on load - Stale-While-Revalidate: Frontend
common.jsuses sessionStorage for instant display + background refresh - Warm-up: On startup, pre-fetches current month data (raw + aggregated). Hourly scheduled task refreshes on the hour
- Rate Limit Protection: Auto-detects GitHub API quota headers, throttles warm-up when approaching limits
Set your GitHub token via config file or environment variable:
[github]
token = "ghp_xxxxxxxxxxxx"
org = "your-org"Or use environment variable:
export GITHUB_TOKEN="ghp_xxxxxxxxxxxx"The data/username.csv file maps GitHub usernames to display names:
账号,姓名
xxxxxx,xx
yyyyyy,yyPurpose:
- Maps usernames to human-readable display names
- Supports any language (Chinese, English, etc.)
- Used in charts and tables for better readability
- Format:
username,display_name(first row is header)
http://localhost:8880
GET /api/monthly-total?month=YYYY-MMResponse:
{
"month": "2026-06",
"total": 185944.03,
"daily": [
{"date": "2026-06-30", "total": 6429.48},
{"date": "2026-06-29", "total": 6528.43}
]
}GET /api/monthly-user?month=YYYY-MMResponse:
{
"month": "2026-06",
"users": [
{
"username": "aaaaa",
"name": "xx",
"total": 8542.33,
"cost": 85.42,
"models": [
{ "model": "GPT-5.4", "total": 4200.12, "cost": 42.00 },
{ "model": "Claude Sonnet 4.6", "total": 4342.21, "cost": 43.42 }
]
}
]
}GET /api/daily-user?date=YYYY-MM-DDResponse: Same structure as monthly, but for a single day.
GET /api/monthly-model?month=YYYY-MMResponse:
{
"month": "2026-06",
"models": [
{ "model": "GPT-5.4", "total": 15234.56, "cost": 152.35 },
{ "model": "Claude Sonnet 4.6", "total": 12456.78, "cost": 124.57 }
]
}GET /api/daily-model?date=YYYY-MM-DDResponse: Same structure as monthly, but for a single day.
Click the "中 | EN" button in the navigation bar to switch languages.
- Default language: Chinese (zh)
- Toggle sets
localStorage('lang')to'en'or'zh' - Page reloads and loads the appropriate i18n file
- All
data-i18nattributes are dynamically translated
Edit web/static/i18n/zh.js and web/static/i18n/en.js:
window.i18n = {
title: {
index: 'Copilot AI Credits 用量分析系统',
// ... more keys
}
};Edit bin/conf/config.toml:
[server]
port = "8880"
# Empty array = allow all IPs
whitelist = []
# Or specify allowed IPs/subnets
whitelist = [
"127.0.0.1",
"::1",
"192.168.1.0/24",
"10.0.0.0/8"
]| Format | Example | Description |
|---|---|---|
| Exact IP | 192.168.1.100 |
Single IP address |
| IPv6 | ::1 |
Loopback address |
| CIDR | 192.168.1.0/24 |
Subnet range (256 addresses) |
| CIDR | 10.0.0.0/8 |
Large subnet (16M addresses) |
- ✅ Empty whitelist: Allow all IPs
- ❌ Non-empty whitelist: Only listed IPs/subnets can access
- 🚫 Blocked: Returns
403 Forbiddenwith{"error": "ip not allowed"}
| Script | Platform | Purpose |
|---|---|---|
build.ps1 |
Windows | Compile Go binary + copy assets to bin/ |
build.sh |
Linux/macOS | Same as above |
| Command | Description |
|---|---|
./run.ps1 start |
Start server in background |
./run.ps1 stop |
Stop running server |
./run.ps1 restart |
Restart server (no rebuild) |
./run.ps1 reload |
Rebuild + restart |
- Server PID is stored in
bin/.pid startchecks if server is already runningstopgracefully terminates the processreloadtriggers full rebuild before restart
This project is licensed under the MIT License - see the LICENSE file for details.
Built with ❤️ using Go + Gin + ECharts + GitHub API