token-dashboard-claude-analytics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Token Dashboard — Claude Code Analytics

Token Dashboard — Claude Code 分析工具

Skill by ara.so — Daily 2026 Skills collection.
Token Dashboard reads the JSONL transcripts Claude Code writes to
~/.claude/projects/
and turns them into per-prompt cost analytics, tool/file heatmaps, cache analytics, project comparisons, and a rule-based tips engine. Everything runs locally — no data leaves your machine.
ara.so开发的Skill——属于Daily 2026 Skills合集。
Token Dashboard 读取Claude Code写入
~/.claude/projects/
的JSONL会话记录,将其转化为按提示拆分的成本分析、工具/文件热力图、缓存分析、项目对比以及基于规则的提示引擎。所有操作均在本地运行——数据不会离开你的设备。

Installation

安装

bash
git clone https://github.com/nateherkai/token-dashboard.git
cd token-dashboard
python3 cli.py dashboard
No
pip install
. No Node.js. No build step. Requires Python 3.8+.
Windows:
bash
git clone https://github.com/nateherkai/token-dashboard.git
cd token-dashboard
py -3 cli.py dashboard
bash
git clone https://github.com/nateherkai/token-dashboard.git
cd token-dashboard
python3 cli.py dashboard
无需
pip install
,无需Node.js,无需构建步骤。要求Python 3.8+。
Windows系统:
bash
git clone https://github.com/nateherkai/token-dashboard.git
cd token-dashboard
py -3 cli.py dashboard

Key CLI Commands

核心CLI命令

bash
undefined
bash
undefined
python3 cli.py dashboard
python3 cli.py dashboard

Populate/refresh the SQLite cache, then exit

填充/刷新SQLite缓存,然后退出

python3 cli.py scan
python3 cli.py scan

Print today's totals in the terminal

在终端打印今日使用总计

python3 cli.py today
python3 cli.py today

Print all-time totals in the terminal

在终端打印全时段使用总计

python3 cli.py stats
python3 cli.py stats

Show active optimization tips in terminal

在终端显示当前优化提示

python3 cli.py tips
python3 cli.py tips

Dashboard with options

带选项启动仪表盘

python3 cli.py dashboard --no-open # don't auto-open browser python3 cli.py dashboard --no-scan # skip initial scan, use cached DB only python3 cli.py dashboard --projects-dir /path/to/projects --db /path/to/cache.db
undefined
python3 cli.py dashboard --no-open # 不自动打开浏览器 python3 cli.py dashboard --no-scan # 跳过初始扫描,仅使用缓存数据库 python3 cli.py dashboard --projects-dir /path/to/projects --db /path/to/cache.db
undefined

Configuration

配置

Environment Variables

环境变量

bash
undefined
bash
undefined

Change port (default: 8080)

修改端口(默认:8080)

PORT=9000 python3 cli.py dashboard
PORT=9000 python3 cli.py dashboard

Change bind address (WARNING: keep 127.0.0.1 — 0.0.0.0 exposes data on network)

修改绑定地址(警告:保持为127.0.0.1——0.0.0.0会在网络上暴露数据)

HOST=127.0.0.1 python3 cli.py dashboard
HOST=127.0.0.1 python3 cli.py dashboard

Custom projects directory

自定义项目目录

CLAUDE_PROJECTS_DIR=/custom/path python3 cli.py dashboard
CLAUDE_PROJECTS_DIR=/custom/path python3 cli.py dashboard

Custom SQLite cache location

自定义SQLite缓存位置

TOKEN_DASHBOARD_DB=/custom/path/cache.db python3 cli.py dashboard
undefined
TOKEN_DASHBOARD_DB=/custom/path/cache.db python3 cli.py dashboard
undefined

Pricing Configuration

定价配置

Edit
pricing.json
directly to update model prices or add plans:
json
{
  "models": {
    "claude-opus-4-5": {
      "input": 15.00,
      "output": 75.00,
      "cache_write": 18.75,
      "cache_read": 1.50
    }
  },
  "plans": {
    "api": { "label": "API", "multiplier": 1.0 },
    "pro": { "label": "Pro ($20/mo)", "multiplier": 0.0 },
    "max": { "label": "Max ($100/mo)", "multiplier": 0.0 }
  }
}
直接编辑
pricing.json
来更新模型价格或添加套餐:
json
{
  "models": {
    "claude-opus-4-5": {
      "input": 15.00,
      "output": 75.00,
      "cache_write": 18.75,
      "cache_read": 1.50
    }
  },
  "plans": {
    "api": { "label": "API", "multiplier": 1.0 },
    "pro": { "label": "Pro ($20/mo)", "multiplier": 0.0 },
    "max": { "label": "Max ($100/mo)", "multiplier": 0.0 }
  }
}

Data Sources

数据源

