AIBattery

skill
SUMMARY

A battery style usage meter for Claude Code. Rate limits, context health, and token usage in your macOS menu bar.

README.md
AI Battery icon

AI Battery

Get the most out of your Claude subscription.

aibattery.dev

Monitor rate limits, context health, and token usage โ€” always visible in your macOS menu bar.

Swift
macOS
License
CI
GitHub stars
Downloads


AI Battery โ€” full dashboard view

๐Ÿ“ฆ Install

Homebrew (recommended)
brew tap KyleNesium/tap
brew install --cask aibattery
โšก Quick install โ€” paste in Terminal
curl -sL https://github.com/KyleNesium/AIBattery/releases/latest/download/AIBattery.zip -o /tmp/AIBattery.zip && ditto -x -k /tmp/AIBattery.zip /Applications && xattr -cr /Applications/AIBattery.app && open /Applications/AIBattery.app
๐Ÿ’ฟ DMG download

Download from Releases:

  1. Open AIBattery.dmg and drag AI Battery to Applications
  2. Launch from Applications โ€” macOS will block it on first run
  3. Open System Settings โ†’ Privacy & Security โ†’ scroll down โ†’ click Open Anyway

[!TIP]
If macOS says the app is damaged, run xattr -cr /Applications/AIBattery.app then relaunch.

๐Ÿ›  Build from source
git clone https://github.com/KyleNesium/AIBattery.git && cd AIBattery
./scripts/build-app.sh
open .build/AIBattery.app

Requires macOS 13+ and Claude Code. See aibattery.dev for more info.


๐Ÿ”„ Update

AI Battery checks for updates once per day. When available, the header arrow turns yellow and a banner appears.

Method How
In-app (recommended) Click Install Update โ€” Sparkle downloads, verifies, replaces, and relaunches
Homebrew brew upgrade --cask aibattery
DMG Download from Releases, drag to Applications

Settings and OAuth sessions carry over automatically. Updates are user-initiated only โ€” nothing downloads in the background.


๐Ÿ” Authentication

OAuth 2.0 with PKCE โ€” same protocol as Claude Code. Supports up to 3 accounts (separate Claude orgs).

Step Action
1 Launch AI Battery โ€” the auth screen appears on first run
2 Click Sign In โ†’ browser opens to Anthropic's sign-in
3 Sign in โ†’ copy the authorization code
4 Paste into AI Battery โ†’ done

Multiple accounts: Use the header dropdown to switch accounts or add new ones (up to 3). Each account has its own rate limits, tokens, and identity.

๐Ÿ”‘ Session details
  • Sessions auto-refresh with a 5-minute buffer to avoid clock-skew issues
  • Temporary server errors retry automatically
  • Refresh token stored in macOS Keychain per account (separate from Claude Code credentials); access token held in memory only
  • Error messages are specific โ€” expired codes, invalid codes, server errors, and network errors each get a clear description
๐Ÿ›ก Why does macOS block the app or ask about Keychain access?

AI Battery isn't notarized โ€” there's no Apple Developer license behind this project, so macOS treats it as unidentified. Two prompts may appear on first launch:

  • Gatekeeper block โ€” macOS prevents the app from opening. Fix: System Settings โ†’ Privacy & Security โ†’ Open Anyway (see Install)
  • Keychain access โ€” the app stores its OAuth refresh token in macOS Keychain (one item per account), Apple's encrypted credential store. Click Always Allow. The prompt may reappear once after an in-app update because the new binary has a different ad-hoc signature.

The Gatekeeper prompt is one-time. The Keychain prompt appears once on first launch and once after each in-app update.


๐Ÿ“ Metrics

A minimal API call reads your rate limit headers each cycle. Local JSONL session logs provide token counts and context health โ€” never your message content. Click the โœฆ icon to open the dashboard.

The tab picker selects which metric drives the โœฆ icon color:

Mode Tracks Best for
โฑ 5-Hour Burst rate limit Knowing when you'll get throttled
๐Ÿ“… 7-Day Sustained rate limit Pacing usage across the week
๐Ÿง  Context Session context fullness Knowing when to start fresh
(A) Auto Highest urgency metric Always seeing the most critical metric

Selected metric moves to the top. The other two stay visible below.

Auto mode: click the (A) button next to the tabs. It glows blue when active and automatically selects whichever metric has the highest percentage โ€” so the menu bar always shows your most critical limit. To switch back to manual, click any tab โ€” auto mode disables and switches in one action.

Rate limits dashboard

๐Ÿง  Context Health

Shows your 5 most recent sessions with context health. Browse with < 1/5 > chevrons or swipe left/right. Stale sessions (idle > 30 min) show an amber "Idle" badge.

Each session displays: project name ยท git branch ยท duration ยท last active time.

Percentages are relative to the usable window โ€” 80% of the model's raw context window. At 100%, Claude Code auto-compacts and quality drops. Keep at least 20-40% free for best results.

