An open API service indexing awesome lists of open source software.

https://github.com/kylenesium/aibattery

A battery style usage meter for Claude Code. Rate limits, context health, and token usage in your macOS menu bar.
https://github.com/kylenesium/aibattery

ai anthropic claude-code developer-tools macos menu-bar rate-limits swiftui

Last synced: 2 months ago
JSON representation

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

Awesome Lists containing this project

README

          

AI Battery icon

# AI Battery

**Get the most out of your Claude subscription.**

[aibattery.dev](https://aibattery.dev)

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

[![Swift](https://img.shields.io/badge/Swift-5.9-orange?logo=swift&logoColor=white)](https://swift.org)
[![macOS](https://img.shields.io/badge/macOS-13%2B-blue?logo=apple&logoColor=white)](https://www.apple.com/macos/)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![CI](https://github.com/KyleNesium/AIBattery/actions/workflows/ci.yml/badge.svg)](https://github.com/KyleNesium/AIBattery/actions/workflows/ci.yml)
[![GitHub stars](https://img.shields.io/github/stars/KyleNesium/AIBattery?style=social&cacheSeconds=3600)](https://github.com/KyleNesium/AIBattery/stargazers)
[![Downloads](https://img.shields.io/github/downloads/KyleNesium/AIBattery/total?logo=github&label=Downloads&cacheSeconds=3600)](https://github.com/KyleNesium/AIBattery/releases)


AI Battery open in the menu bar showing 5-hour and 7-day rate limits, throttling status, context health, projects, and insights

Live rate limits, context health, and usage trends without leaving the menu bar.

## ๐Ÿ“ฆ Install


Homebrew (recommended)

```bash
brew tap KyleNesium/tap
brew install --cask aibattery
```

โšก Quick install โ€” paste in Terminal

```bash
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](https://github.com/KyleNesium/AIBattery/releases/latest):

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

```bash
git clone https://github.com/KyleNesium/AIBattery.git && cd AIBattery
./scripts/build-app.sh
open .build/AIBattery.app
```

Requires **macOS 13+** and [Claude Code](https://docs.anthropic.com/en/docs/claude-code). See [aibattery.dev](https://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](https://sparkle-project.org/) downloads, verifies, replaces, and relaunches |
| **Homebrew** | `brew upgrade --cask aibattery` |
| **DMG** | Download from [Releases](https://github.com/KyleNesium/AIBattery/releases/latest), 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](#-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 fetch reads Claude Code account metadata for 5-hour and 7-day usage, with legacy header fallback when available. 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.

> [!NOTE]
> The 5-hour and 7-day bars come from Anthropic API sliding-window headers. They may differ from Claude Code `/usage`, which uses different plan-usage semantics and reset timings.

**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.


AI Battery dashboard showing 5-hour and 7-day rate limits with reset countdowns

---

## ๐Ÿง  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 showing session context window fullness, model, and turn count

โš ๏ธ 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 panel with refresh interval, idle session cutoff, colorblind mode, alerts, and launch at login

> [!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).


24-hour activity chart with trend arrows, throttle count, and cost breakdown by model

---

## ๐Ÿ’ฐ 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.


Per-project token usage breakdown with costs

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.

```bash
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](https://github.com/KyleNesium/AIBattery/issues) with the crash log

macOS says "AI Battery is damaged and can't be opened"

This is the quarantine flag. Run:

```bash
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

Claude Code usage windows (5-hour / 7-day) are fetched from Anthropic account metadata. If Anthropic changes that response shape, AI Battery falls back to cached values and may show a warning until fresh usage data is available again.

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.

Why can AI Battery differ from Claude Code `/usage`?

AI Battery primarily shows Claude Code 5-hour and 7-day usage from Claude Code account metadata. It may fall back to legacy Anthropic headers or cached values when those windows are temporarily unavailable, so percentages and reset times can still differ from Claude Code `/usage` during API transitions or stale-data fallback.

---

## ๐Ÿ”’ Privacy & Security

| | |
|---|---|
| ๐Ÿ“‚ **Local only** | Reads JSONL for token counts โ€” **never your message content** |
| ๐Ÿ”‘ **Keychain** | OAuth refresh token stored in macOS Keychain (`kSecAttrAccessibleWhenUnlockedThisDeviceOnly`) โ€” access token is memory-only, never written to disk |
| ๐ŸŒ **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. |
| ๐Ÿ” **Open source** | Every line is auditable โ€” [review the code](https://github.com/KyleNesium/AIBattery) |
| โœ… **Release checks** | Each release runs [`verify-release.sh`](scripts/verify-release.sh) โ€” validates codesign, Sparkle signatures, version consistency, and bundle integrity before publish |

---

## ๐Ÿ— 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](https://sparkle-project.org/) for auto-update. Everything else is Apple frameworks (SwiftUI, Charts, Security, Foundation, AppKit).

๐Ÿ“‹ Detailed specs

| File | Covers |
|---|---|
| [`ARCHITECTURE.md`](spec/ARCHITECTURE.md) | Data flow, project tree, build config, network & file access |
| [`DATA_LAYER.md`](spec/DATA_LAYER.md) | Every model, service, and algorithm |
| [`UI_SPEC.md`](spec/UI_SPEC.md) | View hierarchy, layout rules, section specs |
| [`CONSTANTS.md`](spec/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:**

```bash
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:

```bash
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](CONTRIBUTING.md) first. See [CHANGELOG.md](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](https://github.com/sponsors/KyleNesium).

[![Sponsor](https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink?logo=github)](https://github.com/sponsors/KyleNesium)

---

## ๐Ÿงช Test Coverage

**845 tests** across 57 test files.

| Area | Tests | What's covered |
|------|-------|----------------|
| Models | 239 | Token summaries, rate limit parsing (unified + standard + client data edge cases), health status, metric modes, API profiles, usage snapshots (incl. escalation ladder, hysteresis), model pricing, Claude system status indicators, standard rate limits |
| Services | 297 | Token ledger, version checker, Sparkle updates, notifications, health monitor (incl. zero-window safety), 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 | 86 | Activity chart data transforms (5H/7D/12M token-based), trend computation, session info formatting, GaugeBar clamping, deferred rendering, status bar toggle, insights view formatting, metric toggle ordering |
| ViewModels | 44 | Refresh interval clamping, error messages (incl. standard limits fallback), adaptive polling, throttle tracking, idle threshold constants, TTL-based stale rate limit expiry, effective value generic guard |
| 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](LICENSE)