A live, btop-style terminal dashboard for the tokens your coding agents burn — Claude Code, Codex CLI and OpenCode, across every local account and backend, as daily, weekly and monthly views. Read-only, offline by default, and no API keys.
Author: Marcel Petrick mail@marcelpetrick.it
Note: this project is generated with AI.
License: GPLv3 or later. See LICENSE.
History: started in codingWithGPT
and moved here with its full history (see CHANGELOG.md 0.3.8); all work
continues in this repository.
Latest stable release: v0.15.0 — truthful quotas and stronger gates, published on 24 November 2026 with wheel and source downloads. See the documentation index for current guides and historical material.
All-time cost now respects each model's long-context threshold, future events stay out of current totals, and separate dashboards synchronize their shared archive. Unknown Claude routes remain unpriced until configured; malformed source records no longer abort ingestion.
OpenAI-routed gpt-6.1-terra usage now has its published standard input,
output, cached-input, cache-write and long-context rates. The source/accounting
audit also confirms that all current Claude records reach the archive and both
Codex homes reconcile with their native comparable totals. See
why native counters can differ for the exact
boundaries.
Keep pressing p to try shuffled category palettes while the dashboard runs.
The timeline, legend and matching breakdown change together, with 20 distinct
colours before repetition. Stop on a combination you like: it is saved privately
and restored on your next launch.
t cycles the overall theme, Space now pauses/resumes refresh, and
Shift+R restores the factory view. The plain theme stays uncoloured.
Try it with .venv/bin/tokenusage2 --demo.
Redacted live view captured with v0.13.33 in a minimal terminal:

Every frame above comes from the real dashboard renderer and deterministic
synthetic data. Identities are fictional and remain redacted throughout. The
animations use LinkedIn's feed-friendly 4:5 format (720 × 900); matching
tour, groupings
and exploration MP4s are included for platforms
that handle video more reliably than animated GIFs. The three tours are also
available as one 42.8-second LinkedIn cut.
Reproduce all seven files with scripts/record_gifs.py,
or explore the same data interactively with tokenusage2 --demo.
git clone https://github.com/marcelpetrick/tokenUsage2.git && cd tokenUsage2
./localPipeline.sh # set up .venv, run every check, build, then launch
.venv/bin/tokenusage2 # afterwards: the live dashboard
.venv/bin/tokenusage2 --doctor # what was found, and does it add up?localPipeline.sh needs nothing but Python 3.14 on the PATH (or
PYTHON=/path/to/python3.14): it creates .venv, installs the project with
its pinned development tools (through uv when it is installed, pip otherwise),
runs every quality gate, builds and verifies the wheel, times each stage and
ends with a verdict — see Development. Once it says
VERDICT: PASS, .venv/bin/tokenusage2 is all you run.
To update an existing checkout, run git pull --ff-only followed by
./localPipeline.sh --noRun, then restart .venv/bin/tokenusage2.
By hand: python3.14 -m venv .venv && .venv/bin/pip install -e .. Without
installing anything: PYTHONPATH=src python3.14 -m tokenusage2.
The first start indexes every transcript once into a local archive; every later start and refresh only reads what was appended. The latest reference run covered 2,135 logs (3.18 GiB): cold indexing took 21.7 s and an unchanged rescan 39 ms.
| Panel | Content |
|---|---|
| Header | Clock, trailing 5-minute rates shown as <total>/min incl cache · <fresh>/min fresh · 5m avg, today / week / month / all-time totals, and optional separate Claude/OpenAI health bubbles. Green means fully operational, yellow means a partial issue or maintenance, red means all tracked components are down, and grey means unknown/checking. |
| Accounts | One row per discovered account: tool, label, e-mail, plan, today/week/month/all, a 24 h sparkline, idle time, total and fresh 5-minute rates, and live 5 h and weekly quota bars with reset countdowns. A dimmed percentage is more than an hour old; ?% reset means the window passed its reset time after the last observation, so its current use is unknown until the agent logs again. ● marks accounts with a running agent process. |
| Timeline | Stacked bars for the last N days, ISO weeks or months — coloured by account, tool, backend, model or project with 20 distinct series colours before the palette repeats. The cursor selects a bar and scrolls back through the whole history. Retained history whose split is unknown is drawn hatched (▒) — in the fresh, output and cost views, which cannot count it, a bucket holding it is marked ░. The neutral cache% row below the dates is aligned with the buckets and shows cache reads / (fresh input + cache reads + cache writes); it is a reuse ratio, not a health status. |
| Breakdown | The selected bar by model (with backend), project, session (with its first and last request), backend, account or tool: calls, fresh input, cache read, cache write, output, total, share, and the same cache-read share of prompt tokens. |
| Live feed | The newest requests as they land — model, project and token split; rows younger than 20 s are highlighted. |
| Heatmap | Hour-of-day × weekday activity over the last four weeks (replaces the feed on h). |
| Sources | Discovered homes and how each was found, file/event counts, archive path, quota freshness, backend hints, provider health, a reconciliation against Codex's own thread totals, and where Claude's tokens come from with the stats-cache scale (s, or --doctor). |
Four metrics are available: all tokens including cache (the raw total), fresh input + output, output only, and the standard-rate cost estimate.
Alerts appear in the status line when a 5 h or weekly quota reaches 90 %
or the five-minute average total-token burn (including cache) climbs far above
the typical active minute of the last seven days — optionally also as a desktop
notification (notify-send) and a terminal bell. Each fires once per quota
window or burn episode; --json lists them.
| Key | Action |
|---|---|
d w m (or 1 2 3) |
daily / weekly / monthly buckets |
← → [ ] |
move the bucket cursor · PgUp PgDn page · Home oldest · End now |
g |
colour the timeline by account → tool → backend → model → project |
b |
breakdown by model → project → session → backend → account → tool |
v |
metric: total incl. cache → fresh → output → standard-rate cost estimate |
a |
filter to one account (cycles, then back to all) |
h |
heatmap ↔ live feed |
s |
sources overlay · i about (author, licence, dependencies, project page) · ? / F1 help · Esc closes overlays |
e |
export the timeline and the breakdown as CSV (to $XDG_DATA_HOME/tokenusage2/exports) |
p |
shuffle category colours; keep pressing to explore palettes |
t |
theme: default, midnight, amber, plain |
x |
redact e-mail addresses |
r |
rescan now (re-runs discovery) · Space pause · + - refresh interval |
Shift+R |
restore factory view settings and forget saved preferences |
q |
quit |
Interactive choices are restored on the next launch: period, timeline grouping,
breakdown, metric, account filter, theme, category palette, redaction,
heatmap/feed view and refresh interval. Each press of p selects a repeatable
shuffled arrangement of the 20 category colours for the timeline, legend and matching breakdown. t changes
the overall theme; the plain theme stays uncoloured. The selected palette stays
stable during refreshes. Preferences are written atomically to
$XDG_STATE_HOME/tokenusage2/view.json (normally
~/.local/state/tokenusage2/view.json) with private permissions. Cursor position,
open overlays, pause state and notices are deliberately session-only. Explicit
CLI options override saved choices; non-interactive --once, --json, --csv
and --doctor keep stable factory defaults unless flags are supplied.
Shift+R immediately restores the factory view and deletes this state file. It
does not modify config.toml, discovered accounts, prices, alert thresholds or
the usage archive.
A home only becomes an account when its content proves it (projects/ for
Claude Code, sessions/ or auth.json for Codex, the database file for
OpenCode). Candidates come from:
- The config file — extra homes you want included.
- The environment —
CLAUDE_CONFIG_DIR,CODEX_HOME. - Running agent processes — the same variables read from
/proc/<pid>/environof every runningclaude/codex, because a shell function such ascodex-work() { CODEX_HOME=~/.codex-work codex; }is gone once the process starts but its environment is not. Only these named variables are extracted; nothing else of a process environment is kept. - Shell rc files — assignments of those variables in
~/.zshrc,~/.bashrc,~/.profile, fish config, … (functions, aliases, exports). - Default locations —
~/.claude,$XDG_CONFIG_HOME/claude,~/.codex,$XDG_DATA_HOME/opencode/opencode.db. - A scan of
$HOMEfor.claude*/.codex*directories (andclaude*/codex*under$XDG_CONFIG_HOME).
One directory reached through several spellings — a symlink, a path in a running agent's environment — is one account. Its id is where the directory really lives, and its name comes from its steadiest spelling: the config file, rc files, default locations and the scan come before the environment and running processes. So neither changes with which agents happen to be running.
Identities come from the tools' own files: Claude's oauthAccount in
.claude.json, and the e-mail and plan claims of Codex's id_token JWT in
auth.json (the token itself is never stored or shown).
Claude Code can be pointed at Ollama or a proxy with ANTHROPIC_BASE_URL, and
the transcripts then still say "Claude Code". tokenUsage2 separates them:
- Anthropic's API stamps every response with a
req_…request id; local Anthropic-compatible servers do not. - Launchers that set
ANTHROPIC_BASE_URLand a model — in rc files or in the environment of a running process — map each model to its host, shown asollama@192.168.1.10orlocalhost:4747. Credentials in URLs are dropped. - The config file can pin model globs to a label and overrides both.
Labels are resolved when the dashboard draws, not stored: the archive keeps only what the log says, so a config change or a newly found launcher relabels the whole history.
Codex reports its provider per session (model_provider), OpenCode per message.
| Tool | Source | Rule |
|---|---|---|
| Claude Code | <home>/projects/**/*.jsonl |
Every content block rewrites the same message, and streaming copies still carry output_tokens: 0: one request per (message.id, requestId) across all homes, keeping the largest copy — a copied home adds nothing and is flagged by --doctor. |
| Claude Code | <home>/stats-cache.json |
Daily totals of UTC days, used only for days before the first surviving transcript's; the split is unknown, so they count toward the raw total only and are drawn hatched. The cache adds up every transcript line — about two per request — so its totals are scaled by the ratio measured on the whole days it shares with transcripts. |
| Claude Code | statusline snapshots (<home>/*rate-limit*.json, $XDG_STATE_HOME/*/quota/claude.json) |
5 h / weekly quota, newest snapshot wins. Claude Code only exposes quota to a statusline hook, e.g. the one installed by abtop --setup. |
| Codex CLI | <home>/sessions/**/rollout-*.jsonl, archived_sessions/ |
token_count events; rate-limit refreshes repeat the same cumulative total, so one increment per (thread, cumulative total) across all homes — a copied home adds nothing and is flagged by --doctor. Compaction restarts the cumulative total; increments after a restart are kept apart from earlier ones with the same total. input_tokens includes the cached part and is split. Matches Codex's own threads.tokens_used (±0–2 %). |
| Codex CLI | the same events | rate_limits per account — live 5 h and weekly quota for each CODEX_HOME. |
| OpenCode | opencode.db, table message |
per assistant message, read past a watermark. A row whose columns do not hold what the schema promises is skipped, like any other unreadable record. |
Claude Code's stats-cache.json adds the usage attached to every transcript
line. One response is commonly written once per content block, so the native
cache total is often about twice the billed-request total. tokenUsage2 keeps one
largest copy per (message.id, requestId) and uses the measured ratio only when
scaling old cache-only days. On 6 November 2026 the measured whole-day ratios
were 0.481 for claude across 43 days and 0.522 for claude-dmo across 44 days;
every currently surviving Claude source key was present in the archive.
Claude's 5-hour and weekly percentages are server-side subscription quota
windows, not raw token totals, so they cannot be derived from or compared
directly with the token columns. Codex's threads.tokens_used is comparable
only for threads both sides still know and only after the latest compaction,
because compaction restarts its cumulative counter. Use s or --doctor for
the live, per-account reconciliation and retained-history explanation.
All tools are normalised to fresh input · cache read · cache write · output
(reasoning is a subset of output). Every request is attributed to its own
timestamp and bucketed by local midnights, so 23- and 25-hour DST days stay
one day. Records dated after the current snapshot time are retained but do not
enter current buckets, summaries, activity or the live feed until their time
arrives. Anthropic's input_tokens contains only fresh tokens after the last
cache breakpoint; total prompt input is fresh + cache read + cache write, which
is why a fresh value can be tiny beside cache r. Exact counts below 1,000
carry the tok suffix; larger values use k, M, B or T.
Project views collapse nested working directories to their Git worktree root.
Claude-created Codex scratchpads are attributed back to their encoded source
project; other temporary working directories are shown as (temporary). The
archive keeps the original working directory unchanged. When unrelated Git
worktrees have the same basename, their labels gain the shortest parent suffix
that distinguishes them (for example work/api and personal/api).
The cost metric (v) and the breakdown's cost column estimate what the tokens
would cost at standard token rates — a list-price figure, not an invoice. Requests
that Anthropic's API answered use Anthropic's published per-model input, output
and cache rates; cache writes distinguish the 5-minute and 1-hour TTL. Requests
an explicitly recognized local route answered cost nothing. Claude records
without a known route remain unpriced unless a price override is configured.
OpenAI-routed Codex and OpenCode records
use the published OpenAI token rates,
including cache writes and the higher full-request tier above 272K prompt tokens;
models without a final published rate show as —.
The cost timeline uses dollar-scaled bars and a Cost per … title; token views
retain token-scaled axes. Current built-ins cover the provider model IDs used by
Claude Code and Codex/OpenCode, including GPT-6.1 Terra and per-request
long-prompt tiers where the provider publishes them.
Model recognition itself is not allow-list based: the parsers retain every
model ID reported by the tools. An unfamiliar model stays visible, but its cost
is marked unpriced until a built-in or [prices] entry supplies a rate.
Recognized local OpenCode routes such as Ollama and LM Studio have a zero token
price; unknown hosted or custom providers remain unpriced rather than assumed free.
An aggregate that mixes priced and unpriced usage is prefixed with ≥, because
the displayed amount is a known lower bound rather than a complete estimate.
Fast/batch service tiers, regional-processing uplifts and non-token tool-call
fees are deliberately excluded from this standard-rate estimate. [prices]
entries override all built-in rates. Retained daily totals stay unpriced
because their split is unknown.
Events are kept in $XDG_DATA_HOME/tokenusage2/archive.sqlite. Files are
tailed from their last offset; a truncated or replaced file is re-read, and
keys make every re-read idempotent. Claude Code deletes old transcripts after
its cleanup period — the archive keeps their history, and accounts whose home
disappeared are listed as archived. An archive that another tokenusage2 is
writing to, that a newer build already migrated, or that is corrupt is reported
as a single line on stderr with exit status 2; a corrupt one names the file to
move aside so the next start rebuilds it.
If an existing archive contains an invalid event timestamp, the dashboard
reports an error and preserves the archive for maintainer-assisted recovery.
Keep that archive: rebuilding from surviving sources can lose retained history.
Measured on 2026-10-11 with
scripts/profile_app.py against the reference
corpus: 2,135 Claude Code and Codex logs, 3.18 GiB of source data and 113,430
events in the retained archive, on Python 3.14. The values below are one
reference run, not latency guarantees; historical ranges remain in the
changelog.
| Stage | Latest measurement | Why steady-state work stays bounded |
|---|---|---|
| Cold index (first start) | 21.7 s | JSONL is streamed; irrelevant Codex lines are rejected from a 256-byte head |
| Warm start (load archive) | 1.85 s | one archive load and one in-memory index build |
| Idle rescan | 39 ms | append-only offsets, sampled checkpoints and incremental /proc scanning |
| Snapshot · day / week / month | 204–275 ms | lifetime totals are maintained incrementally; only visible periods are walked |
| Render 160 × 48 | 6.5 ms | fixed-size cell canvas; no network or archive work in rendering |
This table records the original design context; it is not a current feature audit of the other projects. The tokenUsage2 column describes its current scope.
tokenUsage |
abtop | AgentWhileTrue | tokenUsage2 | |
|---|---|---|---|---|
| Purpose | one-shot HTML/PNG reports | live per-session monitor | resume agents after quota resets | live usage observability |
| Data | Token Use binary + stats-cache + threads.tokens_used |
open transcripts of running sessions | rollout quota + statusline bridge | all transcripts, own archive |
| Codex accounts | ~/.codex only |
~/.codex only |
per process via CODEX_HOME |
every CODEX_HOME, found automatically |
| Claude backends | not separated | not separated | n/a | Anthropic vs. each Ollama host / proxy |
| History | a snapshot | current sessions | none | daily / weekly / monthly, survives cleanup |
| Claude dedup | Token Use (by message) | sums every line | n/a | by message, largest copy wins |
tokenusage2 [--once | --json | --csv | --doctor] [--demo]
[--period day|week|month]
[--group account|tool|backend|model|project|session]
[--breakdown account|tool|backend|model|project|session]
[--metric total|fresh|output|cost] [--account LABEL_OR_ID]
[--theme default|midnight|amber|plain] [--interval SECONDS]
[--archive PATH] [--no-archive] [--config PATH] [--home DIR] [--tz ZONE]
[--width N] [--height N] [--color auto|always|never]
[--redact | --no-redact]
[--provider-status | --no-provider-status]
[--version]
--onceprints one frame (great in scripts orwatch),--jsona machine-readable snapshot,--csvthe timeline as CSV,--doctorthe sources report.--demouses deterministic synthetic data, for screenshots and trying it out.--provider-statusopts into non-blocking checks of the official Claude API, Claude Code, Codex API and Codex CLI components. Separate Claude and OpenAI bubbles show green when all tracked components are operational, yellow for a partial issue or maintenance, red when every tracked component has a major outage, and grey while checking or when status is unknown. Known problems also take the footer.--no-provider-statusoverrides an enabled config for one run.NO_COLORselects the plain theme.
$XDG_CONFIG_HOME/tokenusage2/config.toml is the hand-written configuration —
separate from the automatically saved view preferences. It is only needed for
homes that cannot be discovered, or to rename and pin things:
[discovery]
claude_homes = ["~/clients/acme/.claude"]
codex_homes = []
opencode_dbs = []
ignore = ["~/.codex-old"]
scan_home = true # look for ~/.claude* and ~/.codex*
# rc_files = ["~/.zshrc"] # override the default rc file list
[labels]
"~/.codex-work" = "codex · company"
[backends]
"qwen3*" = "ollama@gpu-box" # model glob → backend label
[prices."custom-model-*"] # optional override, USD per 1M tokens
input = 1.0
output = 8.0
cache_read = 0.1 # optional: cache_read, cache_write, cache_write_1h
[alerts]
quota_percent = 90 # a 5 h or weekly quota at or above this
burn_factor = 5 # a burn rate above 5x the typical active minute …
burn_floor = 250000 # … and above this many tokens per minute
notify = true # desktop notification through notify-send
bell = false # terminal bell
[provider_status]
enabled = false # opt in; or pass --provider-status
refresh_seconds = 300 # 30–3600; refresh runs off the TUI thread
timeout_seconds = 2 # 0.1–10 per official status endpoint- Read-only: it never writes into any tool's directory. By default it makes no network requests.
- Provider health is explicitly opt-in. When enabled, it sends unauthenticated GET requests—without account, token or usage data—to the official Claude and OpenAI status APIs. Requests have a strict timeout and run outside the rendering thread.
- Only usage metadata is retained — timestamps, model, backend, working directory, session id and token counts. Prompt and response text is never stored. Identity discovery decodes e-mail/plan claims locally; credential values are never stored or shown.
--redact/xmasks e-mail addresses on screen, in JSON and in the sources/doctor report.
./localPipeline.sh # set up, check, build, verify, then launch
./localPipeline.sh --noRun # the same without the launch (what CI and releases run)
./localPipeline.sh --noRun --mutation # additionally gate on the mutmut mutation score (slow)
./localPipeline.sh --fix # apply ruff lint and format fixes first
./localPipeline.sh --verbose # stream every stage's output, not only failures
./localPipeline.sh --report-dir build/pipeline-logs # keep every stage log plus summary.txt
.venv/bin/python scripts/profile_app.py # time and cProfile every stage on your real dataThe pipeline's fourteen stages: find Python 3.14 → create or reuse .venv →
install the project editable with the pinned tools → verify the generated
project-history chart → ruff lint → ruff format check → ShellCheck on the script
itself (skipped when it is not installed) → pytest, where line coverage and
branch coverage must each reach 99 % → one --demo frame → mutation testing
(opt-in) → sdist and wheel → install that wheel into a clean throwaway venv and
run it → check that .venv/bin/tokenusage2 reports the current version →
launch. A failing stage
prints the tail of its log and skips the stages that depend on it. Every stage
is timed, and the run ends with a summary and a verdict; the exit status is 0
only on PASS.
Mutation testing uses mutmut, pinned in the
development extras. It injects small faults into src/tokenusage2/ and reruns
the tests that cover each one; the stage requires that at least 60 % of the
tested mutants are detected (killed or timed out). Tests that check repository
files rather than the package are excluded from that run. A run from scratch is
slow, so the stage is opt-in and not part of CI; later runs reuse the results
kept in the ignored mutants/ directory. Reference run on 24 November 2026
(the 0.15.0 sources: 10,935 mutants from scratch in 48 minutes on 20 CPU
threads, then 211 new About-overlay mutants incrementally): 75.17 % of 11,146
(8,361 killed, 18 timed out, 2,762 survived, 5 without covering tests).
CI (.github/workflows/tokenUsage2.yml)
runs ./localPipeline.sh --noRun on Python 3.14 for every push and pull
request, puts the pipeline's summary table and a demo frame in the job summary,
and uploads coverage, stage logs and built distributions. Every push to
master whose version has no tag yet also becomes a
GitHub release with
sdist, wheel and that version's changelog section as the notes
(release.yml). The C4-style architecture
diagrams are in docs/ARCHITECTURE.md, and the design
rationale is in PLAN.md; the latest documentation audit and release verification are in
review.md. Current and archived documentation is indexed in
docs/README.md.
The chart measures every first-parent commit without checking out or changing the working tree. It stacks non-blank, non-comment-only lines for core logic, terminal UI, tests, tooling and documentation; the black line uses the right axis for the test-to-product-code ratio. Red lines are public release tags and the blue marker is the current version. Generated chart files are excluded from their own count.
- Current counts:
docs/history/loc-current.md. - Refresh:
git fetch --tags && .venv/bin/python scripts/history_chart.pyso release markers match the public repository even immediately after a release. - Enforcement:
localPipeline.shruns the generator in--checkmode, so a stale chart fails local CI and the release workflow.
The SVG and current-count table are documentation only; neither is packaged in the runtime wheel.
Linux (process discovery reads /proc; the dashboard uses termios), Python
3.14+, a terminal of at least 70 × 16 cells — 120 columns and more shows the
breakdown and the live feed side by side. No third-party runtime packages.