Claude Code writes session JSONL files here:
OSPath
macOS / Linux
~/.claude/projects/<project-slug>/<session-id>.jsonl
Windows
C:\Users\<you>\.claude\projects\<project-slug>\<session-id>.jsonl
The dashboard only reads these files — never modifies them. It caches results in SQLite at
~/.claude/token-dashboard.db
.
Claude Code将会话JSONL文件写入以下位置:
操作系统路径
macOS / Linux
~/.claude/projects/<project-slug>/<session-id>.jsonl
Windows
C:\Users\<you>\.claude\projects\<project-slug>\<session-id>.jsonl
仪表盘仅读取这些文件——绝不会修改它们。它会将结果缓存到
~/.claude/token-dashboard.db
的SQLite数据库中。

Dashboard Tabs

仪表盘标签页

TabWhat it shows
OverviewAll-time totals, daily charts, cost by plan, top tools, recent sessions
PromptsMost expensive user prompts ranked by tokens; click to see tool calls and result sizes
SessionsTurn-by-turn view with per-turn tokens and tool calls
ProjectsPer-project comparison: tokens, sessions, files touched
SkillsMost-invoked skills and their token costs
TipsRule-based suggestions (repeated file reads, oversized tool results, low cache-hit rate)
SettingsSwitch between API / Pro / Max pricing plans
标签页展示内容
概览全时段总计、每日图表、按套餐划分的成本、高频使用工具、近期会话
提示按令牌数排序的最昂贵用户提示;点击可查看工具调用和结果大小
会话逐轮次视图,包含每轮的令牌数和工具调用
项目项目对比:令牌数、会话数、涉及文件
Skills调用最频繁的Skills及其令牌成本
提示建议基于规则的优化建议(重复文件读取、过大工具结果、低缓存命中率)
设置在API / Pro / Max定价套餐间切换

API Endpoints

API端点

The dashboard exposes JSON endpoints at
http://127.0.0.1:8080/api/
:
bash
undefined
仪表盘在
http://127.0.0.1:8080/api/
暴露JSON端点:
bash
undefined

Overview stats

概览统计

Most expensive prompts

最昂贵的提示

Session list

会话列表

Single session detail

单个会话详情

Project comparison

项目对比

Optimization tips

优化提示建议

Real Code Examples

代码示例

Scripting Against the SQLite Cache

基于SQLite缓存编写脚本

After running
python3 cli.py scan
, query the cache directly:
python
import sqlite3
import os

db_path = os.path.expanduser("~/.claude/token-dashboard.db")
conn = sqlite3.connect(db_path)
运行
python3 cli.py scan
后,可直接查询缓存:
python
import sqlite3
import os

db_path = os.path.expanduser("~/.claude/token-dashboard.db")
conn = sqlite3.connect(db_path)

Get top 10 most expensive prompts

获取前10个最昂贵的提示

cursor = conn.execute(""" SELECT project_slug, session_id, input_tokens, output_tokens, cache_read_tokens, cost_usd, substr(user_text, 1, 80) as prompt_preview FROM turns ORDER BY cost_usd DESC LIMIT 10 """)
for row in cursor.fetchall(): print(f"${row[5]:.4f} | {row[0]} | {row[6]}")
conn.close()
undefined
cursor = conn.execute(""" SELECT project_slug, session_id, input_tokens, output_tokens, cache_read_tokens, cost_usd, substr(user_text, 1, 80) as prompt_preview FROM turns ORDER BY cost_usd DESC LIMIT 10 """)
for row in cursor.fetchall(): print(f"${row[5]:.4f} | {row[0]} | {row[6]}")
conn.close()
undefined

Get Daily Token Totals

获取每日令牌总计

python
import sqlite3
import os

db_path = os.path.expanduser("~/.claude/token-dashboard.db")
conn = sqlite3.connect(db_path)

cursor = conn.execute("""
    SELECT
        date(created_at) as day,
        SUM(input_tokens) as total_input,
        SUM(output_tokens) as total_output,
        SUM(cache_read_tokens) as total_cache_read,
        SUM(cost_usd) as total_cost
    FROM turns
    GROUP BY date(created_at)
    ORDER BY day DESC
    LIMIT 30
""")

for row in cursor.fetchall():
    print(f"{row[0]}: ${row[4]:.4f} ({row[1]} in, {row[2]} out, {row[3]} cached)")

conn.close()
python
import sqlite3
import os

db_path = os.path.expanduser("~/.claude/token-dashboard.db")
conn = sqlite3.connect(db_path)

cursor = conn.execute("""
    SELECT
        date(created_at) as day,
        SUM(input_tokens) as total_input,
        SUM(output_tokens) as total_output,
        SUM(cache_read_tokens) as total_cache_read,
        SUM(cost_usd) as total_cost
    FROM turns
    GROUP BY date(created_at)
    ORDER BY day DESC
    LIMIT 30
""")

for row in cursor.fetchall():
    print(f"{row[0]}: ${row[4]:.4f} ({row[1]} in, {row[2]} out, {row[3]} cached)")

conn.close()

Programmatic Scan via Python

通过Python程序化扫描

python
import sys
import os
python
import sys
import os

Add the project root to path

将项目根目录添加到路径