Color Range Meaning
๐ŸŸข Green < 60% Plenty of room
๐ŸŸ  Orange 60โ€“80% Quality may degrade
๐Ÿ”ด Red > 80% Start a fresh session
Context Health view
โš ๏ธ Understanding context

Think of context as Claude's short-term memory. Every message, file read, tool call, and response accumulates in a 200K-token window. Nothing is discarded between turns. When it fills up, Claude Code auto-compacts โ€” summarizing the session into a few paragraphs and clearing the rest. That summary is lossy: file contents, specific instructions, and nuanced decisions get compressed. Claude keeps working, but from a recap instead of the real conversation.

Long conversation (15+ turns) โ€” Nothing is discarded between turns. Your messages, Claude's responses, tool calls, and results all accumulate. After ~15 turns the window is full of old history that Claude still reads every turn โ€” slowing responses, reducing quality, and burning through your token budget on stale context.

High input:output ratio (20:1+) โ€” More tokens are going in (file reads, error logs, tool results) than coming out. For example, reading 5 large files dumps thousands of tokens into context that Claude may only reference once. That data stays in the window for the rest of the session, consuming tokens on every subsequent turn and leaving less room for useful work.

Zero-output session โ€” Session has multiple turns but no output tokens. May indicate an error loop or stalled conversation.

Rapid token consumption โ€” Very short session with high token usage. Large files or long pastes may be filling the context window quickly.

[!TIP]
When you hit orange or red:

  1. Run /compact to save a summary to project memory
  2. Keep key decisions in CLAUDE.md โ€” loaded automatically every session
  3. Start a new terminal in the same directory and pick up where you left off

โš™๏ธ Settings

Click โš™๏ธ in the header to configure:

Setting What it does
โž• Add Account Connect another Claude account (up to 3)
โœ๏ธ Account names Custom label per account (shown in picker + menu bar)
๐Ÿ” Auto mode Always show the highest metric (pulsing blue button on metric toggle)
๐Ÿ”„ Refresh Poll interval: 10โ€“60s ยท ~3 tokens per refresh
โณ Idle Hide sessions idle longer than cutoff from context health: 30mโ€“8h or Never
๐ŸŽจ Colorblind Blue/cyan/amber/purple palette
๐Ÿ’ฒ Cost Always visible โ€” API-equivalent cost in Insights and Projects
๐Ÿ”” Alerts Notify on status page outages (all components)
โšก Rate Limit Notify when usage crosses threshold (50โ€“95%)
๐Ÿš€ Launch at Login Start automatically when you log in
Settings view

[!TIP]
Click any stat value (percentages, token counts, costs) to copy it to the clipboard.


๐Ÿ“‰ Activity & Insights

Interactive charts across three time windows:

Mode Window Shows
24H Trailing 24 hours Hourly activity, vs-yesterday trend, peak hour
7D Rolling 7 days Daily activity, weekly trend, busiest day
12M Rolling 12 months Monthly activity, month-over-month trend, busiest month

Below the chart: API-equivalent cost per model, throttle count, and cumulative stats (All Time messages/sessions, Longest session, Period date range).

Activity chart and insights

๐Ÿ’ฐ API Cost Equivalent

Dollar amounts show what your usage would have cost on Anthropic's pay-per-token API โ€” not your actual bill. Pro, Max, and Teams subscribers pay a flat monthly fee. When the API-equivalent exceeds your monthly fee, your subscription is saving you money. The bigger the gap, the better the deal. Pricing uses Anthropic's published per-million-token rates.

How token tracking works

AI Battery reads Claude Code's session logs (~/.claude/projects/) and stats cache (~/.claude/stats-cache.json) โ€” it never writes to Claude Code's files or reads message content, only token counts.

To prevent totals from dropping when Claude Code rebuilds its cache, AI Battery maintains a persistent ledger (~/Library/Application Support/AIBattery/token-ledger.json) that keeps the high-water mark for each model. Token totals never decrease, even across cache rebuilds.

How project tracking works

The Projects section groups token usage by the directory you ran Claude Code in. AI Battery scans all .jsonl session logs under ~/.claude/projects/, deduplicates by message ID, groups by working directory, and computes API-equivalent cost per project.

Project data appears after you've run at least one Claude Code session.


๐Ÿ”ง Troubleshooting & FAQ

App appears in the menu bar then disappears

On first launch: macOS Gatekeeper may silently kill the app because it's not notarized.

xattr -cr /Applications/AIBattery.app

Then relaunch. This removes the quarantine flag that macOS adds to downloaded apps.

After working for a while: If the icon vanishes after the app has been running, update to the latest version โ€” v1.2.3+ fixed concurrency issues that could cause intermittent crashes during background data refresh and sleep/wake cycles.

If it still happens:

  1. Open Console.app โ†’ filter for "AIBattery" โ†’ look for crash logs
  2. Check your macOS version โ€” macOS 13.0โ€“13.2 had MenuBarExtra bugs fixed in 13.3+
  3. Open an issue with the crash log
