Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.
Make setup one command and show only the services you use
click6067-ship-it19e7dcd36cc5
diff --git a/AGENTS.md b/AGENTS.mdindex 1587777..0fdc5e7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,6 +10,28 @@ token-tv demo --out token-tv-demo # every face from sample datapython3 -B -m unittest discover -s tests```+## Set up TokenTV for the user++When the user says "Set up TokenTV for me":++1. Install: `python3 -m venv .venv && .venv/bin/pip install -e .` (Windows: `.venv\Scripts\pip install -e .`),+ or with Node only: `npx github:click6067-ship-it/token-tv demo`.+2. Ask the user for the clock's IP address (shown on the clock's screen).+3. Run `.venv/bin/token-tv start --device-url <ip>`. It finds the Claude, Codex and Grok CLIs that are already+ signed in, reads each account's email through the official login, asks the user to confirm, saves the+ config and opens the dashboard at http://127.0.0.1:8787. The user then presses Clock display → Apply.+4. If it says nothing is signed in, tell the user to sign in to the CLI they use (e.g. `claude`, then /login)+ and run step 3 again. A second account of the same service: `.venv/bin/token-tv connect --account <key>`.++Verified on Linux with one SD_PRO clock. Mac and Windows hosts are untested; report what fails.++## Change how things look++- Clock faces: `docs/clock-faces.md` (one Python function per face, sample data, `token-tv demo`).+- Web dashboard: themes are listed in `THEMES` in `token_tv/web/app.js` and styled with+ `[data-theme=<id>]` rules in `token_tv/web/style.css`. Copy an existing theme's rules to start.+- More services: `docs/adding-a-provider.md`.+## Rules- Never read, print or copy credential files (`.credentials.json`, `auth.json`, Keychain items) ordiff --git a/README.ko.md b/README.ko.mdindex 2408239..b8063d4 100644--- a/README.ko.md+++ b/README.ko.md@@ -1,189 +1,10 @@-# TokenTV+<h1 align="center">TokenTV</h1>-[English README](README.md) · [▶ 라이브 데모](https://token-tv.vercel.app)+<p align="center"><img src="docs/images/real-clock.jpg" alt="작은 책상 시계에 띄운 TokenTV"></p>+<p align="center"><img src="docs/images/clock-faces.png" alt="시계 화면 6종(샘플 데이터)"></p>---**AI 사용 한도를 작은 책상 시계에.** Claude와 Codex 사용량을 여러 계정으로, 시계 펌웨어를 바꾸지 않고 보여줍니다.-Grok은 CLI 예산 정보를 보여주는 실험적 기능입니다. 제작자의 시계는 할인가 약 6,000원(약 $5)에 샀으며 가격과 배송비는 다를 수 있습니다. 켜 두는 컴퓨터(호스트)가 필요합니다.--240×240 책상 시계와 브라우저에서 확인하며, 계정별 인증 홈을 분리하고 실제 조회 실패와 오래된 값을 표시합니다.--## 실행--Python 3.10+와 사용할 공급자의 공식 CLI(`claude`, `codex`, `grok`)가 필요합니다.--```bash-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 각각 한 계정을 세 행으로 보여줍니다. 픽셀 아이콘, 큰 사용률 숫자, 막대, 기간 및 리셋 시간을 표시합니다.-실제 사용량을 제공하는 첫 계정을 선택하며 계정 전환은 수행하지 않습니다. Claude/Codex는 가장 높은 기간 사용률을 표시합니다.-영문 계정명은 `CLAUDE A/B/C`, `CODEX A/B`, `GROK A/B`로 구분합니다. 일곱 계정의 전체 기간과 조회 시각·오류 상태는 웹에서 공급자별로 확인합니다.-기본 조회 주기는 5분이며 브라우저를 열어도 추가 조회하지 않습니다.--### 화면 스타일--웹의 **Clock display**에서 시계 화면 6종을 미리 보고 고릅니다.-**Digital / Neon / Pixel Retro / Sci-Fi HUD**는 같은 이름의 웹 테마와 같은 글꼴·장식·게이지를-쓰고, 원래의 **Pixel**도 남아 있습니다. **Space**는 세 봇이 유리 헬멧을 쓰고 밤하늘을-떠다니는 움직이는 화면(GIF)이며, 사용률이 바뀌거나 30분이 지나면 새로 보냅니다. **Apply to clock**을 누르면 선택을 저장하고 같은 계정-캐시로 기기에 전송합니다. 미리보기만 선택하면 시계에는 적용되지 않습니다.--| Theme | 240×240 화면 표현 |-|---|---|-| Digital | 녹색 형광 터미널, 7세그먼트 숫자(꺼진 칸 표시), 호박색 리셋 시간 |-| Neon | 발광 카드 테두리, 아이콘 웰, 흰 숫자와 공급자 색 번짐, 둥근 칸 게이지 |-| Pixel Retro | 픽셀 프레임, 공급자별 픽셀 풍경, 마스코트, HP 블록 게이지 |-| Sci-Fi HUD | 모서리를 깎은 발광 프레임, 기울어진 칸 게이지 |--기존 Pixel(5×7 비트맵 글꼴과 픽셀 마스코트)도 같은 목록에서 고를 수 있습니다.-각 스타일은 Claude·Codex·Grok 한 계정과 10% 단위 10칸 게이지를 표시합니다.-설정의 `display_style`은 `digital`, `neon`, `retro`, `hud`, `pixel`, `space`를 지원하며 재시작 후에도 유지됩니다. 미설정 기본값은 `pixel`입니다.-숫자는 테마 내 공통 중성색입니다.-로고 색은 공급자별로 유지하며 게이지는 0–49% / 50–79% / 80–89% / 90–100% 구간마다 같은 색 계열의 두 색 그라데이션으로 표시합니다.-색만으로 상태를 전달하지 않으며 실제 숫자, 칸 수, 미인증/오래된 값 표기를 함께 제공합니다.----새 화면은 참고 이미지를 바탕으로 코드로 그렸습니다. 원본 이미지의 가상 통계나 정적인 숫자는 포함하지 않습니다.-이미지를 자동으로 테마로 바꾸는 기능이나 테마 편집기는 현재 구현돼 있지 않습니다.--## 인증과 사용률--설정에는 계정 별칭, 예상 이메일, 공급자, 공식 CLI의 인증 홈 경로만 넣습니다.-비밀번호·API 키·OAuth 토큰 값을 설정에 넣으면 안 됩니다.-기기로 전송되는 내용은 사용률과 별칭을 그린 JPEG뿐입니다.--| 공급자 | 조회 경로 | 수치의 의미 |-|---|---|---|-| Claude | CLI 소유 OAuth의 profile/usage | 5시간 및 주간 **사용한 비율** |-| Codex | 공식 `codex app-server`의 계정/한도 RPC | 응답이 지정한 실제 기간의 **사용한 비율** |-| Grok | 공식 CLI billing RPC, 실험 단계 | 제공된 CLI **비용 한도**. 웹 대화 횟수와 별개 |--Claude/Codex는 예상 이메일과 인증된 이메일을 대조합니다.-Grok은 공식 CLI 인증 홈에 저장된 단일 계정 이메일도 대조합니다.-계정이 여러 개 섞인 인증 홈은 거부하며 billing 인증만으로 이메일을 추정하지 않습니다.-Grok이 한도 수치를 제공하지 않으면 `quota_unavailable`로 표시합니다.-`auth_required`, `identity_mismatch`, `rate_limited`, `error`, `stale`을 구별하며-이전 성공 값에는 `last_success_at`을 붙입니다. 실패한 값을 0%로 바꾸지 않습니다.--`refresh_with_cli: true`인 Claude 계정은 401일 때 공식 CLI로 인증 갱신을 시도합니다.-이 과정은 도구를 끈 짧은 확인 응답 하나를 요청하므로 구독 사용량을 소량 소비할 수 있습니다.-인증 파일의 토큰을 직접 수정하거나 다른 머신으로 복사하지 않습니다.--## 내 디자인 만들기--**동작하는 화면에서 시작하세요. 포크해서 바꾸고, 보여 주세요.** 시계 화면은 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>"`를 추가하면 사진 테마를 사용합니다.-기기 펌웨어를 바꾸지 않습니다. 기존 사진 파일은 보존하고 선택 상태만 변경합니다.-원래 테마와 사진 선택 상태는 설정 폴더의 `state/display-original.json`에 저장됩니다.--복원 전 데몬을 정지한 뒤 실행합니다.--```bash-token-tv run --restore-display-```--사진 API가 없는 다른 펌웨어는 아직 실기기로 검증하지 않았습니다. 확인된 범위와 내 시계 확인 방법은 [docs/hardware-compatibility.md](docs/hardware-compatibility.md)에 있습니다.--## 다른 머신의 기존 인증 사용--Mini에 인증이 아직 없으면 `token_tv.bridge`로 노트북에서 검증한 정규화 JSON만-SSH로 보낼 수 있습니다. 설정의 `snapshot_file`이 해당 파일을 가리키도록 합니다.-그 계정은 화면에 노트북 연동으로 표시되며 15분 이상 갱신되지 않으면 오래된 값이 됩니다.-이 구성은 노트북이 켜져 있어야 동작합니다.--Mini 설정에 `source_home`과 `fallback_snapshot_file`을 함께 지정하면 Mini 로그인을-우선 사용하고, 인증이 없을 때만 노트북 조회로 대체합니다. 이메일 불일치는 대체로 숨기지 않습니다.-Mini의 해당 계정에 로그인하면 다음 5분 조회부터 노트북 의존성이 없어집니다.--```bash-# Mini의 프로젝트 디렉터리에서 계정을 선택합니다.-token-tv connect-```--인증번호는 로그인 터미널 또는 공식 브라우저 화면에 입력합니다. 제품의 HTTP API는-비밀번호나 인증번호를 받지 않습니다. 기본 CLI 홈과 Orca의 선택 계정은 바꾸지 않습니다.--```bash-python3 -m token_tv.bridge --config .runtime/laptop-config.json \- --ssh-host mini --remote-path '~/path/to/token-tv/.runtime/laptop-snapshot.json'-```--## 검증과 기존 mock--```bash-python3 -B -m unittest discover -s tests -v-python3 -m token_tv.app-```--기존 mock 서버는 예시 데이터를 `status: "mock"`으로 제공하며 실제 사용량과 구별됩니다.--### Four web appearances--The live web dashboard provides **Digital Terminal, Neon Cyberpunk, Pixel Retro and-Sci-Fi HUD**. Choose an appearance above the-three provider cards. It is saved in this browser and does not change the physical-clock. Account buttons A/B/C switch each provider independently; expand **more-quota windows** to inspect the other reported limits. The large number always-names its selected quota period.--**Clock display** opens the 240×240 preview and five LCD styles. Previewing-is read-only; **Apply to clock** explicitly sends the chosen LCD style. Unknown-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/`; `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.--For a Mini Codex account whose device-code login is unavailable, use the normal-browser flow with `python3 -m token_tv.connect --config <private-config> --account-<key> --browser`, forwarding localhost port 1455 to the Mini during authentication.-This keeps each account's CLI home separate.--Browser regression checks use local Playwright Chromium:--```sh-PLAYWRIGHT_PACKAGE=/path/to/playwright-package \-CHROMIUM_EXECUTABLE=/path/to/chromium \-TOKEN_TV_TEST_URL=http://127.0.0.1:18787 \-node scripts/test_web_browser.cjs-```--The test captures four desktop/mobile appearances, tests five viewport widths,-account choices, missing/stale/offline data, and clock controls. Its apply request-is intercepted, so running it does not change a connected clock.+약 5달러 Wi-Fi 책상 시계에 Claude·Codex 사용 한도를 띄웁니다. 펌웨어는 그대로예요.+**구경하기:** [라이브 데모](https://token-tv.vercel.app) 또는 `npx github:click6067-ship-it/token-tv demo`, 시계·로그인 없이 바로.+**설치하기:** 이 저장소를 AI에게 주고 *"TokenTV 설정해줘"* 라고 하세요. AI는 [AGENTS.md](AGENTS.md)를 따릅니다.+**내 화면 만들기:** 포크한 뒤 AI에게 화면 하나 바꿔 달라고 하세요. [가이드](docs/clock-faces.md)+자세히: [설정](docs/setup.ko.md) · [호환 시계](docs/hardware-compatibility.md) · MIT · [English](README.md)diff --git a/README.md b/README.mdindex f0171c4..5d6d9e7 100644--- a/README.md+++ b/README.md@@ -1,136 +1,10 @@<h1 align="center">TokenTV</h1>-<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>- <a href="#quick-start"><img alt="Quick start" src="https://img.shields.io/badge/Quick%20start-Python%203.10%2B-7dffd0?style=for-the-badge"></a>- <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 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 tiny desk clock"></p>--## Quick start--Needs Python 3.10+ and the official CLI (`claude`, `codex` or `grok`) for each provider you use.--```bash-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>--<br>----Pick one under **Clock display** in the dashboard, then press **Apply to clock**. Space is an animated-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>--- A GeekMagic **SmallTV**-style 240×240 Wi-Fi clock whose stock firmware has a photo album page.- The author's cost ₩6,000 (about $5) on an AliExpress sale; prices vary.-- Any always-on machine on the same network with Python 3.10+ and the official CLIs you use.--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>-<summary><b>How usage is read</b></summary>--| Provider | Source | The number means |-|---|---|---|-| Claude | Claude Code CLI's own OAuth login (profile and usage) | Share of the 5-hour and weekly limits **used** |-| Codex | Official `codex app-server` account and rate-limit RPC | Share of each reported window **used** |-| Grok | Grok CLI billing RPC (experimental) | Share of the CLI **billing budget**, not web chat limits |--Every login is checked against the email you configured. The clock gets only a picture,-never a password, token or cookie. Polling runs every five minutes; old readings say OLD and-missing data shows a dash, never a fake 0%. Claude accounts with `refresh_with_cli: true` may-refresh an expired login through the CLI, which sends one tiny prompt.-</details>--<details>-<summary><b>Accounts, clock and restore</b></summary>--- `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- `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 `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;-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-```--`scripts/test_web_browser.cjs` runs the browser checks with a local Playwright Chromium.-</details>--MIT, see [LICENSE](LICENSE). Bundled fonts keep their SIL Open Font License notices in-`token_tv/web/`. · [한국어](README.ko.md)+<p align="center"><img src="docs/images/real-clock.jpg" alt="TokenTV on a real tiny desk clock"></p>+<p align="center"><img src="docs/images/clock-faces.png" alt="Six clock faces (sample data)"></p>++Your Claude and Codex usage limits on a ~$5 Wi-Fi desk clock. No firmware flashing.+**Try it:** [live demo](https://token-tv.vercel.app) or `npx github:click6067-ship-it/token-tv demo`, no clock or login needed.+**Set it up:** give this repo to your AI and say *"Set up TokenTV for me."* It follows [AGENTS.md](AGENTS.md).+**Make your own face:** fork, then ask your AI to change one. [Guide](docs/clock-faces.md)+Details: [setup](docs/setup.md) · [compatible clocks](docs/hardware-compatibility.md) · MIT · [한국어](README.ko.md)diff --git a/bin/token-tv.js b/bin/token-tv.jsnew file mode 100755index 0000000..b03bef4--- /dev/null+++ b/bin/token-tv.js@@ -0,0 +1,39 @@+#!/usr/bin/env node+// One-line launcher: `npx github:click6067-ship-it/token-tv demo`.+// Runs the Python package from this checkout with uv if present, otherwise with a private venv.+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');++const root = path.resolve(__dirname, '..');+const args = process.argv.slice(2);+const win = process.platform === 'win32';+const has = (cmd) => spawnSync(win ? 'where' : 'which', [cmd], { stdio: 'ignore' }).status === 0;+const run = (cmd, argv) => {+ const r = spawnSync(cmd, argv, { stdio: 'inherit', shell: win });+ return r.status === null ? 1 : r.status;+};++if (has('uvx')) process.exit(run('uvx', ['--from', root, 'token-tv', ...args]));++const python = ['python3', 'python', 'py'].find(has);+if (!python) {+ console.error('TokenTV needs Python 3.10 or newer: https://www.python.org/downloads/');+ process.exit(1);+}+const version = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version;+const base = win ? (process.env.LOCALAPPDATA || os.homedir()) : (process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'));+const venv = path.join(base, 'token-tv', 'venv');+const bin = path.join(venv, win ? 'Scripts' : 'bin');+const stamp = path.join(venv, '.token-tv-source');+const source = `${root}@${version}`;+if (!fs.existsSync(stamp) || fs.readFileSync(stamp, 'utf8') !== source) {+ console.error('First run: preparing TokenTV (about a minute)...');+ if (run(python, ['-m', 'venv', venv]) || run(path.join(bin, 'python'), ['-m', 'pip', 'install', '-q', root])) {+ console.error('Could not install TokenTV. Try: pip install git+https://github.com/click6067-ship-it/token-tv');+ process.exit(1);+ }+ fs.writeFileSync(stamp, source);+}+process.exit(run(path.join(bin, 'token-tv'), args));diff --git a/docs/adding-a-provider.md b/docs/adding-a-provider.mdnew file mode 100644index 0000000..e67bc66--- /dev/null+++ b/docs/adding-a-provider.md@@ -0,0 +1,23 @@+# Adding a service (provider)++TokenTV reads Claude, Codex and Grok today. A new service is more than one function: the name is+listed in several places. This is the full list as of 2026-10-04; an AI agent can follow it.++**First check the service exposes usage you can read** (percent used and reset time) through its+own signed-in CLI or a documented API. If it does not, it cannot be added honestly.++| Where | What to add |+| --- | --- |+| `token_tv/sources.py` | allowed name in `load_config`; CLI home variable in `scoped_env`; a `<name>_payload()` that reads usage with the CLI's own login; an identity check; a branch in `fetch_account`; a branch in `logged_in_email` |+| `token_tv/usage.py` | `normalize_<name>()` turning the payload into windows (`label`, `used_percent`, `resets_at`) |+| `token_tv/cli.py` | `PROVIDERS` entry: CLI command, default home, login file, login hint |+| `token_tv/connect.py` | `DEFAULT_HOMES` entry and a `login_command` branch |+| `token_tv/display.py` | `PROVIDERS` order and `PROVIDER_INK` colour |+| `token_tv/themes.py` | colours in `ACCENT` (neon/retro/hud), Pixel Retro scene seed and sky, `glyph()` mark |+| `token_tv/space.py` | bubble colour if it should differ |+| `token_tv/assets/<name>-pixel.png` + `token_tv/web_assets.py` | pixel mascot and its allowlist entry |+| `token_tv/web/app.js` | `PROVIDERS`, `COMPANIES`, scene seed |+| `tests/` | a payload → windows test with sample JSON, never real account data |++Limits: every clock face shows at most three rows. With more than three services configured, the+first three in `PROVIDERS` order are shown. Missing readings must stay a dash, never 0%.diff --git a/docs/setup.ko.md b/docs/setup.ko.mdnew file mode 100644index 0000000..6c61258--- /dev/null+++ b/docs/setup.ko.md@@ -0,0 +1,194 @@+# TokenTV 설정·참고 (한국어)++예전 README.ko.md의 전체 내용입니다. 사람과 AI 에이전트 모두를 위한 문서이고, [AGENTS.md](../AGENTS.md)도 함께 봅니다.++# TokenTV++[English README](../README.md) · [▶ 라이브 데모](https://token-tv.vercel.app)++++**AI 사용 한도를 작은 책상 시계에.** Claude와 Codex 사용량을 여러 계정으로, 시계 펌웨어를 바꾸지 않고 보여줍니다.+Grok은 CLI 예산 정보를 보여주는 실험적 기능입니다. 제작자의 시계는 할인가 약 6,000원(약 $5)에 샀으며 가격과 배송비는 다를 수 있습니다. 켜 두는 컴퓨터(호스트)가 필요합니다.++240×240 책상 시계와 브라우저에서 확인하며, 계정별 인증 홈을 분리하고 실제 조회 실패와 오래된 값을 표시합니다.++## 실행++Python 3.10+와 사용할 공급자의 공식 CLI(`claude`, `codex`, `grok`)가 필요합니다.++```bash+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)와+[시계 화면 만들기](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 각각 한 계정을 세 행으로 보여줍니다. 픽셀 아이콘, 큰 사용률 숫자, 막대, 기간 및 리셋 시간을 표시합니다.+실제 사용량을 제공하는 첫 계정을 선택하며 계정 전환은 수행하지 않습니다. Claude/Codex는 가장 높은 기간 사용률을 표시합니다.+영문 계정명은 `CLAUDE A/B/C`, `CODEX A/B`, `GROK A/B`로 구분합니다. 일곱 계정의 전체 기간과 조회 시각·오류 상태는 웹에서 공급자별로 확인합니다.+기본 조회 주기는 5분이며 브라우저를 열어도 추가 조회하지 않습니다.++### 화면 스타일++웹의 **Clock display**에서 시계 화면 6종을 미리 보고 고릅니다.+**Digital / Neon / Pixel Retro / Sci-Fi HUD**는 같은 이름의 웹 테마와 같은 글꼴·장식·게이지를+쓰고, 원래의 **Pixel**도 남아 있습니다. **Space**는 세 봇이 유리 헬멧을 쓰고 밤하늘을+떠다니는 움직이는 화면(GIF)이며, 사용률이 바뀌거나 30분이 지나면 새로 보냅니다. **Apply to clock**을 누르면 선택을 저장하고 같은 계정+캐시로 기기에 전송합니다. 미리보기만 선택하면 시계에는 적용되지 않습니다.++| Theme | 240×240 화면 표현 |+|---|---|+| Digital | 녹색 형광 터미널, 7세그먼트 숫자(꺼진 칸 표시), 호박색 리셋 시간 |+| Neon | 발광 카드 테두리, 아이콘 웰, 흰 숫자와 공급자 색 번짐, 둥근 칸 게이지 |+| Pixel Retro | 픽셀 프레임, 공급자별 픽셀 풍경, 마스코트, HP 블록 게이지 |+| Sci-Fi HUD | 모서리를 깎은 발광 프레임, 기울어진 칸 게이지 |++기존 Pixel(5×7 비트맵 글꼴과 픽셀 마스코트)도 같은 목록에서 고를 수 있습니다.+각 스타일은 Claude·Codex·Grok 한 계정과 10% 단위 10칸 게이지를 표시합니다.+설정의 `display_style`은 `digital`, `neon`, `retro`, `hud`, `pixel`, `space`를 지원하며 재시작 후에도 유지됩니다. 미설정 기본값은 `pixel`입니다.+숫자는 테마 내 공통 중성색입니다.+로고 색은 공급자별로 유지하며 게이지는 0–49% / 50–79% / 80–89% / 90–100% 구간마다 같은 색 계열의 두 색 그라데이션으로 표시합니다.+색만으로 상태를 전달하지 않으며 실제 숫자, 칸 수, 미인증/오래된 값 표기를 함께 제공합니다.++++새 화면은 참고 이미지를 바탕으로 코드로 그렸습니다. 원본 이미지의 가상 통계나 정적인 숫자는 포함하지 않습니다.+이미지를 자동으로 테마로 바꾸는 기능이나 테마 편집기는 현재 구현돼 있지 않습니다.++## 인증과 사용률++설정에는 계정 별칭, 예상 이메일, 공급자, 공식 CLI의 인증 홈 경로만 넣습니다.+비밀번호·API 키·OAuth 토큰 값을 설정에 넣으면 안 됩니다.+기기로 전송되는 내용은 사용률과 별칭을 그린 JPEG뿐입니다.++| 공급자 | 조회 경로 | 수치의 의미 |+|---|---|---|+| Claude | CLI 소유 OAuth의 profile/usage | 5시간 및 주간 **사용한 비율** |+| Codex | 공식 `codex app-server`의 계정/한도 RPC | 응답이 지정한 실제 기간의 **사용한 비율** |+| Grok | 공식 CLI billing RPC, 실험 단계 | 제공된 CLI **비용 한도**. 웹 대화 횟수와 별개 |++Claude/Codex는 예상 이메일과 인증된 이메일을 대조합니다.+Grok은 공식 CLI 인증 홈에 저장된 단일 계정 이메일도 대조합니다.+계정이 여러 개 섞인 인증 홈은 거부하며 billing 인증만으로 이메일을 추정하지 않습니다.+Grok이 한도 수치를 제공하지 않으면 `quota_unavailable`로 표시합니다.+`auth_required`, `identity_mismatch`, `rate_limited`, `error`, `stale`을 구별하며+이전 성공 값에는 `last_success_at`을 붙입니다. 실패한 값을 0%로 바꾸지 않습니다.++`refresh_with_cli: true`인 Claude 계정은 401일 때 공식 CLI로 인증 갱신을 시도합니다.+이 과정은 도구를 끈 짧은 확인 응답 하나를 요청하므로 구독 사용량을 소량 소비할 수 있습니다.+인증 파일의 토큰을 직접 수정하거나 다른 머신으로 복사하지 않습니다.++## 내 디자인 만들기++**동작하는 화면에서 시작하세요. 포크해서 바꾸고, 보여 주세요.** 시계 화면은 240×240을 그리는+Python 함수 하나입니다. [docs/clock-faces.md](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>"`를 추가하면 사진 테마를 사용합니다.+기기 펌웨어를 바꾸지 않습니다. 기존 사진 파일은 보존하고 선택 상태만 변경합니다.+원래 테마와 사진 선택 상태는 설정 폴더의 `state/display-original.json`에 저장됩니다.++복원 전 데몬을 정지한 뒤 실행합니다.++```bash+token-tv run --restore-display+```++사진 API가 없는 다른 펌웨어는 아직 실기기로 검증하지 않았습니다. 확인된 범위와 내 시계 확인 방법은 [docs/hardware-compatibility.md](hardware-compatibility.md)에 있습니다.++## 다른 머신의 기존 인증 사용++Mini에 인증이 아직 없으면 `token_tv.bridge`로 노트북에서 검증한 정규화 JSON만+SSH로 보낼 수 있습니다. 설정의 `snapshot_file`이 해당 파일을 가리키도록 합니다.+그 계정은 화면에 노트북 연동으로 표시되며 15분 이상 갱신되지 않으면 오래된 값이 됩니다.+이 구성은 노트북이 켜져 있어야 동작합니다.++Mini 설정에 `source_home`과 `fallback_snapshot_file`을 함께 지정하면 Mini 로그인을+우선 사용하고, 인증이 없을 때만 노트북 조회로 대체합니다. 이메일 불일치는 대체로 숨기지 않습니다.+Mini의 해당 계정에 로그인하면 다음 5분 조회부터 노트북 의존성이 없어집니다.++```bash+# Mini의 프로젝트 디렉터리에서 계정을 선택합니다.+token-tv connect+```++인증번호는 로그인 터미널 또는 공식 브라우저 화면에 입력합니다. 제품의 HTTP API는+비밀번호나 인증번호를 받지 않습니다. 기본 CLI 홈과 Orca의 선택 계정은 바꾸지 않습니다.++```bash+python3 -m token_tv.bridge --config .runtime/laptop-config.json \+ --ssh-host mini --remote-path '~/path/to/token-tv/.runtime/laptop-snapshot.json'+```++## 검증과 기존 mock++```bash+python3 -B -m unittest discover -s tests -v+python3 -m token_tv.app+```++기존 mock 서버는 예시 데이터를 `status: "mock"`으로 제공하며 실제 사용량과 구별됩니다.++### Four web appearances++The live web dashboard provides **Digital Terminal, Neon Cyberpunk, Pixel Retro and+Sci-Fi HUD**. Choose an appearance above the+three provider cards. It is saved in this browser and does not change the physical+clock. Account buttons A/B/C switch each provider independently; expand **more+quota windows** to inspect the other reported limits. The large number always+names its selected quota period.++**Clock display** opens the 240×240 preview and five LCD styles. Previewing+is read-only; **Apply to clock** explicitly sends the chosen LCD style. Unknown+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/`; `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.++For a Mini Codex account whose device-code login is unavailable, use the normal+browser flow with `python3 -m token_tv.connect --config <private-config> --account+<key> --browser`, forwarding localhost port 1455 to the Mini during authentication.+This keeps each account's CLI home separate.++Browser regression checks use local Playwright Chromium:++```sh+PLAYWRIGHT_PACKAGE=/path/to/playwright-package \+CHROMIUM_EXECUTABLE=/path/to/chromium \+TOKEN_TV_TEST_URL=http://127.0.0.1:18787 \+node scripts/test_web_browser.cjs+```++The test captures four desktop/mobile appearances, tests five viewport widths,+account choices, missing/stale/offline data, and clock controls. Its apply request+is intercepted, so running it does not change a connected clock.+diff --git a/docs/setup.md b/docs/setup.mdnew file mode 100644index 0000000..e7239df--- /dev/null+++ b/docs/setup.md@@ -0,0 +1,120 @@+# TokenTV setup and reference++Everything that used to be in the README. Written for people and for AI coding agents; see also [AGENTS.md](../AGENTS.md).++## Quick start++Needs Python 3.10+ and the official CLI (`claude`, `codex` or `grok`) for each provider you use.++```bash+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="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>++<br>++++Pick one under **Clock display** in the dashboard, then press **Apply to clock**. Space is an animated+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](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>++- A GeekMagic **SmallTV**-style 240×240 Wi-Fi clock whose stock firmware has a photo album page.+ The author's cost ₩6,000 (about $5) on an AliExpress sale; prices vary.+- Any always-on machine on the same network with Python 3.10+ and the official CLIs you use.++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](hardware-compatibility.md) for what is verified and how to check your clock.+</details>++<details>+<summary><b>How usage is read</b></summary>++| Provider | Source | The number means |+|---|---|---|+| Claude | Claude Code CLI's own OAuth login (profile and usage) | Share of the 5-hour and weekly limits **used** |+| Codex | Official `codex app-server` account and rate-limit RPC | Share of each reported window **used** |+| Grok | Grok CLI billing RPC (experimental) | Share of the CLI **billing budget**, not web chat limits |++Every login is checked against the email you configured. The clock gets only a picture,+never a password, token or cookie. Polling runs every five minutes; old readings say OLD and+missing data shows a dash, never a fake 0%. Claude accounts with `refresh_with_cli: true` may+refresh an expired login through the CLI, which sends one tiny prompt.+</details>++<details>+<summary><b>Accounts, clock and restore</b></summary>++- `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+ `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 `token-tv setup` plus CLI logins, it is tested on Linux with+one clock, and it supports Claude, Codex and Grok. A new provider touches several files; see+[adding a provider](adding-a-provider.md). Issues and pull requests for providers, clock models and faces are welcome;+see [CONTRIBUTING.md](../CONTRIBUTING.md) and [making a clock face](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+```++`scripts/test_web_browser.cjs` runs the browser checks with a local Playwright Chromium.+</details>++MIT, see [LICENSE](../LICENSE). Bundled fonts keep their SIL Open Font License notices in+`token_tv/web/`. · [한국어](../README.ko.md)diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..8aded76--- /dev/null+++ b/package.json@@ -0,0 +1,10 @@+{+ "name": "token-tv",+ "version": "0.1.0",+ "description": "Your Claude and Codex usage limits on a tiny Wi-Fi desk clock (launcher for the Python package)",+ "license": "MIT",+ "repository": "github:click6067-ship-it/token-tv",+ "bin": { "token-tv": "bin/token-tv.js" },+ "files": ["bin/", "token_tv/", "pyproject.toml", "README.md", "LICENSE"],+ "engines": { "node": ">=18" }+}diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 8a0cbea..a0323c0 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -192,3 +192,47 @@ class ConnectGuardTest(unittest.TestCase):connect.main()login.assert_not_called()self.assertIn('Keychain', out.getvalue())+++class StartTest(unittest.TestCase):+ def setUp(self):+ self.config = Path(tempfile.mkdtemp()) / 'config.json'++ def start(self, *extra):+ from token_tv import live+ with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/x'), \+ mock.patch.object(cli, 'login_state', side_effect=lambda p, h: 'yes' if p != 'grok' else 'no'), \+ mock.patch('token_tv.sources.logged_in_email',+ side_effect=lambda p, h: {'claude': '[email protected]', 'codex': None}[p]) as detect, \+ mock.patch.object(live, 'main') as run:+ code, out, err = run_cli('start', '--config', str(self.config), '--yes', '--no-browser', *extra)+ return code, out, err, detect, run++ def test_detects_signed_in_email_and_runs(self):+ code, out, _, detect, run = self.start('--device-url', '192.168.0.50')+ self.assertEqual(code, 0)+ data = json.loads(self.config.read_text())+ self.assertEqual([(a['provider'], a['email']) for a in data['accounts']], [('claude', '[email protected]')])+ self.assertEqual(data['device_url'], 'http://192.168.0.50') # bare IP is accepted+ run.assert_called_once()++ def test_existing_config_skips_detection(self):+ self.config.write_text(json.dumps({'accounts': [{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex',+ 'email': '[email protected]', 'source_home': '~/.codex'}]}))+ code, _, _, detect, run = self.start()+ self.assertEqual(code, 0)+ detect.assert_not_called()+ run.assert_called_once()++ def test_nothing_signed_in_explains_next_step(self):+ from token_tv import live+ with mock.patch.object(cli, 'cli_path', return_value=None), mock.patch.object(live, 'main') as run:+ code, _, err = run_cli('start', '--config', str(self.config), '--yes', '--no-browser')+ self.assertEqual(code, 1)+ self.assertIn('token-tv demo', err)+ self.assertFalse(self.config.exists())+ run.assert_not_called()+++def run_cli(*argv):+ return run(*argv)diff --git a/tests/test_display_styles.py b/tests/test_display_styles.pyindex 21ce7a2..7e35638 100644--- a/tests/test_display_styles.py+++ b/tests/test_display_styles.py@@ -109,3 +109,15 @@ class DisplayStyleTests(unittest.TestCase):if __name__ == '__main__':unittest.main()+++class ConfiguredServicesOnlyTest(unittest.TestCase):+ def test_only_services_with_accounts_get_a_row(self):+ import time+ from token_tv.display import STYLES, overview_rows, render_page+ from token_tv.sample import H, snapshot+ data = snapshot(time.time(), [('claude_a', 'CLAUDE A', 'claude', [('5H', 72, 2 * H)])])+ self.assertEqual([r['provider'] for r in overview_rows(data)], ['claude']) # no LOGIN rows for unused services+ for style in STYLES:+ self.assertTrue(render_page(data, style=style)) # every face copes with one row+ self.assertEqual(len(overview_rows({'accounts': {}})), 3) # empty config keeps the placeholdersdiff --git a/tests/test_web.py b/tests/test_web.pyindex 8031023..d863ba0 100644--- a/tests/test_web.py+++ b/tests/test_web.py@@ -66,5 +66,6 @@ class ThemesEndpointTests(unittest.TestCase):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)+ from token_tv.display import STYLES+ self.assertEqual({t['id'] for t in themes['themes'] if t['installed']}, set(STYLES)) # adding a face needs no test editself.assertIn('data-demo', (out / 'index.html').read_text())diff --git a/token_tv/cli.py b/token_tv/cli.pyindex a15d3d0..36a3937 100644--- a/token_tv/cli.py+++ b/token_tv/cli.py@@ -1,5 +1,6 @@"""token-tv: set up, check, preview and run TokenTV.+ token-tv start find your signed-in CLIs, ask for the clock, run (the easy way)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@@ -214,6 +215,59 @@ def demo(args):return 0+def start(args):+ """One command: find signed-in CLIs, confirm their emails, ask for the clock, then run."""+ from token_tv.sources import logged_in_email+ path = Path(args.config).expanduser()+ interactive = not args.yes and sys.stdin.isatty()+ if not path.exists():+ accounts = []+ for provider, (_, home, _, _) in PROVIDERS.items():+ if not cli_path(provider) or login_state(provider, home) == 'no':+ continue+ email = logged_in_email(provider, home)+ if not email:+ continue+ if interactive and not ask(f'Found {provider.title()} signed in as {email}. Use it? [Y/n]', 'y').lower().startswith('y'):+ continue+ accounts.append({'key': f'{provider}_a', 'alias': f'{provider.upper()} A', 'provider': provider,+ 'email': email, 'source_home': home})+ print(f'{provider.title()}: {email}')+ if not accounts:+ print('No signed-in Claude, Codex or Grok CLI found. Sign in to one (for example `claude`, then /login),\n'+ 'or look around first with: token-tv demo', file=sys.stderr)+ return 1+ device = args.device_url+ if device is None and interactive:+ device = ask('Clock address shown on the clock screen, e.g. 192.168.0.50 (blank = dashboard only)')+ if device and not device.startswith(('http://', 'https://')):+ device = 'http://' + device+ 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+ path.parent.mkdir(parents=True, exist_ok=True)+ with open(path, 'x') as handle:+ json.dump(config, handle, indent=2)+ handle.write('\n')+ print(f'Saved {path} (emails and paths only, no secrets).')+ if read_config(path) is None:+ return 1+ if not args.no_browser:+ import threading+ import webbrowser+ threading.Timer(1.5, webbrowser.open, ['http://127.0.0.1:8787']).start()+ print('Dashboard: http://127.0.0.1:8787 (Ctrl+C to stop)')+ from token_tv import live+ sys.argv = ['token-tv start', '--config', str(path), '--state-dir', str(path.parent / 'state')]+ live.main()+ 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:@@ -237,6 +291,10 @@ def main(argv=None):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')+ st = commands.add_parser('start', parents=[config], help='find your signed-in CLIs, ask for the clock, and run')+ st.add_argument('--device-url', help='clock address, e.g. 192.168.0.50')+ st.add_argument('--yes', action='store_true', help='accept every signed-in account without asking')+ st.add_argument('--no-browser', action='store_true', help='do not open the dashboard in a browser')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')@@ -263,7 +321,7 @@ def main(argv=None):if args.command is None:parser.print_help()return 0- return {'setup': setup, 'doctor': doctor, 'demo': demo}[args.command](args)+ return {'setup': setup, 'doctor': doctor, 'demo': demo, 'start': start}[args.command](args)if __name__ == '__main__':diff --git a/token_tv/connect.py b/token_tv/connect.pyindex 9949f99..9ea1ee8 100644--- a/token_tv/connect.py+++ b/token_tv/connect.py@@ -1,11 +1,11 @@-"""Sign in to one account's Mini-local CLI home, without changing defaults."""+"""Sign in to one account's own CLI home, without changing defaults."""import argparseimport osimport subprocessimport sysfrom pathlib import Path-from token_tv.sources import fetch_account, load_config, scoped_env+from token_tv.sources import exe, fetch_account, load_config, scoped_env# provider: (everyday CLI home, file present after login)DEFAULT_HOMES = {"claude": ("~/.claude", ".credentials.json"), "codex": ("~/.codex", "auth.json"),@@ -15,10 +15,10 @@ DEFAULT_HOMES = {"claude": ("~/.claude", ".credentials.json"), "codex": ("~/.coddef login_command(account, browser=False):provider = account["provider"]if provider == "claude":- return ["claude", "auth", "login", "--claudeai", "--email", account["email"]]+ return [exe("claude"), "auth", "login", "--claudeai", "--email", account["email"]]if provider == "codex":- return ["codex", "login"] if browser else ["codex", "login", "--device-auth"]- return [os.environ.get("TOKEN_TV_GROK_BIN", "grok"), "login", "--device-auth"]+ return [exe("codex"), "login"] if browser else [exe("codex"), "login", "--device-auth"]+ return [exe(os.environ.get("TOKEN_TV_GROK_BIN", "grok")), "login", "--device-auth"]def main():@@ -41,7 +41,7 @@ def main():parser.error("Choose one of the listed accounts")account = next((a for a in accounts if a["key"] == key), None)if account is None or not account.get("source_home"):- parser.error("An account with a Mini-local CLI home is required")+ parser.error("An account with its own CLI home (source_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@@ -65,7 +65,7 @@ def main():print("Verification: " + row["status"], flush=True)if row["status"] not in ("ok", "quota_unavailable") or not row["identity_verified"]:raise SystemExit(1)- print("Account verified. The running Mini display will use this login on its next poll.", flush=True)+ print("Account verified. A running TokenTV picks up this login on its next poll.", flush=True)if __name__ == "__main__":diff --git a/token_tv/display.py b/token_tv/display.pyindex 6c27473..2b1f1ac 100644--- a/token_tv/display.py+++ b/token_tv/display.py@@ -46,7 +46,9 @@ def font(size, bold=False, mono=False):def overview_rows(snapshot):"""Select one visible account per provider, in configured order, without merging quotas."""rows = []- for provider in PROVIDERS:+ # Show only the services this person set up; with no accounts at all, keep every placeholder row.+ present = [p for p in PROVIDERS if any(row['provider'] == p for row in snapshot['accounts'].values())]+ for provider in present or PROVIDERS:accounts = [dict(row, key=key) for key, row in snapshot['accounts'].items()if row['provider'] == provider]available = [row for row in accounts if row['status'] == 'ok' and row['windows']]@@ -54,7 +56,12 @@ def overview_rows(snapshot):rows.append((available or previous or accounts or [{'key': provider, 'provider': provider, 'alias': provider.upper() + ' A','status': 'auth_required', 'windows': []}])[0])- return rows+ return rows[:3] # every clock face is laid out for at most three rows+++def row_shift(count, pitch):+ """Vertical offset that centres `count` rows on a screen laid out for three."""+ return (3 - count) * pitch // 2def pages(snapshot):@@ -191,8 +198,9 @@ def pixel_text(draw, xy, text, scale=1, color=TEXT, align='left'):def render_pixel(snapshot):image = Image.new('RGB', (240, 240), BACKGROUND)draw = ImageDraw.Draw(image)- for index, row in enumerate(overview_rows(snapshot)):- y = 8 + index * 78+ rows = overview_rows(snapshot)+ for index, row in enumerate(rows):+ y = 8 + index * 78 + row_shift(len(rows), 78)if index:for x in range(14, 227, 4):draw.point((x, y - 6), fill=RULE)diff --git a/token_tv/sources.py b/token_tv/sources.pyindex b03d4b4..a7192df 100644--- a/token_tv/sources.py+++ b/token_tv/sources.py@@ -4,6 +4,7 @@ import jsonimport osimport queueimport re+import shutilimport subprocessimport sysimport threading@@ -17,6 +18,11 @@ from token_tv.usage import normalize_claude, normalize_codex, normalize_grok, tifrom token_tv.display import STYLES+def exe(name):+ """Full path of a CLI. On Windows npm installs `claude`/`codex` as .cmd shims that a bare name can't start."""+ return shutil.which(name) or name++class SourceError(Exception):def __init__(self, code):self.code = code@@ -165,7 +171,7 @@ def claude_payload(account):raise# The CLI owns refresh/rotation. No manual refresh-token writes.env = scoped_env("claude", root)- subprocess.run(["claude", "-p", "Reply only OK.", "--tools", "",+ subprocess.run([exe("claude"), "-p", "Reply only OK.", "--tools", "","--no-session-persistence", "--max-turns", "1"],env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,timeout=60)@@ -192,7 +198,7 @@ def codex_payload(account):if not (Path(account["source_home"]).expanduser() / "auth.json").is_file():raise SourceError("auth_required")env = scoped_env("codex", Path(account["source_home"]).expanduser())- rpc = RPC(["codex", "app-server"], env)+ rpc = RPC([exe("codex"), "app-server"], env)try:rpc.call("initialize", {"clientInfo": {"name": "token_tv", "title": "TokenTV", "version": "0.1.0"}, "capabilities": {}})rpc.process.stdin.write('{"method":"initialized","params":{}}\n')@@ -213,7 +219,7 @@ def grok_payload(account):raise SourceError("auth_required")env = scoped_env("grok", root)command = os.environ.get("TOKEN_TV_GROK_BIN", "grok")- rpc = RPC([command, "agent", "--no-leader", "stdio"], env)+ rpc = RPC([exe(command), "agent", "--no-leader", "stdio"], env)try:rpc.call("initialize", {"protocolVersion": 1, "clientCapabilities": {"fs": {"readTextFile": False, "writeTextFile": False}, "terminal": False}})@@ -227,6 +233,32 @@ def grok_payload(account):rpc.close()+def logged_in_email(provider, home):+ """The email of the account already signed in to this CLI home, or None. Prints nothing secret."""+ root = Path(home).expanduser()+ try:+ if provider == "claude":+ headers = {"Authorization": "Bearer " + claude_token(root), "Accept": "application/json",+ "User-Agent": "claude-code/2.1.287", "anthropic-beta": "oauth-2025-04-20"}+ return email_from_profile(json_get("https://api.anthropic.com/api/oauth/profile", headers))+ if provider == "codex":+ if not (root / "auth.json").is_file():+ return None+ rpc = RPC([exe("codex"), "app-server"], scoped_env("codex", root))+ try:+ rpc.call("initialize", {"clientInfo": {"name": "token_tv", "title": "TokenTV", "version": "0.1.0"},+ "capabilities": {}})+ rpc.process.stdin.write('{"method":"initialized","params":{}}\n')+ rpc.process.stdin.flush()+ identity = rpc.call("account/read", {"refreshToken": True}).get("account") or {}+ return identity.get("email") if identity.get("type") == "chatgpt" else None+ finally:+ rpc.close()+ return grok_identity({"source_home": str(root)})+ except (SourceError, OSError, ValueError, KeyError, TypeError, HTTPError, subprocess.SubprocessError):+ return None++def grok_identity(account):data = json.loads((Path(account["source_home"]).expanduser() / "auth.json").read_text())emails = set()diff --git a/token_tv/space.py b/token_tv/space.pyindex 30d36ea..0b15d71 100644--- a/token_tv/space.py+++ b/token_tv/space.py@@ -95,14 +95,14 @@ def ease(p):return p * p * (3 - 2 * p)-def schedule(rnd):+def schedule(rnd, bots=3):"""Two or three events at irregular, non-overlapping times inside the loop."""events, start = [], rnd.uniform(0.6, 2.5)for kind in rnd.sample(EVENTS, rnd.choice((2, 3))):duration = {'dash': 1.6, 'hop': 0.9, 'spin': 0.9, 'sparkle': 1.3, 'shooting_star': 1.0, 'huddle': 2.2}[kind]if start + duration > 9.6:break- events.append({'kind': kind, 'start': start, 'end': start + duration, 'bot': rnd.randrange(3),+ events.append({'kind': kind, 'start': start, 'end': start + duration, 'bot': rnd.randrange(bots),'y': rnd.uniform(20, 120), 'angles': [rnd.uniform(0, 2 * math.pi) for _ in range(6)]})start += duration + rnd.uniform(0.9, 3.2)return events@@ -127,8 +127,8 @@ def positions(t, paths, events):elif event['kind'] == 'hop':points[event['bot']][1] -= 15 * abs(math.sin(2 * math.pi * p))for _ in range(10): # a bubble and its tag form one box; resolve box overlaps- for a in range(3):- for b in range(a + 1, 3):+ for a in range(len(points)):+ for b in range(a + 1, len(points)):dx, dy = points[b][0] - points[a][0], points[b][1] - points[a][1]ox, oy = BOX[0] - abs(dx), BOX[1] - abs(dy)if ox > 0 and oy > 0:@@ -177,8 +177,9 @@ def render_frames(snapshot, now=None):rows = readings(snapshot)rnd = random.Random(seed_for(rows, now))paths = [(rnd.uniform(60, 82), rnd.uniform(24, 40), rnd.choice((1, 2)), 1,- rnd.uniform(0, 6.3), rnd.uniform(0, 6.3), 120, cy) for cy in (54, 110, 160)]- events = schedule(rnd)+ rnd.uniform(0, 6.3), rnd.uniform(0, 6.3), 120, cy)+ for cy in {1: (106,), 2: (76, 136)}.get(len(rows), (54, 110, 160))]+ events = schedule(rnd, len(rows))sky, twinkles = backdrop()frames = []for f in range(FRAMES):@@ -195,7 +196,7 @@ def render_frames(snapshot, now=None):for k, color in enumerate((STARS[2], STARS[1], STARS[0])):draw.line((hx - 7 * k, hy - 1.7 * k, hx - 7 * (k + 1), hy - 1.7 * (k + 1)), fill=color)points = positions(t, paths, events)- order = sorted(range(3), key=lambda i: points[i][1])+ order = sorted(range(len(rows)), key=lambda i: points[i][1])for i in order:provider, used, old = rows[i]x, y = round(points[i][0]), round(points[i][1])diff --git a/token_tv/themes.py b/token_tv/themes.pyindex 2fb5902..cd7b892 100644--- a/token_tv/themes.py+++ b/token_tv/themes.py@@ -12,7 +12,7 @@ from pathlib import Pathfrom PIL import Image, ImageDraw, ImageFilter, ImageFontfrom token_tv.display import (- STATUS, account_label, mascot, overview_rows, primary_window, quota_period, time_left,+ STATUS, account_label, mascot, overview_rows, primary_window, quota_period, row_shift, time_left,)WEB = Path(__file__).with_name('web')@@ -231,8 +231,9 @@ def render_digital(snapshot):for y in range(0, SIZE, 3):cv.back.line((0, y, SIZE, y), fill='#04130d')vt, seg = (lambda s: face('vt323.woff2', s)), (lambda s: face('dseg7-classic-bold.woff2', s))- for index, row in enumerate(overview_rows(snapshot)):- y = ROWS[index]+ rows = overview_rows(snapshot)+ for index, row in enumerate(rows):+ y = ROWS[index] + row_shift(len(rows), ROWS[1] - ROWS[0])used, period, old, reset = reading(row)cv.back.rectangle((4, y, 235, y + ROW_H - 1), fill='#03100b', outline=line)cv.back.line((5, y + 25, 234, y + 25), fill='#0f3a2c')@@ -264,8 +265,9 @@ def render_neon(snapshot):for x in range(4, SIZE, 8):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]+ rows = overview_rows(snapshot)+ for index, row in enumerate(rows):+ y = ROWS[index] + row_shift(len(rows), ROWS[1] - ROWS[0])a, a2 = ACCENT['neon'][row['provider']]used, period, old, reset = reading(row)box = (5, y + 1, 234, y + ROW_H - 2)@@ -351,8 +353,9 @@ def render_retro(snapshot):x, y = rnd.randrange(0, SIZE), rnd.randrange(0, SIZE)cv.back.point((x, y), fill=rnd.choice(('#ffffff', '#b9c8ff', '#ffe9a8')))title = lambda s: face('press-start-2p.ttf', s)- for index, row in enumerate(overview_rows(snapshot)):- y = ROWS[index]+ rows = overview_rows(snapshot)+ for index, row in enumerate(rows):+ y = ROWS[index] + row_shift(len(rows), ROWS[1] - ROWS[0])a, a2 = ACCENT['retro'][row['provider']]used, period, old, reset = reading(row)pixel_scene(cv, row['provider'], y)@@ -385,8 +388,9 @@ def render_hud(snapshot):cv.back.line((g, 0, g, SIZE), fill=color)cv.back.line((0, g, SIZE, g), fill=color)chakra = lambda s, bold=True: face('chakra-petch-700.woff2' if bold else 'chakra-petch-500.woff2', s)- for index, row in enumerate(overview_rows(snapshot)):- y = ROWS[index]+ rows = overview_rows(snapshot)+ for index, row in enumerate(rows):+ y = ROWS[index] + row_shift(len(rows), ROWS[1] - ROWS[0])a, a2 = ACCENT['hud'][row['provider']]used, period, old, reset = reading(row)cut = 10diff --git a/token_tv/web/app.js b/token_tv/web/app.jsindex 2b9eaf7..185f820 100644--- a/token_tv/web/app.js+++ b/token_tv/web/app.js@@ -185,13 +185,14 @@ function providerCard(provider, accounts) {let when = el('span', '—', 'stat-v');if (checked) {const d = new Date(checked * 1000); when = el('time', d.toLocaleTimeString('en-GB', {hour:'2-digit', minute:'2-digit'}), 'stat-v'); when.dateTime = d.toISOString(); when.title = d.toLocaleString('en-GB')}const foot = el('div', undefined, 'card-foot');- foot.append(stat('Account', a.alias || '—'), stat('Window', primary ? period(primary) : '—'), stat('Source', a.source === 'mini' ? 'Mini' : a.source ? 'Laptop link' : '—'), stat(stale ? 'Last good' : 'Checked', when), stat('Status', el('span', offline ? 'OFFLINE · Previous value' : STATUS[a.status] || 'Unknown', 'row-status stat-v'), 'stat-status'));+ foot.append(stat('Account', a.alias || '—'), stat('Window', primary ? period(primary) : '—'), stat('Source', a.source === 'mini' ? 'This computer' : a.source ? 'Linked snapshot' : '—'), stat(stale ? 'Last good' : 'Checked', when), stat('Status', el('span', offline ? 'OFFLINE · Previous value' : STATUS[a.status] || 'Unknown', 'row-status stat-v'), 'stat-status'));card.append(foot); shell.append(card); return shell;}function renderAccounts() {if (!snapshot) return;const focused = document.activeElement?.dataset?.account, rows = Object.values(snapshot.accounts || {}), fragment = document.createDocumentFragment();- for (const provider of PROVIDERS) fragment.append(providerCard(provider, rows.filter(a => a.provider === provider)));+ const used = PROVIDERS.filter(p => rows.some(a => a.provider === p)); // only services that are set up+ for (const provider of used.length ? used : PROVIDERS) fragment.append(providerCard(provider, rows.filter(a => a.provider === provider)));$('#providers').replaceChildren(fragment);const reporting = offline ? 0 : rows.filter(a => a.status === 'ok' && (a.windows || []).some(w => Number.isFinite(w.used_percent))).length;$('#account-count').textContent = pad(rows.length); $('#reporting-count').textContent = pad(reporting);@@ -211,13 +212,13 @@ async function update() {const data = DEMO ? demoSnapshot(await r.json()) : await r.json(); if (!data.accounts || !Number.isFinite(data.updated_at)) throw Error();snapshot = data; offline = false;const staleCount = Object.values(data.accounts).filter(a => a.status === 'stale').length;- $('#connection').textContent = DEMO ? 'Demo · sample data' : staleCount ? `${staleCount} stale · Live server` : 'Live from Mini';+ $('#connection').textContent = DEMO ? 'Demo · sample data' : staleCount ? `${staleCount} stale · Live server` : 'Live';$('#notice').hidden = !staleCount; $('#notice').textContent = staleCount + ' account' + (staleCount === 1 ? ' has' : 's have') + ' an older reading. Check the selected account’s source and last successful update.';$('#updated').textContent = data.updated_at ? 'Server checked ' + new Date(data.updated_at * 1000).toLocaleTimeString('en-GB') : 'Waiting for first reading';$('#signal').dataset.strength = staleCount ? '2' : '3';} catch {offline = true; $('#connection').textContent = 'Server offline'; $('#notice').hidden = false; $('#signal').dataset.strength = '0';- $('#notice').textContent = snapshot ? 'Connection lost. Showing the last received readings as OLD.' : 'Cannot reach Mini. Retry after the connection is restored.';+ $('#notice').textContent = snapshot ? 'Connection lost. Showing the last received readings as OLD.' : 'Cannot reach TokenTV. Is token-tv still running?';if (!snapshot) $('#providers').replaceChildren(el('p', 'No usage data received.', 'loading'));} finally {polling = false; document.body.dataset.offline = String(offline); renderAccounts()}}