sys.path.insert(0, '/path/to/token-dashboard')
from token_dashboard.scanner import Scanner
projects_dir = os.path.expanduser("/.claude/projects") db_path = os.path.expanduser("/.claude/token-dashboard.db")
scanner = Scanner(projects_dir=projects_dir, db_path=db_path) scanner.scan() print("Scan complete")
undefined
sys.path.insert(0, '/path/to/token-dashboard')
from token_dashboard.scanner import Scanner
projects_dir = os.path.expanduser("/.claude/projects") db_path = os.path.expanduser("/.claude/token-dashboard.db")
scanner = Scanner(projects_dir=projects_dir, db_path=db_path) scanner.scan() print("扫描完成")
undefined

Fetch Overview Stats Programmatically

程序化获取概览统计

python
import urllib.request
import json
python
import urllib.request
import json

Requires dashboard to be running: python3 cli.py dashboard --no-open

需要仪表盘处于运行状态:python3 cli.py dashboard --no-open

with urllib.request.urlopen("http://127.0.0.1:8080/api/overview") as resp: data = json.loads(resp.read())
print(f"Total sessions: {data['total_sessions']}") print(f"Total cost (API): ${data['total_cost_usd']:.2f}") print(f"Cache hit rate: {data['cache_hit_rate']:.1%}")
undefined
with urllib.request.urlopen("http://127.0.0.1:8080/api/overview") as resp: data = json.loads(resp.read())
print(f"总会话数: {data['total_sessions']}") print(f"总成本(API): ${data['total_cost_usd']:.2f}") print(f"缓存命中率: {data['cache_hit_rate']:.1%}")
undefined

Common Patterns

常见用法

Reset and Rebuild the Cache

重置并重建缓存

bash
rm ~/.claude/token-dashboard.db
python3 cli.py scan
bash
rm ~/.claude/token-dashboard.db
python3 cli.py scan

Run on a Different Port to Avoid Conflicts

使用不同端口避免冲突

bash
PORT=9090 python3 cli.py dashboard
bash
PORT=9090 python3 cli.py dashboard

Export Tips to File

将提示建议导出到文件

bash
python3 cli.py tips > optimization-tips.txt
bash
python3 cli.py tips > optimization-tips.txt

Automate Daily Stats Logging

自动记录每日统计

bash
undefined
bash
undefined

Add to crontab: 0 9 * * * /path/to/daily-stats.sh

添加到crontab: 0 9 * * * /path/to/daily-stats.sh

cd /path/to/token-dashboard && python3 cli.py today >> ~/claude-usage-log.txt
undefined
cd /path/to/token-dashboard && python3 cli.py today >> ~/claude-usage-log.txt
undefined

Point at a Different Projects Directory

指定不同的项目目录

bash
undefined
bash
undefined

If Claude Code projects are in a non-standard location

如果Claude Code项目位于非标准位置

python3 cli.py dashboard --projects-dir ~/work/.claude/projects
undefined
python3 cli.py dashboard --projects-dir ~/work/.claude/projects
undefined

Troubleshooting

故障排除

ProblemSolution
"No data" / empty chartsRun
python3 cli.py scan
then reload
Port 8080 in use
PORT=9000 python3 cli.py dashboard
Numbers stuck/wrongDelete
~/.claude/token-dashboard.db
, re-run
python3 cli.py scan
Two instances runningStop all instances first — they fight over the SQLite DB
python3
not found on Windows
Use
py -3
instead
No sessions foundEnsure Claude Code has been used and files exist in
~/.claude/projects/
问题解决方案
"无数据"/图表为空运行
python3 cli.py scan
然后重新加载页面
端口8080被占用使用
PORT=9000 python3 cli.py dashboard
数据停滞/错误删除
~/.claude/token-dashboard.db
,重新运行
python3 cli.py scan
两个实例同时运行先停止所有实例——它们会争夺SQLite数据库
Windows系统找不到
python3
使用
py -3
替代
未找到会话确保已使用Claude Code,且
~/.claude/projects/
目录下存在文件

Architecture Overview

架构概览

cli.py
  └─► token_dashboard/scanner.py   # reads JSONL, dedupes by message.id, writes SQLite
  └─► token_dashboard/server.py    # serves /api/* JSON routes + web/ static files
        └─► web/                   # vanilla JS + vendored ECharts, no build step
pricing.json                       # editable model/plan pricing
~/.claude/token-dashboard.db       # SQLite cache (auto-created)
Deduplication note: Claude Code writes each assistant response 2–3 times during streaming. The scanner dedupes by
message.id
so tallies match actual API billing — expect lower numbers than tools that sum every raw JSONL row.
cli.py
  └─► token_dashboard/scanner.py   # 读取JSONL,按message.id去重,写入SQLite
  └─► token_dashboard/server.py    # 提供/api/* JSON路由 + web/静态文件
        └─► web/                   # 原生JS + 引入的ECharts,无需构建步骤
pricing.json                       # 可编辑的模型/套餐定价
~/.claude/token-dashboard.db       # SQLite缓存(自动创建)
去重说明: Claude Code在流式传输过程中会将每个助手响应写入2–3次。扫描器会按
message.id
去重,因此统计结果与实际API账单一致——相比那些直接累加所有原始JSONL行的工具,这里的数值会更低。