macOS says "AI Battery is damaged and can't be opened"

This is the quarantine flag. Run:

xattr -cr /Applications/AIBattery.app

Then relaunch.

Keychain access dialog keeps appearing

Click Always Allow when prompted. AI Battery stores its OAuth refresh token in macOS Keychain (one item per account). After a Sparkle in-app update, a single Keychain prompt may appear because the new binary has a different ad-hoc signature. This is a one-time prompt per update.

Only rate limits show โ€” tokens, models, and activity are all empty?

Token usage, context health, and activity stats come from Claude Code's local session logs (~/.claude/). These populate after you've used Claude Code for a bit. To kickstart it:

  1. Run a few Claude Code sessions from the terminal
  2. Run /stats inside Claude Code โ€” this generates the stats cache
  3. AI Battery refreshes automatically every polling cycle

Rate limits (5-hour / 7-day) always work immediately since they come from the API.

Green โœฆ at 0%?

Credits just reset, or no usage yet โ€” this is normal.

What's "binding"?

Whichever rate limit window is currently the active constraint. The binding window determines the percentage shown in the menu bar.

What's โš ๏ธ "throttled"?

Anthropic is actively limiting your requests. Wait for the reset timer.


๐Ÿ”’ Privacy

๐Ÿ“‚ Local only Reads JSONL for token counts โ€” never your message content
๐ŸŒ Network api.anthropic.com (rate limits) ยท console.anthropic.com (OAuth) ยท status.claude.com (status) ยท api.github.com (update check, once/24h) ยท kylenesium.github.io (Sparkle appcast)
๐Ÿšซ No tracking No analytics. No telemetry. No data collection. Period.

๐Ÿ— Architecture

AIBattery/
  Models/       โ€” Data structs (UsageSnapshot, RateLimitUsage, TokenHealthStatus, ...)
  Services/     โ€” OAuthManager, RateLimitFetcher, SessionLogReader, TokenHealthMonitor, ...
  ViewModels/   โ€” Single UsageViewModel (@MainActor, ObservableObject)
  Views/        โ€” SwiftUI views (popover sections, menu bar label, auth screen)
  Utilities/    โ€” TokenFormatter, ModelNameMapper, ThemeColors, AppLogger

One dependency โ€” Sparkle 2 for auto-update. Everything else is Apple frameworks (SwiftUI, Charts, Security, Foundation, AppKit).

๐Ÿ“‹ Detailed specs
File Covers
ARCHITECTURE.md Data flow, project tree, build config, network & file access
DATA_LAYER.md Every model, service, and algorithm
UI_SPEC.md View hierarchy, layout rules, section specs
CONSTANTS.md Every hardcoded value โ€” thresholds, URLs, pricing, sizes

โ™ฟ Accessibility

  • VoiceOver โ€” all interactive elements include accessibility labels and hints; collapsible sections announce state; copy actions announce confirmation
  • Keyboard navigation โ€” fully navigable without a mouse
  • Colorblind mode โ€” Settings โ†’ Display โ†’ Colorblind switches to a blue/cyan/amber/purple palette
  • First-launch tutorial โ€” 3-step walkthrough on first use

๐Ÿ—‘ Uninstall

Homebrew:

brew uninstall --cask aibattery
๐Ÿงน Manual uninstall
  1. Right-click AI Battery in the menu bar โ†’ Quit
  2. Open Applications in Finder โ†’ drag AI Battery to the Trash

To also remove stored settings:

security delete-generic-password -s "AIBattery" 2>/dev/null   # OAuth tokens (all accounts)
defaults delete com.KyleNesium.AIBattery 2>/dev/null           # Preferences

AI Battery doesn't write any other files. Your Claude Code data (~/.claude/) is untouched.


๐Ÿค Contributing & Support

Contributions welcome โ€” read the contributing guide first. See CHANGELOG.md for version history.

AI Battery is free and open source โ€” always will be. If it helps you get more out of Claude, consider sponsoring the project.

Sponsor


๐Ÿงช Test Coverage

785 tests across 55 test files.

Area Tests What's covered
Models 192 Token summaries, rate limit parsing, health status, metric modes, API profiles, usage snapshots, model pricing
Services 296 Token ledger, version checker, Sparkle updates, notifications, health monitor, status checker, session log reader (incl. NSLock/pendingInvalidation concurrency, incremental scanning, entry eviction), account store, stats cache, usage aggregator (incl. side-effects, integration tests), rate limit fetcher, OAuth
Views 96 Activity chart data transforms, trend computation, session info formatting, GaugeBar clamping, deferred rendering, status bar toggle, insights view formatting, metric toggle ordering
ViewModels 29 Refresh interval clamping, error messages, adaptive polling, throttle tracking, idle threshold constants
Utilities 175 Token/duration formatting, model name mapping, theme colors, secure networking, menu bar icon animations, throttle tracker, typography, spacing, idle suspension policy

๐Ÿ“„ License

MIT

Yorumlar (0)

Sonuc bulunamadi