# Token Usage Indicator

Personal-desk firmware that polls **Anthropic Claude** and **OpenAI/Codex** token
usage and shows session (5h) and weekly (7d) utilization on a small
microcontroller display. Two device builds are supported from a shared codebase:

| Device | Display | MCU | Status |
|---|---|---|---|
| **ESP8266-D1 + 0.96" SSD1306 OLED** (4-wire SPI, 128×64 mono) | yellow/blue OLED | ESP8266 ESP-12F | original target, still default in `platformio.ini` |
| **TTGO T-Display ESP32** (1.14" ST7789V color TFT, 240×135) | full-color IPS, neon UI | ESP32-D0WD, 16 MB flash | added 2026-05; battery + buttons + retro neon UI |

The codebase is **portable**: hardware-agnostic core logic (parsing, cache,
timers, format helpers, battery curve, charging heuristic) lives in
`src/core/`, all unit-tested natively. Per-device differences are isolated
behind a single `Board` interface (`src/board/board.h`) plus a per-device
renderer (`src/ui/screen_<board>.cpp`). Adding another device is one new
`board_*.cpp` + a new `[env:*]` in `platformio.ini`.

## Build & flash

```bash
# First-time setup
python3 -m venv .venv && .venv/bin/pip install platformio
cp include/config.example.h src/config.h         # src/config.h is gitignored

# Build (both envs)
.venv/bin/pio run -e esp8266_d1                  # default
.venv/bin/pio run -e ttgo_t_display              # ESP32 + color TFT

# Flash
./tools/flash.sh COM13                           # ESP8266 (Wemos D1 Mini)
./tools/flash-ttgo.sh COM14                      # TTGO T-Display
```

Both `flash*.sh` scripts shell out to the Windows-side `python -m esptool`
because WSL2 only auto-maps COM1..COM4 to `/dev/ttyS0..3` — USB serial
adapters above COM4 aren't reachable from WSL without `usbipd-win`. The
scripts auto-locate the four ESP32 images (bootloader, partitions, OTA
selector, firmware) or the single ESP8266 image and pass them to esptool
with the correct offsets.

Drivers on Windows:
- ESP8266 D1 Mini: usually CH340 (auto-installed on modern Windows).
- TTGO T-Display: **CH9102F**, needs the WCH VCP driver
  (https://www.wch-ic.com/products/CH343.html). Linux ≥ 5.9 and
  macOS Ventura+ are native.

## Native unit tests

```bash
./tools/run_native_tests.sh
```

Coverage: JSON parser (leap-year-safe epoch math), usage cache
(retain-on-failure + staleness), poll timer (rollover-safe), format helpers
(RSSI bars, reset string compact + verbose, backoff), HTTP outcome
classification, Li-Ion `vbatToPercent` table, charging heuristic.

## First-time portal setup (both boards)

On a fresh device (or after a factory reset), the screen shows **SETUP MODE**
with the AP name and password. Join AP `token-indicator-setup`
(default password `tokensetup` — see `src/config.h`), browse to
`http://192.168.4.1`, fill in:

1. **WiFi SSID + password**
2. **`creds_json`** — paste your `~/.claude/.credentials.json` content
   (the entire file, or just the inner `claudeAiOauth` object). The portal
   has a *Validate JSON* button that checks structure client-side before save.
3. **Codex proxy URL** (optional) — e.g. `http://192.168.0.24:8767/codex-usage`.
   See *OpenAI/Codex* below.

Save → device reboots. Within one poll cycle (default 300 s) the dashboard
populates.

After WiFi connects the device **never starts the AP again on its own**.
The portal stays available at `http://<station-ip>/` as an async ESPAsyncWebServer.
The top of the page now identifies the board (`device: TTGO T-Display ESP32 ...`
or `device: ESP8266 D1 mini ...`) so a mixed-board setup is unambiguous.

Saving with a field left blank leaves that stored value unchanged — so a
token-only update can't accidentally wipe your WiFi creds. The Codex proxy
URL is the one always-overwrite field, so clearing it disables the OpenAI rows.

## On-screen layout

### ESP8266 + 0.96" SSD1306 (monochrome, yellow/blue split)

![ESP8266 SSD1306 display in operation](docs/img/oled-esp8266-display.png)

The SSD1306 128×64 OLED is a two-color panel: the top 16 rows are **yellow
phosphor**, the bottom 48 rows are **blue phosphor**. This is a hardware
property of this OLED family, not a software choice — the code just puts the
status header in the yellow strip and the four data rows in the blue area.

Header (yellow band, top):

| Element | What it shows |
|---|---|
| `22:42` | Local wall-clock time, `HH:MM` from SNTP. Shows `TOKEN USAGE` until first NTP sync. |
| ☀ (8-point burst, left icon) | **Claude** auth indicator — lit once the Anthropic API has returned at least one `200 OK` since boot. Dim/off = no valid auth. |
| ◆ (diamond, right icon) | **Codex/OpenAI** proxy indicator — lit once the LAN proxy has returned at least one `200 OK`. Off if no proxy URL configured. |
| WiFi bars (far right) | RSSI mapped to 0–4 bars. Missing entirely when the STA link is down. |

Body (blue area, 4 rows):

| Row | Meaning | Left label | Bar fill | Right caption |
|---|---|---|---|---|
| 1 | Anthropic **5-hour session** utilization | `C5h` | `sessionUtilPct` (0-100) | Time until session reset (`2h17`, `--` if unknown) |
| 2 | Anthropic **7-day weekly** utilization | `C7d` | `weekUtilPct` | Time until weekly reset (`4d00`) |
| 3 | OpenAI/Codex **5-hour session** utilization | `O5h` | via LAN proxy | `1h00` |
| 4 | OpenAI/Codex **7-day weekly** utilization | `O7d` | via LAN proxy | `6d02` |

Each bar is an **inverted-percent** bar: the filled portion is drawn as a
solid rectangle, and the digit glyphs (`58%`) are cut *out* of the fill so
they stay readable regardless of how full the bar is. When `%` is unknown
(no data yet, or a `--` reset caption) the row is left empty.

Error / fallback screens:
- **SETUP MODE** — no WiFi credentials yet; shows AP name/password/IP.
- **CONNECTING…** — creds present but station link not up (retries in background).
- **`NET` / `AUTH` / `RATE` + IP** — full-screen error state, shown only
  when we can't fall back to cached data (see `src/core/status_model.cpp`).

### TTGO T-Display (color, "Miami Synthwave" theme)

- **Header (h=18 px):** large cyan `HH:MM` clock, 4-bar WiFi indicator,
  battery icon with color-coded fill (green / yellow / red), battery
  percent, charging-bolt overlay when charging.
- **Body (4 rows × 27 px):** each row is a single horizontal block.
  The filled portion grows left-to-right in a **dark accent color**
  (deep magenta for Claude rows, deep navy blue for Codex rows). Bright
  accent text **overlays** the whole row: 16×16 logo (Claude star / Codex
  burst) + `5h` or `7d` suffix + a large `47%` percent value + `rst 3h12m`
  reset caption right-aligned. No gridlines, no anti-alias halos — solid
  colors throughout.
- **Two user buttons** (TTGO only):
  - **Top (GPIO35):** click → force an immediate API poll.
  - **Bottom (GPIO0):** click → cycle backlight 100/40/10/off/100.
    Hold ≥5 s → factory reset (clears stored creds + reboots into AP).

## How it works (data flow)

```mermaid
flowchart LR
    subgraph LAN
        DEV["Device<br/>(ESP8266 / TTGO)"]
        PROXY["Codex proxy<br/>(Docker on LAN)"]
    end
    subgraph Internet
        ANT["api.anthropic.com<br/>/v1/oauth/*<br/>/api/oauth/usage"]
        CGT["chatgpt.com<br/>usage endpoints"]
    end
    PC["Your PC<br/>(Claude Code /login)"]
    PC -- ".credentials.json paste" --> DEV
    DEV -- "GET /api/oauth/usage<br/>Bearer &lt;access&gt;" --> ANT
    DEV -- "POST /v1/oauth/token<br/>refresh_token grant<br/>(on 401 or near expiry)" --> ANT
    DEV -- "GET /codex-usage" --> PROXY
    PROXY -- "curl_cffi<br/>(Chrome TLS)" --> CGT
    DEV -- "renders" --> OLED[("SSD1306 OLED<br/>/ TFT")]
```

Two independent data paths converge on the same 4-row layout:
- **Anthropic** is direct HTTPS from the device with OAuth Bearer auth.
  Refresh tokens **rotate on every use** — if your PC's Claude Code refreshes
  after you paste creds into the device, the device's chain is invalidated
  and you'll see `AUTH` / `HTTP 400 invalid_grant` in `/log` until you
  re-paste. Only one client can hold the refresh chain at a time.
- **Codex/OpenAI** requires a LAN proxy because `chatgpt.com` rejects any
  non-Codex-CLI TLS fingerprint at the Cloudflare edge (HTTP 403 regardless
  of headers). The proxy fakes the Chrome fingerprint via `curl_cffi`.

## Poll cycle & self-heal

```mermaid
stateDiagram-v2
    [*] --> Idle
    Idle --> Fetching : timer.due()
    Fetching --> Ok        : HTTP 200 + parse OK
    Fetching --> AuthError : HTTP 401
    Fetching --> RateLimit : HTTP 429
    Fetching --> Transport : status 0 (TLS/heap)
    Ok        --> Idle : cache updated, 300 s interval
    AuthError --> Refresh : one-shot retry
    Refresh   --> Fetching : new access token
    Refresh   --> Idle : refresh failed (invalid_grant)
    RateLimit --> Idle : exponential backoff
    Transport --> Idle : count++, 60 s fast-retry
    Transport --> Reboot : streak >= 8
    Reboot    --> [*]
```

Behaviors worth knowing about:
- **Reactive refresh on 401** (`src/app.cpp`): every fetch that returns
  `AuthError` triggers exactly one refresh attempt; on success the fetch is
  retried in the same tick.
- **Proactive refresh near expiry**: fires only in a narrow window around
  the stored `expires_at` (avoids hammering when the token is long-expired
  or fresh).
- **Auto-reboot on stuck HTTPS**: after 8 consecutive `status==0` fetches
  (i.e. the BearSSL 24 KB heap-block guard tripping — classic ESP8266
  fragmentation after multi-day uptime), the device calls `ESP.restart()`
  to reset the heap. Look for `[reboot] transport streak` in serial.
- **`/log` endpoint** shows the ring of the last 20 outbound calls with
  `epoch / uptime / kind / status / heap / maxBlk / note` so you can see
  the fragmentation happening. `/poll` triggers an immediate fetch;
  `/reboot` restarts the device (button on `/` too).

### TTGO T-Display (color, "Miami Synthwave" theme)

- **Header (h=18 px):** large cyan `HH:MM` clock, 4-bar WiFi indicator,
  battery icon with color-coded fill (green / yellow / red), battery
  percent, charging-bolt overlay when charging.
- **Body (4 rows × 27 px):** each row is a single horizontal block.
  The filled portion grows left-to-right in a **dark accent color**
  (deep magenta for Claude rows, deep navy blue for Codex rows). Bright
  accent text **overlays** the whole row: 16×16 logo (Claude star / Codex
  burst) + `5h` or `7d` suffix + a large `47%` percent value + `rst 3h12m`
  reset caption right-aligned. No gridlines, no anti-alias halos — solid
  colors throughout.
- **Two user buttons** (TTGO only):
  - **Top (GPIO35):** click → force an immediate API poll.
  - **Bottom (GPIO0):** click → cycle backlight 100/40/10/off/100.
    Hold ≥5 s → factory reset (clears stored creds + reboots into AP).

## OpenAI / Codex rows (optional, LAN proxy)

`chatgpt.com` rejects every non-Codex-CLI client at the Cloudflare
TLS-fingerprint layer (HTTP 403 regardless of headers), so the device cannot
fetch Codex usage directly. A small Python proxy on the LAN does the
Cloudflare-fingerprint dance with [`curl_cffi`](https://github.com/yifeikong/curl_cffi)
(Chrome 120 TLS impersonation), refreshes the Codex OAuth token on 401, and
exposes the result as plain HTTP JSON in the **same shape Anthropic uses** —
so the device parser handles both providers identically.

- Deploy the proxy via Docker Compose: see `tools/codex-proxy/README.md`.
- Paste the proxy URL into the device portal's *Codex proxy URL* field.
- The device speaks plain HTTP only (no OpenAI secrets on-device).
- **Device on a different network?** The proxy supports a `PROXY_TOKEN`
  env var that gates the endpoint at `/t/<token>/codex-usage`. Forward
  one non-standard port on your router → LAN:8767, put the token in the
  URL you paste into the device portal. Chosen over WireGuard because
  WG's Curve25519 + ChaCha20 keying on ESP8266 fights BearSSL for the
  same 24 KB heap block and worsens fragmentation. Details:
  `tools/codex-proxy/README.md` → *Exposing the proxy over the internet*.
- Known fragility: `curl-impersonate` is an arms race vs Cloudflare. If
  the proxy starts returning HTTP 403, bump `curl_cffi` or change the
  `IMPERSONATE` env var (e.g. `chrome131`). Anthropic rows are unaffected.

## Storage keys (NVS / LittleFS)

The portal writes the following keys via `Board::storageWrite()`:

| Key (≤15 chars for ESP32 NVS) | Contents |
|---|---|
| `ssid` | WiFi SSID |
| `pass` | WiFi password |
| `interval` | Poll interval seconds (60-3600) |
| `token` | Anthropic OAuth access token |
| `refresh_token` | Anthropic OAuth refresh token (rotates) |
| `expires_at` | Anthropic access-token expiry (unix seconds) |
| `openai_url` | Codex proxy URL (empty = OpenAI rows disabled) |

**ESP32 NVS gotcha:** Preferences (ESP32's NVS) silently fails for any key
name longer than 15 characters. ESP8266 LittleFS doesn't have this limit, so
the same code path "worked" there. The earlier `openai_proxy_url` (16 chars)
was the cause of one full debug cycle — now renamed.

## Known limitations

- OpenAI/Codex rows depend on the LAN proxy above (Cloudflare arms race +
  plain-HTTP-on-LAN trust model).
- TLS certificate is not pinned (`setInsecure` on both BearSSL/ESP8266 and
  WiFiClientSecure/ESP32).
- Reset-time countdowns rely on SNTP (UTC). They show `--` briefly on first
  boot until NTP sync or when the API omits `resets_at`.
- OAuth tokens are stored in plaintext (LittleFS on ESP8266, NVS on ESP32).
  Personal-desk-gadget threat model.
- WiFi initial connect can block up to 30 s on boot; the portal is
  unreachable during that window only. After that the portal is async and
  responsive at all times.

## Repo layout

```
src/
  app.cpp, app.h, main.cpp     — board-agnostic application loop
  config.h                      — local copy of config (gitignored)
  board/                        — Board interface + per-device impls
    board.h
    board_esp8266_d1.{h,cpp}
    board_ttgo_t_display.{h,cpp}
  core/                         — hardware-agnostic logic (native-testable)
    anthropic_parser, format, oauth_client, poll_timer,
    status_model, usage_cache, usage_model,
    battery_calc, charging_detect   (ESP32 only at runtime)
  net/                          — HTTP outcome classification
  ui/                           — per-device renderers + shared ScreenState
    screen.h                       (ScreenState only — no GFX deps)
    screen_esp8266_d1.{h,cpp}      (U8g2 monochrome renderer)
    screen_ttgo_t_display.cpp      (TFT_eSPI color sprite renderer)
    ttgo_palette.h                 (RGB565 color constants)
  webconfig/                    — async portal (ESPAsyncWebServer)

test/native/                    — single-file g++ unit tests
tools/
  flash.sh                      — Windows-esptool flash helper, ESP8266
  flash-ttgo.sh                 — Windows-esptool flash helper, TTGO
  codex-proxy/                  — Docker-Compose'd LAN proxy

docs/
  obtaining-oauth-token.md      — how to capture credentials.json
  superpowers/specs/            — design docs (frozen)
  superpowers/plans/            — implementation plans (frozen)

ESP8266-D1/                     — per-device hardware notes
TTGO_T-Display_ESP32_1.14_LCD_CH9102_16MB/
                                — per-device hardware notes + pinout
```
