Skip to content

Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.

Add theme sharing, setup command and fork guide

click6067-ship-it5289db55a422
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000..5e6b90b
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,27 @@
+---
+name: Bug report
+about: Something in TokenTV does not work as described
+labels: bug
+---
+
+**Do not paste passwords, tokens, cookies, `.credentials.json`, `auth.json` or your real
+emails.** Replace emails with `[email protected]`.
+
+**What happened**
+
+
+**What you expected**
+
+
+**Steps**
+1.
+
+**`token-tv doctor` output** (emails replaced)
+```
+```
+
+**Environment**
+- OS and version:
+- Python version (`python3 --version`):
+- How you installed TokenTV (pipx / pip / clone):
+- Clock face in use:
diff --git a/.github/ISSUE_TEMPLATE/hardware_compatibility.md b/.github/ISSUE_TEMPLATE/hardware_compatibility.md
new file mode 100644
index 0000000..c18a5bd
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/hardware_compatibility.md
@@ -0,0 +1,16 @@
+---
+name: Hardware compatibility
+about: Report whether TokenTV works on your clock model
+labels: hardware
+---
+
+**Do not include your Wi-Fi name, passwords or public IP addresses.**
+
+- Clock model and seller listing name:
+- Firmware version shown on the clock's web page:
+- Does the clock's web page have a photo album / photo upload page? (yes / no)
+- Result of `token-tv run` with `device_url` set: works / upload fails / image shows wrong
+- Which faces you tried:
+- A photo of the clock running TokenTV (optional, sample data is fine):
+
+**Anything else** (screen size if not 240×240, odd colours, refresh issues)
diff --git a/.github/PULL_REQUEST_TEMPLATE/theme.md b/.github/PULL_REQUEST_TEMPLATE/theme.md
new file mode 100644
index 0000000..10068ac
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE/theme.md
@@ -0,0 +1,19 @@
+## New clock face
+
+- **id** (lowercase, used in `STYLES`):
+- **name**:
+- **author** (GitHub handle shown in the Themes list):
+- **license** of any font or image you added:
+- **source / inspiration** (link, or "original"):
+
+### Checks
+
+- [ ] Renderer added to `token_tv/themes.py` `RENDERERS` and the id to `STYLES` in `token_tv/display.py`
+- [ ] 240×240 preview attached, rendered from sample data (`token-tv demo`), viewed at real size
+- [ ] Missing readings show a dash, never `0%`; old readings are marked
+- [ ] No credentials, real emails or real usage in code, images or this PR
+- [ ] `python3 -B -m unittest discover -s tests` passes
+
+The maintainer adds `added_at`, `min_version` and the likes issue to `token_tv/assets/theme-catalog.json`
+when the face ships in a release. You can use your face from your own fork right away; see
+`docs/clock-faces.md`.
diff --git a/.gitignore b/.gitignore
index 77d75a5..c6f269b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,4 @@ __pycache__/
/.runtime/
/.venv/
*.egg-info/
+build/
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..1587777
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,26 @@
+# Agent guide
+
+TokenTV draws AI usage limits on a 240×240 desk clock. Python 3.10+, Pillow, no other runtime deps.
+
+## Run without accounts or a clock
+
+```bash
+pip install -e .
+token-tv demo --out token-tv-demo # every face from sample data
+python3 -B -m unittest discover -s tests
+```
+
+## Rules
+
+- Never read, print or copy credential files (`.credentials.json`, `auth.json`, Keychain items) or
+ real config files. Tests use `token_tv/sample.py` and temporary folders.
+- Do not publish, push, open issues or create releases on the user's behalf.
+- A missing reading is a dash, an old one is marked OLD. Never turn unknown into `0`.
+- `token-tv setup --yes --<provider>-email ...` is non-interactive and never overwrites a config.
+ `token-tv doctor --live` contacts providers; ask the user before running it.
+
+## Make a clock face
+
+Follow `docs/clock-faces.md`: write a render function, add it to `RENDERERS` and `STYLES`, render
+with `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.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..80852ea
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,25 @@
+# Contributing
+
+Thanks for helping. The most useful contributions right now are:
+
+- **Clock faces.** See [docs/clock-faces.md](docs/clock-faces.md). One function, previewed
+ from sample data.
+- **Hardware reports.** Does your clock model work? Open a *Hardware compatibility* issue.
+- **Bug reports** with the output of `token-tv doctor`.
+
+## Set up
+
+```bash
+git clone https://github.com/click6067-ship-it/token-tv && cd token-tv
+python3 -m venv .venv && .venv/bin/pip install -e .
+.venv/bin/token-tv demo # renders every face with sample data, no login needed
+.venv/bin/python -B -m unittest discover -s tests
+```
+
+## Ground rules
+
+- Never put passwords, tokens, cookies, `.credentials.json`, `auth.json` or real config files
+ in an issue, a pull request, a test or a screenshot. Tests use synthetic accounts
+ (`token_tv/sample.py`, `@example.com` emails) and temporary folders.
+- A missing reading shows as a dash and an old one says OLD. Please keep that true.
+- Keep pull requests small: one face, one provider fix or one clock model at a time.
diff --git a/README.ko.md b/README.ko.md
index 6a36e9c..2408239 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -4,22 +4,37 @@
![실제 시계에 띄운 Digital, Pixel Retro, Sci-Fi HUD 화면](docs/images/real-clock.jpg)
-여러 AI 계정의 사용량을 240×240 책상 시계와 브라우저에서 확인합니다.
-계정별 인증 홈을 분리하고, 실제 조회 실패와 오래된 값을 표시합니다.
+**AI 사용 한도를 작은 책상 시계에.** Claude와 Codex 사용량을 여러 계정으로, 시계 펌웨어를 바꾸지 않고 보여줍니다.
+Grok은 CLI 예산 정보를 보여주는 실험적 기능입니다. 제작자의 시계는 할인가 약 6,000원(약 $5)에 샀으며 가격과 배송비는 다를 수 있습니다. 켜 두는 컴퓨터(호스트)가 필요합니다.
+
+240×240 책상 시계와 브라우저에서 확인하며, 계정별 인증 홈을 분리하고 실제 조회 실패와 오래된 값을 표시합니다.
## 실행
-Python 3.10+와 Pillow가 필요합니다.
+Python 3.10+와 사용할 공급자의 공식 CLI(`claude`, `codex`, `grok`)가 필요합니다.
```bash
-python3 -m venv .venv
-.venv/bin/pip install -r requirements.txt
-mkdir -p .runtime
-cp config.example.json .runtime/config.json
-# 이메일과 해당 계정의 공식 CLI 인증 홈을 지정합니다.
-.venv/bin/python -m token_tv.live --config .runtime/config.json
+pipx install git+https://github.com/click6067-ship-it/token-tv
+token-tv demo # 로그인 없이 샘플 데이터로 모든 시계 화면을 렌더
+token-tv setup # 공급자당 최대 3계정 이메일과 시계 IP만 묻고, 기존 설정은 덮어쓰지 않음
+token-tv doctor --live # 지금 각 공급자에 조회해 빠진 CLI·로그인과 해결 명령을 안내
+token-tv run # 대시보드 http://127.0.0.1:8787 + 시계 전송
```
+설정 파일은 `~/.config/token-tv/config.json`이며 모든 명령이 `--config`를 받습니다.
+A 계정은 평소 쓰던 로그인(`~/.claude` 등)을 재사용할 수 있고, B·C 계정은
+`~/.config/token-tv/homes/` 아래 별도 로그인 폴더를 씁니다. `token-tv connect --account codex_b`로
+별도 계정에 로그인하며, 평소 로그인 위에 다시 로그인하려면 REPLACE를 입력해야 합니다.
+`doctor`는 로그인 파일 존재만 보고, `doctor --live`는 실제 조회(만료 시 CLI 갱신 가능)를 하되
+계정별 상태만 출력합니다. 기여 방법은 [CONTRIBUTING.md](CONTRIBUTING.md)와
+[시계 화면 만들기](docs/clock-faces.md)를 봅니다.
+아직 PyPI에 올리지 않았으므로 `uvx token-tv`는 동작하지 않습니다. 설치 없이 실행하려면
+`uvx --from git+https://github.com/click6067-ship-it/token-tv token-tv demo`를 씁니다.
+클론에서는 `pip install .`로 같은 명령을 설치합니다.
+
+macOS(실기기 미검증): Claude Code가 로그인을 Keychain에 두므로, CLI 홈에
+`.credentials.json`이 없으면 `security`로 읽기 전용 조회합니다. 이메일 대조는 그대로 합니다.
+
브라우저: `http://127.0.0.1:8787/`. `/snapshot`과 `/snapshot/<key>`는 JSON,
`/frame/0.jpg`는 시계와 같은 240×240 JPEG이며 `/frame/1.jpg`는 호환 별칭입니다.
시계는 Claude·Codex·Grok 각각 한 계정을 세 행으로 보여줍니다. 픽셀 아이콘, 큰 사용률 숫자, 막대, 기간 및 리셋 시간을 표시합니다.
@@ -77,20 +92,30 @@ Grok이 한도 수치를 제공하지 않으면 `quota_unavailable`로 표시합
이 과정은 도구를 끈 짧은 확인 응답 하나를 요청하므로 구독 사용량을 소량 소비할 수 있습니다.
인증 파일의 토큰을 직접 수정하거나 다른 머신으로 복사하지 않습니다.
+## 내 디자인 만들기
+
+**동작하는 화면에서 시작하세요. 포크해서 바꾸고, 보여 주세요.** 시계 화면은 240×240을 그리는
+Python 함수 하나입니다. [docs/clock-faces.md](docs/clock-faces.md)를 따라 시계나 로그인 없이 샘플 데이터로
+만들 수 있습니다. 내 포크에서 바로 실행되고, 대시보드 **Themes** 목록에 *Local*로 나타나 시계에 적용할 수 있습니다.
+
+다른 사람과 나누려면 *New clock face* 템플릿으로 PR을 보내 주세요. 공유된 화면은 다음 릴리스부터
+**Themes**에서 **Popular**(테마별 GitHub 이슈의 👍) 또는 **New** 순으로 보입니다. 좋아요는 릴리스 전에
+수동으로 집계하며, 목록에 집계 시각이 표시됩니다.
+
## 시계 연결
확인된 경로는 SD_PRO 웹 UI의 `/theme/list`, `/photo/list`, `/photo/upload`입니다.
설정에 `"device_url": "http://<clock-ip>"`를 추가하면 사진 테마를 사용합니다.
기기 펌웨어를 바꾸지 않습니다. 기존 사진 파일은 보존하고 선택 상태만 변경합니다.
-원래 테마와 사진 선택 상태는 `.runtime/display-original.json`에 저장됩니다.
+원래 테마와 사진 선택 상태는 설정 폴더의 `state/display-original.json`에 저장됩니다.
복원 전 데몬을 정지한 뒤 실행합니다.
```bash
-python3 -m token_tv.live --config .runtime/config.json --restore-display
+token-tv run --restore-display
```
-사진 API가 없는 다른 펌웨어는 아직 실기기로 검증하지 않았습니다.
+사진 API가 없는 다른 펌웨어는 아직 실기기로 검증하지 않았습니다. 확인된 범위와 내 시계 확인 방법은 [docs/hardware-compatibility.md](docs/hardware-compatibility.md)에 있습니다.
## 다른 머신의 기존 인증 사용
@@ -105,7 +130,7 @@ Mini의 해당 계정에 로그인하면 다음 5분 조회부터 노트북 의
```bash
# Mini의 프로젝트 디렉터리에서 계정을 선택합니다.
-python3 -m token_tv.connect --config .runtime/config.json
+token-tv connect
```
인증번호는 로그인 터미널 또는 공식 브라우저 화면에 입력합니다. 제품의 HTTP API는
@@ -140,7 +165,7 @@ quota is shown as a dash, old readings carry an OLD label, and disconnected web
sessions retain their last readings with an offline notice. Grok CLI budget is
not the Grok web conversation quota.
-Web files live in `token_tv/web/`; `tokens.css` defines appearance colors and fonts.
+Web files live in `token_tv/web/`; `token_tv/web/tokens.css` defines appearance colors and fonts.
`token_tv/web_assets.py` allowlists public files. The bundled fonts (Manrope, Orbitron,
Oxanium, Press Start 2P, Jersey 10, VT323, DSEG7 Classic, Chakra Petch) are served locally with their SIL Open Font License notices; the dashboard makes
no external font requests, and the clock renderer reuses the same files.
diff --git a/README.md b/README.md
index 85767a9..f0171c4 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,8 @@
<h1 align="center">TokenTV</h1>
-<p align="center"><b>Your AI usage limits on a $5 desk clock</b><br>
-Claude · Codex · Grok — multiple accounts — no firmware flashing</p>
+<p align="center"><b>Your AI limits, on a tiny desk clock</b><br>
+Claude and Codex usage — multiple accounts — no firmware flashing<br>
+<sub>Grok CLI budget: experimental. My clock cost about $5 on sale; prices and shipping vary. Needs a computer that stays on (the host).</sub></p>
<p align="center">
<a href="https://token-tv.vercel.app"><img alt="Live demo" src="https://img.shields.io/badge/%E2%96%B6%20Live%20demo-token--tv.vercel.app-22d3ee?style=for-the-badge"></a>
@@ -9,23 +10,32 @@ Claude · Codex · Grok — multiple accounts — no firmware flashing</p>
<a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-9aa6b6?style=for-the-badge"></a>
</p>
-<p align="center"><img src="docs/images/real-clock.jpg" alt="TokenTV on a real $5 clock: Digital, Pixel Retro and Sci-Fi HUD faces"></p>
+<p align="center"><img src="docs/images/real-clock.jpg" alt="TokenTV on a real tiny desk clock: Digital, Pixel Retro and Sci-Fi HUD faces"></p>
<p align="center"><img src="docs/images/space.gif" width="480" alt="Space face: the Claude, Codex and Grok bots drift in glass helmets, each with its usage"></p>
<p align="center"><a href="https://token-tv.vercel.app"><img src="docs/images/web-demo.png" alt="Web dashboard in four themes. Click to open the live demo"></a></p>
-<p align="center"><img src="docs/images/how-it-works.png" alt="Your CLI logins → TokenTV on your computer → a picture over Wi-Fi → the $5 clock"></p>
+<p align="center"><img src="docs/images/how-it-works.png" alt="Your CLI logins → TokenTV on your computer → a picture over Wi-Fi → the tiny desk clock"></p>
## Quick start
+Needs Python 3.10+ and the official CLI (`claude`, `codex` or `grok`) for each provider you use.
+
```bash
-git clone https://github.com/click6067-ship-it/token-tv && cd token-tv
-python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
-mkdir -p .runtime && cp config.example.json .runtime/config.json # add accounts + clock IP
-.venv/bin/python -m token_tv.live --config .runtime/config.json # → localhost:8787
+pipx install git+https://github.com/click6067-ship-it/token-tv # or: pip install --user git+...
+token-tv demo # every clock face with sample data, no login
+token-tv setup # asks for emails (up to 3 per provider) and the clock IP
+token-tv doctor --live # asks each provider now; says what is missing and the fix
+token-tv run # dashboard at http://127.0.0.1:8787, drives the clock
```
+`uvx --from git+https://github.com/click6067-ship-it/token-tv token-tv demo` runs it without installing.
+TokenTV is not on PyPI yet, so plain `uvx token-tv` does not work. From a clone, `pip install .`
+gives the same `token-tv` command.
+
+<p align="center"><img src="docs/images/usage-examples.png" alt="Digital face at low, busy and near-limit usage (sample data)"></p>
+
<details>
<summary><b>All six clock faces</b></summary>
@@ -37,6 +47,17 @@ Pick one under **Clock display** in the dashboard, then press **Apply to clock**
GIF that the stock photo album plays; it is re-sent only when a number changes or every 30 minutes.
</details>
+## Make it yours
+
+**Start with a working face. Fork it, change it, show us yours.** A face is one Python function
+that draws 240×240 pixels; [docs/clock-faces.md](docs/clock-faces.md) walks through it with sample
+data, no clock or login needed. Your face runs from your own fork right away and shows up in the
+dashboard's **Themes** list as *Local*.
+
+Want others to use it? Open a pull request with the *New clock face* template. Shared faces appear in
+**Themes** for everyone on the next release, sorted by **Popular** (👍 on each theme's GitHub issue)
+or **New**. Likes are counted by hand before releases, so the list says when they were counted.
+
<details>
<summary><b>Hardware</b></summary>
@@ -46,6 +67,7 @@ GIF that the stock photo album plays; it is re-sent only when a number changes o
The stock photo API (`/theme/list`, `/photo/list`, `/photo/upload`) is verified on the author's
clock. Clones with other firmware are untested.
+See [docs/hardware-compatibility.md](docs/hardware-compatibility.md) for what is verified and how to check your clock.
</details>
<details>
@@ -66,28 +88,44 @@ refresh an expired login through the CLI, which sends one tiny prompt.
<details>
<summary><b>Accounts, clock and restore</b></summary>
-- `python3 -m token_tv.connect --config .runtime/config.json` logs each account in with its
- official CLI and keeps every account in its own CLI home.
+- `setup` lets account A reuse the login you already have (`~/.claude`, `~/.codex`, `~/.grok`)
+ and gives accounts B and C their own login folder under `~/.config/token-tv/homes/`.
+ Non-interactive: repeat the flag, e.g. `token-tv setup --yes --codex-email [email protected] --codex-email [email protected]`;
+ add `--isolate` to give account A its own folder too.
+- `token-tv connect --account codex_b` logs a separate account in with its official CLI. It
+ will not log in again over your everyday `~/.claude` / `~/.codex` login unless you type REPLACE.
+- `token-tv doctor` only checks that login files exist. `doctor --live` runs the same check
+ as the dashboard: it asks each provider for usage, may let the CLI refresh an expired login,
+ and prints only a status per account, never a token.
+- The config lives at `~/.config/token-tv/config.json`. `setup` never overwrites one, and
+ every command takes `--config` for another path.
- The config holds aliases, emails and CLI home paths only. Never put passwords, API keys or
tokens in it.
- Add `"device_url": "http://<clock-ip>"` to drive the clock.
- To give the clock back its original photo and theme, stop TokenTV and run
- `python3 -m token_tv.live --config .runtime/config.json --restore-display`.
+ `token-tv run --restore-display`.
+- **macOS (untested on a real Mac):** Claude Code keeps its login in the Keychain, so TokenTV
+ reads it there read-only with `security` when the CLI home has no `.credentials.json`.
+ The login is still checked against the configured email. Codex and Grok read files as on Linux.
</details>
<details>
<summary><b>Status and contributing</b></summary>
-Early and built for one desk: setup is a JSON file plus CLI logins, it is tested on Linux with
+Early and built for one desk: setup is `token-tv setup` plus CLI logins, it is tested on Linux with
one clock, and it supports Claude, Codex and Grok. A new provider is one payload function in
-`token_tv/sources.py`. Issues and pull requests for providers, clock models and faces are welcome.
+`token_tv/sources.py`. Issues and pull requests for providers, clock models and faces are welcome;
+see [CONTRIBUTING.md](CONTRIBUTING.md) and [making a clock face](docs/clock-faces.md).
</details>
<details>
<summary><b>Development</b></summary>
```bash
+pip install -e .
python3 -B -m unittest discover -s tests -v
+python3 scripts/render_usage_examples.py # docs/images/usage-examples.png
+python3 scripts/render_clock_faces.py # docs/images/clock-faces.png
python3 scripts/build_demo.py --out site # the static live demo
```
diff --git a/docs/clock-faces.md b/docs/clock-faces.md
new file mode 100644
index 0000000..a8b1287
--- /dev/null
+++ b/docs/clock-faces.md
@@ -0,0 +1,96 @@
+# Making a clock face
+
+A clock face is one Python function that turns a usage snapshot into a 240×240 picture.
+The clock only ever receives that picture.
+
+## 1. Try a face without touching the code
+
+Save this as `my_face.py` in the repository root and run `python3 my_face.py`.
+It draws one line per provider with the same helpers the built-in faces use, from sample data.
+
+```python
+"""A tiny clock face: one line per provider. Run: python3 my_face.py"""
+import time
+
+from token_tv.display import account_label, overview_rows
+from token_tv.sample import D, H, snapshot
+from token_tv.themes import Canvas, band, face, gauge, number_text, reading
+
+
+def render_mono(data):
+ cv = Canvas('#000000')
+ for index, row in enumerate(overview_rows(data)):
+ y = 8 + index * 78
+ used, period, old, reset = reading(row) # used is None when there is no reading
+ cv.text((10, y), account_label(row), face('vt323.woff2', 20), '#c8c8c8')
+ cv.text((10, y + 18), number_text(used), face('vt323.woff2', 40), '#ffffff') # a dash, never a fake 0
+ cv.text((230, y + 30), ('OLD ' if old else '') + reset, face('vt323.woff2', 20),
+ '#ff5d8f' if old else '#c8c8c8', anchor='ra')
+ gauge(cv, (10, y + 60, 230, y + 66), used, band('digital', used or 0), stale=old)
+ return cv.finish()
+
+
+if __name__ == '__main__':
+ data = snapshot(time.time(), [
+ ('claude_a', 'CLAUDE A', 'claude', [('5H', 72, 2 * H)]),
+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 15, 4 * D)]),
+ ('grok_a', 'GROK A', 'grok', []), # unknown: no window was reported
+ ])
+ data['accounts']['codex_a']['status'] = 'stale' # an old reading must look old
+ render_mono(data).save('my-face.png')
+ print('wrote my-face.png')
+```
+
+Open `my-face.png`. Judge it at its real size too: the clock is 240 pixels wide and about
+3 cm across, so text under about 9 px is hard to read.
+
+## 2. Add it to TokenTV
+
+1. Move the function into `token_tv/themes.py` and add it to `RENDERERS`.
+2. Add its name to `STYLES` in `token_tv/display.py`. The dashboard's **Clock display** list
+ reads `STYLES`, so the new face appears there without other changes.
+3. Run `token-tv demo` (or `python3 -m token_tv demo`) and check `token-tv-demo/demo-<name>.jpg`.
+4. Run `python3 -B -m unittest discover -s tests`.
+5. Optionally refresh the README sheet with `python3 scripts/render_clock_faces.py`.
+
+## 3. Use it from your own fork — no approval needed
+
+```bash
+git clone https://github.com/<you>/token-tv && cd token-tv
+python3 -m venv .venv && .venv/bin/pip install -e .
+.venv/bin/token-tv demo # your face from sample data; no config, login or clock needed
+```
+
+To show it on a real clock you need the normal setup first: a config (`token-tv setup`, or reuse
+the one you already have with `--config`), logged-in accounts (`token-tv connect`, then
+`token-tv doctor --live`) and `device_url` set to your clock. Then:
+
+```bash
+.venv/bin/token-tv run # dashboard → Clock display → Themes
+```
+
+Your face is listed under **Themes** as **Local**. Press **Preview**, then the usual
+**Apply to clock**. It works without any pull request; nothing is downloaded from anyone else.
+Because the install is editable, later edits to your renderer show up after restarting `token-tv run`.
+
+## 4. Share it (optional)
+
+Open a pull request with the *New clock face* template: id, name, author, license, a 240×240 preview
+rendered from sample data. After review the maintainer adds it to
+`token_tv/assets/theme-catalog.json` (with `added_at`, `min_version` and a `theme` issue for likes)
+in the next release. People with that release see it in **Themes**, sorted by **Popular** (👍 on the
+theme issue, refreshed by hand before releases) or **New**. Older installs show "update TokenTV"
+instead of downloading anything.
+
+## Rules every face keeps
+
+- **Sample data only.** Build previews with `token_tv.sample.snapshot`. Never paste real
+ account names, emails or usage into issues, pull requests or images.
+- **Unknown is not zero.** When `used` is `None`, draw a dash and an empty gauge (`gauge`
+ does this for you). Never show `0%` for a missing reading.
+- **Old is visibly old.** When `reading()` returns `old=True`, mark it (the built-in faces
+ write `OLD` and hatch the gauge with `stale=True`).
+- **Live text, not pictures of text.** Numbers and times must come from the snapshot.
+- **One picture, 240×240, JPEG.** `render_page` saves the image; animated faces return GIF
+ bytes like `token_tv/space.py`.
+- Fonts must be in `token_tv/web/` with their license file next to them.
diff --git a/docs/hardware-compatibility.md b/docs/hardware-compatibility.md
new file mode 100644
index 0000000..3f7a384
--- /dev/null
+++ b/docs/hardware-compatibility.md
@@ -0,0 +1,35 @@
+# Hardware compatibility
+
+Only what has been checked on a real clock is listed as verified. Everything else is unknown,
+not "probably fine".
+
+## Verified
+
+| Clock | Firmware web UI | What TokenTV uses | Checked |
+| --- | --- | --- | --- |
+| The author's 240×240 GeekMagic SmallTV-style Wi-Fi clock (bought on an AliExpress sale for about ₩6,000 / $5) | Stock firmware with the **SD_PRO** web UI and a photo album | `/theme/list`, `/photo/list`, `/photo/upload`, photo theme id `2` | One unit, Linux host |
+
+TokenTV never flashes firmware and never deletes your photos. It uploads one picture, switches the
+clock to its photo theme, and `token-tv run --restore-display` puts the original theme back.
+
+## Not verified
+
+- Other GeekMagic models, SmallTV Pro, and clones that look the same. A similar case is not evidence
+ of the same firmware.
+- Firmware without the photo album page or with different photo API paths.
+- macOS and Windows hosts.
+
+## Check your own clock before connecting accounts
+
+1. Open the clock's address (shown on its screen) in a browser on the same network.
+2. Look for a photo album / photo upload page. Without one, TokenTV cannot draw on it.
+3. `token-tv demo` needs no clock and no login. `token-tv setup` then asks for the clock address
+ (`http://<ip>`) and checks its form before writing anything.
+
+Tried another model? Please open a **Hardware compatibility** issue with the model, the firmware
+web UI name and the result. Leave out Wi-Fi names, passwords and public IP addresses.
+
+## What you need besides the clock
+
+A computer that stays on in the same network (Python 3.10+). The clock only shows the picture;
+the computer reads usage and draws it.
diff --git a/docs/images/clock-faces.png b/docs/images/clock-faces.png
index f9c6545..76fdc8f 100644
Binary files a/docs/images/clock-faces.png and b/docs/images/clock-faces.png differ
diff --git a/docs/images/usage-examples.png b/docs/images/usage-examples.png
new file mode 100644
index 0000000..9f79517
Binary files /dev/null and b/docs/images/usage-examples.png differ
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..72400d9
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,25 @@
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "token-tv"
+version = "0.1.0"
+description = "Your AI usage limits on a $5 desk clock: Claude, Codex and Grok on a 240x240 Wi-Fi clock"
+readme = "README.md"
+license = "MIT"
+requires-python = ">=3.10"
+dependencies = ["Pillow>=10.2,<13"]
+
+[project.urls]
+Homepage = "https://github.com/click6067-ship-it/token-tv"
+Demo = "https://token-tv.vercel.app"
+
+[project.scripts]
+token-tv = "token_tv.cli:main"
+
+[tool.setuptools]
+packages = ["token_tv", "token_tv.providers"]
+
+[tool.setuptools.package-data]
+token_tv = ["web/*", "assets/*.png", "assets/*.json"]
diff --git a/scripts/build_demo.py b/scripts/build_demo.py
index d65d2a8..f013adf 100644
--- a/scripts/build_demo.py
+++ b/scripts/build_demo.py
@@ -14,41 +14,19 @@ ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from token_tv.display import STYLES, render_page # noqa: E402
from token_tv.web_assets import ASSETS, WEB # noqa: E402
+from token_tv.sample import snapshot # noqa: E402
+from token_tv.catalog import payload as theme_payload # noqa: E402
REPO = 'https://github.com/click6067-ship-it/token-tv'
-H, D = 3600, 86400
-# key, alias, provider, [(window, used %, seconds until reset)]
-SAMPLE = [
- ('claude_a', 'CLAUDE A', 'claude', [('WEEK', 86, 3 * D), ('5H', 41, 2 * H)]),
- ('claude_b', 'CLAUDE B', 'claude', [('5H', 52, 3 * H + 41 * 60), ('WEEK', 30, 5 * D)]),
- ('claude_c', 'CLAUDE C', 'claude', [('5H', 97, 38 * 60), ('WEEK', 64, 4 * D)]),
- ('codex_a', 'CODEX A', 'codex', [('5H', 34, 2 * H + 12 * 60)]),
- ('codex_b', 'CODEX B', 'codex', [('WEEK', 91, D + 4 * H)]),
- ('grok_a', 'GROK A', 'grok', [('BUDGET', 61, 6 * D + 2 * H)]),
- ('grok_b', 'GROK B', 'grok', [('BUDGET', 18, 12 * D + 3 * H)]),
-]
-META = '''<meta name="description" content="Your AI usage limits on a $5 desk clock. Claude, Codex and Grok, several accounts, no firmware flashing.">
+META = '''<meta name="description" content="Your AI limits, on a tiny desk clock. Claude and Codex usage, several accounts, no firmware flashing. Grok CLI budget is experimental.">
<meta property="og:title" content="TokenTV · Live demo">
-<meta property="og:description" content="Your AI usage limits on a $5 desk clock. Claude · Codex · Grok · multiple accounts · no flashing.">
+<meta property="og:description" content="Your AI limits, on a tiny desk clock. Claude and Codex · multiple accounts · no flashing.">
<meta property="og:image" content="{site}/og.png">
<meta property="og:url" content="{site}/">
<meta name="twitter:card" content="summary_large_image">'''
BAR = f'<div class="demo-bar">Live demo with sample data<a href="{REPO}">Get TokenTV on GitHub ★</a></div>'
-def snapshot(now=None):
- accounts = {}
- for key, alias, provider, windows in SAMPLE:
- row = {'key': key, 'alias': alias, 'provider': provider, 'status': 'ok', 'identity_verified': True,
- 'windows': [{'label': label, 'used_percent': used, 'resets_in': reset} for label, used, reset in windows]}
- if now is not None:
- row['fetched_at'] = row['last_success_at'] = now
- for window in row['windows']:
- window['resets_at'] = now + window['resets_in']
- accounts[key] = row
- return {'schema': 1, 'updated_at': now or 0, 'accounts': accounts}
-
-
def build(out, site):
out.mkdir(parents=True, exist_ok=True)
for child in out.iterdir(): # keep the host's project link (.vercel)
@@ -78,6 +56,7 @@ def build(out, site):
paths[style] = f'/frames/{name}'
display = {'style': 'digital', 'applied_style': 'digital', 'status': 'preview_only', 'styles': list(STYLES), 'frames': paths}
(out / 'demo-display.json').write_text(json.dumps(display))
+ (out / 'demo-themes.json').write_text(json.dumps(theme_payload()))
shutil.copy2(ROOT / 'docs' / 'images' / 'social-preview.png', out / 'og.png')
return sorted(str(p.relative_to(out)) for p in out.rglob('*') if p.is_file() and '.vercel' not in p.parts)
diff --git a/scripts/render_clock_faces.py b/scripts/render_clock_faces.py
new file mode 100644
index 0000000..4e306c9
--- /dev/null
+++ b/scripts/render_clock_faces.py
@@ -0,0 +1,53 @@
+"""Render docs/images/clock-faces.png: all six clock faces from the real renderers.
+
+Each face gets its own synthetic accounts so the sheet shows a spread of usage:
+ python3 scripts/render_clock_faces.py
+"""
+import io
+import sys
+import time
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+from token_tv.display import render_page # noqa: E402
+from token_tv.sample import D, H, snapshot # noqa: E402
+
+
+def rows(claude, codex, grok):
+ return [(f'{p}_{k.lower()}', f'{p.upper()} {k}', p, [(w, used, reset)])
+ for p, (k, w, used, reset) in zip(('claude', 'codex', 'grok'), (claude, codex, grok))]
+
+
+FACES = [
+ ('digital', 'Digital', rows(('A', 'WEEK', 86, 3 * D), ('A', '5H', 34, 2 * H + 12 * 60), ('B', 'BUDGET', 94, D + H))),
+ ('neon', 'Neon', rows(('B', '5H', 52, 3 * H + 41 * 60), ('B', 'WEEK', 91, D + 4 * H), ('A', 'BUDGET', 18, 12 * D + 3 * H))),
+ ('retro', 'Pixel Retro', rows(('C', 'WEEK', 73, 2 * D + 6 * H), ('A', '5H', 8, 4 * H + 51 * 60), ('B', 'BUDGET', 61, 6 * D + 2 * H))),
+ ('hud', 'Sci-Fi HUD', rows(('A', '5H', 97, 38 * 60), ('B', 'WEEK', 45, 5 * D + 11 * H), ('A', 'BUDGET', 82, 2 * D + 9 * H))),
+ ('pixel', 'Pixel', rows(('B', 'WEEK', 27, 6 * D + H), ('A', '5H', 66, H + 5 * 60), ('B', 'BUDGET', 88, 3 * D + 14 * H))),
+ ('space', 'Space (animated)', rows(('A', 'WEEK', 86, 3 * D), ('A', '5H', 34, 2 * H), ('B', 'BUDGET', 61, 6 * D))),
+]
+TILE, GAP, MARGIN, CAPTION = 480, 36, 38, 62
+
+
+def main():
+ out = ROOT / 'docs' / 'images' / 'clock-faces.png'
+ width = 2 * MARGIN + 3 * TILE + 2 * GAP
+ sheet = Image.new('RGB', (width, 2 * MARGIN + 2 * (TILE + CAPTION)), '#0b0e12')
+ draw = ImageDraw.Draw(sheet)
+ font = ImageFont.truetype(str(ROOT / 'token_tv' / 'web' / 'manrope.ttf'), 22)
+ now = time.time()
+ for index, (style, title, sample) in enumerate(FACES):
+ frame = Image.open(io.BytesIO(render_page(snapshot(now, sample), style=style))).convert('RGB')
+ x = MARGIN + index % 3 * (TILE + GAP)
+ y = MARGIN + index // 3 * (TILE + CAPTION)
+ sheet.paste(frame.resize((TILE, TILE), Image.Resampling.NEAREST), (x, y))
+ draw.text((x + TILE / 2, y + TILE + 30), title, font=font, fill='#c9d1d9', anchor='mm')
+ sheet.save(out, optimize=True)
+ print(out)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/render_usage_examples.py b/scripts/render_usage_examples.py
new file mode 100644
index 0000000..9015a7a
--- /dev/null
+++ b/scripts/render_usage_examples.py
@@ -0,0 +1,52 @@
+"""Render docs/images/usage-examples.png: the Digital face at several sample usage levels.
+
+Every frame comes from the real renderer with synthetic accounts (no real usage):
+ python3 scripts/render_usage_examples.py
+"""
+import io
+import sys
+import time
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+from token_tv.display import render_page # noqa: E402
+from token_tv.sample import D, H, snapshot # noqa: E402
+
+SCENES = [
+ ('Fresh morning', [('claude_a', 'CLAUDE A', 'claude', [('5H', 8, 4 * H + 50 * 60)]),
+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 21, 5 * D)]),
+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 12, 20 * D)])]),
+ ('Busy afternoon', [('claude_a', 'CLAUDE A', 'claude', [('5H', 63, 2 * H + 5 * 60)]),
+ ('codex_a', 'CODEX A', 'codex', [('5H', 47, 3 * H)]),
+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 55, 9 * D)])]),
+ ('Near the limit', [('claude_a', 'CLAUDE A', 'claude', [('5H', 97, 18 * 60)]),
+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 88, D + 6 * H)]),
+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 92, 2 * D)])]),
+]
+SCALE, PAD, LABEL = 2, 24, 44
+
+
+def main():
+ out = ROOT / 'docs' / 'images' / 'usage-examples.png'
+ side = 240 * SCALE
+ sheet = Image.new('RGB', (PAD + len(SCENES) * (side + PAD), LABEL + side + PAD + 30), '#0b0e12')
+ draw = ImageDraw.Draw(sheet)
+ font = ImageFont.truetype(str(ROOT / 'token_tv' / 'web' / 'manrope.ttf'), 22)
+ small = ImageFont.truetype(str(ROOT / 'token_tv' / 'web' / 'manrope.ttf'), 16)
+ now = time.time()
+ for index, (title, sample) in enumerate(SCENES):
+ frame = Image.open(io.BytesIO(render_page(snapshot(now, sample), style='digital'))).convert('RGB')
+ x = PAD + index * (side + PAD)
+ sheet.paste(frame.resize((side, side), Image.Resampling.NEAREST), (x, LABEL))
+ draw.text((x, 12), title, font=font, fill='#d9dde1')
+ draw.text((PAD, LABEL + side + 10), 'DEMO · sample data rendered by TokenTV’s own Digital face (240×240, shown 2×)',
+ font=small, fill='#8a949e')
+ sheet.save(out, optimize=True)
+ print(out)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/test_web_browser.cjs b/scripts/test_web_browser.cjs
index 9a71c68..8d1dab7 100644
--- a/scripts/test_web_browser.cjs
+++ b/scripts/test_web_browser.cjs
@@ -25,4 +25,24 @@ async function clock_independence_checks(page){
await page.route('**/display/style',r=>{assert.deepEqual(r.request().postDataJSON(),{style:'neon'});return r.fulfill({json:{style:'neon',applied_style:'neon',status:'ok',styles:original.styles}})});
await page.locator('#apply').click();await page.waitForFunction(()=>document.querySelector('#display-state').textContent==='Image sent · Neon');assert.equal((await(await page.request.get(url+'/display')).json()).style,original.style);await page.locator('#close-clock').click();assert.equal(await page.locator('#clock-toggle').getAttribute('aria-expanded'),'false');
}
-(async()=>{const browser=await chromium.launch({headless:true,executablePath:process.env.CHROMIUM_EXECUTABLE});try{const page=await browser.newPage({viewport:{width:1440,height:1100}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(url);await page.waitForSelector('[data-account]');await theme_and_responsive_checks(page);await account_and_state_checks(page);await clock_independence_checks(page);assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/result.json`,JSON.stringify({themes,widths:[320,375,414,768,1440],accounts:7,clockUnchanged:true,pageErrors:errors,passed:true},null,2));console.log('PASS: four themes, five widths, seven accounts, stale/missing/offline states, clock independence and apply.');}finally{await browser.close()}})().catch(e=>{console.error(e);process.exitCode=1});
+async function themes_checks(page){
+ const t=(id,added,likes,state,extra={})=>Object.assign({id,name:id,author:'tester',local:false,installed:true,needs_update:false,min_version:'0.1.0',added_at:added,source_url:'https://github.com/x/y',license:'MIT',preview_url:null,likes,likes_state:state,likes_counted_at:likes===null?null:'2026-10-03T12:00:00Z',like_url:likes===null?null:'https://github.com/x/y/issues/1'},extra);
+ const fixture={last_attempt_at:'2026-10-03T12:00:00Z',version:'0.1.0',themes:[t('digital','2026-10-01T00:00:00Z',8,'counted'),t('neon','2026-10-02T00:00:00Z',0,'counted'),t('retro','2026-10-03T00:00:00Z',null,'unavailable'),t('space',null,null,'local',{local:true,author:null,added_at:null,source_url:null}),t('vapor','2026-10-04T00:00:00Z',null,'not_open',{installed:false,needs_update:true,min_version:'0.3.0'})]};
+ await page.route('**/themes',r=>r.fulfill({json:fixture}));await page.reload();await page.waitForSelector('[data-account]');
+ let posts=0;page.on('request',r=>{if(r.method()==='POST')posts++});
+ await page.locator('#clock-toggle').click();await page.waitForSelector('.theme-card');
+ assert.deepEqual(await page.locator('.theme-card').evaluateAll(n=>n.map(x=>x.dataset.id)),['digital','neon','vapor','retro','space']);
+ assert.match(await page.locator('[data-id=neon] .theme-likes').innerText(),/👍 0/);assert.match(await page.locator('[data-id=retro] .theme-likes').innerText(),/unavailable/);assert.match(await page.locator('[data-id=space]').innerText(),/Local/);
+ assert.match(await page.locator('[data-id=vapor]').innerText(),/Needs v0.3.0/);assert.equal(await page.locator('[data-id=vapor] button').count(),0);
+ await page.locator('[data-sort=new]').click();assert.deepEqual(await page.locator('.theme-card').evaluateAll(n=>n.map(x=>x.dataset.id)),['vapor','retro','neon','digital','space']);
+ await page.locator('[data-id=neon] button').click();assert.equal(await page.locator('#clock-style').inputValue(),'neon');assert.equal(posts,0);
+ await page.unroute('**/themes');await page.locator('#close-clock').click();
+}
+async function demo_checks(browser,demo){
+ const page=await browser.newPage({viewport:{width:375,height:900}});let posts=0;page.on('request',r=>{if(r.method()==='POST')posts++});
+ await page.goto(demo);await page.locator('#clock-toggle').click();await page.waitForSelector('.theme-card');await page.locator('.theme-card button').first().click();
+ await page.waitForFunction(()=>{const i=document.querySelector('#frame');return i.complete&&i.naturalWidth===240});
+ assert.equal(await page.locator('#apply').isVisible(),false);assert.ok(await page.locator('.theme-actions a',{hasText:'Get'}).count()>0);assert.equal(posts,0);
+ assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:`${out}/demo-themes-375.png`,fullPage:true});await page.close();
+}
+(async()=>{const browser=await chromium.launch({headless:true,executablePath:process.env.CHROMIUM_EXECUTABLE});try{const page=await browser.newPage({viewport:{width:1440,height:1100}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(url);await page.waitForSelector('[data-account]');await theme_and_responsive_checks(page);await account_and_state_checks(page);await clock_independence_checks(page);await themes_checks(page);if(process.env.TOKEN_TV_DEMO_URL)await demo_checks(browser,process.env.TOKEN_TV_DEMO_URL);assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/result.json`,JSON.stringify({themes,widths:[320,375,414,768,1440],accounts:7,clockUnchanged:true,pageErrors:errors,passed:true},null,2));console.log('PASS: four themes, five widths, seven accounts, stale/missing/offline states, clock independence and apply.');}finally{await browser.close()}})().catch(e=>{console.error(e);process.exitCode=1});
diff --git a/scripts/update_theme_votes.py b/scripts/update_theme_votes.py
new file mode 100644
index 0000000..43477fc
--- /dev/null
+++ b/scripts/update_theme_votes.py
@@ -0,0 +1,71 @@
+"""Refresh token_tv/assets/theme-votes.json by hand before a release.
+
+Counts only the 👍 on each theme issue's body (not comments, not other reactions), through the
+anonymous public GitHub REST API. A failed lookup keeps the last count and marks it stale; a theme
+that was never counted stays unknown. Nothing is posted and no token is used.
+
+ python3 scripts/update_theme_votes.py # write the snapshot
+ python3 scripts/update_theme_votes.py --dry-run # print it
+"""
+import argparse
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from urllib.request import Request, urlopen
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+from token_tv.catalog import CATALOG_PATH, REPO, VOTES_PATH, load_catalog, load_votes # noqa: E402
+
+
+def thumbs_up(payload):
+ reactions = payload.get('reactions') if isinstance(payload, dict) else None
+ count = reactions.get('+1') if isinstance(reactions, dict) else None
+ if isinstance(count, bool) or not isinstance(count, int) or count < 0:
+ raise ValueError('No 👍 count in the response')
+ return count
+
+
+def github_fetch(issue, repo=REPO):
+ request = Request(f'https://api.github.com/repos/{repo}/issues/{int(issue)}',
+ headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'token-tv-vote-refresh'})
+ with urlopen(request, timeout=15) as response:
+ return thumbs_up(json.load(response))
+
+
+def refresh(catalog, votes, fetch, now):
+ """Fresh counts get `now`; a failed issue keeps its old count *and* its old time, marked stale."""
+ counts = {k: dict(v) for k, v in votes.get('counts', {}).items()}
+ for theme in catalog['themes']:
+ issue = theme['like_issue']
+ if not issue:
+ continue
+ try:
+ counts[str(issue)] = {'count': fetch(issue), 'status': 'fresh', 'fetched_at': now}
+ except (OSError, ValueError) as error:
+ print(f'{theme["id"]}: issue #{issue} not counted ({type(error).__name__}); keeping the last value',
+ file=sys.stderr)
+ if str(issue) in counts:
+ counts[str(issue)]['status'] = 'stale'
+ return {'schema_version': 1, 'last_attempt_at': now, 'counts': counts}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument('--dry-run', action='store_true')
+ args = parser.parse_args()
+ now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
+ out = refresh(load_catalog(CATALOG_PATH), load_votes(VOTES_PATH), github_fetch, now)
+ text = json.dumps(out, indent=2) + '\n'
+ if args.dry_run:
+ print(text, end='')
+ return
+ temp = VOTES_PATH.with_suffix('.tmp')
+ temp.write_text(text)
+ temp.replace(VOTES_PATH)
+ print(f'Wrote {VOTES_PATH} ({sum(v["status"] == "fresh" for v in out["counts"].values())} counted now, attempt at {out["last_attempt_at"]})')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/test_catalog.py b/tests/test_catalog.py
new file mode 100644
index 0000000..565805a
--- /dev/null
+++ b/tests/test_catalog.py
@@ -0,0 +1,194 @@
+import importlib.util
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+from token_tv import __version__, catalog
+from token_tv.display import STYLES
+
+ROOT = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location('update_theme_votes', ROOT / 'scripts' / 'update_theme_votes.py')
+updater = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(updater)
+
+
+def entry(id, added, issue=None, min_version='0.1.0', **extra):
+ return dict({'id': id, 'name': id.title(), 'author': 'tester', 'added_at': added, 'min_version': min_version,
+ 'source_url': 'https://github.com/example/token-tv', 'license': 'MIT', 'like_issue': issue}, **extra)
+
+
+CATALOG = {'schema_version': 1, 'themes': [
+ entry('digital', '2026-10-01T00:00:00Z', issue=11),
+ entry('neon', '2026-10-02T00:00:00Z', issue=12),
+ entry('retro', '2026-10-03T00:00:00Z', issue=13),
+ entry('hud', '2026-10-02T00:00:00Z', issue=14),
+ entry('pixel', '2026-09-01T00:00:00Z'),
+]}
+OLD = '2026-10-01T09:00:00Z'
+VOTES = {'schema_version': 1, 'last_attempt_at': '2026-10-03T12:00:00Z', 'counts': {
+ '11': {'count': 8, 'status': 'fresh', 'fetched_at': '2026-10-03T12:00:00Z'},
+ '12': {'count': 0, 'status': 'fresh', 'fetched_at': '2026-10-03T12:00:00Z'},
+ '14': {'count': 8, 'status': 'stale', 'fetched_at': OLD},
+}}
+
+
+def listed(installed=('pixel', 'digital', 'neon', 'retro', 'hud', 'space'), cat=CATALOG, votes=VOTES, version='0.1.0'):
+ return catalog.theme_list(installed=installed, catalog=cat, votes=votes, version=version)
+
+
+class CatalogTest(unittest.TestCase):
+ def ids(self, data, mode):
+ return [t['id'] for t in catalog.sort_themes(data['themes'], mode)]
+
+ def test_popular_and_new_order(self):
+ data = listed()
+ # counted (8, 8 stale, 0) first; then never-counted and Local, newest first.
+ self.assertEqual(self.ids(data, 'popular'), ['hud', 'digital', 'neon', 'retro', 'pixel', 'space'])
+ self.assertEqual(self.ids(data, 'new'), ['retro', 'hud', 'neon', 'digital', 'pixel', 'space'])
+
+ def test_ties_break_by_newest_then_id(self):
+ cat = {'schema_version': 1, 'themes': [entry('neon', '2026-10-02T00:00:00Z', 1), entry('hud', '2026-10-02T00:00:00Z', 2)]}
+ stamp = '2026-10-03T00:00:00Z'
+ votes = {'schema_version': 1, 'last_attempt_at': stamp, 'counts': {
+ '1': {'count': 3, 'status': 'fresh', 'fetched_at': stamp}, '2': {'count': 3, 'status': 'fresh', 'fetched_at': stamp}}}
+ data = listed(installed=('neon', 'hud'), cat=cat, votes=votes)
+ self.assertEqual(self.ids(data, 'popular'), ['hud', 'neon'])
+ self.assertEqual(self.ids(data, 'new'), ['hud', 'neon'])
+
+ def test_unknown_likes_are_not_zero(self):
+ themes = {t['id']: t for t in listed()['themes']}
+ self.assertEqual((themes['retro']['likes'], themes['retro']['likes_state']), (None, 'unavailable'))
+ self.assertEqual((themes['pixel']['likes'], themes['pixel']['likes_state']), (None, 'not_open'))
+ self.assertIsNone(themes['pixel']['like_url'])
+ self.assertEqual((themes['hud']['likes'], themes['hud']['likes_state']), (8, 'stale'))
+ self.assertEqual(themes['hud']['likes_counted_at'], OLD) # an old count keeps its own time
+
+ def test_zero_likes_stay_zero(self):
+ neon = next(t for t in listed()['themes'] if t['id'] == 'neon')
+ self.assertEqual((neon['likes'], neon['likes_state']), (0, 'counted'))
+ self.assertTrue(neon['like_url'].endswith('/issues/12'))
+
+ def test_blank_snapshot_is_still_useful(self):
+ data = listed(votes=catalog.BLANK_VOTES)
+ self.assertIsNone(data['last_attempt_at'])
+ self.assertEqual(len(data['themes']), 6)
+ self.assertTrue(all(t['likes'] is None for t in data['themes']))
+ self.assertEqual(self.ids(data, 'popular'), self.ids(data, 'new'))
+
+ def test_local_face_without_catalog_entry_is_listed_as_local(self):
+ space = next(t for t in listed()['themes'] if t['id'] == 'space')
+ self.assertTrue(space['local'] and space['installed'])
+ self.assertEqual(space['likes_state'], 'local')
+ self.assertFalse(space['needs_update'])
+
+ def test_newer_theme_needs_update_and_is_not_installed(self):
+ cat = {'schema_version': 1, 'themes': CATALOG['themes'] + [entry('vapor', '2026-10-04T00:00:00Z', min_version='0.3.0')]}
+ vapor = next(t for t in listed(cat=cat)['themes'] if t['id'] == 'vapor')
+ self.assertEqual((vapor['installed'], vapor['needs_update']), (False, True))
+ self.assertEqual(vapor['min_version'], '0.3.0')
+
+ def test_version_compare(self):
+ self.assertTrue(catalog.version_at_least('0.10.0', '0.9.1'))
+ self.assertFalse(catalog.version_at_least('0.1.0', '0.2.0'))
+ self.assertTrue(catalog.version_at_least('1.0', '1.0.0'))
+
+ def test_bad_catalog_is_rejected(self):
+ for broken in ({'schema_version': 2, 'themes': []},
+ {'schema_version': 1, 'themes': [entry('digital', 'x'), entry('digital', 'x')]},
+ {'schema_version': 1, 'themes': [dict(entry('digital', '2026-10-01T00:00:00Z'), like_issue='12')]},
+ {'schema_version': 1, 'themes': [dict(entry('Bad Id', '2026-10-01T00:00:00Z'))]},
+ {'schema_version': 1, 'themes': [dict(entry('digital', '2026-10-01T00:00:00Z'), source_url='javascript:x')]}):
+ with self.assertRaises(ValueError):
+ catalog.validate_catalog(broken)
+
+ def test_corrupt_vote_file_means_unavailable_not_zero(self):
+ path = Path(tempfile.mkdtemp()) / 'votes.json'
+ path.write_text('{"counts": ')
+ votes = catalog.load_votes(path)
+ self.assertEqual(votes['counts'], {})
+ self.assertIsNone(votes['last_attempt_at'])
+
+ def test_bad_or_missing_count_times_are_unknown_not_new(self):
+ path = Path(tempfile.mkdtemp()) / 'votes.json'
+ path.write_text(json.dumps({'last_attempt_at': 'yesterday', 'counts': {
+ '11': {'count': 5, 'status': 'fresh', 'fetched_at': 'not a time'}, # unreadable -> unavailable
+ '12': {'count': 5, 'status': 'fresh'}, # fresh without time -> unavailable
+ '14': {'count': 7, 'status': 'stale'}}})) # old count, time unknown
+ votes = catalog.load_votes(path)
+ self.assertIsNone(votes['last_attempt_at'])
+ themes = {t['id']: t for t in listed(votes=votes)['themes']}
+ self.assertEqual([themes[i]['likes_state'] for i in ('digital', 'neon')], ['unavailable', 'unavailable'])
+ self.assertIsNone(themes['digital']['likes'])
+ self.assertEqual((themes['hud']['likes'], themes['hud']['likes_state'], themes['hud']['likes_counted_at']),
+ (7, 'stale', None))
+
+ def test_installed_face_needing_newer_version_cannot_be_picked_from_catalog(self):
+ cat = {'schema_version': 1, 'themes': [entry('neon', '2026-10-02T00:00:00Z', min_version='0.2.0')]}
+ neon = next(t for t in listed(installed=('neon', 'mine'), cat=cat)['themes'] if t['id'] == 'neon')
+ self.assertEqual((neon['installed'], neon['needs_update']), (True, True))
+ mine = next(t for t in listed(installed=('neon', 'mine'), cat=cat)['themes'] if t['id'] == 'mine')
+ self.assertEqual((mine['local'], mine['needs_update']), (True, False))
+
+ 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)
+ self.assertEqual({t['id']: t['like_issue'] for t in data['themes']},
+ {'pixel': 1, 'digital': 2, 'neon': 3, 'retro': 4, 'hud': 5, 'space': 6})
+ 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 dated
+
+ def test_broken_bundled_catalog_still_lists_installed_faces(self):
+ from unittest import mock
+ with mock.patch.object(catalog, 'CATALOG_PATH', Path(tempfile.mkdtemp()) / 'missing.json'):
+ data = catalog.payload()
+ self.assertTrue(data['catalog_error'])
+ self.assertEqual({t['id'] for t in data['themes'] if t['local']}, set(STYLES))
+
+ def test_package_version_matches_pyproject(self):
+ self.assertIn(f'version = "{__version__}"', (ROOT / 'pyproject.toml').read_text())
+
+
+class RefreshTest(unittest.TestCase):
+ def test_refresh_keeps_last_count_on_failure(self):
+ def fetch(issue):
+ if issue == 11:
+ return 9
+ raise OSError('timeout')
+ now = '2026-10-04T00:00:00Z'
+ out = updater.refresh(CATALOG, VOTES, fetch, now=now)
+ self.assertEqual(out['counts']['11'], {'count': 9, 'status': 'fresh', 'fetched_at': now})
+ # kept, marked stale, and still dated when it was really counted
+ self.assertEqual(out['counts']['12'], {'count': 0, 'status': 'stale', 'fetched_at': '2026-10-03T12:00:00Z'})
+ self.assertEqual(out['counts']['14']['fetched_at'], OLD)
+ self.assertNotIn('13', out['counts']) # never counted stays unknown, not 0
+ self.assertEqual(out['last_attempt_at'], now)
+ themes = {t['id']: t for t in listed(votes=out)['themes']}
+ self.assertEqual((themes['neon']['likes_state'], themes['neon']['likes_counted_at']), ('stale', '2026-10-03T12:00:00Z'))
+
+ def test_refresh_without_issue_skips_network(self):
+ calls = []
+ cat = {'schema_version': 1, 'themes': [entry('pixel', '2026-09-01T00:00:00Z')]}
+ out = updater.refresh(cat, catalog.BLANK_VOTES, lambda n: calls.append(n), now='2026-10-04T00:00:00Z')
+ self.assertEqual((calls, out['counts']), ([], {}))
+
+ def test_refresh_counts_issue_body_thumbs_only(self):
+ payload = {'reactions': {'+1': 4, 'heart': 9, 'total_count': 13}, 'comments': 7}
+ self.assertEqual(updater.thumbs_up(payload), 4)
+ for bad in ({}, {'reactions': {'+1': -1}}, {'reactions': {'+1': '4'}}, [], {'reactions': None}):
+ with self.assertRaises(ValueError):
+ updater.thumbs_up(bad)
+
+ def test_all_failures_keep_every_count_time(self):
+ def fail(issue):
+ raise ValueError('bad json')
+ out = updater.refresh(CATALOG, VOTES, fail, now='2026-10-04T00:00:00Z')
+ self.assertTrue(all(v['status'] == 'stale' for v in out['counts'].values()))
+ self.assertEqual({k: v['fetched_at'] for k, v in out['counts'].items()},
+ {k: v['fetched_at'] for k, v in VOTES['counts'].items()})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_cli.py b/tests/test_cli.py
new file mode 100644
index 0000000..8a0cbea
--- /dev/null
+++ b/tests/test_cli.py
@@ -0,0 +1,194 @@
+import contextlib
+import io
+import json
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from token_tv import cli, sources
+from token_tv.display import STYLES
+
+
+def run(*argv):
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = cli.main(list(argv))
+ return code, out.getvalue(), err.getvalue()
+
+
+class CliTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp())
+ self.config = self.tmp / 'config.json'
+
+ def test_setup_writes_metadata_only_and_never_overwrites(self):
+ code, out, _ = run('setup', '--config', str(self.config), '--yes',
+ '--claude-email', '[email protected]', '--device-url', 'http://10.0.0.9/')
+ self.assertEqual(code, 0)
+ data = json.loads(self.config.read_text())
+ self.assertEqual(data['device_url'], 'http://10.0.0.9')
+ self.assertEqual(data['accounts'][0], {'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude',
+ 'email': '[email protected]', 'source_home': '~/.claude'})
+ sources.load_config(self.config) # the daemon accepts what setup writes
+ before = self.config.read_text()
+ code, _, err = run('setup', '--config', str(self.config), '--yes', '--codex-email', '[email protected]')
+ self.assertEqual(code, 1)
+ self.assertIn('never overwrites', err)
+ self.assertEqual(self.config.read_text(), before)
+
+ def test_setup_without_accounts_fails_and_writes_nothing(self):
+ code, _, err = run('setup', '--config', str(self.config), '--yes')
+ self.assertEqual(code, 1)
+ self.assertFalse(self.config.exists())
+ self.assertIn('--claude-email', err)
+
+ def test_doctor_points_missing_logins_at_connect(self):
+ home = self.tmp / 'codex-home'
+ self.config.write_text(json.dumps({'accounts': [
+ {'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex', 'email': '[email protected]',
+ 'source_home': str(home)}]}))
+ with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/codex'):
+ code, out, _ = run('doctor', '--config', str(self.config))
+ self.assertEqual(code, 1)
+ self.assertIn('token-tv connect --config', out)
+ home.mkdir()
+ (home / 'auth.json').write_text('{}') # existence only; doctor never opens it
+ code, out, _ = run('doctor', '--config', str(self.config))
+ self.assertEqual(code, 0)
+ self.assertIn('not verified', out)
+ self.assertNotIn('Ready', out)
+ bad = {'status': 'identity_mismatch', 'identity_verified': False}
+ with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/codex'), \
+ mock.patch('token_tv.sources.fetch_account', return_value=bad):
+ code, out, _ = run('doctor', '--config', str(self.config), '--live')
+ self.assertEqual(code, 1)
+ self.assertIn('IDENTITY_MISMATCH', out)
+ good = {'status': 'ok', 'identity_verified': True}
+ with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/codex'), \
+ mock.patch('token_tv.sources.fetch_account', return_value=good):
+ code, out, _ = run('doctor', '--config', str(self.config), '--live')
+ self.assertEqual(code, 0)
+ self.assertIn('Ready', out)
+
+ def test_doctor_never_calls_an_unchecked_keychain_ready(self):
+ self.config.write_text(json.dumps({'accounts': [
+ {'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]',
+ 'source_home': str(self.tmp / 'empty')}]}))
+ with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/claude'), \
+ mock.patch.object(cli.sys, 'platform', 'darwin'):
+ code, out, _ = run('doctor', '--config', str(self.config))
+ self.assertEqual(code, 1)
+ self.assertIn('Keychain unchecked', out)
+
+ def test_broken_config_gets_a_sentence_not_a_traceback(self):
+ self.config.write_text('{"accounts": [')
+ for command in ('doctor', 'run'):
+ code, _, err = run(command, '--config', str(self.config))
+ self.assertEqual(code, 1)
+ self.assertIn('not a valid TokenTV config', err)
+
+ def test_setup_two_accounts_reuse_then_isolate(self):
+ code, out, _ = run('setup', '--config', str(self.config), '--yes',
+ '--codex-email', '[email protected]', '--codex-email', '[email protected]')
+ self.assertEqual(code, 0)
+ a, b = json.loads(self.config.read_text())['accounts']
+ self.assertEqual((a['key'], a['source_home']), ('codex_a', '~/.codex'))
+ self.assertEqual((b['key'], b['alias'], b['source_home']),
+ ('codex_b', 'CODEX B', str(self.tmp / 'homes' / 'codex_b')))
+ self.assertIn('separate login', out)
+ sources.load_config(self.config)
+
+ def test_setup_isolate_never_points_at_the_everyday_home(self):
+ run('setup', '--config', str(self.config), '--yes', '--isolate', '--claude-email', '[email protected]')
+ self.assertNotEqual(json.loads(self.config.read_text())['accounts'][0]['source_home'], '~/.claude')
+
+ def test_bad_clock_address_is_rejected_before_writing(self):
+ for bad in ('192.168.0.50', 'ftp://clock', 'http://', 'http://clock/photo', 'http://clock:99999'):
+ code, _, err = run('setup', '--config', str(self.config), '--yes',
+ '--claude-email', '[email protected]', '--device-url', bad)
+ self.assertEqual(code, 1, bad)
+ self.assertFalse(self.config.exists())
+ self.assertEqual(cli.device_address('http://10.0.0.9:8080/'), 'http://10.0.0.9:8080')
+
+ def test_doctor_without_config_explains_setup(self):
+ code, _, err = run('doctor', '--config', str(self.config))
+ self.assertEqual(code, 1)
+ self.assertIn('token-tv setup', err)
+
+ def test_demo_renders_every_face_from_sample_data(self):
+ code, out, _ = run('demo', '--out', str(self.tmp / 'demo'), '--scale', '2')
+ self.assertEqual(code, 0)
+ files = list((self.tmp / 'demo').iterdir())
+ self.assertEqual(len([p for p in files if '@' not in p.name]), len(STYLES))
+ self.assertIn('demo-space.gif', [p.name for p in files])
+ signature = {'.jpg': b'\xff\xd8\xff', '.gif': b'GIF8', '.png': b'\x89PNG'}
+ for path in files: # every extension matches the bytes inside
+ self.assertTrue(path.read_bytes().startswith(signature[path.suffix]), path.name)
+ self.assertIn('Sample data only', out)
+
+
+class KeychainTest(unittest.TestCase):
+ def test_service_names_follow_claude_code(self):
+ root = Path('/Users/me/.token-tv/claude-b')
+ self.assertEqual(sources.keychain_services(root), ['Claude Code-credentials-' + __import__('hashlib')
+ .sha256(str(root).encode()).hexdigest()[:8]])
+ default = Path('~/.claude').expanduser()
+ self.assertEqual(sources.keychain_services(default)[-1], 'Claude Code-credentials')
+
+ def test_keychain_is_used_only_on_macos_without_a_file(self):
+ root = Path(tempfile.mkdtemp())
+ with mock.patch.object(sources.sys, 'platform', 'linux'):
+ with self.assertRaises(FileNotFoundError):
+ sources.claude_token(root)
+ found = mock.Mock(returncode=0, stdout=json.dumps({'claudeAiOauth': {'accessToken': 'synthetic'}}))
+ with mock.patch.object(sources.sys, 'platform', 'darwin'), \
+ mock.patch.object(sources.subprocess, 'run', return_value=found) as call, \
+ mock.patch.dict(os.environ, {'USER': 'me'}):
+ self.assertEqual(sources.claude_token(root), 'synthetic')
+ self.assertEqual(call.call_args[0][0][:5], ['security', 'find-generic-password', '-a', 'me', '-w'])
+ missing = mock.Mock(returncode=44, stdout='')
+ with mock.patch.object(sources.sys, 'platform', 'darwin'), \
+ mock.patch.object(sources.subprocess, 'run', return_value=missing):
+ with self.assertRaises(sources.SourceError):
+ sources.claude_token(root)
+
+
+if __name__ == '__main__':
+ unittest.main()
+
+
+class ConnectGuardTest(unittest.TestCase):
+ def test_everyday_login_is_kept_without_explicit_replace(self):
+ from token_tv import connect
+ home = Path(tempfile.mkdtemp())
+ (home / '.codex').mkdir()
+ (home / '.codex' / 'auth.json').write_text('{}')
+ config = home / 'config.json'
+ config.write_text(json.dumps({'accounts': [{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex',
+ 'email': '[email protected]', 'source_home': '~/.codex'}]}))
+ with mock.patch.dict(os.environ, {'HOME': str(home)}), \
+ mock.patch.object(connect.subprocess, 'run') as login, \
+ mock.patch.object(connect.sys, 'argv', ['connect', '--config', str(config), '--account', 'codex_a']):
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out):
+ connect.main()
+ login.assert_not_called()
+ self.assertIn('Kept the existing login', out.getvalue())
+
+ def test_macos_keychain_login_is_protected_without_a_file(self):
+ from token_tv import connect
+ home = Path(tempfile.mkdtemp()) # no ~/.claude/.credentials.json at all
+ config = home / 'config.json'
+ config.write_text(json.dumps({'accounts': [{'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude',
+ 'email': '[email protected]', 'source_home': '~/.claude'}]}))
+ with mock.patch.dict(os.environ, {'HOME': str(home)}), \
+ mock.patch.object(connect.sys, 'platform', 'darwin'), \
+ mock.patch.object(connect.subprocess, 'run') as login, \
+ mock.patch.object(connect.sys, 'argv', ['connect', '--config', str(config), '--account', 'claude_a']):
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out):
+ connect.main()
+ login.assert_not_called()
+ self.assertIn('Keychain', out.getvalue())
diff --git a/tests/test_web.py b/tests/test_web.py
index 9526675..8031023 100644
--- a/tests/test_web.py
+++ b/tests/test_web.py
@@ -35,3 +35,36 @@ class WebAssetTests(unittest.TestCase):
server.shutdown()
server.server_close()
thread.join()
+
+
+class ThemesEndpointTests(unittest.TestCase):
+ def test_themes_endpoint_lists_installed_styles(self):
+ import json
+ from token_tv.display import STYLES
+ server = ThreadingHTTPServer(('127.0.0.1', 0), handler(UsageStore([])))
+ thread = threading.Thread(target=server.serve_forever)
+ thread.start()
+ try:
+ with urlopen(f'http://127.0.0.1:{server.server_port}/themes') as response:
+ data = json.load(response)
+ self.assertEqual({t['id'] for t in data['themes'] if t['installed']}, set(STYLES))
+ self.assertIn('last_attempt_at', data)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+ def test_demo_build_writes_themes_without_apply(self):
+ import importlib.util
+ import json
+ import tempfile
+ from pathlib import Path
+ root = Path(__file__).resolve().parents[1]
+ spec = importlib.util.spec_from_file_location('build_demo', root / 'scripts' / 'build_demo.py')
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ out = Path(tempfile.mkdtemp()) / 'site'
+ module.build(out, 'https://example.com')
+ themes = json.loads((out / 'demo-themes.json').read_text())
+ self.assertEqual(len(themes['themes']), 6)
+ self.assertIn('data-demo', (out / 'index.html').read_text())
diff --git a/token_tv/__init__.py b/token_tv/__init__.py
index cf771ca..8a007fd 100644
--- a/token_tv/__init__.py
+++ b/token_tv/__init__.py
@@ -1 +1,2 @@
-"""TokenTV Mini daemon scaffold."""
+"""TokenTV: AI usage limits on a tiny desk clock."""
+__version__ = "0.1.0"
diff --git a/token_tv/__main__.py b/token_tv/__main__.py
new file mode 100644
index 0000000..1b254ee
--- /dev/null
+++ b/token_tv/__main__.py
@@ -0,0 +1,3 @@
+from token_tv.cli import main
+
+raise SystemExit(main())
diff --git a/token_tv/assets/theme-catalog.json b/token_tv/assets/theme-catalog.json
new file mode 100644
index 0000000..18a3493
--- /dev/null
+++ b/token_tv/assets/theme-catalog.json
@@ -0,0 +1,65 @@
+{
+ "schema_version": 1,
+ "themes": [
+ {
+ "id": "pixel",
+ "name": "Pixel",
+ "author": "TokenTV",
+ "added_at": "2026-10-03T00:00:00Z",
+ "min_version": "0.1.0",
+ "source_url": "https://github.com/click6067-ship-it/token-tv",
+ "license": "MIT",
+ "like_issue": 1
+ },
+ {
+ "id": "digital",
+ "name": "Digital",
+ "author": "TokenTV",
+ "added_at": "2026-10-03T00:00:00Z",
+ "min_version": "0.1.0",
+ "source_url": "https://github.com/click6067-ship-it/token-tv",
+ "license": "MIT",
+ "like_issue": 2
+ },
+ {
+ "id": "neon",
+ "name": "Neon",
+ "author": "TokenTV",
+ "added_at": "2026-10-03T00:00:00Z",
+ "min_version": "0.1.0",
+ "source_url": "https://github.com/click6067-ship-it/token-tv",
+ "license": "MIT",
+ "like_issue": 3
+ },
+ {
+ "id": "retro",
+ "name": "Pixel Retro",
+ "author": "TokenTV",
+ "added_at": "2026-10-03T00:00:00Z",
+ "min_version": "0.1.0",
+ "source_url": "https://github.com/click6067-ship-it/token-tv",
+ "license": "MIT",
+ "like_issue": 4
+ },
+ {
+ "id": "hud",
+ "name": "Sci-Fi HUD",
+ "author": "TokenTV",
+ "added_at": "2026-10-03T00:00:00Z",
+ "min_version": "0.1.0",
+ "source_url": "https://github.com/click6067-ship-it/token-tv",
+ "license": "MIT",
+ "like_issue": 5
+ },
+ {
+ "id": "space",
+ "name": "Space",
+ "author": "TokenTV",
+ "added_at": "2026-10-03T00:00:00Z",
+ "min_version": "0.1.0",
+ "source_url": "https://github.com/click6067-ship-it/token-tv",
+ "license": "MIT",
+ "like_issue": 6
+ }
+ ]
+}
diff --git a/token_tv/assets/theme-votes.json b/token_tv/assets/theme-votes.json
new file mode 100644
index 0000000..1e24a1f
--- /dev/null
+++ b/token_tv/assets/theme-votes.json
@@ -0,0 +1,36 @@
+{
+ "schema_version": 1,
+ "last_attempt_at": "2026-10-03T14:32:40Z",
+ "counts": {
+ "1": {
+ "count": 0,
+ "status": "fresh",
+ "fetched_at": "2026-10-03T14:32:40Z"
+ },
+ "2": {
+ "count": 0,
+ "status": "fresh",
+ "fetched_at": "2026-10-03T14:32:40Z"
+ },
+ "3": {
+ "count": 0,
+ "status": "fresh",
+ "fetched_at": "2026-10-03T14:32:40Z"
+ },
+ "4": {
+ "count": 0,
+ "status": "fresh",
+ "fetched_at": "2026-10-03T14:32:40Z"
+ },
+ "5": {
+ "count": 0,
+ "status": "fresh",
+ "fetched_at": "2026-10-03T14:32:40Z"
+ },
+ "6": {
+ "count": 0,
+ "status": "fresh",
+ "fetched_at": "2026-10-03T14:32:40Z"
+ }
+ }
+}
diff --git a/token_tv/catalog.py b/token_tv/catalog.py
new file mode 100644
index 0000000..a475b44
--- /dev/null
+++ b/token_tv/catalog.py
@@ -0,0 +1,138 @@
+"""Theme catalog: installed faces plus reviewed metadata and a manually refreshed likes snapshot.
+
+Installed STYLES are the source of truth. The catalog only adds name/author/source/likes, so a face
+you added in your own fork shows up as Local. Nothing here downloads or runs theme code.
+"""
+import json
+import re
+from datetime import datetime
+from pathlib import Path
+
+from token_tv import __version__
+from token_tv.display import STYLES
+
+ASSETS = Path(__file__).with_name('assets')
+CATALOG_PATH = ASSETS / 'theme-catalog.json'
+VOTES_PATH = ASSETS / 'theme-votes.json'
+REPO = 'click6067-ship-it/token-tv'
+BLANK_VOTES = {'schema_version': 1, 'last_attempt_at': None, 'counts': {}}
+FIELDS = ('id', 'name', 'author', 'added_at', 'min_version', 'source_url', 'license', 'like_issue')
+
+
+def version_tuple(text):
+ parts = [int(p) for p in str(text).split('.')]
+ while parts and parts[-1] == 0:
+ parts.pop()
+ return tuple(parts)
+
+
+def version_at_least(have, need):
+ return version_tuple(have) >= version_tuple(need)
+
+
+def validate_catalog(data):
+ if not isinstance(data, dict) or data.get('schema_version') != 1 or not isinstance(data.get('themes'), list):
+ raise ValueError('Unsupported theme catalog')
+ seen = set()
+ for theme in data['themes']:
+ if not isinstance(theme, dict) or set(FIELDS) - set(theme):
+ raise ValueError('Theme entries need ' + ', '.join(FIELDS))
+ if not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,31}', str(theme['id'])) or theme['id'] in seen:
+ raise ValueError('Theme ids must be unique lowercase names')
+ seen.add(theme['id'])
+ issue = theme['like_issue']
+ if issue is not None and (isinstance(issue, bool) or not isinstance(issue, int) or issue < 1):
+ raise ValueError('like_issue must be an issue number or null')
+ if not str(theme['source_url']).startswith('https://'):
+ raise ValueError('source_url must be an https link')
+ if theme.get('preview_url') is not None and not str(theme['preview_url']).startswith('https://'):
+ raise ValueError('preview_url must be an https link')
+ datetime.fromisoformat(str(theme['added_at']).replace('Z', '+00:00'))
+ version_tuple(theme['min_version'])
+ return data
+
+
+def load_catalog(path=None):
+ return validate_catalog(json.loads(Path(path or CATALOG_PATH).read_text()))
+
+
+def parse_time(text):
+ """A UTC timestamp string, or None when missing or unreadable."""
+ try:
+ return datetime.fromisoformat(str(text).replace('Z', '+00:00')).timestamp() if text else None
+ except ValueError:
+ return None
+
+
+def load_votes(path=None):
+ """The saved snapshot, or a blank one. Each count keeps the time it was really counted.
+
+ A broken file, a bad count or an unreadable count time means unknown, never zero.
+ """
+ try:
+ data = json.loads(Path(path or VOTES_PATH).read_text())
+ counts = {}
+ for issue, value in data['counts'].items():
+ count, status, stamp = value.get('count'), value.get('status'), value.get('fetched_at')
+ if isinstance(count, bool) or not isinstance(count, int) or count < 0 or status not in ('fresh', 'stale'):
+ continue
+ if stamp is not None and parse_time(stamp) is None:
+ continue # unreadable time: we cannot say when this number was true
+ if status == 'fresh' and stamp is None:
+ continue
+ counts[str(issue)] = {'count': count, 'status': status, 'fetched_at': stamp}
+ attempt = data.get('last_attempt_at')
+ return {'schema_version': 1, 'last_attempt_at': attempt if parse_time(attempt) else None, 'counts': counts}
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ return dict(BLANK_VOTES)
+
+
+def theme_list(installed=STYLES, catalog=None, votes=None, version=__version__, repo=REPO):
+ catalog = load_catalog() if catalog is None else catalog
+ votes = load_votes() if votes is None else votes
+ known = {t['id']: t for t in catalog['themes']}
+ themes = []
+ for id in list(installed) + [i for i in known if i not in installed]:
+ meta = known.get(id)
+ if meta is None:
+ themes.append({'id': id, 'name': id.replace('-', ' ').title(), 'author': None, 'local': True,
+ 'installed': True, 'needs_update': False, 'min_version': None, 'added_at': None,
+ 'source_url': None, 'license': None, 'preview_url': None,
+ 'likes': None, 'likes_state': 'local', 'likes_counted_at': None, 'like_url': None})
+ continue
+ issue = meta['like_issue']
+ count = votes['counts'].get(str(issue)) if issue else None
+ state = 'not_open' if not issue else 'unavailable' if count is None else \
+ 'counted' if count['status'] == 'fresh' else 'stale'
+ themes.append({'id': id, 'name': meta['name'], 'author': meta['author'], 'local': False,
+ 'installed': id in installed,
+ 'needs_update': id not in installed or not version_at_least(version, meta['min_version']),
+ 'min_version': meta['min_version'], 'added_at': meta['added_at'],
+ 'source_url': meta['source_url'], 'license': meta['license'],
+ 'preview_url': meta.get('preview_url'),
+ 'likes': count['count'] if count else None, 'likes_state': state,
+ 'likes_counted_at': count['fetched_at'] if count else None,
+ 'like_url': f'https://github.com/{repo}/issues/{issue}' if issue else None})
+ return {'last_attempt_at': votes.get('last_attempt_at'), 'version': version, 'themes': sort_themes(themes, 'new')}
+
+
+def _newest(theme):
+ stamp = theme['added_at']
+ return -datetime.fromisoformat(stamp.replace('Z', '+00:00')).timestamp() if stamp else float('inf')
+
+
+def sort_themes(themes, mode):
+ """New: newest first, then id. Popular: known counts high to low, then the rest in New order."""
+ new = sorted(themes, key=lambda t: (_newest(t), t['id']))
+ if mode == 'new':
+ return new
+ counted = sorted((t for t in new if t['likes'] is not None), key=lambda t: -t['likes']) # stable: keeps New order
+ return counted + [t for t in new if t['likes'] is None]
+
+
+def payload():
+ """theme_list() for the dashboard; a broken catalog still lists every installed face as Local."""
+ try:
+ return theme_list()
+ except (OSError, ValueError, KeyError, TypeError):
+ return dict(theme_list(catalog={'schema_version': 1, 'themes': []}), catalog_error=True)
diff --git a/token_tv/cli.py b/token_tv/cli.py
new file mode 100644
index 0000000..a15d3d0
--- /dev/null
+++ b/token_tv/cli.py
@@ -0,0 +1,270 @@
+"""token-tv: set up, check, preview and run TokenTV.
+
+ token-tv setup write a credential-free config (never overwrites one)
+ token-tv doctor check CLIs and login files (--live asks each provider)
+ token-tv demo render every clock face with sample data
+ token-tv connect sign an account in with its official CLI
+ token-tv run start the dashboard and drive the clock
+"""
+import argparse
+import io
+import json
+import os
+import shutil
+import sys
+import time
+from pathlib import Path
+from urllib.parse import urlparse
+
+PROVIDERS = {
+ # provider: (CLI command, default home, file the CLI writes after login, login hint)
+ 'claude': ('claude', '~/.claude', '.credentials.json', 'claude auth login'),
+ 'codex': ('codex', '~/.codex', 'auth.json', 'codex login'),
+ 'grok': ('grok', '~/.grok', 'auth.json', 'grok login'),
+}
+
+
+def default_config():
+ base = os.environ.get('XDG_CONFIG_HOME') or '~/.config'
+ return str(Path(base).expanduser() / 'token-tv' / 'config.json')
+
+
+def cli_path(provider):
+ command = os.environ.get('TOKEN_TV_GROK_BIN', 'grok') if provider == 'grok' else PROVIDERS[provider][0]
+ return shutil.which(command)
+
+
+def login_state(provider, home):
+ """'yes', 'no' or 'keychain'. Only checks that the login file exists; never opens it."""
+ root = Path(home).expanduser()
+ if (root / PROVIDERS[provider][2]).is_file():
+ return 'yes'
+ if provider == 'claude' and sys.platform == 'darwin':
+ return 'keychain'
+ return 'no'
+
+
+def ask(prompt, default=''):
+ try:
+ answer = input(f'{prompt}{f" [{default}]" if default else ""}: ').strip()
+ except EOFError:
+ answer = ''
+ return answer or default
+
+
+def device_address(text):
+ """'http://host[:port]' with the trailing slash removed, or ValueError with a fix."""
+ url = urlparse(text.strip())
+ if url.scheme not in ('http', 'https') or not url.hostname or url.path.strip('/') or url.query:
+ raise ValueError(f'{text!r} is not a clock address; use the form http://192.168.0.50')
+ try:
+ url.port
+ except ValueError:
+ raise ValueError(f'{text!r} has an invalid port') from None
+ return f'{url.scheme}://{url.netloc}'
+
+
+def setup(args):
+ path = Path(args.config).expanduser()
+ if path.exists():
+ print(f'{path} already exists; TokenTV never overwrites a config.\n'
+ f'Edit it, or choose another path with --config.', file=sys.stderr)
+ return 1
+ interactive = not args.yes and sys.stdin.isatty()
+ homes = path.parent / 'homes'
+ accounts = []
+ for provider, (_, home, _, hint) in PROVIDERS.items():
+ emails = list(getattr(args, f'{provider}_email') or [])
+ if interactive and not emails:
+ print(f'\n{provider.title()}: CLI {"found" if cli_path(provider) else "not found"}')
+ for letter in 'ABC':
+ email = ask(f' {provider.title()} account {letter} email (blank to {"skip" if letter == "A" else "finish"})')
+ if not email:
+ break
+ emails.append(email)
+ if len(emails) > 3:
+ print(f'At most three {provider} accounts (A, B, C).', file=sys.stderr)
+ return 1
+ for index, email in enumerate(emails):
+ letter = 'ABC'[index]
+ key = f'{provider}_{letter.lower()}'
+ reuse = index == 0 and not args.isolate
+ if reuse and interactive:
+ print(f' {letter}: reuse the {provider} login in {home} (y), or keep a separate login '
+ f'for TokenTV in {homes / key} (n)?')
+ reuse = ask(' Reuse', 'y').lower().startswith('y')
+ accounts.append({'key': key, 'alias': f'{provider.upper()} {letter}', 'provider': provider,
+ 'email': email, 'source_home': home if reuse else str(homes / key)})
+ if not accounts:
+ print('No accounts given. Pass --claude-email, --codex-email or --grok-email (repeat for B and C), '
+ 'or run setup in a terminal to be asked.', file=sys.stderr)
+ return 1
+ device = args.device_url
+ while device is None and interactive:
+ device = ask('\nClock address, e.g. http://192.168.0.50 (blank for dashboard only)')
+ try:
+ device = device and device_address(device)
+ except ValueError as error:
+ print(f' {error}')
+ device = None
+ try:
+ device = device and device_address(device)
+ except ValueError as error:
+ print(error, file=sys.stderr)
+ return 1
+ config = {'poll_seconds': 300, 'accounts': accounts, 'display_style': 'digital'}
+ if device:
+ config['device_url'] = device
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, 'x') as handle: # 'x' refuses to replace a file created meanwhile
+ json.dump(config, handle, indent=2)
+ handle.write('\n')
+ except OSError as error:
+ print(f'Could not write {path}: {error.strerror or error}', file=sys.stderr)
+ return 1
+ flag = '' if str(path) == default_config() else f' --config {path}'
+ print(f'Wrote {path} ({len(accounts)} account{"s" * (len(accounts) != 1)}; emails and paths only, no secrets).')
+ for account in accounts:
+ shared = account['source_home'] == PROVIDERS[account['provider']][1]
+ print(f' {account["alias"]:<9} {"reuses your existing CLI login" if shared else "separate login"} '
+ f'in {account["source_home"]}')
+ print(f'Next: token-tv doctor{flag} (separate logins need: token-tv connect{flag} --account <key>)')
+ return 0
+
+
+def read_config(path):
+ """The validated config, or None after printing a one-line reason."""
+ from token_tv.sources import load_config
+ path = Path(path).expanduser()
+ if not path.is_file():
+ print(f'No config at {path}. Run: token-tv setup', file=sys.stderr)
+ return None
+ try:
+ return load_config(path)
+ except OSError as error:
+ print(f'Could not read {path}: {error.strerror or error}', file=sys.stderr)
+ except (ValueError, KeyError, TypeError, AttributeError) as error:
+ print(f'{path} is not a valid TokenTV config ({error}). Compare it with config.example.json.', file=sys.stderr)
+ return None
+
+
+def doctor(args):
+ config = read_config(args.config)
+ if config is None:
+ return 1
+ flag = '' if str(Path(args.config).expanduser()) == default_config() else f' --config {args.config}'
+ ready = True
+ for account in config['accounts']:
+ provider = account['provider']
+ home = 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"} '
+ if args.live:
+ from token_tv.sources import fetch_account
+ row = fetch_account(account)
+ good = row['status'] in ('ok', 'quota_unavailable') and row.get('identity_verified')
+ line += f'live check {"ok" if good else row["status"].upper()}'
+ ready &= bool(good)
+ if not good:
+ line += f' -> token-tv connect{flag} --account {account["key"]}'
+ elif state == 'yes':
+ line += 'login file present (not verified yet)'
+ elif state == 'keychain':
+ ready = False
+ line += 'no login file; macOS Keychain unchecked (untested on real Macs) -> doctor --live'
+ else:
+ ready = False
+ line += f'login MISSING -> token-tv connect{flag} --account {account["key"]}'
+ if not found:
+ ready = False
+ line += f'\n{"":<18}install the {provider} CLI, then log in ({PROVIDERS[provider][3]})'
+ print(line)
+ 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:
+ print(f'Ready: every account answered with the expected email. Start with: token-tv run{flag}')
+ else:
+ print(f'Files are in place, but logins are not verified. Check them with: token-tv doctor{flag} --live')
+ return 0 if ready else 1
+
+
+def demo(args):
+ from PIL import Image
+ from token_tv.display import STYLES, render_page
+ from token_tv.sample import snapshot
+ out = Path(args.out).expanduser()
+ try:
+ out.mkdir(parents=True, exist_ok=True)
+ except OSError as error:
+ print(f'Could not create {out}: {error.strerror or error}', file=sys.stderr)
+ return 1
+ data = snapshot(time.time())
+ for style in STYLES:
+ image = render_page(data, style=style)
+ kind = 'gif' if image[:4] == b'GIF8' else 'jpg' if image[:3] == b'\xff\xd8\xff' else 'png'
+ name = out / f'demo-{style}.{kind}'
+ name.write_bytes(image)
+ if args.scale > 1 and kind != 'gif':
+ big = Image.open(io.BytesIO(image)).resize((240 * args.scale,) * 2, Image.Resampling.NEAREST)
+ big.save(out / f'demo-{style}@{args.scale}x.png')
+ print(name)
+ print('Sample data only (DEMO). Your real usage appears after setup, connect and run.')
+ return 0
+
+
+def passthrough(module, args, extra):
+ sys.argv = [f'token-tv {args.command}', '--config', str(Path(args.config).expanduser()), *extra]
+ if not {'-h', '--help'} & set(extra) and read_config(args.config) is None:
+ return 1
+ module.main()
+ return 0
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(prog='token-tv', description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ commands = parser.add_subparsers(dest='command', metavar='command')
+ config = argparse.ArgumentParser(add_help=False)
+ config.add_argument('--config', default=default_config(), help='config path (default: %(default)s)')
+
+ s = commands.add_parser('setup', parents=[config], help='write a config; never overwrites one')
+ for provider in PROVIDERS:
+ s.add_argument(f'--{provider}-email', action='append',
+ help=f'{provider.title()} account email; repeat for accounts B and C')
+ s.add_argument('--isolate', action='store_true',
+ help='give every account its own login home instead of reusing your existing CLI login')
+ s.add_argument('--device-url', help='clock address, e.g. http://192.168.0.50')
+ s.add_argument('--yes', action='store_true', help='do not ask; use only the flags given')
+ o = commands.add_parser('doctor', parents=[config], help='check CLIs and logins')
+ o.add_argument('--live', action='store_true', help='ask each provider now and compare the email; the CLI may refresh an expired login; prints status only')
+ d = commands.add_parser('demo', help='render every clock face with sample data')
+ d.add_argument('--out', default='token-tv-demo', help='output folder (default: %(default)s)')
+ d.add_argument('--scale', type=int, default=3, help='extra enlarged PNG copy (1 = none)')
+ commands.add_parser('connect', parents=[config], help='log an account in with its official CLI',
+ add_help=False)
+ commands.add_parser('run', parents=[config], help='start the dashboard and drive the clock',
+ add_help=False)
+
+ args, extra = parser.parse_known_args(argv)
+ if args.command in ('connect', 'run'):
+ if args.command == 'run':
+ from token_tv import live as module
+ extra = extra or []
+ state = Path(args.config).expanduser().parent / 'state'
+ if '--state-dir' not in extra:
+ extra += ['--state-dir', str(state)]
+ else:
+ from token_tv import connect as module
+ return passthrough(module, args, extra)
+ if extra:
+ parser.error('unrecognized arguments: ' + ' '.join(extra))
+ if args.command is None:
+ parser.print_help()
+ return 0
+ return {'setup': setup, 'doctor': doctor, 'demo': demo}[args.command](args)
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/token_tv/connect.py b/token_tv/connect.py
index 68db5d3..9949f99 100644
--- a/token_tv/connect.py
+++ b/token_tv/connect.py
@@ -2,10 +2,15 @@
import argparse
import os
import subprocess
+import sys
from pathlib import Path
from token_tv.sources import fetch_account, load_config, scoped_env
+# provider: (everyday CLI home, file present after login)
+DEFAULT_HOMES = {"claude": ("~/.claude", ".credentials.json"), "codex": ("~/.codex", "auth.json"),
+ "grok": ("~/.grok", "auth.json")}
+
def login_command(account, browser=False):
provider = account["provider"]
@@ -38,6 +43,16 @@ def main():
if account is None or not account.get("source_home"):
parser.error("An account with a Mini-local CLI home is required")
root = Path(account["source_home"]).expanduser()
+ default, marker = DEFAULT_HOMES[account["provider"]]
+ keychain = account["provider"] == "claude" and sys.platform == "darwin" # Claude Code on macOS keeps it there
+ if root == Path(default).expanduser() and ((root / marker).is_file() or keychain):
+ state = "may already be signed in (macOS keeps it in the Keychain)" if keychain else "it is already signed in"
+ print(f"{account['alias']} reuses your everyday {account['provider']} login in {default}; {state}.\n"
+ "Logging in again replaces that login for every tool that uses it. To keep it,\n"
+ "just run token-tv doctor --live. For a separate login, point source_home elsewhere.", flush=True)
+ if not sys.stdin.isatty() or input("Type REPLACE to log in again anyway: ").strip() != "REPLACE":
+ print("Kept the existing login.", flush=True)
+ return
root.mkdir(parents=True, exist_ok=True)
os.chmod(root, 0o700)
print("Sign in as " + account["email"] + ". Enter login codes here, not in chat.", flush=True)
diff --git a/token_tv/live.py b/token_tv/live.py
index 8d86ba8..957b727 100644
--- a/token_tv/live.py
+++ b/token_tv/live.py
@@ -10,6 +10,7 @@ from pathlib import Path
from urllib.parse import parse_qs, urlparse
from token_tv.device import FILES, PhotoDisplay
+from token_tv.catalog import payload as theme_payload
from token_tv.display import STYLES, render_page
from token_tv.web_assets import HTML, ASSETS, asset
from token_tv.sources import load_config
@@ -86,6 +87,8 @@ def handler(store, preferences=None):
return
body = render_page(snapshot, int(path[7]), style)
content_type = "image/gif" if body[:4] == b"GIF8" else "image/jpeg"
+ elif path == '/themes':
+ body = json.dumps(theme_payload()).encode()
elif path == '/display':
body = json.dumps(display).encode()
elif path == "/health":
diff --git a/token_tv/sample.py b/token_tv/sample.py
new file mode 100644
index 0000000..2973e27
--- /dev/null
+++ b/token_tv/sample.py
@@ -0,0 +1,25 @@
+"""Synthetic accounts for the demo, the sample renders and tests. No real account data."""
+H, D = 3600, 86400
+# key, alias, provider, [(window, used %, seconds until reset)]
+SAMPLE = [
+ ('claude_a', 'CLAUDE A', 'claude', [('WEEK', 86, 3 * D), ('5H', 41, 2 * H)]),
+ ('claude_b', 'CLAUDE B', 'claude', [('5H', 52, 3 * H + 41 * 60), ('WEEK', 30, 5 * D)]),
+ ('claude_c', 'CLAUDE C', 'claude', [('5H', 97, 38 * 60), ('WEEK', 64, 4 * D)]),
+ ('codex_a', 'CODEX A', 'codex', [('5H', 34, 2 * H + 12 * 60)]),
+ ('codex_b', 'CODEX B', 'codex', [('WEEK', 91, D + 4 * H)]),
+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 61, 6 * D + 2 * H)]),
+ ('grok_b', 'GROK B', 'grok', [('BUDGET', 18, 12 * D + 3 * H)]),
+]
+
+
+def snapshot(now=None, sample=SAMPLE):
+ accounts = {}
+ for key, alias, provider, windows in sample:
+ row = {'key': key, 'alias': alias, 'provider': provider, 'status': 'ok', 'identity_verified': True,
+ 'windows': [{'label': label, 'used_percent': used, 'resets_in': reset} for label, used, reset in windows]}
+ if now is not None:
+ row['fetched_at'] = row['last_success_at'] = now
+ for window in row['windows']:
+ window['resets_at'] = now + window['resets_in']
+ accounts[key] = row
+ return {'schema': 1, 'updated_at': now or 0, 'accounts': accounts}
diff --git a/token_tv/sources.py b/token_tv/sources.py
index aad0788..b03d4b4 100644
--- a/token_tv/sources.py
+++ b/token_tv/sources.py
@@ -1,11 +1,14 @@
"""Use credentials in their owning CLI homes; export only approved fields."""
+import hashlib
import json
import os
import queue
import re
import subprocess
+import sys
import threading
import time
+import unicodedata
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
@@ -126,9 +129,32 @@ def json_get(url, headers=None):
return json.load(response)
+def keychain_services(root):
+ """macOS Keychain item names Claude Code uses for a CLI home (read from Claude Code 2.1.281)."""
+ home = str(root)
+ services = ["Claude Code-credentials-" + hashlib.sha256(unicodedata.normalize("NFC", home).encode()).hexdigest()[:8]]
+ if root == Path("~/.claude").expanduser():
+ services.append("Claude Code-credentials")
+ return services
+
+
+def claude_token(root):
+ """Access token from the CLI home's file, or on macOS from the login Keychain (read only)."""
+ path = root / ".credentials.json"
+ if path.is_file() or sys.platform != "darwin":
+ return json.loads(path.read_text())["claudeAiOauth"]["accessToken"]
+ user = os.environ.get("USER") or "claude-code-user"
+ for service in keychain_services(root):
+ result = subprocess.run(["security", "find-generic-password", "-a", user, "-w", "-s", service],
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=10)
+ if result.returncode == 0 and result.stdout.strip():
+ return json.loads(result.stdout)["claudeAiOauth"]["accessToken"]
+ raise SourceError("auth_required")
+
+
def claude_payload(account):
root = Path(account["source_home"]).expanduser()
- token = json.loads((root / ".credentials.json").read_text())["claudeAiOauth"]["accessToken"]
+ token = claude_token(root)
headers = {"Authorization": "Bearer " + token, "Accept": "application/json",
"User-Agent": "claude-code/2.1.287", "anthropic-beta": "oauth-2025-04-20"}
try:
@@ -143,7 +169,7 @@ def claude_payload(account):
"--no-session-persistence", "--max-turns", "1"],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=60)
- token = json.loads((root / ".credentials.json").read_text())["claudeAiOauth"]["accessToken"]
+ token = claude_token(root)
headers["Authorization"] = "Bearer " + token
profile = json_get("https://api.anthropic.com/api/oauth/profile", headers)
usage = json_get("https://api.anthropic.com/api/oauth/usage", headers)
diff --git a/token_tv/themes.py b/token_tv/themes.py
index a8f95a4..2fb5902 100644
--- a/token_tv/themes.py
+++ b/token_tv/themes.py
@@ -258,37 +258,37 @@ def render_digital(snapshot):
def render_neon(snapshot):
- cv = Canvas('#05040c')
+ """Neon tubes: a bright core line over a wide halo; the number glows in the provider colour."""
+ cv = Canvas('#04030a')
for y in range(4, SIZE, 8):
for x in range(4, SIZE, 8):
- cv.back.point((x, y), fill='#120f24')
+ cv.back.point((x, y), fill='#0e0b1c')
orb, ox = (lambda s, w=700: face('orbitron.ttf', s, w)), (lambda s, w=800: face('oxanium.woff2', s, w))
for index, row in enumerate(overview_rows(snapshot)):
y = ROWS[index]
a, a2 = ACCENT['neon'][row['provider']]
used, period, old, reset = reading(row)
- cv.back.rounded_rectangle((4, y, 235, y + ROW_H - 1), radius=13, fill=mix('#0b0918', a, .07))
- cv.draw.rounded_rectangle((4, y, 235, y + ROW_H - 1), radius=13, outline=mix(a, a2, .3), width=1)
- cv.glow.rounded_rectangle((4, y, 235, y + ROW_H - 1), radius=13, outline=rgb(a) + (200,), width=2)
- cv.draw.rounded_rectangle((11, y + 9, 46, y + 44), radius=9, fill=mix('#0b0918', a, .18), outline=a)
- cv.glow.rounded_rectangle((11, y + 9, 46, y + 44), radius=9, outline=rgb(a) + (220,), width=2)
- mark = glyph(row['provider'], 22, mix(a, '#ffffff', .25))
- cv.ink.alpha_composite(mark, (18, y + 16))
- cv.bloom.alpha_composite(glyph(row['provider'], 22, a), (18, y + 16))
- cv.text((55, y + 8), account_label(row), orb(11), '#ffffff')
- cv.text((55, y + 51), period + (' OLD' if old else ''), orb(7, 600), '#ff5d8f' if old else '#aaa4cc', anchor='ls')
+ box = (5, y + 1, 234, y + ROW_H - 2)
+ cv.back.rounded_rectangle(box, radius=12, fill=mix('#06050e', a, .05))
+ cv.glow.rounded_rectangle(box, radius=12, outline=rgb(a) + (255,), width=3)
+ cv.draw.rounded_rectangle(box, radius=12, outline=mix(a, '#ffffff', .45), width=1)
+ cv.ink.alpha_composite(glyph(row['provider'], 24, mix(a, '#ffffff', .35)), (14, y + 10))
+ cv.bloom.alpha_composite(glyph(row['provider'], 24, a, stroke=4), (14, y + 10))
+ cv.text((46, y + 9), account_label(row), orb(11), '#ffffff')
+ cv.text((228, y + 9), period + (' OLD' if old else ''), orb(10), '#ff5d8f' if old else mix(a, '#ffffff', .2),
+ glow=rgb(a) + (160,), anchor='ra')
number = number_text(used)
- cv.text((54, y + 19), number, ox(29), '#ffffff', glow=rgb(a) + (255,))
+ cv.text((45, y + 22), number, ox(33), '#ffffff')
+ cv.glow.text((45, y + 22), number, font=ox(33), fill=rgb(a) + (255,), stroke_width=2, stroke_fill=rgb(a) + (255,))
if used is not None:
- x = 54 + cv.draw.textlength(number, font=ox(29)) + 2
- cv.text((x, y + 31), '%', ox(15, 700), '#ffffff')
- cv.text((229, y + 12), 'RESETS IN', orb(7, 600), '#aaa4cc', anchor='ra')
- cv.text((229, y + 24), reset, ox(16, 700), '#ffffff', glow=rgb(a) + (150,), anchor='ra')
- ring = 229 - cv.draw.textlength(reset, font=ox(16, 700)) - 13
- clock_mark(cv, (ring, y + 33), 7, a, 1)
- cv.glow.ellipse((ring - 8, y + 25, ring + 8, y + 41), outline=rgb(a) + (200,), width=2)
- gauge(cv, (12, y + 60, 228, y + 66), used, band('neon', used or 0), gap=3, shape='round', radius=3,
- track='#1a1730', empty='#4a4170', stale=old, glow=True)
+ x = 45 + cv.draw.textlength(number, font=ox(33)) + 2
+ cv.text((x, y + 36), '%', ox(16, 700), mix(a, '#ffffff', .6))
+ cv.text((228, y + 31), reset, ox(17, 700), '#ffffff', glow=rgb(a) + (170,), anchor='ra')
+ ring = 228 - cv.draw.textlength(reset, font=ox(17, 700)) - 12
+ clock_mark(cv, (ring, y + 40), 7, mix(a, '#ffffff', .3), 1)
+ cv.glow.ellipse((ring - 8, y + 32, ring + 8, y + 48), outline=rgb(a) + (220,), width=2)
+ gauge(cv, (14, y + 59, 226, y + 66), used, band('neon', used or 0), gap=3, shape='round', radius=3,
+ track='#15122a', empty='#4a4170', stale=old, glow=True)
return cv.finish(blur=3)
diff --git a/token_tv/web/app.js b/token_tv/web/app.js
index 16f7669..2b9eaf7 100644
--- a/token_tv/web/app.js
+++ b/token_tv/web/app.js
@@ -243,9 +243,42 @@ function paintClock(forceImage = false) {
const styleName = s => s === 'retro' ? 'Pixel Retro' : s === 'hud' ? 'Sci-Fi HUD' : s ? s[0].toUpperCase() + s.slice(1) : 'Unknown';
let displayPolling = false;
async function refreshDisplay(forceImage = false) {if (displayPolling) return; displayPolling = true; try {const r = await fetch(DEMO ? '/demo-display.json' : '/display', {cache:'no-store'}); if (!r.ok) throw Error(); const data = await r.json(); const dirty = displayInfo && clockChoice !== displayInfo.style; displayInfo = data; if (!clockChoice || !dirty) clockChoice = data.style; const select = $('#clock-style'); if (!select.options.length) for (const s of data.styles) {const o = el('option', styleName(s)); o.value = s; select.append(o)} select.value = clockChoice; paintClock(forceImage)} catch {$('#display-state').textContent = 'Clock status unavailable'} finally {displayPolling = false}}
-$('#clock-style').onchange = e => {clockChoice = e.target.value; clockError = false; paintClock(true)};
+$('#clock-style').onchange = e => {clockChoice = e.target.value; clockError = false; paintClock(true); paintThemes()};
$('#apply').onclick = async () => {if (applying || !clockChoice) return; applying = true; clockError = false; paintClock(); try {const r = await fetch('/display/style', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({style:clockChoice})}); if (!r.ok) throw Error(); displayInfo = await r.json()} catch {clockError = true} finally {applying = false; paintClock(true)}};
+let themeData = null, themeSort = 'popular';
+const REPO_URL = 'https://github.com/click6067-ship-it/token-tv';
+const day = s => new Date(s).toLocaleDateString();
+const likeText = t => ({counted: `👍 ${t.likes} · counted ${day(t.likes_counted_at)}`, stale: `👍 ${t.likes} · last counted ${t.likes_counted_at ? day(t.likes_counted_at) : 'at an unknown time'}`, unavailable: 'Likes unavailable', not_open: 'Likes not open yet', local: 'Your local face'})[t.likes_state] || 'Likes unavailable';
+function sortThemes(list, mode) {
+ const added = t => t.added_at ? -Date.parse(t.added_at) : Infinity;
+ const fresh = [...list].sort((a, b) => added(a) - added(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
+ return mode === 'new' ? fresh : [...fresh.filter(t => t.likes !== null).sort((a, b) => b.likes - a.likes), ...fresh.filter(t => t.likes === null)];
+}
+function paintThemes() {
+ const list = $('#theme-list'); list.replaceChildren();
+ document.querySelectorAll('.theme-sort button').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.sort === themeSort)));
+ if (!themeData) return;
+ $('#likes-as-of').textContent = themeData.last_attempt_at ? 'Last likes refresh: ' + day(themeData.last_attempt_at) : 'Likes not counted yet';
+ for (const t of sortThemes(themeData.themes, themeSort)) {
+ const item = el('li', undefined, 'theme-card'); item.dataset.id = t.id;
+ const head = el('div', undefined, 'theme-title'); head.append(el('strong', t.name), el('span', t.local ? 'Local' : 'by ' + t.author, 'theme-author')); item.append(head);
+ item.append(el('p', likeText(t), 'theme-likes'));
+ const actions = el('div', undefined, 'theme-actions');
+ if (t.installed && !t.needs_update) {
+ const preview = el('button', clockChoice === t.id ? 'Previewing' : 'Preview', 'control'); preview.type = 'button';
+ preview.onclick = () => {clockChoice = t.id; clockError = false; $('#clock-style').value = t.id; paintClock(true); paintThemes()};
+ actions.append(preview);
+ } else actions.append(el('span', `Needs v${t.min_version} · update TokenTV`, 'theme-update'));
+ const link = (text, href) => {const a = el('a', text); a.href = href; a.rel = 'noopener'; a.target = '_blank'; actions.append(a)};
+ if (DEMO) link('Get', REPO_URL + '#quick-start');
+ if (t.like_url) link('Like on GitHub', t.like_url);
+ if (t.source_url) link('Source', t.source_url);
+ item.append(actions); list.append(item);
+ }
+}
+async function loadThemes() {try {const r = await fetch(DEMO ? '/demo-themes.json' : '/themes', {cache:'no-store'}); if (!r.ok) throw Error(); themeData = await r.json(); paintThemes()} catch {$('#likes-as-of').textContent = 'Themes unavailable · your clock styles still work'}}
+document.querySelectorAll('.theme-sort button').forEach(b => {b.onclick = () => {themeSort = b.dataset.sort; paintThemes()}});
$('#frame').onerror = () => {$('#display-state').textContent = 'Clock preview unavailable. Reopen to retry.'};
$('#mascot').append(retroMascot()); buildStarfield(); tick();
-update(); refreshDisplay(); setInterval(update, 30000); setInterval(tick, 1000); setInterval(() => {if (!$('#clock-panel').hidden) refreshDisplay()}, 5000);
+update(); refreshDisplay(); loadThemes(); setInterval(update, 30000); setInterval(tick, 1000); setInterval(() => {if (!$('#clock-panel').hidden) refreshDisplay()}, 5000);
diff --git a/token_tv/web/index.html b/token_tv/web/index.html
index 0ebab1c..d8f14d6 100644
--- a/token_tv/web/index.html
+++ b/token_tv/web/index.html
@@ -63,6 +63,12 @@
<button class="control primary" id="apply" type="button" disabled>Apply to clock</button>
<p id="display-state" role="status">Loading clock status</p>
<p class="quiet">240 × 240 · The web appearance is separate from your clock style.</p>
+ <section class="clock-themes" aria-labelledby="themes-title">
+ <div class="themes-head"><h3 id="themes-title">Themes</h3><div class="theme-sort" role="group" aria-label="Sort themes"><button type="button" class="control" data-sort="popular" aria-pressed="true">Popular</button><button type="button" class="control" data-sort="new" aria-pressed="false">New</button></div></div>
+ <p class="quiet" id="likes-as-of">Loading themes</p>
+ <ul id="theme-list" class="theme-list"></ul>
+ <p class="quiet theme-fork">Start with a working face. <a href="https://github.com/click6067-ship-it/token-tv/blob/main/docs/clock-faces.md">Fork it, make it yours</a>.</p>
+ </section>
</aside>
</div>
<details class="help"><summary>How to read this display</summary><p>Percentages show <strong>used quota</strong>. The main gauge shows the selected account’s highest reported window; other windows open below it. Timers belong to that same window. A previous value is marked OLD and is not a current reading.</p><p>Grok CLI budget is a billing limit, not the Grok web conversation limit. If a provider does not report quota, it stays unknown. Laptop-linked accounts need the laptop online.</p></details>
diff --git a/token_tv/web/style.css b/token_tv/web/style.css
index dac3cb6..23f5d89 100644
--- a/token_tv/web/style.css
+++ b/token_tv/web/style.css
@@ -697,3 +697,18 @@ h1{margin:0;font:600 48px/1.04 var(--font-display);letter-spacing:-.03em;color:v
.demo-bar a:hover{border-color:var(--ink-3)}
[data-theme=digital] .demo-bar{font-size:19px;font-weight:400;letter-spacing:.06em;text-transform:uppercase}
[data-theme=retro] .demo-bar{font-size:19px;font-weight:400}
+.clock-themes{display:block;margin-top:22px;padding-top:18px;border-top:1px solid var(--line)}
+.clock-themes .themes-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:6px}
+.themes-head h3{margin:0;font:700 12px/1 var(--font-label);letter-spacing:.18em;text-transform:uppercase;color:var(--ink-2)}
+.theme-sort{display:flex;gap:4px}.theme-sort .control{min-height:28px;padding:4px 10px;font-size:12px}
+.theme-sort .control[aria-pressed=true]{border-color:var(--ink-2);color:var(--ink)}
+.theme-list{display:grid;gap:8px;margin:10px 0;padding:0;list-style:none}
+.theme-card{padding:10px 12px;border:1px solid var(--line);border-radius:10px}
+.theme-title{display:flex;align-items:baseline;justify-content:space-between;gap:8px}
+.theme-author{font-size:12px;color:var(--ink-3)}
+.theme-likes{margin:4px 0 8px;font-size:12px;color:var(--ink-2)}
+.theme-actions{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px;font-size:12px}
+.theme-actions .control{min-height:28px;padding:4px 12px;font-size:12px}
+.theme-actions a{color:var(--ink-2)}.theme-update{color:var(--ink-3)}
+.theme-fork{margin-top:4px}
+[data-demo] #apply{display:none}
diff --git a/tokens.css b/token_tv/web/tokens.css
similarity index 100%
rename from tokens.css
rename to token_tv/web/tokens.css
diff --git a/token_tv/web_assets.py b/token_tv/web_assets.py
index 40f250f..d2bd3b1 100644
--- a/token_tv/web_assets.py
+++ b/token_tv/web_assets.py
@@ -7,7 +7,7 @@ HTML = (WEB / 'index.html').read_text()
ASSETS = {
'/assets/style.css': (WEB / 'style.css', 'text/css; charset=utf-8'),
'/assets/app.js': (WEB / 'app.js', 'text/javascript; charset=utf-8'),
- '/assets/tokens.css': (ROOT.parent / 'tokens.css', 'text/css; charset=utf-8'),
+ '/assets/tokens.css': (WEB / 'tokens.css', 'text/css; charset=utf-8'),
'/assets/manrope.ttf': (WEB / 'manrope.ttf', 'font/ttf'),
'/assets/vt323.woff2': (WEB / 'vt323.woff2', 'font/woff2'),
'/assets/dseg7-classic-bold.woff2': (WEB / 'dseg7-classic-bold.woff2', 'font/woff2'),