Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.
Add CodexBar usage input and a selectable Game Boy face
click6067-ship-itf3ddb3ff94ce
diff --git a/AGENTS.md b/AGENTS.mdindex 0fdc5e7..3e84b11 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,6 +1,6 @@# Agent guide-TokenTV draws AI usage limits on a 240×240 desk clock. Python 3.10+, Pillow, no other runtime deps.+TokenTV puts Claude and Codex usage limits on a ~$5 AliExpress Wi-Fi desk clock (240×240, SmallTV-style) by uploading pictures to its stock photo album, so the clock keeps its firmware. A computer that stays on reads usage and draws the pictures. Python 3.10+, Pillow, no other runtime deps.## Run without accounts or a clock@@ -45,4 +45,4 @@ Verified on Linux with one SD_PRO clock. Mac and Windows hosts are untested; repFollow `docs/clock-faces.md`: write a render function, add it to `RENDERERS` and `STYLES`, renderwith `token-tv demo`, and look at the 240×240 result at real size. It then appears in the dashboard's-Themes list as a Local face and can be applied to the clock without any upstream change.+Gallery as a Local face and can be applied to the clock without any upstream change.diff --git a/README.ko.md b/README.ko.mdindex 014df81..f39a8b7 100644--- a/README.ko.md+++ b/README.ko.md@@ -7,6 +7,7 @@**구경하기:** [라이브 데모](https://token-tv.vercel.app) 또는 `npx github:click6067-ship-it/token-tv demo`, 시계·로그인 없이 바로.**설치하기:** 이 저장소를 AI에게 주고 *"TokenTV 설정해줘"* 라고 하세요. AI는 [AGENTS.md](AGENTS.md)를 따릅니다.**내 화면 만들기:** 시계 없이 [Game Boy 예제](examples/gameboy)에서 시작해 AI에게 바꿔 달라고 하세요. [가이드](docs/clock-faces.md) · [공유하기](https://github.com/click6067-ship-it/token-tv/issues/new?template=share_a_face.md)-자세히: [설정](docs/setup.ko.md) · [호환 시계](docs/hardware-compatibility.md) · MIT · [English](README.md)+자세히: [설정](docs/setup.ko.md) · [호환 시계](docs/hardware-compatibility.md) · [CodexBar 연동](docs/codexbar.md) · MIT · [English](README.md)+[Hackaday에 소개됐습니다](https://hackaday.com/2026/10/06/smalltv-hacking-with-surprisingly-little-fuss/).<p align="center"><a href="examples/gameboy"><img src="examples/gameboy/comparison.png" width="640" alt="내 화면 만들기: 같은 샘플 사용량으로 그린 원래 픽셀 화면과 4색 Game Boy 예제"></a></p>diff --git a/README.md b/README.mdindex ec4e247..dc4c3f3 100644--- a/README.md+++ b/README.md@@ -7,6 +7,7 @@ Your Claude and Codex usage limits on a ~$5 Wi-Fi desk clock. No firmware flashi**Try it:** [live demo](https://token-tv.vercel.app) or `npx github:click6067-ship-it/token-tv demo`, no clock or login needed.**Set it up:** give this repo to your AI and say *"Set up TokenTV for me."* It follows [AGENTS.md](AGENTS.md).**Make your own face:** no clock needed, start from the [Game Boy example](examples/gameboy) and ask your AI to change it. [Guide](docs/clock-faces.md) · [Share it](https://github.com/click6067-ship-it/token-tv/issues/new?template=share_a_face.md)-Details: [how it works](docs/stock-photo-display.md) · [setup](docs/setup.md) · [compatible clocks](docs/hardware-compatibility.md) · MIT · [한국어](README.ko.md)+Details: [how it works](docs/stock-photo-display.md) · [setup](docs/setup.md) · [compatible clocks](docs/hardware-compatibility.md) · [CodexBar input](docs/codexbar.md) · MIT · [한국어](README.ko.md)+Featured on [Hackaday](https://hackaday.com/2026/10/06/smalltv-hacking-with-surprisingly-little-fuss/).<p align="center"><a href="examples/gameboy"><img src="examples/gameboy/comparison.png" width="640" alt="Change a face: original pixel style and a four-colour Game Boy example, rendered from the same sample readings"></a></p>diff --git a/docs/clock-faces.md b/docs/clock-faces.mdindex 3afd85e..96c1d7c 100644--- a/docs/clock-faces.md+++ b/docs/clock-faces.md@@ -104,3 +104,8 @@ It is not a live ranking. Older installs show "update TokenTV" instead of downlo## Worked example[Pixel → Game Boy](../examples/gameboy/README.md) includes the render function, the same sample data before and after, and an old/missing-data check. It was made with Claude Code and runs without a clock or account.++## Game Boy LCD face++**Game Boy** uses four green LCD shades and ten-cell gauges.+Choose it under **Gallery → Game Boy → Apply to clock**. OLD and missing readings remain explicit.diff --git a/docs/codexbar.md b/docs/codexbar.mdnew file mode 100644index 0000000..ea941b8--- /dev/null+++ b/docs/codexbar.md@@ -0,0 +1,61 @@+# Reading usage from CodexBar++Already watching your limits with [CodexBar](https://github.com/steipete/CodexBar)? TokenTV can take+CodexBar's usage JSON and put it on a ~$5 AliExpress Wi-Fi desk clock, with no firmware flashing.+CodexBar keeps doing the sign-in and fetching; TokenTV only reads what CodexBar prints, draws the+picture and uploads it to the clock's stock photo album.++## What has been checked++CodexBar CLI 0.74.0 (Linux x86_64 release tarball) on Ubuntu 24.04, 2026-10-11, with real accounts:++| Provider | CodexBar call | Result on the clock |+|---|---|---|+| Claude | `codexbar usage --provider claude --source oauth --format json` | 5-hour and weekly windows |+| Codex | `codexbar usage --provider codex --format json` (CodexBar used its `oauth` source) | Weekly window. This account reported no 5-hour window, so that stays a dash |+| Claude, default source | `codexbar usage --provider claude --format json` | Failed: on Linux CodexBar fell back to Claude Code's `/usage` and could not read the output of Claude Code 2.1.289. Set `"codexbar_source": "oauth"` |++`codexbar serve` (`GET /usage`) returned the same entries for both providers. TokenTV accepts the+CodexBar input for `claude` and `codex` accounts only, because no other provider has been checked.+CodexBar's macOS app has not been tried.++## Config++```json+{+ "device_url": "http://<clock-ip>",+ "accounts": [+ {"key": "claude_a", "alias": "CLAUDE A", "provider": "claude", "email": "[email protected]",+ "codexbar_command": "codexbar", "codexbar_source": "oauth"},+ {"key": "codex_a", "alias": "CODEX A", "provider": "codex", "email": "[email protected]",+ "codexbar_command": "codexbar"}+ ]+}+```++- `codexbar_command`: the CodexBar CLI, a name on `PATH` or a full path. Each poll runs+ `<command> usage --provider <provider> --format json`.+- `codexbar_source` (optional): passed as `--source` (`auto`, `web`, `cli`, `oauth`, `api`).+ Without it, CodexBar uses its own setting.+- `codexbar_url` instead of `codexbar_command`: a `codexbar serve` address such as+ `http://127.0.0.1:8080/usage`. CodexBar's config then picks the source. The address may carry+ `?provider=` but no user name, password or other query. CodexBar asks for a bearer token on+ non-loopback addresses and TokenTV does not send one, so run TokenTV on the same computer.+- `source_home` (optional): runs CodexBar with that CLI home (`CLAUDE_CONFIG_DIR` or `CODEX_HOME`),+ for example for a second Codex account.++Then `token-tv doctor --live` and `token-tv run`, as in [setup](setup.md). The dashboard lists the+account's source as CodexBar.++## What is read++- The `primary` and `secondary` windows. A 300-minute window is the 5-hour limit and a 10080-minute+ window is the weekly limit. A window without a length is shown without a label; TokenTV does not+ guess one from CodexBar's display names.+- Model-only windows (for example Claude's "Fable only") and `tertiary` are not shown, so they never+ replace the weekly reading.+- A missing window is a dash, never 0%.+- If CodexBar reports an account email (it did for Codex), every reported email must match `email`+ or the account shows a mismatch. CodexBar's Claude OAuth output carried no email, so that account is unverified and+ `doctor --live` says so.+- When CodexBar fails, the account shows an error status. CodexBar's error text is not kept.diff --git a/docs/setup.ko.md b/docs/setup.ko.mdindex fa5224a..af7c3b5 100644--- a/docs/setup.ko.md+++ b/docs/setup.ko.md@@ -11,7 +11,7 @@**AI 사용 한도를 작은 책상 시계에.** Claude와 Codex 사용량을 여러 계정으로, 시계 펌웨어를 바꾸지 않고 보여줍니다.Grok은 CLI 예산 정보를 보여주는 실험적 기능입니다. 제작자의 시계 구매 영수증은 5,650원(한국 알리익스프레스 할인가)이며 가격은 지역마다 다릅니다. 다른 기기는 확인하지 않았습니다. 켜 두는 컴퓨터(호스트)가 필요합니다.-240×240 책상 시계와 브라우저에서 확인하며, 계정별 인증 홈을 분리하고 실제 조회 실패와 오래된 값을 표시합니다.+사용량은 240×240 책상 시계에 띄우고, 계정별 세부는 브라우저에서 봅니다. 계정별 인증 홈을 분리하고 실제 조회 실패와 오래된 값을 표시합니다.## 실행@@ -96,6 +96,9 @@ Grok이 한도 수치를 제공하지 않으면 `quota_unavailable`로 표시합이 과정은 도구를 끈 짧은 확인 응답 하나를 요청하므로 구독 사용량을 소량 소비할 수 있습니다.인증 파일의 토큰을 직접 수정하거나 다른 머신으로 복사하지 않습니다.+[CodexBar](https://github.com/steipete/CodexBar)를 이미 쓰고 있다면 Claude·Codex 계정은 CodexBar의+사용량 JSON을 대신 읽을 수 있습니다. 설정과 확인한 범위는 [docs/codexbar.md](codexbar.md)에 있습니다.+**5시간과 주간 중 무엇을 보여 주나요?** 둘 다 읽습니다. 시계는 사용률이 더 높은 쪽과 그 창의 리셋 시간을보여 줍니다. 웹 대시보드도 같은 창을 먼저 보여 주고, 그 아래 다른 창 항목을 펼치면 나머지를 볼 수 있습니다.diff --git a/docs/setup.md b/docs/setup.mdindex a09b443..73d65d6 100644--- a/docs/setup.md+++ b/docs/setup.md@@ -73,6 +73,9 @@ never a password, token or cookie. Polling runs every five minutes; old readingsmissing data shows a dash, never a fake 0%. Claude accounts with `refresh_with_cli: true` mayrefresh an expired login through the CLI, which sends one tiny prompt.+Already use [CodexBar](https://github.com/steipete/CodexBar)? A Claude or Codex account can read+CodexBar's usage JSON instead: see [docs/codexbar.md](codexbar.md).+**5-hour or weekly?** Both windows are read. The clock shows whichever is more used, with thatwindow's reset time. The web dashboard shows the same window first; open the other windowsunder it to see the rest.diff --git a/examples/gameboy/README.md b/examples/gameboy/README.mdindex bbc6545..044e0ea 100644--- a/examples/gameboy/README.md+++ b/examples/gameboy/README.md@@ -2,7 +2,8 @@**Request:** «게임보이 스타일로 시계 화면 바꿔줘» ("change the clock face to a Game Boy style")**Made by:** the TokenTV author with Claude Code (CC). Sample data only, not a real account.-This is a separate example. It is **not** registered as a product theme and was not applied to any clock.+Game Boy is also a built-in clock face: open **Gallery → Game Boy → Apply to clock**.+This standalone example remains editable for experimenting with your own four-colour palette.| before (built-in Pixel) | after (Game Boy) | after, old + unknown || --- | --- | --- |diff --git a/tests/fixtures/codexbar/serve-usage.json b/tests/fixtures/codexbar/serve-usage.jsonnew file mode 100644index 0000000..651fd59--- /dev/null+++ b/tests/fixtures/codexbar/serve-usage.json@@ -0,0 +1,133 @@+[+ {+ "source": "oauth",+ "pace": {+ "secondary": {+ "willLastToReset": false,+ "etaSeconds": 405546,+ "stage": "onTrack",+ "deltaPercent": 2,+ "summary": "On pace | Expected 4% used | Runs out in 4d 16h",+ "expectedUsedPercent": 4+ }+ },+ "version": "0.160.0",+ "account": "[email protected]",+ "resetCredits": {+ "available": 1,+ "nextExpiresAt": "2026-11-06T23:37:16Z"+ },+ "usage": {+ "accountEmail": "[email protected]",+ "secondary": {+ "resetsAt": "2026-10-18T04:02:43Z",+ "usedPercent": 6,+ "windowMinutes": 10080,+ "resetDescription": "Oct 18 at 1:02 PM"+ },+ "primary": null,+ "codexResetCredits": {+ "credits": [+ {+ "expires_at": "2026-11-06T23:37:16Z",+ "title": "Full reset",+ "status": "available",+ "description": "Thanks for using Codex! You've been granted one free rate limit reset.",+ "reset_type": "codex_rate_limits",+ "id": "codex-reset-credit-v1-0000000000000000000000000000000000000000",+ "granted_at": "2026-10-07T23:37:16Z"+ }+ ],+ "updatedAt": "2026-10-11T11:14:08Z",+ "availableCount": 1+ },+ "updatedAt": "2026-10-11T11:14:08Z",+ "dataConfidence": "exact",+ "loginMethod": "pro",+ "providerCost": {+ "balanceUpdatedAt": "2026-10-11T11:14:08Z",+ "currencyCode": "Credits",+ "limit": 0,+ "balance": 100.0,+ "period": "Extra usage",+ "updatedAt": "2026-10-11T11:14:08Z",+ "used": 0+ },+ "identity": {+ "loginMethod": "pro",+ "providerID": "codex",+ "accountEmail": "[email protected]"+ },+ "tertiary": null+ },+ "rateWindowLabels": {+ "secondary": "Weekly"+ },+ "credits": {+ "balanceIsWorkspace": false,+ "remaining": 100.0,+ "creditsAvailable": true,+ "balanceReadSucceeded": true,+ "events": [],+ "updatedAt": "2026-10-11T11:14:08Z"+ },+ "provider": "codex"+ },+ {+ "pace": {+ "primary": {+ "summary": "51% in reserve | Expected 61% used | Lasts until reset",+ "expectedUsedPercent": 61,+ "willLastToReset": true,+ "deltaPercent": -51,+ "stage": "farBehind"+ },+ "secondary": {+ "summary": "On pace | Expected 79% used | Lasts until reset",+ "expectedUsedPercent": 79,+ "willLastToReset": true,+ "deltaPercent": -2,+ "stage": "onTrack"+ }+ },+ "rateWindowLabels": {+ "primary": "Session",+ "secondary": "Weekly"+ },+ "source": "oauth",+ "provider": "claude",+ "usage": {+ "extraRateWindows": [+ {+ "title": "Fable only",+ "id": "claude-weekly-scoped-fable",+ "window": {+ "windowMinutes": 10080,+ "resetsAt": "2026-10-12T22:59:59Z",+ "resetDescription": "Oct 13 at 7:59AM",+ "usedPercent": 0+ }+ }+ ],+ "secondary": {+ "usedPercent": 77,+ "windowMinutes": 10080,+ "resetsAt": "2026-10-12T22:59:59Z",+ "resetDescription": "Oct 13 at 7:59AM"+ },+ "primary": {+ "usedPercent": 10,+ "windowMinutes": 300,+ "resetsAt": "2026-10-11T13:09:59Z",+ "resetDescription": "Oct 11 at 10:09PM"+ },+ "updatedAt": "2026-10-11T11:14:08Z",+ "loginMethod": "Claude Max 20x",+ "identity": {+ "loginMethod": "Claude Max 20x",+ "providerID": "claude"+ },+ "tertiary": null+ }+ }+]diff --git a/tests/fixtures/codexbar/usage-claude-cli-error.json b/tests/fixtures/codexbar/usage-claude-cli-error.jsonnew file mode 100644index 0000000..2aab516--- /dev/null+++ b/tests/fixtures/codexbar/usage-claude-cli-error.json@@ -0,0 +1,11 @@+[+ {+ "provider": "claude",+ "error": {+ "code": 1,+ "message": "Could not parse Claude usage: Claude CLI could not load usage data. Open the CLI and retry `/usage`.",+ "kind": "provider"+ },+ "source": "auto"+ }+]diff --git a/tests/fixtures/codexbar/usage-claude-oauth.json b/tests/fixtures/codexbar/usage-claude-oauth.jsonnew file mode 100644index 0000000..2acc326--- /dev/null+++ b/tests/fixtures/codexbar/usage-claude-oauth.json@@ -0,0 +1,59 @@+[+ {+ "pace": {+ "primary": {+ "deltaPercent": -51,+ "expectedUsedPercent": 61,+ "willLastToReset": true,+ "stage": "farBehind",+ "summary": "51% in reserve | Expected 61% used | Lasts until reset"+ },+ "secondary": {+ "deltaPercent": -2,+ "expectedUsedPercent": 79,+ "willLastToReset": true,+ "stage": "onTrack",+ "summary": "On pace | Expected 79% used | Lasts until reset"+ }+ },+ "provider": "claude",+ "rateWindowLabels": {+ "primary": "Session",+ "secondary": "Weekly"+ },+ "usage": {+ "identity": {+ "loginMethod": "Claude Max 20x",+ "providerID": "claude"+ },+ "secondary": {+ "resetsAt": "2026-10-12T23:00:00Z",+ "resetDescription": "Oct 13 at 8:00AM",+ "usedPercent": 77,+ "windowMinutes": 10080+ },+ "extraRateWindows": [+ {+ "title": "Fable only",+ "window": {+ "resetsAt": "2026-10-12T23:00:00Z",+ "resetDescription": "Oct 13 at 8:00AM",+ "windowMinutes": 10080,+ "usedPercent": 0+ },+ "id": "claude-weekly-scoped-fable"+ }+ ],+ "primary": {+ "resetsAt": "2026-10-11T13:10:00Z",+ "resetDescription": "Oct 11 at 10:10PM",+ "usedPercent": 10,+ "windowMinutes": 300+ },+ "loginMethod": "Claude Max 20x",+ "tertiary": null,+ "updatedAt": "2026-10-11T11:13:36Z"+ },+ "source": "oauth"+ }+]diff --git a/tests/fixtures/codexbar/usage-codex.json b/tests/fixtures/codexbar/usage-codex.jsonnew file mode 100644index 0000000..f2fc5fa--- /dev/null+++ b/tests/fixtures/codexbar/usage-codex.json@@ -0,0 +1,75 @@+[+ {+ "credits": {+ "events": [],+ "balanceReadSucceeded": true,+ "remaining": 100.0,+ "creditsAvailable": true,+ "balanceIsWorkspace": false,+ "updatedAt": "2026-10-11T11:11:54Z"+ },+ "resetCredits": {+ "nextExpiresAt": "2026-11-06T23:37:16Z",+ "available": 1+ },+ "rateWindowLabels": {+ "secondary": "Weekly"+ },+ "source": "oauth",+ "provider": "codex",+ "version": "0.160.0",+ "usage": {+ "dataConfidence": "exact",+ "loginMethod": "pro",+ "identity": {+ "loginMethod": "pro",+ "providerID": "codex",+ "accountEmail": "[email protected]"+ },+ "secondary": {+ "windowMinutes": 10080,+ "resetsAt": "2026-10-18T04:02:43Z",+ "usedPercent": 6,+ "resetDescription": "Oct 18 at 1:02 PM"+ },+ "updatedAt": "2026-10-11T11:11:54Z",+ "primary": null,+ "providerCost": {+ "currencyCode": "Credits",+ "limit": 0,+ "balanceUpdatedAt": "2026-10-11T11:11:54Z",+ "updatedAt": "2026-10-11T11:11:54Z",+ "used": 0,+ "balance": 100.0,+ "period": "Extra usage"+ },+ "codexResetCredits": {+ "availableCount": 1,+ "credits": [+ {+ "granted_at": "2026-10-07T23:37:16Z",+ "title": "Full reset",+ "description": "Thanks for using Codex! You've been granted one free rate limit reset.",+ "expires_at": "2026-11-06T23:37:16Z",+ "id": "codex-reset-credit-v1-0000000000000000000000000000000000000000",+ "reset_type": "codex_rate_limits",+ "status": "available"+ }+ ],+ "updatedAt": "2026-10-11T11:11:54Z"+ },+ "tertiary": null,+ "accountEmail": "[email protected]"+ },+ "pace": {+ "secondary": {+ "etaSeconds": 403433,+ "stage": "onTrack",+ "summary": "On pace | Expected 4% used | Runs out in 4d 16h",+ "expectedUsedPercent": 4,+ "willLastToReset": false,+ "deltaPercent": 2+ }+ }+ }+]diff --git a/tests/test_catalog.py b/tests/test_catalog.pyindex 565805a..ee49aec 100644--- a/tests/test_catalog.py+++ b/tests/test_catalog.py@@ -133,9 +133,9 @@ class CatalogTest(unittest.TestCase):def test_bundled_catalog_matches_installed_faces(self):data = catalog.validate_catalog(json.loads(catalog.CATALOG_PATH.read_text()))self.assertLessEqual({t['id'] for t in data['themes']}, set(STYLES)) # a fork may add Local faces- # one public theme issue per built-in face (issues #1-#6 in the public repository)+ # Existing public issues stay mapped; new faces have no voting issue yet.self.assertEqual({t['id']: t['like_issue'] for t in data['themes']},- {'pixel': 1, 'digital': 2, 'neon': 3, 'retro': 4, 'hud': 5, 'space': 6})+ {'pixel': 1, 'digital': 2, 'neon': 3, 'retro': 4, 'hud': 5, 'space': 6, 'gameboy': None})votes = catalog.load_votes()self.assertTrue(set(votes['counts']) <= {str(t['like_issue']) for t in data['themes']})self.assertTrue(all(v['fetched_at'] for v in votes['counts'].values())) # every count is dateddiff --git a/tests/test_cli.py b/tests/test_cli.pyindex a0323c0..0cdb084 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -82,6 +82,25 @@ class CliTest(unittest.TestCase):self.assertEqual(code, 1)self.assertIn('Keychain unchecked', out)+ def test_doctor_checks_codexbar_instead_of_a_login_file(self):+ self.config.write_text(json.dumps({'accounts': [+ {'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]',+ 'codexbar_command': str(self.tmp / 'missing-codexbar'), 'codexbar_source': 'oauth'}]}))+ code, out, _ = run('doctor', '--config', str(self.config))+ self.assertEqual(code, 1)+ self.assertIn('install the CodexBar CLI', out)+ self.assertNotIn('token-tv connect', out)+ unreported = {'status': 'ok', 'identity_verified': False}+ with mock.patch('token_tv.sources.fetch_account', return_value=unreported):+ code, out, _ = run('doctor', '--config', str(self.config), '--live')+ self.assertEqual(code, 0)+ self.assertIn('CodexBar did not report the email for CLAUDE A', out)+ failed = {'status': 'error', 'identity_verified': False}+ with mock.patch('token_tv.sources.fetch_account', return_value=failed):+ code, out, _ = run('doctor', '--config', str(self.config), '--live')+ self.assertEqual(code, 1)+ self.assertIn('live check ERROR', out)+def test_broken_config_gets_a_sentence_not_a_traceback(self):self.config.write_text('{"accounts": [')for command in ('doctor', 'run'):diff --git a/tests/test_codexbar.py b/tests/test_codexbar.pynew file mode 100644index 0000000..b077fc0--- /dev/null+++ b/tests/test_codexbar.py@@ -0,0 +1,237 @@+"""CodexBar input. Fixtures are real CodexBar 0.74.0 output on Linux with emails and IDs replaced."""+import io+import json+import subprocess+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++from PIL import Image++from token_tv.display import render_page+from token_tv.sources import fetch_account, load_config+from token_tv.state import UsageStore+from token_tv.usage import normalize_codexbar++FIXTURES = Path(__file__).parent / "fixtures" / "codexbar"+++def fixture(name):+ return json.loads((FIXTURES / name).read_text())+++def ran(stdout, code=0):+ return subprocess.CompletedProcess([], code, stdout=stdout)+++CLAUDE = {"key": "claude_a", "alias": "CLAUDE A", "provider": "claude", "email": "[email protected]",+ "codexbar_command": "codexbar", "codexbar_source": "oauth"}+CODEX = {"key": "codex_a", "alias": "CODEX A", "provider": "codex", "email": "[email protected]",+ "codexbar_command": "codexbar"}+++class NormalizeTests(unittest.TestCase):+ def test_claude_session_and_weekly(self):+ windows = normalize_codexbar(fixture("usage-claude-oauth.json")[0])+ self.assertEqual(windows, [+ {"label": "5H", "used_percent": 10.0, "resets_at": 1791724200, "duration_minutes": 300},+ {"label": "WEEK", "used_percent": 77.0, "resets_at": 1791846000, "duration_minutes": 10080}])++ def test_model_scoped_window_never_replaces_weekly(self):+ entry = fixture("usage-claude-oauth.json")[0]+ self.assertEqual(entry["usage"]["extraRateWindows"][0]["window"]["usedPercent"], 0)+ entry["usage"]["tertiary"] = {"usedPercent": 1, "windowMinutes": 10080}+ self.assertEqual([w["used_percent"] for w in normalize_codexbar(entry)], [10.0, 77.0])++ def test_missing_session_stays_missing(self):+ entry = fixture("usage-codex.json")[0]+ self.assertIsNone(entry["usage"]["primary"])+ self.assertEqual(normalize_codexbar(entry), [+ {"label": "WEEK", "used_percent": 6.0, "resets_at": 1792296163, "duration_minutes": 10080}])++ def test_unknown_cadence_is_not_guessed_from_display_label(self):+ entry = {"rateWindowLabels": {"primary": "Session"},+ "usage": {"primary": {"usedPercent": 40, "resetsAt": "2026-10-11T13:10:00Z"}}}+ self.assertEqual(normalize_codexbar(entry), [+ {"label": "WINDOW", "used_percent": 40.0, "resets_at": 1791724200, "duration_minutes": None}])++ def test_missing_percent_is_not_zero(self):+ entry = {"usage": {"primary": {"windowMinutes": 300, "resetsAt": "2026-10-11T13:10:00Z"}}}+ self.assertEqual(normalize_codexbar(entry), [])+ self.assertEqual(normalize_codexbar({"provider": "claude", "error": {"kind": "provider"}}), [])+++class FetchTests(unittest.TestCase):+ def test_cli_command_line_and_row(self):+ stdout = (FIXTURES / "usage-claude-oauth.json").read_text()+ with patch("token_tv.sources.subprocess.run", return_value=ran(stdout)) as run:+ row = fetch_account(CLAUDE)+ command = run.call_args.args[0]+ self.assertEqual(command[1:], ["usage", "--provider", "claude", "--format", "json", "--source", "oauth"])+ self.assertEqual(run.call_args.kwargs["stdin"], subprocess.DEVNULL)+ self.assertEqual((row["status"], row["source"]), ("ok", "codexbar"))+ self.assertEqual([w["label"] for w in row["windows"]], ["5H", "WEEK"])+ # CodexBar's Claude OAuth path reports no email, so nothing is claimed.+ self.assertFalse(row["identity_verified"])++ def test_source_flag_is_omitted_unless_configured(self):+ stdout = (FIXTURES / "usage-codex.json").read_text()+ with patch("token_tv.sources.subprocess.run", return_value=ran(stdout)) as run:+ row = fetch_account(CODEX)+ self.assertNotIn("--source", run.call_args.args[0])+ self.assertIsNone(run.call_args.kwargs["env"])+ self.assertEqual((row["status"], row["identity_verified"]), ("ok", True))++ def test_source_home_scopes_the_cli_home(self):+ account = dict(CODEX, source_home="/explicit/codex-home")+ with patch.dict("os.environ", {"OPENAI_API_KEY": "DO-NOT-INHERIT"}), \+ patch("token_tv.sources.subprocess.run", return_value=ran((FIXTURES / "usage-codex.json").read_text())) as run:+ fetch_account(account)+ env = run.call_args.kwargs["env"]+ self.assertEqual(env["CODEX_HOME"], "/explicit/codex-home")+ self.assertNotIn("OPENAI_API_KEY", env)++ def test_reported_email_must_match(self):+ stdout = (FIXTURES / "usage-codex.json").read_text()+ with patch("token_tv.sources.subprocess.run", return_value=ran(stdout)):+ row = fetch_account(dict(CODEX, email="[email protected]"))+ self.assertEqual((row["status"], row["windows"]), ("identity_mismatch", []))++ def test_every_reported_email_must_match(self):+ entry = fixture("usage-codex.json")[0]+ entry["usage"]["accountEmail"] = "[email protected]"+ with patch("token_tv.sources.subprocess.run", return_value=ran(json.dumps([entry]))):+ row = fetch_account(CODEX)+ self.assertEqual((row["status"], row["windows"]), ("identity_mismatch", []))++ def test_malformed_entry_fails_only_that_account(self):+ broken = [{"provider": "codex", "usage": "x"},+ {"provider": "codex", "usage": {"identity": [], "primary": "x", "secondary": 5}}]+ for entry in broken:+ with patch("token_tv.sources.subprocess.run", return_value=ran(json.dumps([entry]))):+ row = fetch_account(CODEX)+ self.assertIn(row["status"], ("error", "quota_unavailable"), entry)+ self.assertEqual(row["windows"], [])+ direct = {"key": "claude_d", "alias": "CLAUDE D", "provider": "claude", "email": "[email protected]",+ "source_home": "/unused"}+ store = UsageStore([dict(CODEX), direct])+ with patch("token_tv.sources.subprocess.run", return_value=ran(json.dumps(broken[:1]))), \+ patch("token_tv.sources.claude_payload", return_value=({"account": {"email": "[email protected]"}},+ {"five_hour": {"utilization": 8}})):+ store.refresh()+ self.assertEqual(store.snapshot()["accounts"]["claude_d"]["session_percent"], 8.0)++ def test_failed_provider_keeps_no_numbers_and_no_message(self):+ stdout = (FIXTURES / "usage-claude-cli-error.json").read_text()+ with patch("token_tv.sources.subprocess.run", return_value=ran(stdout, 1)):+ row = fetch_account(dict(CLAUDE, codexbar_source="cli"))+ self.assertEqual((row["status"], row["error_code"], row["windows"]), ("error", "codexbar_provider", []))+ self.assertNotIn("Could not parse", json.dumps(row))++ def test_auth_failure_is_reported_as_sign_in(self):+ stdout = json.dumps([{"provider": "codex", "source": "auto",+ "error": {"code": 1, "kind": "provider", "message": "Codex login required"}}])+ with patch("token_tv.sources.subprocess.run", return_value=ran(stdout, 1)):+ row = fetch_account(CODEX)+ self.assertEqual(row["status"], "auth_required")++ def test_missing_cli_is_not_a_login_problem(self):+ with patch("token_tv.sources.subprocess.run", side_effect=FileNotFoundError):+ row = fetch_account(CODEX)+ self.assertEqual((row["status"], row["error_code"]), ("error", "cli_unavailable"))++ def test_unreadable_output_is_an_error(self):+ for stdout in ("", "not json", "{}", "[]"):+ with patch("token_tv.sources.subprocess.run", return_value=ran(stdout)):+ row = fetch_account(CODEX)+ self.assertEqual((row["status"], row["windows"]), ("error", []), stdout)++ def test_timeout_is_an_error(self):+ with patch("token_tv.sources.subprocess.run", side_effect=subprocess.TimeoutExpired("codexbar", 60)):+ row = fetch_account(CODEX)+ self.assertEqual(row["status"], "error")++ def test_serve_url_picks_this_accounts_provider(self):+ account = {"key": "claude_a", "alias": "CLAUDE A", "provider": "claude", "email": "[email protected]",+ "codexbar_url": "http://127.0.0.1:8080/usage"}+ with patch("token_tv.sources.json_get", return_value=fixture("serve-usage.json")) as get, \+ patch("token_tv.sources.subprocess.run") as run:+ row = fetch_account(account)+ get.assert_called_once_with("http://127.0.0.1:8080/usage")+ run.assert_not_called()+ self.assertEqual([w["used_percent"] for w in row["windows"]], [10.0, 77.0])+ with patch("token_tv.sources.json_get", return_value=fixture("serve-usage.json")):+ row = fetch_account(dict(account, provider="codex", key="codex_a", alias="CODEX A"))+ self.assertEqual(([w["label"] for w in row["windows"]], row["identity_verified"]), (["WEEK"], True))++ def test_serve_picks_the_matching_codex_account(self):+ first = fixture("usage-codex.json")[0]+ second = json.loads(json.dumps(first))+ second["usage"]["identity"]["accountEmail"] = second["usage"]["accountEmail"] = "[email protected]"+ second["usage"]["secondary"]["usedPercent"] = 55+ account = dict(CODEX, email="[email protected]", codexbar_url="http://127.0.0.1:8080/usage")+ del account["codexbar_command"]+ with patch("token_tv.sources.json_get", return_value=[first, second]):+ row = fetch_account(account)+ self.assertEqual([w["used_percent"] for w in row["windows"]], [55.0])+ with patch("token_tv.sources.json_get", return_value=[first, second]):+ row = fetch_account(dict(account, email="[email protected]"))+ self.assertEqual(row["status"], "identity_mismatch")++ def test_provider_absent_from_output(self):+ with patch("token_tv.sources.subprocess.run", return_value=ran((FIXTURES / "usage-codex.json").read_text())):+ row = fetch_account(CLAUDE)+ self.assertEqual((row["status"], row["error_code"]), ("error", "codexbar_provider_missing"))++ def test_store_and_clock_render_from_real_output(self):+ outputs = {"claude": (FIXTURES / "usage-claude-oauth.json").read_text(),+ "codex": (FIXTURES / "usage-codex.json").read_text()}+ def fake(command, **kwargs):+ return ran(outputs[command[command.index("--provider") + 1]])+ store = UsageStore([CLAUDE, CODEX])+ with patch("token_tv.sources.subprocess.run", side_effect=fake), \+ patch("time.time", return_value=1791717216):+ store.refresh()+ snapshot = store.snapshot()+ claude, codex = snapshot["accounts"]["claude_a"], snapshot["accounts"]["codex_a"]+ self.assertEqual((claude["session_percent"], claude["weekly_percent"]), (10.0, 77.0))+ self.assertEqual((codex["session_percent"], codex["weekly_percent"]), (None, 6.0))+ image = Image.open(io.BytesIO(render_page(snapshot, 0, "pixel")))+ self.assertEqual(image.size, (240, 240))+++class ConfigTests(unittest.TestCase):+ def check(self, **account):+ base = {"key": "a", "alias": "A", "provider": "claude", "email": "[email protected]"}+ with tempfile.TemporaryDirectory() as folder:+ path = Path(folder) / "config.json"+ path.write_text(json.dumps({"accounts": [dict(base, **account)]}))+ return load_config(path)++ def test_accepts_cli_or_url_for_verified_providers(self):+ self.check(codexbar_command="~/.local/opt/codexbar/codexbar", codexbar_source="oauth")+ self.check(provider="codex", codexbar_url="http://127.0.0.1:8080/usage")+ self.check(codexbar_url="http://127.0.0.1:8080/usage?provider=claude")++ def test_url_carries_no_credentials(self):+ for url in ("http://user:[email protected]:8080/usage", "http://127.0.0.1:8080/usage?token=secret",+ "http://127.0.0.1:8080/usage#secret"):+ with self.assertRaises(ValueError, msg=url):+ self.check(codexbar_url=url)++ def test_rejects_unclear_or_unverified_input(self):+ for account in ({"provider": "grok", "codexbar_command": "codexbar"},+ {"codexbar_command": "codexbar", "codexbar_url": "http://127.0.0.1:8080/usage"},+ {"codexbar_url": "file:///etc/passwd"},+ {"codexbar_command": ""},+ {"codexbar_command": "codexbar", "codexbar_source": "browser"},+ {"codexbar_url": "http://127.0.0.1:8080/usage", "codexbar_source": "oauth"},+ {"codexbar_source": "oauth"},+ {"codexbar_command": "codexbar", "snapshot_file": "/tmp/snapshot.json"}):+ with self.assertRaises(ValueError, msg=account):+ self.check(**account)+++if __name__ == "__main__":+ unittest.main()diff --git a/token_tv/assets/theme-catalog.json b/token_tv/assets/theme-catalog.jsonindex 18a3493..888f09a 100644--- a/token_tv/assets/theme-catalog.json+++ b/token_tv/assets/theme-catalog.json@@ -60,6 +60,16 @@"source_url": "https://github.com/click6067-ship-it/token-tv","license": "MIT","like_issue": 6+ },+ {+ "id": "gameboy",+ "name": "Game Boy",+ "author": "TokenTV",+ "added_at": "2026-10-07T00:00:00Z",+ "min_version": "0.1.0",+ "source_url": "https://github.com/click6067-ship-it/token-tv",+ "license": "MIT",+ "like_issue": null}]}diff --git a/token_tv/cli.py b/token_tv/cli.pyindex 36a3937..4cf8659 100644--- a/token_tv/cli.py+++ b/token_tv/cli.py@@ -156,8 +156,29 @@ def doctor(args):return 1flag = '' if str(Path(args.config).expanduser()) == default_config() else f' --config {args.config}'ready = True+ unreported = []for account in config['accounts']:provider = account['provider']+ if account.get('codexbar_command') or account.get('codexbar_url'):+ # CodexBar owns this login; TokenTV only checks that it answers.+ command = account.get('codexbar_command')+ line = f'{account["alias"]:<10} {provider:<6} CodexBar '+ if args.live:+ from token_tv.sources import fetch_account+ row = fetch_account(account)+ good = row['status'] in ('ok', 'quota_unavailable')+ line += f'live check {"ok" if good else row["status"].upper()}'+ if good and not row.get('identity_verified'):+ line += ' (CodexBar reported no email)'+ unreported.append(account['alias'])+ ready &= good+ elif command and not shutil.which(os.path.expanduser(command)):+ ready = False+ line += f'MISSING: {command} not found -> install the CodexBar CLI'+ else:+ line += f'{command or account["codexbar_url"]} (not checked yet)'+ print(line)+ continuehome = account.get('source_home') or PROVIDERS[provider][1]found, state = cli_path(provider), login_state(provider, home)line = f'{account["alias"]:<10} {provider:<6} CLI {"ok" if found else "MISSING"} '@@ -184,6 +205,9 @@ def doctor(args):print('Clock: ' + (config.get('device_url') or 'none (dashboard only)'))if not ready:print(f'Fix the lines above, then run token-tv doctor{flag} again.')+ elif args.live and unreported:+ print(f'Ready, but CodexBar did not report the email for {", ".join(unreported)}; '+ f'check it reads the account you expect. Start with: token-tv run{flag}')elif args.live:print(f'Ready: every account answered with the expected email. Start with: token-tv run{flag}')else:diff --git a/token_tv/display.py b/token_tv/display.pyindex 2b1f1ac..6a21ced 100644--- a/token_tv/display.py+++ b/token_tv/display.py@@ -23,7 +23,7 @@ PROVIDER_INK = {'claude': '#d68e68', 'codex': '#a799e5', 'grok': '#cbd1d7'}ICON_PAPER = PROVIDER_INK['grok']FONT_MAIN = '/usr/share/fonts/truetype/dejavu/DejaVuSans'FONT_NUMBERS = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono'-STYLES = ('pixel', 'digital', 'neon', 'retro', 'hud', 'space')+STYLES = ('pixel', 'digital', 'neon', 'retro', 'hud', 'space', 'gameboy')# Gauge-only levels; labels/percentages always use TEXT, logos retain provider ink.GAUGE_LEVELS = ((50, '#76a99a'), (80, '#93c9b9'), (90, '#d1b275'), (101, '#d8877e'))STATUS = {'loading': 'WAIT', 'auth_required': 'LOGIN', 'identity_mismatch': 'CHECK',diff --git a/token_tv/sources.py b/token_tv/sources.pyindex a7192df..323b4ae 100644--- a/token_tv/sources.py+++ b/token_tv/sources.py@@ -12,11 +12,15 @@ import timeimport unicodedatafrom pathlib import Pathfrom urllib.error import HTTPError+from urllib.parse import parse_qs, urlparsefrom urllib.request import Request, urlopen-from token_tv.usage import normalize_claude, normalize_codex, normalize_grok, timestamp, window+from token_tv.usage import normalize_claude, normalize_codex, normalize_codexbar, normalize_grok, timestamp, windowfrom token_tv.display import STYLES+CODEXBAR_SOURCES = {"auto", "web", "cli", "oauth", "api"}+AUTH_WORDS = ("auth", "login", "sign in", "token")+def exe(name):"""Full path of a CLI. On Windows npm installs `claude`/`codex` as .cmd shims that a bare name can't start."""@@ -85,7 +89,7 @@ class RPC:if "error" in reply:error = reply["error"]message = str(error.get("message", "")).lower()- code = "auth_required" if any(x in message for x in ("auth", "login", "sign in", "token")) else "rpc_error"+ code = "auth_required" if any(x in message for x in AUTH_WORDS) else "rpc_error"if error.get("code") == -32601:code = "method_unavailable"raise SourceError(code)@@ -111,12 +115,14 @@ def load_config(path):if data.get('display_style', 'pixel') not in STYLES:raise ValueError('Unknown display style')seen = set()- allowed = {"key", "alias", "provider", "source_home", "email", "snapshot_file", "fallback_snapshot_file", "refresh_with_cli"}+ allowed = {"key", "alias", "provider", "source_home", "email", "snapshot_file", "fallback_snapshot_file", "refresh_with_cli",+ "codexbar_command", "codexbar_url", "codexbar_source"}for account in data.get("accounts", []):if set(account) - allowed:raise ValueError("Only credential-free account metadata is allowed")if account.get("provider") not in ("claude", "codex", "grok"):raise ValueError("Unknown provider")+ check_codexbar(account)key = account.get("key", "")if not re.fullmatch(r"[a-z0-9_-]{1,48}", key) or key in seen:raise ValueError("Account keys must be unique")@@ -130,6 +136,32 @@ def load_config(path):return data+def uses_codexbar(account):+ return bool(account.get("codexbar_command") or account.get("codexbar_url"))+++def check_codexbar(account):+ """CodexBar input is either its CLI or a `codexbar serve` /usage URL, for providers checked against it."""+ fields = {"codexbar_command", "codexbar_url", "codexbar_source"} & set(account)+ if not fields:+ return+ command, url = account.get("codexbar_command"), account.get("codexbar_url")+ if account["provider"] not in ("claude", "codex"):+ raise ValueError("CodexBar input is checked for claude and codex accounts only")+ if bool(command) == bool(url) or account.get("snapshot_file"):+ raise ValueError("Use one of codexbar_command or codexbar_url, without snapshot_file")+ if command is not None and not (isinstance(command, str) and command.strip()):+ raise ValueError("codexbar_command must be a command or path")+ if url is not None:+ parts = urlparse(url) if isinstance(url, str) else None+ # Credential-free: no user:password@, and no query other than CodexBar's provider filter.+ if (not parts or parts.scheme not in ("http", "https") or not parts.hostname or "@" in parts.netloc+ or parts.fragment or set(parse_qs(parts.query, keep_blank_values=True)) - {"provider"}):+ raise ValueError("codexbar_url must be an http(s) /usage address without credentials")+ if "codexbar_source" in account and (url or account["codexbar_source"] not in CODEXBAR_SOURCES):+ raise ValueError("codexbar_source is one of " + ", ".join(sorted(CODEXBAR_SOURCES)) + " and only for codexbar_command")++def json_get(url, headers=None):with urlopen(Request(url, headers=headers or {}), timeout=20) as response:return json.load(response)@@ -233,6 +265,60 @@ def grok_payload(account):rpc.close()+def codexbar_payload(account):+ """CodexBar's usage JSON. CodexBar owns the login; TokenTV only reads what it prints or serves."""+ if account.get("codexbar_url"):+ return json_get(account["codexbar_url"])+ command = [exe(os.path.expanduser(account["codexbar_command"])), "usage",+ "--provider", account["provider"], "--format", "json"]+ if account.get("codexbar_source"):+ command += ["--source", account["codexbar_source"]]+ env = scoped_env(account["provider"], Path(account["source_home"]).expanduser()) if account.get("source_home") else None+ try:+ result = subprocess.run(command, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL, text=True, timeout=60)+ except FileNotFoundError:+ raise SourceError("cli_unavailable") from None+ try:+ # A failed provider still prints its JSON error entry, with a non-zero exit.+ return json.loads(result.stdout)+ except ValueError:+ raise SourceError("invalid_codexbar_output") from None+++def codexbar_emails(entry):+ """Account emails CodexBar reported for this entry (its `account` label is a display name, not one)."""+ usage = entry.get("usage") if isinstance(entry.get("usage"), dict) else {}+ identity = usage.get("identity") if isinstance(usage.get("identity"), dict) else {}+ return [value for value in (identity.get("accountEmail"), usage.get("accountEmail"))+ if isinstance(value, str) and value.strip()]+++def codexbar_entry(data, account):+ """This account's entry and whether CodexBar reported its email. Every reported email must match."""+ if not isinstance(data, list):+ raise SourceError("invalid_codexbar_output")+ entries = [entry for entry in data if isinstance(entry, dict) and entry.get("provider") == account["provider"]]+ if not entries:+ raise SourceError("codexbar_provider_missing")+ for entry in entries:+ emails = codexbar_emails(entry)+ if emails and all(identity_matches(account["email"], email) for email in emails):+ return entry, True+ if len(entries) == 1 and not codexbar_emails(entries[0]):+ return entries[0], False+ raise SourceError("identity_mismatch")+++def codexbar_error(error):+ """An error code only; CodexBar's message text is never kept."""+ message = str(error.get("message", "")).lower() if isinstance(error, dict) else ""+ if any(word in message for word in AUTH_WORDS):+ return "auth_required"+ kind = error.get("kind") if isinstance(error, dict) else None+ return "codexbar_" + kind if kind in ("args", "config", "provider", "runtime") else "codexbar_error"++def logged_in_email(provider, home):"""The email of the account already signed in to this CLI home, or None. Prints nothing secret."""root = Path(home).expanduser()@@ -315,7 +401,16 @@ def fetch_account(account):try:if account.get("snapshot_file"):return imported_row(account)- if account["provider"] == "claude":+ if uses_codexbar(account):+ row["source"] = "codexbar"+ entry, verified = codexbar_entry(codexbar_payload(account), account)+ if entry.get("error"):+ raise SourceError(codexbar_error(entry["error"]))+ if not isinstance(entry.get("usage"), dict):+ raise SourceError("invalid_codexbar_output")+ row["windows"] = normalize_codexbar(entry)+ row["identity_verified"] = verified+ elif account["provider"] == "claude":profile, data = claude_payload(account)if not identity_matches(account["email"], email_from_profile(profile)):raise SourceError("identity_mismatch")diff --git a/token_tv/themes.py b/token_tv/themes.pyindex f5c6ee4..555eb3a 100644--- a/token_tv/themes.py+++ b/token_tv/themes.py@@ -212,7 +212,8 @@ def prompt_cloud_mark(size, color):draw = ImageDraw.Draw(image)for box in ((s * .02, s * .30, s * .56, s * .92), (s * .20, s * .06, s * .82, s * .66), (s * .44, s * .30, s * .98, s * .92)):draw.ellipse(box, fill=color)- draw.rounded_rectangle((s * .14, s * .50, s * .86, s * .92), radius=s * .2, fill=color)+ box = tuple(round(s * v) for v in (.14, .50, .86, .92))+ draw.rounded_rectangle(box, radius=min(round(s * .2), (box[3] - box[1]) // 2), fill=color)cut = Image.new('L', (s, s), 0)cd = ImageDraw.Draw(cut)w, cx, cy = round(s * .09), s * .27, s * .52@@ -501,4 +502,39 @@ def render_hud(snapshot):return cv.finish(blur=2)-RENDERERS = {'digital': render_digital, 'neon': render_neon, 'retro': render_retro, 'hud': render_hud}+GB_DARKEST, GB_DARK, GB_LIGHT, GB_LIGHTEST = '#0f380f', '#306230', '#8bac0f', '#9bbc0f'+GB_PALETTE = [GB_DARKEST, GB_DARK, GB_LIGHT, GB_LIGHTEST]+++def to_four_shades(image):+ """Snap every pixel to the nearest of the four LCD shades (the real Game Boy had only four)."""+ palette = Image.new('P', (1, 1))+ flat = [int(c[i:i + 2], 16) for c in GB_PALETTE for i in (1, 3, 5)]+ palette.putpalette(flat + [0] * (768 - len(flat)))+ return image.convert('RGB').quantize(palette=palette, dither=Image.Dither.NONE).convert('RGB')+++def render_gameboy(data):+ cv = Canvas(GB_LIGHTEST)+ pixel = lambda size: face('press-start-2p.ttf', size)+ rows = overview_rows(data)+ pitch = 79+ for index, row in enumerate(rows):+ y = 3 + index * pitch + row_shift(len(rows), pitch)+ used, period, old, reset = reading(row) # used is None when nothing was reported+ cv.draw.rectangle((4, y, 235, y + 74), outline=GB_DARKEST, width=2)+ cv.draw.rectangle((7, y + 3, 232, y + 71), outline=GB_DARK, width=1)+ place_bot(cv.ink, bot_sprite(row['provider'], 22, 18, GB_DARKEST, GB_LIGHTEST), (11, y + 7, 22, 18))+ cv.text((38, y + 11), account_label(row), pixel(8), GB_DARKEST)+ cv.text((229, y + 11), ('OLD ' if old else '') + period, pixel(8), GB_DARK, anchor='ra')+ cv.text((12, y + 31), number_text(used), pixel(20), GB_DARKEST) # a dash, never a fake 0+ if used is not None:+ cv.text((12 + cv.draw.textlength(number_text(used), font=pixel(20)) + 2, y + 39), '%', pixel(10), GB_DARKEST)+ cv.text((229, y + 34), 'RESET', pixel(7), GB_DARK, anchor='ra')+ cv.text((229, y + 45), reset, pixel(8), GB_DARKEST, anchor='ra')+ gauge(cv, (12, y + 58, 227, y + 66), used, (GB_DARKEST, GB_DARK), gap=2, track=GB_LIGHT, empty=GB_DARK, stale=old)+ return to_four_shades(cv.finish())++++RENDERERS = {'digital': render_digital, 'neon': render_neon, 'retro': render_retro, 'hud': render_hud, 'gameboy': render_gameboy}diff --git a/token_tv/usage.py b/token_tv/usage.pyindex bc0c2c5..dd51902 100644--- a/token_tv/usage.py+++ b/token_tv/usage.py@@ -51,6 +51,26 @@ def normalize_codex(data):return result+def normalize_codexbar(entry):+ """One provider entry of CodexBar's usage JSON (`codexbar usage --format json`, `serve` GET /usage).+ Only the primary and secondary slots: tertiary and extra windows are model-scoped and would+ overwrite the weekly reading if they shared its label."""+ result = []+ usage = entry.get("usage")+ for key in ("primary", "secondary"):+ value = usage.get(key) if isinstance(usage, dict) else None+ if not isinstance(value, dict):+ continue+ duration = value.get("windowMinutes")+ if not isinstance(duration, int) or isinstance(duration, bool) or duration <= 0:+ duration = None+ label = {300: "5H", 10080: "WEEK"}.get(duration, "WINDOW")+ item = window(label, value.get("usedPercent"), value.get("resetsAt"), duration)+ if item:+ result.append(item)+ return result++def normalize_grok(data):config = data.get("config") or {}percent = config.get("creditUsagePercent")diff --git a/token_tv/web/app.js b/token_tv/web/app.jsindex 6c99324..8d8fe4e 100644--- a/token_tv/web/app.js+++ b/token_tv/web/app.js@@ -185,7 +185,7 @@ function providerCard(provider, accounts) {let when = el('span', '—', 'stat-v');if (checked) {const d = new Date(checked * 1000); when = el('time', d.toLocaleTimeString('en-GB', {hour:'2-digit', minute:'2-digit'}), 'stat-v'); when.dateTime = d.toISOString(); when.title = d.toLocaleString('en-GB')}const foot = el('div', undefined, 'card-foot');- foot.append(stat('Account', a.alias || '—'), stat('Window', primary ? period(primary) : '—'), stat('Source', a.source === 'mini' ? 'This computer' : a.source ? 'Linked snapshot' : '—'), stat(stale ? 'Last good' : 'Checked', when), stat('Status', el('span', offline ? 'OFFLINE · Previous value' : STATUS[a.status] || 'Unknown', 'row-status stat-v'), 'stat-status'));+ foot.append(stat('Account', a.alias || '—'), stat('Window', primary ? period(primary) : '—'), stat('Source', a.source === 'mini' ? 'This computer' : a.source === 'codexbar' ? 'CodexBar' : a.source ? 'Linked snapshot' : '—'), stat(stale ? 'Last good' : 'Checked', when), stat('Status', el('span', offline ? 'OFFLINE · Previous value' : STATUS[a.status] || 'Unknown', 'row-status stat-v'), 'stat-status'));card.append(foot); shell.append(card); return shell;}function renderAccounts() {