Skip to content

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

TokenTV: live AI usage on a $5 desk clock

click6067-ship-ita7670ab58334
diff --git a/.gitignore b/.gitignore
index 421c27d..77d75a5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,6 @@
/vendor/
__pycache__/
*.pyc
+/.runtime/
+/.venv/
+*.egg-info/
diff --git a/BRIEF.md b/BRIEF.md
deleted file mode 100644
index e90b5cf..0000000
--- a/BRIEF.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# TokenTV — $5 AliExpress 시계를 AI 사용량 물리 대시보드로
-
-## 목표 (왜)
-GitHub 스타/레딧 바이럴이 목적. 훅은 "6천원짜리 알리 날씨시계가 Claude/Codex 사용량을 보여준다".
-사용자는 이미 기기를 갖고 있고 (`~/ghq/.../token-tv`가 작업 디렉터리), 과거에 한 번 비슷한 걸 만들어봤음
-(smalltv-mod 포크 + ai-usage-taskbar-widget에서 쿼터 받아 푸시) — 다만 디자인(AI생성 이미지 기반)이 별로였음.
-
-## 하드웨어 현황 (중요: 아직 준비 안 됨)
-- GeekMagic SmallTV 계열 시계, 현재 Mini PC에 USB로 전원만 연결된 상태.
-- 아직 어떤 WiFi에도 붙어있지 않음 (사용자가 폰으로 핫스팟→집 WiFi 전환 작업을 곧 할 예정).
-- **지금 단계에서는 기기 IP/실물 테스트가 불가능** — 그 전까지 할 수 있는 소프트웨어 작업만 먼저 진행.
-- 기기가 WiFi에 붙으면 사용자가 IP를 알려줄 것 — 그 전까지는 이 작업을 TODO로 남겨두고 블로킹하지 말 것.
-
-## 참고 레포 (반드시 먼저 clone해서 실제 코드 읽고 시작할 것 — 추측으로 짜지 말 것)
-1. https://github.com/giovi321/smalltv-mod — 펌웨어 베이스 (ESP8266/SmallTV-ultra/ESP32-C2/ESP32 지원,
- WiFi OTA 지원, Claude usage meter 모드 이미 있음). 이 레포의 구조·OTA 업데이트 절차·기존 Claude 모드
- 코드를 먼저 읽고, 거기에 얹는 방식으로 접근.
-2. https://github.com/sallyHADEV/ai-usage-taskbar-widget — 멀티계정 인증 + 사용량 조회 로직 참고용.
- 여기서 Claude/Codex 등 provider별 사용량을 어떻게 긁어오는지 확인하고 재사용 가능한 부분 파악.
-
-## 아키텍처 (이전 기획 논의에서 정리된 방향)
-```
-PC(Mini) 데몬 ─(provider adapter: claude/codex/...)→ normalized JSON ─(LAN, HTTP)→ SmallTV(펌웨어)
-```
-- API 키/세션 토큰은 기기(ESP)에 절대 넣지 않는다 — Mini의 데몬에만 둔다.
-- 데몬은 provider별로 플러그인 구조 (`providers/claude.ts`, `providers/codex.ts` 등 — 언어는 기존 참고
- 레포들과 맞춰서 판단, 억지로 TS 고집할 필요 없음).
-- 기기 쪽은 "dumb display"로 유지 — 가능하면 smalltv-mod의 기존 OTA/웹UI 인터페이스를 그대로 활용하고
- 새 커스텀 펌웨어 빌드를 최소화 (논의에서 나온 "무플래싱에 가까운" 방향과, 사용자가 이미 자체 포크로
- 진행한 "펌웨어 뜯어고침" 방향 중, smalltv-mod 코드를 실제로 읽어본 뒤 더 간단한 쪽으로 판단해도 됨 —
- 단, 이 판단 근거를 나중에 설명할 수 있게 남겨둘 것).
-- 다계정 지원 필수 (예: Claude personal/work 등 alias로 구분해서 화면에 표시).
-
-## 지금 할 일 (기기 연결 전에 가능한 범위)
-1. `smalltv-mod`, `ai-usage-taskbar-widget` 를 `vendor/` 또는 `reference/` 하위에 clone해서 코드 구조 파악
- (이 디렉터리는 git submodule이 아니라 그냥 참고용 — .gitignore 처리하거나 별도 clone 경로 사용).
-2. 두 레포를 분석한 결과를 바탕으로, 이 프로젝트의 구체적 구현 계획(데몬 언어/구조, 펌웨어에 얹을 방식,
- provider 플러그인 인터페이스)을 `PLAN.md`로 작성. 추측 금지 — 읽은 코드 기반으로만 작성.
-3. Mini 데몬 쪽 스캐폴딩(디렉터리 구조, provider interface, mock JSON 응답)까지는 기기 없이도 구현/테스트 가능 —
- 거기까지 진행.
-4. 기기 플래싱/실제 통신이 필요한 부분은 명확히 TODO로 표시하고 멈출 것 — 기기 IP를 받기 전까지는
- 추측으로 "이 IP일 것이다" 하고 진행하지 말 것.
-
-## 하지 말 것
-- 존재하지 않는 API/엔드포인트를 추측해서 구현하지 말 것 — 반드시 clone한 레포의 실제 코드를 읽고 확인.
-- 기기에 API 키/크리덴셜 저장하는 구조로 설계하지 말 것.
-- 커밋/푸시는 아직 하지 말 것 (로컬 작업만, 사용자 확인 후 리모트 결정).
-
-## 보고
-작업 끝나면 무엇을 clone했는지, PLAN.md에 뭘 썼는지, 스캐폴딩 범위, 남은 블로커(기기 연결 대기 등)를
-간결하게 정리해서 알려줘.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..7004dd8
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 click6067-ship-it
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/PLAN.md b/PLAN.md
deleted file mode 100644
index 4da4bb1..0000000
--- a/PLAN.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# TokenTV 구현 계획
-
-## 근거와 현재 결정
-
-참고 코드는 `vendor/`에 별도 clone했고 Git 추적에서 제외했다.
-
-| 저장소 | 확인한 코드 | 결론 |
-| --- | --- | --- |
-| `giovi321/smalltv-mod` @ `32d4832` | `src/features/usage/UsageClient.cpp:30`, `src/WebPortal.cpp:370`, `src/features/theme/ThemeDataClient.cpp:91`, `docs/src/content/docs/features/themes.md:163` | 기본 Claude 모드는 `{s,sr,w,wr,st,ok}`의 **단일** 사용량만 처리한다. `/api/usage` POST도 같은 단일 형식이다. 다계정은 테마의 JSON 데이터 바인딩으로 구현한다. |
-| `giovi321/smalltv-mod` @ `32d4832` | `docs/src/content/docs/getting-started/flashing.md:14`, `src/WebPortal.cpp:513` | 설치 방법은 보드에 따라 다르다. ESP8266 일부와 Pro는 stock 웹 OTA가 가능하지만 ESP32-C2는 초기 설치에 USB 직렬 플래시가 필요하다. 현재 보드 미확인. |
-| `sallyHADEV/ai-usage-taskbar-widget` @ `ac348ab` | `src/services/claude-local-client.ts:14`, `src/services/codex-app-server-client.ts:273`, `src/services/account-store.ts:32`, `src/services/usage-push.ts:4` | Claude는 로컬 CLI 세션 파일과 usage 조회를, Codex는 app-server의 `account/read`와 `account/rateLimits/read`를 사용한다. 위젯의 계정 목록은 있으나 Claude 로컬 소스가 전역 자격 증명을 공유하므로 personal/work의 독립 사용량을 이 코드만으로 보장하지 못한다. 위젯의 push 형식(`screen`, `items`)도 smalltv-mod의 `/api/usage` 형식과 호환되지 않는다. |
-
-따라서 첫 화면 구현은 **smalltv-mod 정규 이미지 + `.stheme` 사용자 테마 + Mini HTTP 데몬**으로 한다. 테마는 펌웨어 재빌드 없이 URL에서 JSON 필드를 읽는다. Claude 기본 모드는 단일 계정 대안으로만 남긴다. 모델 확인 전에는 이미지와 설치 절차를 확정하지 않는다.
-
-## 데이터 흐름
-
-1. Mini 데몬에 `key`, `alias`, `provider`, 추후 `source`를 가진 계정을 등록한다. `key`는 테마 URL에 쓰는 안정적인 영숫자 ID이고 `alias`는 화면 표기명이다. 서로 다른 계정은 서로 다른 인증 소스를 가져야 한다.
-2. provider adapter `fetch(account) -> Usage`가 세션/주간 사용률, 리셋까지 남은 분, 상태를 반환한다. 값이 없으면 `null`로 표현한다. 실패를 0% 사용으로 위장하지 않는다.
-3. `GET /snapshot/<key>`는 한 계정의 작은 JSON을 제공한다. 테마는 계정당 data source 하나를 두고 `alias`, `status`, `session_percent`, `weekly_percent` 등의 scalar path를 바인딩한다. 전체 목록 `GET /snapshot`은 로컬 점검용이다.
-4. smalltv-mod 테마의 제한은 source 최대 4개, source당 field 최대 8개, 응답 최대 2 KiB, 최소 갱신 간격 10초다 (`docs/src/content/docs/features/themes.md:163`). 그러므로 첫 테마는 최대 4개 계정을 한 화면에 고정 배치한다. 초과 계정의 페이지 전환은 후속 설계가 필요하다.
-
-현재 스캐폴드는 Python 3 표준 라이브러리로 작성했다. Mini에서 의존성 없이 실행 가능하고, HTTP 서버와 provider 인터페이스를 빠르게 검증할 수 있다. 위젯의 Electron/Windows 전용 코드를 그대로 가져오지 않는다. 실데이터 adapter는 소스별 동작과 현재 인증 방식 확인 후 별도 구현한다.
-
-## 단계
-
-1. **지금: 완료** — 데몬 모듈, `Provider` 인터페이스, 구별되는 3개 mock 계정, `/snapshot` 및 `/snapshot/<key>` JSON 응답, 로컬 테스트. mock 값은 `status: "mock"`으로 명시한다. 인증 정보는 응답에 없다. 기본 바인드는 `127.0.0.1`이다.
-2. **Mini 실데이터** — Claude/Codex adapter를 추가한다. 소스별 계정 구분 방법부터 검증한다. 다른 OS 계정/별도 세션 경로 등이 필요할 수 있으나 지금은 미검증이다. 실제 인증 파일의 원문을 로그/응답/저장소에 싣지 않는다. provider 조회 실패와 오래된 데이터를 `error`/`stale`로 노출하고 갱신 시각을 보존한다. 현재 API 동작은 구현 시 재확인한다.
-3. **화면** — `smalltv-mod`의 `examples/themes/live-status/theme.json` 형식을 토대로 240×240 테마를 만든다. 계정 alias를 문자로 표시하고 사용률을 수치와 막대로 함께 표시한다. `tools/smalltv_theme.py validate`와 오프라인 preview로 디자인을 확인한다. URL은 확인된 Mini LAN 주소로 구성한다.
-4. **기기 연결 후 TODO** — WiFi 연결 및 IP 확보, 실제 MCU/모델 확인, stock 펌웨어 백업 가능 여부와 설치 경로 확인, 해당 모델에 맞는 정규 이미지 설치, 테마 업로드, 기기에서 Mini URL 접근과 JSON 렌더 실측. ESP32-C2라면 초기 설치는 OTA가 아니라 USB 직렬 플래시 경로다. 실제 IP와 모델을 받기 전에는 플래싱하지 않는다.
-
-## 판정 기준
-
-- mock 단계: 서로 다른 3개 alias가 서로 다른 키로 조회되고, JSON에 토큰/자격 증명이 없고, 응답이 2 KiB 이하다.
-- 실데이터 단계: 같은 provider의 두 계정이 실제로 서로 다른 세션에서 조회됨을 확인한다. 검증 전에는 다계정 실사용 완료로 표시하지 않는다.
-- 기기 단계: 실제 240×240 화면에 alias와 사용률이 구별되어 렌더되고, 실패/오래된 값이 정상값으로 오인되지 않는다.
-
-## 미해결 사항
-
-- 기기 IP, 정확한 보드와 현재 firmware, Mini에서 접근 가능한 LAN 주소가 아직 없다.
-- 실계정별 Claude/Codex 인증 소스는 아직 검증하지 않았다. reference 위젯만으로는 다계정 독립 조회가 성립하지 않는다.
-- 테마 JSON URL은 LAN HTTP다. 사용량 수치만 노출하며 Mini의 자격 증명은 서버 안에 둔다. LAN 공개 시 접근 제어 방식은 실제 네트워크 확인 후 결정한다.
diff --git a/README.ko.md b/README.ko.md
new file mode 100644
index 0000000..86ebb3b
--- /dev/null
+++ b/README.ko.md
@@ -0,0 +1,164 @@
+# TokenTV
+
+[English README](README.md)
+
+여러 AI 계정의 사용량을 240×240 책상 시계와 브라우저에서 확인합니다.
+계정별 인증 홈을 분리하고, 실제 조회 실패와 오래된 값을 표시합니다.
+
+## 실행
+
+Python 3.10+와 Pillow가 필요합니다.
+
+```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
+```
+
+브라우저: `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**에서 시계 화면 11종을 미리 보고 고릅니다. 새 6종
+**Digital / Neon / Pixel Retro / Modern / Sakura / Sci-Fi HUD**는 같은 이름의 웹 테마와
+같은 글꼴·장식·게이지를 씁니다. **Apply to clock**을 누르면 선택을 저장하고 같은 계정
+캐시로 기기에 전송합니다. 미리보기만 선택하면 시계에는 적용되지 않습니다.
+
+| Theme | 240×240 화면 표현 |
+|---|---|
+| Digital | 녹색 형광 터미널, 7세그먼트 숫자(꺼진 칸 표시), 호박색 리셋 시간 |
+| Neon | 발광 카드 테두리, 아이콘 웰, 흰 숫자와 공급자 색 번짐, 둥근 칸 게이지 |
+| Pixel Retro | 픽셀 프레임, 공급자별 픽셀 풍경, 마스코트, HP 블록 게이지 |
+| Modern | 차분한 카드, 큰 숫자, 세로 구분선과 리셋 열 |
+| Sakura | 밝은 종이색, 세리프 숫자, 꽃잎 장식, 분홍 칸 게이지 |
+| Sci-Fi HUD | 모서리를 깎은 발광 프레임, 기울어진 칸 게이지 |
+
+기존 Pixel / Clean / Arcade / Columns / Orbit도 같은 목록에서 고를 수 있습니다.
+각 스타일은 Claude·Codex·Grok 한 계정과 10% 단위 10칸 게이지를 표시합니다.
+설정의 `display_style`은 `digital`, `neon`, `retro`, `modern`, `sakura`, `hud`와 기존 5개 값을 지원하며 재시작 후에도 유지됩니다. 미설정 기본값은 기존 `pixel`입니다.
+숫자는 테마 내 공통 중성색입니다. Sakura는 짙은 회색, 나머지는 밝은 회색입니다.
+로고 색은 공급자별로 유지하며 게이지는 0–49% / 50–79% / 80–89% / 90–100% 구간마다 같은 색 계열의 두 색 그라데이션으로 표시합니다.
+색만으로 상태를 전달하지 않으며 실제 숫자, 칸 수, 미인증/오래된 값 표기를 함께 제공합니다.
+
+![새 시계 화면 6종의 실제 240×240 이미지(예시 데이터)](docs/images/clock-faces.png)
+
+새 6종은 참고 이미지를 바탕으로 코드로 그렸습니다. 원본 이미지의 가상 통계나 정적인 숫자는 포함하지 않습니다.
+이미지를 자동으로 테마로 바꾸는 기능이나 테마 편집기는 현재 구현돼 있지 않습니다.
+
+## 인증과 사용률
+
+설정에는 계정 별칭, 예상 이메일, 공급자, 공식 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로 인증 갱신을 시도합니다.
+이 과정은 도구를 끈 짧은 확인 응답 하나를 요청하므로 구독 사용량을 소량 소비할 수 있습니다.
+인증 파일의 토큰을 직접 수정하거나 다른 머신으로 복사하지 않습니다.
+
+## 시계 연결
+
+확인된 경로는 SD_PRO 웹 UI의 `/theme/list`, `/photo/list`, `/photo/upload`입니다.
+설정에 `"device_url": "http://<clock-ip>"`를 추가하면 사진 테마를 사용합니다.
+기기 펌웨어를 바꾸지 않습니다. 기존 사진 파일은 보존하고 선택 상태만 변경합니다.
+원래 테마와 사진 선택 상태는 `.runtime/display-original.json`에 저장됩니다.
+
+복원 전 데몬을 정지한 뒤 실행합니다.
+
+```bash
+python3 -m token_tv.live --config .runtime/config.json --restore-display
+```
+
+사진 API가 없는 다른 펌웨어는 아직 실기기로 검증하지 않았습니다.
+
+## 다른 머신의 기존 인증 사용
+
+Mini에 인증이 아직 없으면 `token_tv.bridge`로 노트북에서 검증한 정규화 JSON만
+SSH로 보낼 수 있습니다. 설정의 `snapshot_file`이 해당 파일을 가리키도록 합니다.
+그 계정은 화면에 노트북 연동으로 표시되며 15분 이상 갱신되지 않으면 오래된 값이 됩니다.
+이 구성은 노트북이 켜져 있어야 동작합니다.
+
+Mini 설정에 `source_home`과 `fallback_snapshot_file`을 함께 지정하면 Mini 로그인을
+우선 사용하고, 인증이 없을 때만 노트북 조회로 대체합니다. 이메일 불일치는 대체로 숨기지 않습니다.
+Mini의 해당 계정에 로그인하면 다음 5분 조회부터 노트북 의존성이 없어집니다.
+
+```bash
+# Mini의 프로젝트 디렉터리에서 계정을 선택합니다.
+python3 -m token_tv.connect --config .runtime/config.json
+```
+
+인증번호는 로그인 터미널 또는 공식 브라우저 화면에 입력합니다. 제품의 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"`으로 제공하며 실제 사용량과 구별됩니다.
+
+### Six web appearances
+
+The live web dashboard provides **Digital Terminal, Neon Cyberpunk, Pixel Retro,
+Modern Minimal, Sakura Blossom, 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 eleven 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/`; `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, Cormorant Garamond, 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 six 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/README.md b/README.md
index d2c7bd2..4ad331f 100644
--- a/README.md
+++ b/README.md
@@ -1,26 +1,103 @@
# TokenTV
-Mini 데몬 스캐폴드와 구현 계획은 [PLAN.md](PLAN.md)에 있다. 현재 응답은 **mock 데이터**이며 실제 계정 사용량을 조회하지 않는다.
+**A $5 AliExpress weather clock, turned into a live usage meter for your AI subscriptions.**
-Python 3.10+에서 실행:
+Claude · Codex · Grok — several accounts per provider — no firmware flashing.
+
+<p align="center">
+ <img src="docs/images/clock-faces.gif" width="360" alt="TokenTV cycling through its clock faces (sample data)">
+</p>
+
+TokenTV runs on a small always-on computer such as a mini PC or home server. It reads
+how much of each subscription window you have used, draws a 240×240 picture and uploads
+it to a GeekMagic SmallTV-style desk clock through the clock's own photo page. The clock
+keeps its stock firmware and never receives a password, token or cookie.
+
+![Six clock faces rendered by TokenTV (sample data)](docs/images/clock-faces.png)
+
+## What you get
+
+- **On the clock:** one account per provider, its most-used quota window, the time until
+ that window resets, and a ten-cell gauge where each cell is 10%. The gauge colour changes
+ as you approach the limit.
+- **11 clock faces:** Digital, Neon, Pixel Retro, Modern, Sakura and Sci-Fi HUD, plus
+ Pixel, Clean, Arcade, Columns and Orbit. Pick one from the web page.
+- **A web dashboard** with six matching themes, every account (A/B/C…) and every reported
+ window: 5-hour, weekly or CLI budget.
+- **Several accounts per provider.** Each account keeps its own CLI login home, so a work
+ and a personal Claude never mix.
+- **Honest states.** Old readings are marked OLD, failed logins say so, and missing data
+ shows a dash, never a fake 0%.
+
+![The web dashboard in its six themes (sample data)](docs/images/web-themes.png)
+
+## Hardware
+
+- A GeekMagic **SmallTV**-style 240×240 Wi-Fi desk clock whose stock firmware has a photo
+ album page. The author's unit 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 of the
+ services you use.
+
+The stock-firmware photo API (`/theme/list`, `/photo/list`, `/photo/upload`) is verified
+on the author's clock. Clones with other firmware are untested.
+
+## How usage is read
+
+| Provider | Source | What the number means |
+|---|---|---|
+| Claude | The Claude Code CLI's own OAuth login (profile and usage) | Share of the 5-hour and weekly limits **used** |
+| Codex | The official `codex app-server` account and rate-limit RPC | Share of each reported window **used** |
+| Grok | The Grok CLI billing RPC (experimental) | Share of the CLI **billing budget** used, not web chat limits |
+
+TokenTV checks that every login belongs to the email you configured and refuses CLI homes
+that mix accounts. It polls every five minutes; opening the dashboard does not add requests.
+Claude accounts with `refresh_with_cli: true` may refresh an expired login through the CLI,
+which sends one tiny prompt.
+
+## Quick start
```bash
-python3 -m token_tv.app
-curl http://127.0.0.1:8787/snapshot
-curl http://127.0.0.1:8787/snapshot/claude_work
-python3 -m unittest discover -s tests
+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
+# Edit .runtime/config.json: one entry per account (alias, provider, email, CLI home).
+# Add "device_url": "http://<clock-ip>" to drive the clock.
+.venv/bin/python -m token_tv.live --config .runtime/config.json
```
-기기에서 접근할 때는 Mini의 실제 LAN 인터페이스 주소로 바인드해야 한다. 확인한 주소를 `--host`에 넣어 실행한다. 기기 IP와 보드 모델 확인 전까지 테마 설치와 통신 검증은 보류한다.
+Open `http://127.0.0.1:8787/`. Under **Clock display**, choose a face and press
+**Apply to clock**.
+
+Log each account in with its official CLI first. `python3 -m token_tv.connect --config
+.runtime/config.json` walks you through it and keeps every account in its own CLI home.
+The config holds aliases, emails and CLI home paths only. Never put passwords, API keys or
+tokens in it.
+
+To give the clock back its original photo and theme selection, stop TokenTV and run
+`python3 -m token_tv.live --config .runtime/config.json --restore-display`.
+
+## Status
+
+Early and built for one desk:
+
+- Setup is manual: a JSON file and CLI logins. There is no one-command installer yet.
+- Developed and tested on Linux with one clock. Other platforms are untested.
+- Claude, Codex and Grok only. A new provider is one payload function in
+ `token_tv/sources.py`.
+
+Issues and pull requests are welcome, especially new providers, clock models and faces.
+
+## Development
```bash
-python3 -m token_tv.app --host <mini-lan-ip> --port 8787
+python3 -B -m unittest discover -s tests -v
```
-응답의 `status: "mock"`은 예시 수치임을 뜻한다. `/snapshot/<key>`는 smalltv-mod 테마 JSON source용이며, `/snapshot`은 전체 계정 점검용이다. 데몬에 자격 증명을 등록하거나 기기에 전송하는 기능은 아직 없다.
+`scripts/test_web_browser.cjs` runs the browser checks with a local Playwright Chromium.
-`/snapshot/claude_work` 응답 예시:
+## License
-```json
-{"alias":"Claude work","provider":"claude","status":"mock","session_percent":61,"session_reset_minutes":80,"weekly_percent":22,"weekly_reset_minutes":2400}
-```
+MIT, see [LICENSE](LICENSE). Bundled fonts keep their SIL Open Font License notices in
+`token_tv/web/`.
+
+[한국어 README](README.ko.md)
diff --git a/config.example.json b/config.example.json
new file mode 100644
index 0000000..853c517
--- /dev/null
+++ b/config.example.json
@@ -0,0 +1,34 @@
+{
+ "poll_seconds": 300,
+ "accounts": [
+ {
+ "key": "claude_a",
+ "alias": "CLAUDE A",
+ "provider": "claude",
+ "email": "[email protected]",
+ "source_home": "~/.claude"
+ },
+ {
+ "key": "codex_a",
+ "alias": "CODEX A",
+ "provider": "codex",
+ "email": "[email protected]",
+ "source_home": "~/.codex"
+ },
+ {
+ "key": "codex_b",
+ "alias": "CODEX B",
+ "provider": "codex",
+ "email": "[email protected]",
+ "source_home": "~/.codex-account-b"
+ },
+ {
+ "key": "grok_a",
+ "alias": "GROK A",
+ "provider": "grok",
+ "email": "[email protected]",
+ "source_home": "~/.grok"
+ }
+ ],
+ "display_style": "pixel"
+}
diff --git a/docs/images/clock-faces.gif b/docs/images/clock-faces.gif
new file mode 100644
index 0000000..d449d4f
Binary files /dev/null and b/docs/images/clock-faces.gif differ
diff --git a/docs/images/clock-faces.png b/docs/images/clock-faces.png
new file mode 100644
index 0000000..aa813cb
Binary files /dev/null and b/docs/images/clock-faces.png differ
diff --git a/docs/images/web-neon.png b/docs/images/web-neon.png
new file mode 100644
index 0000000..3ef500e
Binary files /dev/null and b/docs/images/web-neon.png differ
diff --git a/docs/images/web-themes.png b/docs/images/web-themes.png
new file mode 100644
index 0000000..9cd5812
Binary files /dev/null and b/docs/images/web-themes.png differ
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..145dde9
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1 @@
+Pillow>=10.2,<13
diff --git a/scripts/e2e_live.py b/scripts/e2e_live.py
new file mode 100644
index 0000000..7d7eba2
--- /dev/null
+++ b/scripts/e2e_live.py
@@ -0,0 +1,42 @@
+"""Check the running dashboard without opening credential files."""
+import argparse
+import json
+from pathlib import Path
+from urllib.request import urlopen
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--url", default="http://127.0.0.1:18787")
+ parser.add_argument("--require-all", action="store_true")
+ parser.add_argument("--expect", type=int, help="number of configured accounts")
+ parser.add_argument("--output")
+ args = parser.parse_args()
+ with urlopen(args.url.rstrip("/") + "/snapshot", timeout=15) as response:
+ payload = response.read()
+ status = response.status
+ snapshot = json.loads(payload)
+ assert snapshot["schema"] == 1
+ assert snapshot["accounts"], "no accounts reported"
+ if args.expect is not None:
+ assert len(snapshot["accounts"]) == args.expect, f"expected {args.expect} accounts"
+ connected = []
+ pending = []
+ for key, row in snapshot["accounts"].items():
+ assert not set(row) & {"email", "password", "access_token", "refresh_token", "source_home"}
+ if row["status"] in ("ok", "quota_unavailable") and row["identity_verified"] is True:
+ connected.append(key)
+ else:
+ pending.append(key)
+ result = {"http_status": status, "connected": sorted(connected), "pending": sorted(pending),
+ "quota_unavailable": sorted(k for k, row in snapshot["accounts"].items() if row["status"] == "quota_unavailable"),
+ "expected": len(snapshot["accounts"]), "all_authenticated": not pending, "updated_at": snapshot["updated_at"]}
+ if args.output:
+ Path(args.output).write_text(json.dumps(result, indent=2))
+ print(json.dumps(result, indent=2))
+ if args.require_all and pending:
+ raise SystemExit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_web_browser.cjs b/scripts/test_web_browser.cjs
new file mode 100644
index 0000000..70fe8fd
--- /dev/null
+++ b/scripts/test_web_browser.cjs
@@ -0,0 +1,28 @@
+/* Local browser verification. No provider credentials or external browser service. */
+const assert=require('node:assert/strict');
+const fs=require('node:fs');
+const {chromium}=require(process.env.PLAYWRIGHT_PACKAGE||'playwright');
+const url=process.env.TOKEN_TV_TEST_URL||'http://127.0.0.1:18788';
+const out=process.env.TOKEN_TV_SCREENSHOTS||'.runtime/web-screenshots';fs.mkdirSync(out,{recursive:true});
+const themes=['digital','neon','retro','modern','sakura','hud'];
+async function theme_and_responsive_checks(page){
+ for(const theme of themes){await page.locator(`[data-theme-choice=${theme}]`).click();assert.equal(await page.locator('html').getAttribute('data-theme'),theme);await page.screenshot({path:`${out}/${theme}-desktop.png`,fullPage:true});for(const width of[320,375,414,768]){await page.setViewportSize({width,height:1000});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true,`${theme} overflow at ${width}`);if(width===375)await page.screenshot({path:`${out}/${theme}-mobile.png`,fullPage:true});}await page.setViewportSize({width:1440,height:1100});}
+ await page.reload();await page.waitForSelector('.provider-card');assert.equal(await page.locator('html').getAttribute('data-theme'),'hud');
+}
+async function account_and_state_checks(page){
+ const accounts=page.locator('[data-account]');assert.equal(await accounts.count(),7);
+ for(const b of await accounts.all()){const key=await b.getAttribute('data-account');await b.click();assert.equal(await page.locator(`.provider-card[data-key="${key}"]`).count(),1);assert.equal(await page.locator(`[data-account="${key}"]`).getAttribute('aria-pressed'),'true');}
+ const fixture={schema:1,updated_at:Date.now()/1000,accounts:{a:{key:'a',alias:'CLAUDE A',provider:'claude',status:'stale',source:'laptop',windows:[{label:'5H',used_percent:82,resets_at:Date.now()/1000+3600},{label:'WEEK',used_percent:50,resets_at:Date.now()/1000+8000}],last_success_at:Date.now()/1000-3600,fetched_at:Date.now()/1000-3600},b:{key:'b',alias:'CODEX A',provider:'codex',status:'identity_mismatch',windows:[{label:'WEEK',used_percent:99}]},c:{key:'c',alias:'GROK A',provider:'grok',status:'quota_unavailable',windows:[],source:'mini'}}};
+ await page.route('**/snapshot',r=>r.fulfill({json:fixture}));await page.reload();await page.waitForSelector('[data-key=a]');assert.match(await page.locator('[data-key=a] .row-status').innerText(),/OLD/);assert.equal(await page.locator('[data-key=a] .meter').first().getAttribute('aria-valuenow'),'82');await page.locator('.more-windows summary').click();assert.equal(await page.locator('.window-percent').innerText(),'50%');assert.equal(await page.locator('[data-key=b] [role=meter]').count(),0);assert.equal(await page.locator('[data-key=c] .percentage').innerText(),'—');
+ await page.route('**/snapshot',r=>r.abort());await page.evaluate(()=>update());await page.waitForFunction(()=>document.body.dataset.offline==='true');assert.match(await page.locator('#notice').innerText(),/Connection lost/);assert.match(await page.locator('[data-key=a] .row-status').innerText(),/OFFLINE/);
+ await page.unroute('**/snapshot');await page.reload();await page.waitForSelector('[data-account]');
+}
+async function clock_independence_checks(page){
+ const original=await (await page.request.get(url+'/display')).json();let posts=0;page.on('request',r=>{if(r.method()==='POST')posts++});
+ for(const theme of themes)await page.locator(`[data-theme-choice=${theme}]`).click();for(const b of await page.locator('[data-account]').all())await b.click();assert.equal(posts,0);assert.equal((await(await page.request.get(url+'/display')).json()).style,original.style);
+ await page.locator('#clock-toggle').click();await page.waitForFunction(()=>{const i=document.querySelector('#frame');return i.complete&&i.naturalWidth===240&&i.currentSrc.includes('style='+document.querySelector('#clock-style').value)});await page.locator('#frame').evaluate(i=>i.decode());await page.locator('#clock-style').selectOption('neon');await page.waitForFunction(()=>{const i=document.querySelector('#frame');return i.complete&&i.naturalWidth===240&&i.currentSrc.includes('style='+document.querySelector('#clock-style').value)});await page.locator('#frame').evaluate(i=>i.decode());assert.equal(posts,0);assert.equal((await(await page.request.get(url+'/display')).json()).style,original.style);
+ // Exercise apply against intercepted delivery, never mutate the real clock from a web test.
+ 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: six 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/tests/test_device.py b/tests/test_device.py
new file mode 100644
index 0000000..ddde039
--- /dev/null
+++ b/tests/test_device.py
@@ -0,0 +1,77 @@
+import json
+import threading
+import unittest
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import parse_qs, urlparse
+
+from token_tv.device import PhotoDisplay
+
+
+class DisplayTests(unittest.TestCase):
+ def test_upload_contract_preserves_existing_files_and_restores_theme(self):
+ calls = []
+ themes = {"interval": 10, "themes": [{"id": 0, "enabled": True}, {"id": 2, "enabled": False}]}
+ photos = {"interval": 10, "files": [{"name": "original.jpg", "size": 10, "enabled": True}, {"name": "space man.gif", "size": 20, "enabled": True}], "total": 3000000, "used": 1000000}
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ return
+ def do_GET(self):
+ calls.append(("GET", self.path, b""))
+ url = urlparse(self.path)
+ if url.path == "/photo/toggle":
+ query = parse_qs(url.query)
+ for photo in photos["files"]:
+ if photo["name"] == query["name"][0]:
+ photo["enabled"] = query["state"][0] == "1"
+ if url.path == "/theme/toggle":
+ query = parse_qs(url.query)
+ identifier, enabled = int(query["id"][0]), query["state"][0] == "1"
+ proposed = [dict(t, enabled=enabled) if t["id"] == identifier else t for t in themes["themes"]]
+ if not any(t["enabled"] for t in proposed):
+ self.send_response(403)
+ self.end_headers()
+ return
+ themes["themes"] = proposed
+ data = themes if self.path == "/theme/list" else photos if self.path == "/photo/list" else {"ok": True}
+ body = json.dumps(data).encode()
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(body)
+ def do_POST(self):
+ body = self.rfile.read(int(self.headers["Content-Length"]))
+ calls.append(("POST", self.path, body))
+ self.send_response(200)
+ self.end_headers()
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever)
+ thread.start()
+ try:
+ display = PhotoDisplay(f"http://127.0.0.1:{server.server_port}")
+ original = display.capture()
+ photos["files"].extend([{"name": name, "enabled": True} for name in ("tokentv-c.jpg", "tokentv-m.jpg", "tokentv.jpg")])
+ display.upload("tokentv.jpg", b"EXACT-JPEG")
+ display.activate(original)
+ self.assertEqual([p["name"] for p in photos["files"] if p["enabled"]], ["tokentv.jpg"])
+ display.restore(original)
+ self.assertEqual([p["name"] for p in photos["files"] if p["enabled"]], ["original.jpg", "space man.gif"])
+ uploads = [c for c in calls if c[0] == "POST"]
+ self.assertEqual(len(uploads), 1)
+ self.assertEqual(uploads[0][1], "/photo/upload")
+ self.assertIn(b'name="file"; filename="tokentv.jpg"', uploads[0][2])
+ self.assertIn(b"\r\n\r\nEXACT-JPEG\r\n", uploads[0][2])
+ paths = [c[1] for c in calls]
+ self.assertIn("/theme/toggle?id=2&state=1", paths)
+ self.assertIn("/theme/toggle?id=0&state=0", paths)
+ self.assertIn("/theme/toggle?id=0&state=1", paths)
+ self.assertIn("/photo/toggle?name=original.jpg&state=1", paths)
+ self.assertIn("/photo/toggle?name=space%20man.gif&state=0", paths)
+ self.assertIn("/photo/toggle?name=space%20man.gif&state=1", paths)
+ self.assertFalse(any("delete" in p or "restart" in p or "update" in p for p in paths))
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_display_styles.py b/tests/test_display_styles.py
new file mode 100644
index 0000000..5b7a780
--- /dev/null
+++ b/tests/test_display_styles.py
@@ -0,0 +1,105 @@
+import copy
+import io
+import json
+import tempfile
+import threading
+import unittest
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+from urllib.error import HTTPError
+from urllib.request import Request, urlopen
+from unittest.mock import Mock
+
+from PIL import Image
+
+from token_tv.display import STYLES, gauge_color, render_page
+from token_tv.live import DisplayPreferences, handler
+from token_tv.sources import load_config
+from token_tv.state import UsageStore
+
+
+class DisplayStyleTests(unittest.TestCase):
+ def test_style_picker_persists_without_querying_accounts(self):
+ account = {'key': 'a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]'}
+ row = dict(account, status='ok', windows=[{'label': 'WEEK', 'used_percent': 94, 'resets_at': None}], fetched_at=100)
+ fetch = Mock(return_value=row)
+ store = UsageStore([account], fetch=fetch)
+ store.refresh()
+ baseline = copy.deepcopy(store.snapshot())
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'config.json'
+ config = {'accounts': [account], 'display_style': 'pixel'}
+ path.write_text(json.dumps(config))
+ prefs = DisplayPreferences(path, config)
+ server = ThreadingHTTPServer(('127.0.0.1', 0), handler(store, prefs))
+ thread = threading.Thread(target=server.serve_forever)
+ thread.start()
+ root = f'http://127.0.0.1:{server.server_port}'
+ try:
+ with urlopen(root + '/frame/0.jpg?style=clean') as response:
+ preview = response.read()
+ self.assertEqual(Image.open(io.BytesIO(preview)).size, (240, 240))
+ self.assertEqual(prefs.snapshot()['style'], 'pixel')
+ request = Request(root + '/display/style', data=b'{"style":"clean"}', headers={'Content-Type': 'application/json'})
+ with urlopen(request) as response:
+ self.assertEqual(json.load(response)['style'], 'clean')
+ self.assertTrue(prefs.changed.is_set())
+ self.assertEqual(load_config(path)['display_style'], 'clean')
+ self.assertEqual(DisplayPreferences(path, load_config(path)).snapshot()['style'], 'clean')
+ for style in STYLES:
+ with urlopen(root + '/frame/0.jpg?style=' + style) as response:
+ self.assertEqual(Image.open(io.BytesIO(response.read())).size, (240, 240))
+ request = Request(root + '/display/style', data=json.dumps({'style': style}).encode(), headers={'Content-Type': 'application/json'})
+ with urlopen(request) as response:
+ self.assertEqual(json.load(response)['style'], style)
+ self.assertEqual(DisplayPreferences(path, load_config(path)).snapshot()['style'], style)
+ for payload, origin in ((b'{"style":"unknown"}', None), (b'{"style":"pixel"}', 'https://unrelated.example')):
+ headers = {'Content-Type': 'application/json'}
+ if origin:
+ headers['Origin'] = origin
+ with self.assertRaises(HTTPError) as raised:
+ urlopen(Request(root + '/display/style', data=payload, headers=headers))
+ self.assertIn(raised.exception.code, (400, 403))
+ self.assertEqual(load_config(path)['display_style'], STYLES[-1])
+ self.assertEqual(store.snapshot(), baseline)
+ self.assertEqual(fetch.call_count, 1)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+ def test_all_styles_keep_same_payload_contract_and_unknown_states(self):
+ sample = {'accounts': {'a': {'alias': 'CLAUDE A', 'provider': 'claude', 'status': 'auth_required', 'windows': []}}}
+ frames = [render_page(sample, style=style) for style in STYLES]
+ self.assertEqual(len(set(frames)), len(STYLES))
+ for status in ('ok', 'stale'):
+ sample['accounts']['a'].update(status=status, windows=[{'label': 'WEEK', 'used_percent': 100, 'resets_at': None}])
+ frames.extend(render_page(sample, style=style) for style in STYLES)
+ for frame in frames:
+ image = Image.open(io.BytesIO(frame))
+ self.assertEqual(image.size, (240, 240))
+ self.assertEqual(image.format, 'JPEG')
+ self.assertLess(len(frame), 60000)
+ with self.assertRaises(ValueError):
+ render_page(sample, style='unknown')
+
+ def test_gauge_enters_high_at_80_and_critical_at_90(self):
+ self.assertEqual(gauge_color(49), (118, 169, 154))
+ self.assertEqual(gauge_color(50), (147, 201, 185))
+ self.assertEqual(gauge_color(79), (147, 201, 185))
+ self.assertEqual(gauge_color(80), (209, 178, 117))
+ self.assertEqual(gauge_color(89), (209, 178, 117))
+ self.assertEqual(gauge_color(90), (216, 135, 126))
+ self.assertEqual(gauge_color(100), (216, 135, 126))
+
+ def test_config_rejects_unknown_display_style(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'config.json'
+ config = {'accounts': [{'key': 'a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]'}], 'display_style': 'unknown'}
+ path.write_text(json.dumps(config))
+ with self.assertRaises(ValueError):
+ load_config(path)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_live.py b/tests/test_live.py
new file mode 100644
index 0000000..8d2d3f5
--- /dev/null
+++ b/tests/test_live.py
@@ -0,0 +1,147 @@
+import copy
+import io
+import json
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from PIL import Image
+
+from token_tv.usage import normalize_claude, normalize_codex, normalize_grok
+from token_tv.sources import fetch_account, load_config, grok_identity, scoped_env
+from token_tv.state import UsageStore
+from token_tv.display import render_page, pages, overview_rows, primary_window
+
+
+class LiveTests(unittest.TestCase):
+ def test_provider_cli_environment_does_not_inherit_other_authentication(self):
+ with patch.dict("os.environ", {"OPENAI_API_KEY": "DO-NOT-INHERIT", "GROK_OAUTH_TOKEN": "DO-NOT-INHERIT", "CLAUDE_CODE_OAUTH_TOKEN": "DO-NOT-INHERIT"}):
+ for provider, variable in (("claude", "CLAUDE_CONFIG_DIR"), ("codex", "CODEX_HOME"), ("grok", "GROK_HOME")):
+ env = scoped_env(provider, "/explicit/account/home")
+ self.assertEqual(env[variable], "/explicit/account/home")
+ self.assertFalse(any(key in env for key in ("OPENAI_API_KEY", "GROK_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")))
+
+ def test_codex_uses_reported_window_duration(self):
+ data = {"rateLimits": {"primary": {"usedPercent": 78, "windowDurationMins": 10080, "resetsAt": 2000000000}, "secondary": None}}
+ self.assertEqual(normalize_codex(data), [{"label": "WEEK", "used_percent": 78.0, "resets_at": 2000000000, "duration_minutes": 10080}])
+
+ def test_missing_grok_quota_is_unknown(self):
+ self.assertEqual(normalize_grok({"config": {"currentPeriod": {"end": "2026-10-05T00:00:00Z"}}}), [])
+ self.assertEqual(normalize_claude({"five_hour": {"utilization": None}, "seven_day": {"utilization": 24, "resets_at": None}})[0]["label"], "WEEK")
+
+ def test_credentials_and_identity_never_enter_snapshot(self):
+ account = {"key": "a", "alias": "CLAUDE A", "provider": "claude", "source_home": "/unused", "email": "[email protected]"}
+ with patch("token_tv.sources.claude_payload", return_value=({"account": {"email": "[email protected]"}}, {"five_hour": {"utilization": 8}, "access_token": "DO-NOT-EXPORT"})):
+ row = fetch_account(account)
+ self.assertEqual(row["status"], "identity_mismatch")
+ self.assertEqual(row["windows"], [])
+ self.assertNotIn("DO-NOT-EXPORT", json.dumps(row))
+ self.assertNotIn("[email protected]", json.dumps(row))
+
+ def test_configuration_rejects_secret_fields(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "config.json"
+ path.write_text(json.dumps({"accounts": [{"key": "a", "alias": "A", "provider": "claude", "password": "DO-NOT-USE"}]}))
+ with self.assertRaises(ValueError):
+ load_config(path)
+
+ def test_grok_owner_identity_must_match_expected_email(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "auth.json"
+ path.write_text(json.dumps({"issuer::client": {"email": "[email protected]", "key": "NEVER-EXPORT", "refresh_token": "NEVER-EXPORT"}}))
+ self.assertEqual(grok_identity({"source_home": directory}), "[email protected]")
+ account = {"key": "g", "alias": "G", "provider": "grok", "source_home": directory, "email": "[email protected]"}
+ with patch("token_tv.sources.grok_payload") as billing:
+ row = fetch_account(account)
+ billing.assert_not_called()
+ self.assertEqual(row["status"], "identity_mismatch")
+ self.assertNotIn("NEVER-EXPORT", json.dumps(row))
+
+ def test_cache_is_per_account_and_failure_preserves_stale_values(self):
+ accounts = [{"key": "a", "alias": "A", "provider": "claude"}, {"key": "b", "alias": "B", "provider": "claude"}]
+ replies = {
+ "a": {"key": "a", "alias": "A", "provider": "claude", "status": "ok", "windows": [{"label": "WEEK", "used_percent": 31, "resets_at": None, "duration_minutes": 10080}], "fetched_at": 100},
+ "b": {"key": "b", "alias": "B", "provider": "claude", "status": "auth_required", "windows": [], "fetched_at": 100},
+ }
+ calls = []
+ def fetch(account):
+ calls.append(account["key"])
+ return copy.deepcopy(replies[account["key"]])
+ store = UsageStore(accounts, fetch=fetch)
+ store.refresh()
+ one = store.snapshot()
+ two = store.snapshot()
+ self.assertEqual(calls, ["a", "b"])
+ self.assertEqual(one, two)
+ self.assertEqual(one["accounts"]["a"]["windows"][0]["used_percent"], 31)
+ self.assertEqual(one["accounts"]["b"]["windows"], [])
+ replies["a"].update(status="error", windows=[], fetched_at=200)
+ store.refresh()
+ row = store.snapshot()["accounts"]["a"]
+ self.assertEqual(row["status"], "stale")
+ self.assertEqual(row["windows"][0]["used_percent"], 31)
+ self.assertEqual(row["last_success_at"], 100)
+ self.assertEqual(row["error_code"], "error")
+
+ def test_wrong_identity_does_not_reuse_previous_account_values(self):
+ account = {"key": "a", "alias": "A", "provider": "claude"}
+ replies = [dict(account, status="ok", windows=[{"label": "WEEK", "used_percent": 31}], fetched_at=time.time(), identity_verified=True),
+ dict(account, status="identity_mismatch", windows=[], fetched_at=time.time(), identity_verified=False)]
+ store = UsageStore([account], fetch=lambda _: replies.pop(0))
+ store.refresh()
+ store.refresh()
+ row = store.snapshot()["accounts"]["a"]
+ self.assertEqual(row["status"], "identity_mismatch")
+ self.assertEqual(row["windows"], [])
+
+ def test_laptop_fallback_is_replaced_by_verified_mini_login(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "bridge.json"
+ row = {"key": "a", "alias": "A", "provider": "claude", "status": "ok", "fetched_at": time.time(), "identity_verified": True,
+ "windows": [{"label": "WEEK", "used_percent": 31, "resets_at": None, "duration_minutes": 10080}]}
+ path.write_text(json.dumps({"accounts": {"a": row}}))
+ account = {"key": "a", "alias": "A", "provider": "claude", "email": "[email protected]", "source_home": str(Path(directory)/"absent"), "fallback_snapshot_file": str(path)}
+ actual = fetch_account(account)
+ self.assertEqual(actual["source"], "laptop")
+ self.assertEqual(actual["status"], "ok")
+ self.assertEqual(actual["mini_auth_status"], "auth_required")
+ with patch("token_tv.sources.claude_payload", return_value=({"account": {"email": "[email protected]"}}, {"seven_day": {"utilization": 24}})):
+ actual = fetch_account(account)
+ self.assertEqual(actual["source"], "mini")
+ self.assertEqual(actual["windows"][0]["used_percent"], 24)
+ self.assertNotIn("mini_auth_status", actual)
+
+ def test_renderer_has_real_pixel_dimensions_and_missing_state(self):
+ snapshot = {"schema": 1, "accounts": {"a": {"alias": "CLAUDE A", "provider": "claude", "status": "auth_required", "windows": [], "fetched_at": 100}}}
+ self.assertEqual(len(pages(snapshot)), 1)
+ body = render_page(snapshot, 0)
+ image = Image.open(io.BytesIO(body))
+ self.assertEqual(image.size, (240, 240))
+ self.assertEqual(image.format, "JPEG")
+ self.assertGreater(len(image.getcolors(240 * 240)), 20)
+ self.assertLess(len(body), 60000)
+
+ def test_overview_keeps_one_account_per_provider_without_losing_details(self):
+ def account(provider, alias, status="ok"):
+ return {"provider": provider, "alias": alias, "status": status,
+ "windows": [] if status != "ok" else [{"label": "WEEK", "used_percent": 94, "resets_at": None}]}
+ snapshot = {"accounts": {
+ "ca": account("claude", "CLAUDE A"), "cb": account("claude", "CLAUDE B"),
+ "cc": account("claude", "CLAUDE C"), "xa": account("codex", "CODEX A"),
+ "ga": account("grok", "GROK A", "auth_required"), "gb": account("grok", "GROK B")}}
+ rows = overview_rows(snapshot)
+ self.assertEqual([r["key"] for r in rows], ["ca", "xa", "gb"])
+ self.assertEqual(len(snapshot["accounts"]), 6)
+ self.assertEqual(render_page(snapshot, 0), render_page(snapshot, 1))
+
+ def test_overview_preserves_quota_period_and_unknown_values(self):
+ windows = [{"label": "5H", "used_percent": 2}, {"label": "WEEK", "used_percent": 94}]
+ self.assertEqual(primary_window({"windows": windows})["label"], "WEEK")
+ self.assertIsNone(primary_window({"windows": []}))
+ self.assertEqual(primary_window({"windows": [{"label": "BUDGET", "used_percent": 100}]})["label"], "BUDGET")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_web.py b/tests/test_web.py
new file mode 100644
index 0000000..9526675
--- /dev/null
+++ b/tests/test_web.py
@@ -0,0 +1,37 @@
+import threading
+import unittest
+from http.server import ThreadingHTTPServer
+from urllib.error import HTTPError
+from urllib.request import urlopen
+from token_tv.live import handler
+from token_tv.state import UsageStore
+from token_tv.web_assets import ASSETS
+
+
+class WebAssetTests(unittest.TestCase):
+ def test_assets_are_allowlisted_and_dashboard_is_live(self):
+ store = UsageStore([])
+ server = ThreadingHTTPServer(('127.0.0.1', 0), handler(store))
+ thread = threading.Thread(target=server.serve_forever)
+ thread.start()
+ root = f'http://127.0.0.1:{server.server_port}'
+ try:
+ html = urlopen(root).read().decode()
+ self.assertIn('/assets/app.js', html)
+ for name, mime in [('app.js', 'text/javascript'), ('style.css', 'text/css'), ('tokens.css', 'text/css')]:
+ with urlopen(root + '/assets/' + name) as response:
+ self.assertEqual(response.status, 200)
+ self.assertTrue(response.headers['Content-Type'].startswith(mime))
+ self.assertGreater(len(response.read()), 100)
+ for path, (_, mime) in ASSETS.items():
+ with urlopen(root + path) as response:
+ self.assertEqual(response.headers['Content-Type'], mime, path)
+ self.assertGreater(len(response.read()), 100, path)
+ for path in ['/assets/../.runtime/config.json', '/assets/%2e%2e/.runtime/config.json', '/assets/config.json']:
+ with self.assertRaises(HTTPError) as caught:
+ urlopen(root + path)
+ self.assertEqual(caught.exception.code, 404)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
diff --git a/token_tv/assets/README.md b/token_tv/assets/README.md
new file mode 100644
index 0000000..1fb3e5c
--- /dev/null
+++ b/token_tv/assets/README.md
@@ -0,0 +1,19 @@
+# Pixel mascots
+
+User-provided references were adapted with the image_gen tool to transparent pixel mascots. The supplied references are treated as Claude (orange Clawd), Codex (purple terminal blossom), and Grok (black face with white eyes); this mapping is a project design assumption.
+
+Selected generated outputs were cropped to their visible bounds and resized with nearest-neighbor sampling to 32×32 PNGs for the LCD renderer. Claude uses the second generated variant, which removes the first variant’s glow. Codex retains discrete purple shades; Grok appears on a light tile for contrast.
+
+| Asset | Generation |
+|---|---|
+| claude-pixel.png | exec-23c46822-b44a-4aa3-87b5-577912a8f79d.png |
+| codex-pixel.png | exec-494a638e-5e74-415d-ad92-829e7c1d59f5.png |
+| grok-pixel.png | exec-e62075c9-d38b-4b00-a450-4dc7b00bbe37.png |
+
+## Generation instructions
+
+The three requests preserve the reference silhouette, use a logical 32×32 pixel grid, hard edges, transparent background, a few original colors, and no text or extra elements.
+
+Final Claude prompt:
+
+> Make this exact orange pixel crab into a crisp flat game UI sprite. Use only ONE opaque solid peach-orange color (#D9845E) and opaque black rectangular eyes. Identical stepped silhouette, two side arms and four short square legs. This is a flat 32 by 32 logical pixel sprite, enlarged with nearest-neighbor square pixels. Transparent empty canvas. Absolutely NO glow, NO light, NO smoke, NO shadows, NO texture, NO gradients, NO highlights, NO blur, NO scene or background, NO white outline. Center the icon with a little transparent margin. Preserve the original simple pixel geometry. Pure solid opaque fills and hard right-angle edges. Output just the sprite.
diff --git a/token_tv/assets/claude-pixel.png b/token_tv/assets/claude-pixel.png
new file mode 100644
index 0000000..7ce140f
Binary files /dev/null and b/token_tv/assets/claude-pixel.png differ
diff --git a/token_tv/assets/codex-pixel.png b/token_tv/assets/codex-pixel.png
new file mode 100644
index 0000000..645951e
Binary files /dev/null and b/token_tv/assets/codex-pixel.png differ
diff --git a/token_tv/assets/grok-pixel.png b/token_tv/assets/grok-pixel.png
new file mode 100644
index 0000000..4176c1e
Binary files /dev/null and b/token_tv/assets/grok-pixel.png differ
diff --git a/token_tv/bridge.py b/token_tv/bridge.py
new file mode 100644
index 0000000..11ffeac
--- /dev/null
+++ b/token_tv/bridge.py
@@ -0,0 +1,47 @@
+"""Transfer normalized usage only; credentials stay on the source computer."""
+import argparse
+import json
+import shlex
+import subprocess
+import time
+
+from token_tv.sources import load_config
+from token_tv.state import UsageStore
+
+REMOTE_WRITE = """import json,os,pathlib,sys
+p=pathlib.Path(sys.argv[1]).expanduser()
+data=json.load(sys.stdin)
+p.parent.mkdir(parents=True,exist_ok=True)
+t=p.with_suffix('.tmp')
+t.write_text(json.dumps(data,ensure_ascii=False,separators=(',',':')))
+os.chmod(t,0o600)
+t.replace(p)
+"""
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--config", required=True)
+ parser.add_argument("--ssh-host", required=True)
+ parser.add_argument("--remote-path", required=True)
+ args = parser.parse_args()
+ if args.ssh_host.startswith("-"):
+ parser.error("A host name is required")
+ config = load_config(args.config)
+ store = UsageStore(config["accounts"])
+ while True:
+ try:
+ store.refresh()
+ data = json.dumps(store.snapshot(), ensure_ascii=False, separators=(",", ":"))
+ command = "python3 -c " + shlex.quote(REMOTE_WRITE) + " " + shlex.quote(args.remote_path)
+ subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10",
+ args.ssh_host, command], input=data, text=True, check=True,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
+ print("TokenTV normalized account snapshot delivered.", flush=True)
+ except (OSError, subprocess.SubprocessError):
+ print("TokenTV bridge unavailable; display will mark stale.", flush=True)
+ time.sleep(max(60, int(config.get("poll_seconds", 300))))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/token_tv/connect.py b/token_tv/connect.py
new file mode 100644
index 0000000..68db5d3
--- /dev/null
+++ b/token_tv/connect.py
@@ -0,0 +1,57 @@
+"""Sign in to one account's Mini-local CLI home, without changing defaults."""
+import argparse
+import os
+import subprocess
+from pathlib import Path
+
+from token_tv.sources import fetch_account, load_config, scoped_env
+
+
+def login_command(account, browser=False):
+ provider = account["provider"]
+ if provider == "claude":
+ return ["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"]
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--config", required=True)
+ parser.add_argument("--account", help="Stable account key; omit to choose interactively")
+ parser.add_argument("--browser", action="store_true", help="Use Codex browser login (forward localhost:1455 when running over SSH)")
+ args = parser.parse_args()
+ accounts = load_config(args.config)["accounts"]
+ key = args.account
+ if key is None:
+ for index, account in enumerate(accounts, 1):
+ print(f"{index}. {account['provider']} · {account['alias']}")
+ try:
+ choice = int(input("Choose account number: "))
+ if not 1 <= choice <= len(accounts):
+ raise ValueError("Out of range")
+ key = accounts[choice - 1]["key"]
+ except (ValueError, IndexError, EOFError):
+ 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")
+ root = Path(account["source_home"]).expanduser()
+ 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)
+ result = subprocess.run(login_command(account, args.browser), env=scoped_env(account["provider"], root))
+ if result.returncode:
+ raise SystemExit(result.returncode)
+ # Verification must use the newly authenticated source, never its fallback.
+ direct = {k: v for k, v in account.items() if k not in ("snapshot_file", "fallback_snapshot_file")}
+ row = fetch_account(direct)
+ 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)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/token_tv/device.py b/token_tv/device.py
new file mode 100644
index 0000000..28417b1
--- /dev/null
+++ b/token_tv/device.py
@@ -0,0 +1,79 @@
+"""Confirmed SD_PRO photo API. Never flash or delete existing photographs."""
+import json
+import uuid
+from urllib.parse import quote, urlencode, urlparse
+from urllib.request import Request, urlopen
+
+
+FILES = ("tokentv.jpg",)
+LEGACY_FILES = ("tokentv-c.jpg", "tokentv-m.jpg")
+
+
+class PhotoDisplay:
+ def __init__(self, base_url):
+ parsed = urlparse(base_url)
+ if parsed.scheme != "http" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.path not in ("", "/"):
+ raise ValueError("A plain local display URL is required")
+ self.base_url = base_url.rstrip("/")
+
+ def request(self, path, data=None, headers=None):
+ with urlopen(Request(self.base_url + path, data=data, headers=headers or {}), timeout=20) as response:
+ body = response.read()
+ return response.status, body
+
+ def capture(self):
+ _, raw = self.request("/theme/list")
+ themes = json.loads(raw)
+ _, raw = self.request("/photo/list")
+ photos = json.loads(raw)
+ if not any(t["id"] == 2 for t in themes["themes"]):
+ raise ValueError("The confirmed photo theme is missing")
+ return {"themes": themes["themes"], "theme_interval": themes["interval"],
+ "files": [{"name": f["name"], "enabled": f["enabled"]} for f in photos["files"]],
+ "photo_interval": photos["interval"]}
+
+ def upload(self, name, jpeg):
+ if name not in FILES or len(jpeg) > 60000:
+ raise ValueError("Unexpected display image")
+ boundary = "TokenTV" + uuid.uuid4().hex
+ body = (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{name}"\r\n'
+ 'Content-Type: image/jpeg\r\n\r\n').encode() + jpeg + f"\r\n--{boundary}--\r\n".encode()
+ status, _ = self.request("/photo/upload", body,
+ {"Content-Type": "multipart/form-data; boundary=" + boundary})
+ return {"file": name, "status": status, "bytes": len(jpeg)}
+
+ def toggle(self, category, key, value, enabled):
+ self.request("/" + category + "/toggle?" + urlencode({key: value, "state": int(enabled)}, quote_via=quote))
+
+ def activate(self, original):
+ # Select our files first, then select the photo theme; retain old files.
+ current = self.capture()
+ enabled = {f['name']: f['enabled'] for f in current['files']}
+ for name in FILES:
+ if not enabled.get(name):
+ self.toggle("photo", "name", name, True)
+ for f in current['files']:
+ if f["name"] not in FILES and f['enabled']:
+ self.toggle("photo", "name", f["name"], False)
+ if current['photo_interval'] != 10:
+ self.request("/photo/interval?val=10")
+ if not any(t['id'] == 2 and t['enabled'] for t in current['themes']):
+ self.toggle("theme", "id", 2, True)
+ for t in current["themes"]:
+ if t["id"] != 2 and t['enabled']:
+ self.toggle("theme", "id", t["id"], False)
+
+ def restore(self, original):
+ for f in original["files"]:
+ self.toggle("photo", "name", f["name"], f["enabled"])
+ _, raw = self.request("/photo/list")
+ present = {f["name"] for f in json.loads(raw)["files"]}
+ for name in FILES + LEGACY_FILES:
+ if name in present and not any(f["name"] == name for f in original["files"]):
+ self.toggle("photo", "name", name, False)
+ self.request("/photo/interval?val=" + str(original["photo_interval"]))
+ self.request("/theme/interval?val=" + str(original["theme_interval"]))
+ for enabled in (True, False):
+ for t in original["themes"]:
+ if t["enabled"] == enabled:
+ self.toggle("theme", "id", t["id"], enabled)
diff --git a/token_tv/display.py b/token_tv/display.py
new file mode 100644
index 0000000..8566785
--- /dev/null
+++ b/token_tv/display.py
@@ -0,0 +1,450 @@
+"""A three-row desk instrument; the web retains every account's details.
+
+Hallmark · component: LCD overview · genre: instrument · scope: 240×240
+Hallmark · pre-emit critique: P4 H4 E4 S4 R4 V4 (self-review)
+"""
+import io
+import math
+import os
+import time
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+
+BACKGROUND = '#0b0e12'
+# Text and brand inks; usage levels affect gauges only.
+# Numeric text stays gray, with OLD/LOGIN carrying data status.
+TEXT = '#d9dde1'
+MUTED = TEXT
+TRACK = '#28313a'
+RULE = '#202730'
+PROVIDER_INK = {'claude': '#d68e68', 'codex': '#a799e5', 'grok': '#cbd1d7'}
+ICON_PAPER = PROVIDER_INK['grok']
+FONT_MAIN = '/usr/share/fonts/truetype/dejavu/DejaVuSans'
+FONT_NUMBERS = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono'
+STYLES = ('pixel', 'clean', 'arcade', 'columns', 'orbit',
+ 'digital', 'neon', 'retro', 'modern', 'sakura', 'hud')
+# Gauge-only levels; labels/percentages always use TEXT, logos retain provider ink.
+GAUGE_LEVELS = ((50, '#76a99a'), (80, '#93c9b9'), (90, '#d1b275'), (101, '#d8877e'))
+STATUS = {'loading': 'WAIT', 'auth_required': 'LOGIN', 'identity_mismatch': 'CHECK',
+ 'quota_unavailable': 'NO DATA', 'error': 'ERROR', 'rate_limited': 'RETRY', 'stale': 'OLD'}
+PROVIDERS = ('claude', 'codex', 'grok')
+ASSETS = Path(__file__).with_name('assets')
+
+
+def font(size, bold=False, mono=False):
+ candidates = [os.environ.get('TOKEN_TV_FONT', ''),
+ (FONT_NUMBERS if mono else FONT_MAIN) + ('-Bold' if bold else '') + '.ttf',
+ '~/.local/share/fonts/malgun.ttf']
+ for candidate in candidates:
+ path = Path(candidate).expanduser()
+ if candidate and path.is_file():
+ return ImageFont.truetype(str(path), size)
+ return ImageFont.load_default()
+
+
+def overview_rows(snapshot):
+ """Select one visible account per provider, in configured order, without merging quotas."""
+ rows = []
+ for provider in 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']]
+ previous = [row for row in accounts if row['status'] == 'stale' and row['windows']]
+ rows.append((available or previous or accounts or [
+ {'key': provider, 'provider': provider, 'alias': provider.upper() + ' A',
+ 'status': 'auth_required', 'windows': []}])[0])
+ return rows
+
+
+def pages(snapshot):
+ return [('OVERVIEW', overview_rows(snapshot))]
+
+
+def primary_window(row):
+ return max(row['windows'], key=lambda value: value['used_percent'], default=None)
+
+
+def time_left(reset):
+ if not reset:
+ return '--'
+ minutes = max(0, int((reset - time.time() + 59) // 60))
+ if minutes >= 1440:
+ return str(minutes // 1440) + 'd ' + str(minutes % 1440 // 60) + 'h'
+ return str(minutes // 60) + 'h ' + str(minutes % 60) + 'm'
+
+
+def right(draw, xy, text, face, color):
+ x, y = xy
+ draw.text((x - draw.textlength(text, font=face), y), text, font=face, fill=color)
+
+
+def mascot(image, provider, xy, pixel=False, size=40):
+ path = ASSETS / (provider + '-pixel.png')
+ if path.is_file():
+ with Image.open(path) as original:
+ icon = original.convert('RGBA')
+ box = icon.getbbox()
+ if box:
+ icon = icon.crop(box)
+ scale = (size / 2 if pixel else size) / max(icon.size)
+ icon = icon.resize((round(icon.width * scale), round(icon.height * scale)), Image.Resampling.NEAREST)
+ if pixel:
+ icon = icon.resize((icon.width * 2, icon.height * 2), Image.Resampling.NEAREST)
+ x, y = xy
+ image.paste(icon, (x + (48 - icon.width) // 2, y + (48 - icon.height) // 2), icon)
+ else:
+ ImageDraw.Draw(image).text((xy[0]+16, xy[1]+12), provider[0].upper(), font=font(22, True), fill=PROVIDER_INK[provider])
+
+
+def gauge_color(used, segment=9):
+ base = next(color for upper, color in GAUGE_LEVELS if used < upper)
+ # A short ramp within one hue: the last filled cell is the brightest.
+ last = max(1, math.ceil(used / 10) - 1)
+ strength = .78 + .22 * min(1, segment / last)
+ return tuple(round(int(base[i:i + 2], 16) * strength) for i in (1, 3, 5))
+
+
+def horizontal_gauge(draw, xy, used, step=16, width=14, height=4, rounded=False, track=TRACK):
+ for segment in range(10):
+ x, y = xy[0] + segment * step, xy[1]
+ box = (x, y, x + width - 1, y + height - 1)
+ if rounded:
+ draw.rounded_rectangle(box, radius=1, fill=track)
+ else:
+ draw.rectangle(box, fill=track)
+ filled = round(max(0, min(1, used / 10 - segment)) * width) if used is not None else 0
+ if filled:
+ box = (x, y, x + filled - 1, y + height - 1)
+ color = gauge_color(used, segment)
+ if rounded:
+ draw.rounded_rectangle(box, radius=1, fill=color)
+ else:
+ draw.rectangle(box, fill=color)
+
+
+def account_label(row):
+ prefix = row['provider'].upper() + ' '
+ return row['alias'] if row['alias'].startswith(prefix) else prefix + 'A'
+
+
+def quota_period(value):
+ return {'WEEK': 'WK', 'BUDGET': 'BUD'}.get(value['label'], value['label'])
+
+
+def render_clean(snapshot):
+ image = Image.new('RGB', (240, 240), BACKGROUND)
+ draw = ImageDraw.Draw(image)
+ for index, row in enumerate(overview_rows(snapshot)):
+ y = 6 + 78 * index
+ if index:
+ draw.line((14, y - 3, 226, y - 3), fill=RULE)
+ if row['provider'] == 'grok':
+ draw.ellipse((16, y + 12, 59, y + 55), fill=ICON_PAPER)
+ mascot(image, row['provider'], (14, y + 10))
+ label = row['alias']
+ # Product labels are provider + A/B/C, rather than personal names.
+ if not label.startswith(row['provider'].upper() + ' '):
+ label = row['provider'].upper() + ' A'
+ draw.text((68, y + 9), label, font=font(12, True), fill=TEXT)
+ value = primary_window(row)
+ if value is None:
+ right(draw, (226, y + 2), '--', font(26, mono=True), MUTED)
+ draw.text((68, y + 48), STATUS.get(row['status'], 'NO DATA'), font=font(10, mono=True), fill=MUTED)
+ for segment in range(10):
+ x = 68 + segment * 16
+ draw.rounded_rectangle((x, y + 36, x + 13, y + 39), radius=1, fill=TRACK)
+ continue
+ used = max(0, min(100, value['used_percent']))
+ old = row['status'] != 'ok'
+ right(draw, (226, y + 2), str(round(used)) + '%', font(26, mono=True), TEXT)
+ period = {'WEEK': 'WK', 'BUDGET': 'BUD'}.get(value['label'], value['label'])
+ draw.text((68, y + 48), period + (' OLD' if old else ' USED'), font=font(10, mono=True), fill=MUTED)
+ right(draw, (226, y + 48), time_left(value.get('resets_at')), font(11, mono=True), MUTED)
+ horizontal_gauge(draw, (68, y + 36), used, rounded=True)
+ return image
+
+
+# A code-native 5×7 alphabet keeps LCD text on a visible pixel grid.
+PIXEL_GLYPHS = {
+ 'A': '01110/10001/10001/11111/10001/10001/10001',
+ 'B': '11110/10001/10001/11110/10001/10001/11110',
+ 'C': '01111/10000/10000/10000/10000/10000/01111',
+ 'D': '11110/10001/10001/10001/10001/10001/11110',
+ 'E': '11111/10000/10000/11110/10000/10000/11111',
+ 'F': '11111/10000/10000/11110/10000/10000/10000',
+ 'G': '01111/10000/10000/10111/10001/10001/01111',
+ 'H': '10001/10001/10001/11111/10001/10001/10001',
+ 'I': '11111/00100/00100/00100/00100/00100/11111',
+ 'J': '00111/00010/00010/00010/00010/10010/01100',
+ 'K': '10001/10010/10100/11000/10100/10010/10001',
+ 'L': '10000/10000/10000/10000/10000/10000/11111',
+ 'M': '10001/11011/10101/10101/10001/10001/10001',
+ 'N': '10001/11001/10101/10011/10001/10001/10001',
+ 'O': '01110/10001/10001/10001/10001/10001/01110',
+ 'P': '11110/10001/10001/11110/10000/10000/10000',
+ 'Q': '01110/10001/10001/10001/10101/10010/01101',
+ 'R': '11110/10001/10001/11110/10100/10010/10001',
+ 'S': '01111/10000/10000/01110/00001/00001/11110',
+ 'T': '11111/00100/00100/00100/00100/00100/00100',
+ 'U': '10001/10001/10001/10001/10001/10001/01110',
+ 'V': '10001/10001/10001/10001/10001/01010/00100',
+ 'W': '10001/10001/10001/10101/10101/10101/01010',
+ 'X': '10001/10001/01010/00100/01010/10001/10001',
+ 'Y': '10001/10001/01010/00100/00100/00100/00100',
+ 'Z': '11111/00001/00010/00100/01000/10000/11111',
+ '0': '01110/10001/10011/10101/11001/10001/01110',
+ '1': '00100/01100/00100/00100/00100/00100/01110',
+ '2': '01110/10001/00001/00010/00100/01000/11111',
+ '3': '11110/00001/00001/01110/00001/00001/11110',
+ '4': '00010/00110/01010/10010/11111/00010/00010',
+ '5': '11111/10000/10000/11110/00001/00001/11110',
+ '6': '01110/10000/10000/11110/10001/10001/01110',
+ '7': '11111/00001/00010/00100/01000/01000/01000',
+ '8': '01110/10001/10001/01110/10001/10001/01110',
+ '9': '01110/10001/10001/01111/00001/00001/01110',
+ '%': '11001/11010/00010/00100/01000/01011/10011',
+ '-': '00000/00000/00000/11111/00000/00000/00000',
+ '?': '01110/10001/00001/00010/00100/00000/00100',
+ ' ': '00000/00000/00000/00000/00000/00000/00000',
+}
+
+
+def pixel_text(draw, xy, text, scale=1, color=TEXT, align='left'):
+ text = str(text).upper()
+ width = max(0, len(text) * 6 - 1) * scale
+ x, y = xy
+ if align == 'right':
+ x -= width
+ for index, character in enumerate(text):
+ pattern = PIXEL_GLYPHS.get(character, PIXEL_GLYPHS['?']).split('/')
+ for yy, line in enumerate(pattern):
+ for xx, bit in enumerate(line):
+ if bit == '1':
+ px = x + (index * 6 + xx) * scale
+ py = y + yy * scale
+ draw.rectangle((px, py, px + scale - 1, py + scale - 1), fill=color)
+
+
+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
+ if index:
+ for x in range(14, 227, 4):
+ draw.point((x, y - 6), fill=RULE)
+ if row['provider'] == 'grok':
+ disc = Image.new('RGB', (24, 24), BACKGROUND)
+ ImageDraw.Draw(disc).ellipse((1, 1, 22, 22), fill=ICON_PAPER)
+ image.paste(disc.resize((48, 48), Image.Resampling.NEAREST), (14, y + 10))
+ mascot(image, row['provider'], (14, y + 10), pixel=True)
+ label = row['alias']
+ if not label.startswith(row['provider'].upper() + ' '):
+ label = row['provider'].upper() + ' A'
+ pixel_text(draw, (68, y + 3), label)
+ value = primary_window(row)
+ used = max(0, min(100, value['used_percent'])) if value else None
+ old = row['status'] != 'ok'
+ number = '--' if used is None else str(round(used)) + '%'
+ pixel_text(draw, (68, y + 21), number, scale=3, color=TEXT)
+ if value:
+ period = {'WEEK': 'WK', 'BUDGET': 'BUD'}.get(value['label'], value['label'])
+ pixel_text(draw, (226, y + 3), period + (' OLD' if old else ' USED'), color=MUTED, align='right')
+ pixel_text(draw, (226, y + 25), time_left(value.get('resets_at')).replace(' ', ''), scale=2, color=MUTED, align='right')
+ else:
+ pixel_text(draw, (226, y + 25), STATUS.get(row['status'], 'NO DATA'), color=MUTED, align='right')
+ horizontal_gauge(draw, (68, y + 52), used)
+ return image
+
+
+def render_arcade(snapshot):
+ image = Image.new('RGB', (240, 240), BACKGROUND)
+ draw = ImageDraw.Draw(image)
+ for index, row in enumerate(overview_rows(snapshot)):
+ y = 4 + index * 80
+ if index:
+ for x in range(14, 227, 4):
+ draw.point((x, y - 4), fill=RULE)
+ if row['provider'] == 'grok':
+ draw.ellipse((11, y + 14, 54, y + 57), fill=ICON_PAPER)
+ mascot(image, row['provider'], (8, y + 12), pixel=True)
+ pixel_text(draw, (70, y + 5), account_label(row))
+ value = primary_window(row)
+ used = max(0, min(100, value['used_percent'])) if value else None
+ pixel_text(draw, (70, y + 23), '--' if used is None else str(round(used)) + '%', scale=3)
+ pixel_text(draw, (226, y + 5), quota_period(value) + (' OLD' if row['status'] != 'ok' else ' USED') if value else '', align='right')
+ pixel_text(draw, (226, y + 29), time_left(value.get('resets_at')).replace(' ', '') if value else STATUS.get(row['status'], 'NO DATA'), scale=2 if value else 1, align='right')
+ horizontal_gauge(draw, (14, y + 66), used, step=22, width=20)
+ return image
+
+
+def render_columns(snapshot):
+ image = Image.new('RGB', (240, 240), BACKGROUND)
+ draw = ImageDraw.Draw(image)
+ for index, row in enumerate(overview_rows(snapshot)):
+ center = 40 + index * 80
+ if index:
+ for y in range(9, 232, 4):
+ draw.point((index * 80, y), fill=RULE)
+ if row['provider'] == 'grok':
+ draw.ellipse((center - 21, 13, center + 21, 55), fill=ICON_PAPER)
+ mascot(image, row['provider'], (center - 24, 10), pixel=True)
+ label = account_label(row).split(' ', 1)
+ pixel_text(draw, (center - (len(label[0]) * 6 - 1) // 2, 63), label[0])
+ pixel_text(draw, (center - (len(label[1]) * 6 - 1) // 2, 75), label[1])
+ value = primary_window(row)
+ used = max(0, min(100, value['used_percent'])) if value else None
+ number = '--' if used is None else str(round(used)) + '%'
+ pixel_text(draw, (center - (len(number) * 6 - 1), 91), number, scale=2)
+ for segment in range(10):
+ y = 184 - segment * 8
+ draw.rectangle((center - 10, y, center + 9, y + 4), fill=TRACK)
+ height = round(max(0, min(1, used / 10 - segment)) * 5) if used is not None else 0
+ if height:
+ draw.rectangle((center - 10, y + 5 - height, center + 9, y + 4), fill=gauge_color(used, segment))
+ period = quota_period(value) + (' OLD' if row['status'] != 'ok' else ' USED') if value else STATUS.get(row['status'], 'NO DATA')
+ pixel_text(draw, (center - (len(period) * 6 - 1) // 2, 204), period)
+ reset = time_left(value.get('resets_at')).replace(' ', '') if value else '--'
+ pixel_text(draw, (center - (len(reset) * 6 - 1) // 2, 218), reset)
+ return image
+
+
+def render_orbit(snapshot):
+ image = Image.new('RGB', (240, 240), BACKGROUND)
+ draw = ImageDraw.Draw(image)
+ for index, row in enumerate(overview_rows(snapshot)):
+ y = 8 + index * 78
+ center = (46, y + 31)
+ if row['provider'] == 'grok':
+ draw.ellipse((center[0] - 17, center[1] - 17, center[0] + 17, center[1] + 17), fill=ICON_PAPER)
+ mascot(image, row['provider'], (center[0] - 24, center[1] - 24), pixel=True, size=30)
+ value = primary_window(row)
+ used = max(0, min(100, value['used_percent'])) if value else None
+ for segment in range(10):
+ angle = math.radians(-90 + segment * 36)
+ x = round(center[0] + 28 * math.cos(angle)) - 3
+ yy = round(center[1] + 28 * math.sin(angle)) - 3
+ draw.rectangle((x, yy, x + 5, yy + 5), fill=TRACK)
+ width = round(max(0, min(1, used / 10 - segment)) * 6) if used is not None else 0
+ if width:
+ draw.rectangle((x, yy, x + width - 1, yy + 5), fill=gauge_color(used, segment))
+ pixel_text(draw, (92, y + 4), account_label(row))
+ pixel_text(draw, (226, y + 4), 'OLD' if value and row['status'] != 'ok' else 'USED', align='right')
+ pixel_text(draw, (92, y + 22), '--' if used is None else str(round(used)) + '%', scale=3)
+ pixel_text(draw, (92, y + 54), quota_period(value) if value else STATUS.get(row['status'], 'NO DATA'))
+ if value:
+ pixel_text(draw, (226, y + 54), time_left(value.get('resets_at')).replace(' ', ''), align='right')
+ return image
+
+
+def render_page(snapshot, page=0, style='pixel'):
+ # Keep the former second-frame URL usable while publishing only one LCD image.
+ if page not in (0, 1):
+ raise IndexError('Unknown frame')
+ if style not in STYLES:
+ raise ValueError('Unknown display style')
+ from token_tv.themes import RENDERERS
+ renderer = {'pixel': render_pixel, 'clean': render_clean, 'arcade': render_arcade,
+ 'columns': render_columns, 'orbit': render_orbit, **RENDERERS}[style]
+ image = renderer(snapshot)
+ buffer = io.BytesIO()
+ image.save(buffer, format='JPEG', quality=92, subsampling=0)
+ return buffer.getvalue()
+
+
+HTML = '''<!doctype html>
+<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>TokenTV · Account usage</title>
+<style>
+:root{--color-text:#d9dde1;--color-claude:#d68e68;--color-codex:#a799e5;--color-grok:#cbd1d7;--color-level-low:#76a99a;--color-level-medium:#93c9b9;--color-level-high:#d1b275;--color-level-critical:#d8877e;color-scheme:dark;font-family:system-ui,sans-serif;background:#0d1115;color:var(--color-text)}
+*{box-sizing:border-box}html,body{overflow-x:clip}body{margin:0}main{max-width:1060px;margin:auto;padding:32px}
+header{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #303b46;padding-bottom:18px}
+.brand{letter-spacing:.18em;font-weight:700;font-size:13px}.muted{color:var(--color-text);opacity:.75;font-size:13px}
+h1{font-size:32px;letter-spacing:-.035em;margin:28px 0;overflow-wrap:anywhere;min-width:0}.layout{display:grid;grid-template-columns:290px minmax(0,1fr);gap:42px}
+.screen{background:#07090b;padding:24px;border-radius:16px;border:1px solid #303b46;width:290px}
+.screen img{display:block;width:240px;height:240px;image-rendering:pixelated}
+:root{--color-control:#172028;--color-control-hover:#24313d;--color-control-ink:var(--color-text);--color-control-border:#455363;--color-focus:var(--color-text);--color-control-selected:var(--color-text);--color-control-selected-ink:#10151b;--color-control-muted:var(--color-text);--color-control-error:var(--color-text)}
+.style-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;width:290px;margin-top:14px}
+.style-button{font:inherit;font-size:13px;line-height:1.2;white-space:nowrap;padding:11px 14px;border:1px solid var(--color-control-border);border-radius:5px;background:var(--color-control);color:var(--color-control-ink);cursor:pointer}
+.style-button:hover,.style-button.is-hover{background:var(--color-control-hover)}
+.style-button:focus-visible,.style-button.is-focus{outline:2px solid var(--color-focus);outline-offset:3px}
+.style-button:active,.style-button.is-active{background:var(--color-control-border)}
+.style-button[aria-pressed=true]{background:var(--color-control-selected);color:var(--color-control-selected-ink);font-weight:650}
+.style-button:disabled{opacity:.5;cursor:default}
+.style-button[data-state=loading]{color:var(--color-control-muted)}
+.style-button[data-state=error]{border-color:var(--color-control-error);border-style:dashed}
+.style-button[data-state=success]{border-color:var(--color-control-selected)}
+.more-styles{margin-top:12px}.more-styles summary{font-size:12px;cursor:pointer}.apply-style{grid-column:1/-1}.display-state{min-height:16px;width:290px;font-size:12px;color:var(--color-control-muted)}
+.display-state[data-state=error]{color:var(--color-control-error)}
+.group{margin-bottom:24px;--provider-ink:var(--color-text)}.group[data-provider=claude]{--provider-ink:var(--color-claude)}.group[data-provider=codex]{--provider-ink:var(--color-codex)}.group[data-provider=grok]{--provider-ink:var(--color-grok)}.group h2{font-size:12px;letter-spacing:.1em;color:var(--color-text);opacity:.75;margin:0 0 6px}
+.card{padding:12px 0;border-bottom:1px solid #26313c}.cardhead{display:flex;justify-content:space-between;align-items:center}
+.name{font-size:16px;font-weight:600}.status{font-size:12px;color:var(--color-text);opacity:.75}
+.window{display:grid;grid-template-columns:58px minmax(0,1fr) 44px 74px;align-items:center;gap:10px;margin-top:9px;font-variant-numeric:tabular-nums;font-size:12px}
+.usage-meter{width:100%;height:6px;background:#28313a;--gauge-ink:var(--color-level-low)}.usage-meter[data-level=medium]{--gauge-ink:var(--color-level-medium)}.usage-meter[data-level=high]{--gauge-ink:var(--color-level-high)}.usage-meter[data-level=critical]{--gauge-ink:var(--color-level-critical)}.usage-fill{display:block;height:100%;background:linear-gradient(90deg,rgba(0,0,0,.22),transparent),var(--gauge-ink)}.note{font-size:11px;color:var(--color-text);opacity:.75;margin-top:7px}
+.gauge-legend{display:flex;flex-wrap:wrap;gap:8px;font-size:10px;color:var(--color-text);margin-top:12px;max-width:290px}.gauge-legend span{display:flex;align-items:center;gap:4px}.gauge-legend i{width:6px;height:6px;background:var(--color-level-low)}.gauge-legend .medium{background:var(--color-level-medium)}.gauge-legend .high{background:var(--color-level-high)}.gauge-legend .critical{background:var(--color-level-critical)}
+footer{margin-top:24px;border-top:1px solid #303b46;padding-top:16px;color:var(--color-text);opacity:.75;font-size:12px;line-height:1.8}
+@media(max-width:740px){main{padding:24px 18px}.layout{grid-template-columns:minmax(0,1fr);gap:24px}.screen{width:282px;padding:20px}.style-picker,.display-state{width:282px}.window{grid-template-columns:52px minmax(0,1fr) 42px 65px}}
+</style>
+<main><header><span class="brand">TOKENTV</span><span class="muted" id="updated">Connecting</span></header>
+<h1>Account usage</h1><div class="layout">
+<section><div class="screen"><img id="frame" width="240" height="240" alt="Live three-provider clock overview" src="/frame/0.jpg"></div>
+<div class="style-picker" role="group" aria-label="Clock style">
+<button type="button" class="style-button" id="digital" aria-pressed="false">Digital</button>
+<button type="button" class="style-button" id="neon" aria-pressed="false">Neon</button>
+<button type="button" class="style-button" id="retro" aria-pressed="false">Pixel Retro</button>
+<button type="button" class="style-button" id="modern" aria-pressed="false">Modern</button>
+<button type="button" class="style-button" id="sakura" aria-pressed="false">Sakura</button>
+</div><details class="more-styles"><summary>More styles</summary>
+<div class="style-picker" role="group" aria-label="Earlier clock styles">
+<button type="button" class="style-button" id="pixel" aria-pressed="true">Pixel</button>
+<button type="button" class="style-button" id="clean" aria-pressed="false">Clean</button>
+<button type="button" class="style-button" id="arcade" aria-pressed="false">Arcade</button>
+<button type="button" class="style-button" id="columns" aria-pressed="false">Columns</button>
+<button type="button" class="style-button" id="orbit" aria-pressed="false">Orbit</button>
+</div></details><div class="style-picker">
+<button type="button" class="style-button apply-style" id="apply" disabled aria-describedby="display-state">Apply to clock</button></div>
+<p class="display-state" id="display-state" role="status" aria-live="polite">Loading clock style</p>
+<p class="muted">240 × 240 · Live clock view</p><div class="gauge-legend" aria-label="Used quota levels"><span><i></i>0–49%</span><span><i class="medium"></i>50–79%</span><span><i class="high"></i>80–89%</span><span><i class="critical"></i>90–100%</span></div></section><section id="accounts"></section></div>
+<footer>Percentages and bars show <strong>used</strong> quota. Times show when that quota resets.<br>
+The clock shows the highest reported usage window for one account per provider. All account windows appear here.<br>
+Grok BUDGET measures the CLI billing budget, not web conversation limits.<br>
+Laptop-linked accounts update while the laptop is online. Missing quotas are shown as unknown.</footer></main>
+<script>
+const labels={ok:'Connected',loading:'Loading',auth_required:'Login needed',identity_mismatch:'Check account',quota_unavailable:'Quota unavailable',stale:'Previous value',rate_limited:'Retry later',error:'Fetch failed'};
+function el(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e}
+function reset(value){if(!value)return '--';let m=Math.max(0,Math.ceil((value-Date.now()/1000)/60));return m>=1440?Math.floor(m/1440)+'d '+Math.floor(m%1440/60)+'h':Math.floor(m/60)+'h '+m%60+'m'}
+let selectedStyle=null,displayInfo=null,busy=false,localError=false;
+const styles=['pixel','clean','arcade','columns','orbit','digital','neon','retro','modern','sakura'];
+const styleName=s=>s==='retro'?'Pixel Retro':s?s.charAt(0).toUpperCase()+s.slice(1):'Pixel';
+function paintStyle(){
+const choice=selectedStyle||'pixel';
+for(const s of styles){const b=document.querySelector('#'+s);b.setAttribute('aria-pressed',String(s===choice));b.disabled=busy}
+const apply=document.querySelector('#apply');apply.disabled=busy||!displayInfo||(choice===displayInfo.style&&displayInfo.status!=='error'&&!localError);
+apply.textContent=busy?'Applying...':'Apply to clock';apply.dataset.state=busy?'loading':localError||displayInfo?.status==='error'?'error':displayInfo?.status==='ok'?'success':'default';
+const note=document.querySelector('#display-state');note.dataset.state=localError||displayInfo?.status==='error'?'error':'default';
+note.textContent=localError?'Could not apply style. Retry.':!displayInfo?'Loading clock style':displayInfo.status==='queued'?'Sending '+styleName(displayInfo.style)+' image...':displayInfo.status==='error'?'Clock upload failed. Retry.':displayInfo.status==='preview_only'?'Preview only': 'Image sent: '+styleName(displayInfo.applied_style);
+if(displayInfo&&choice!==displayInfo.style&&!busy&&!localError&&displayInfo.status!=='error')note.textContent='Preview: '+styleName(choice)+' · Apply to use';
+document.querySelector('#frame').alt=styleName(choice)+' clock preview';
+document.querySelector('#frame').src='/frame/0.jpg?style='+choice+'&t='+Date.now();
+}
+async function refreshDisplay(){try{const r=await fetch('/display',{cache:'no-store'});if(!r.ok)throw Error();const data=await r.json();const dirty=displayInfo&&selectedStyle!==displayInfo.style;displayInfo=data;if(!selectedStyle||!dirty)selectedStyle=data.style;paintStyle()}catch(e){document.querySelector('#display-state').textContent='Clock status unavailable'}}
+for(const s of styles)document.querySelector('#'+s).onclick=()=>{selectedStyle=s;localError=false;paintStyle()};
+document.querySelector('#apply').onclick=async()=>{busy=true;localError=false;paintStyle();try{const r=await fetch('/display/style',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({style:selectedStyle})});if(!r.ok)throw Error();displayInfo=await r.json()}catch(e){localError=true}finally{busy=false;paintStyle()}};
+async function update(){try{
+const response=await fetch('/snapshot',{cache:'no-store'});if(!response.ok)throw Error();const data=await response.json();
+const container=document.querySelector('#accounts');container.replaceChildren();
+for(const provider of ['claude','codex','grok']){const group=el('section',undefined,'group');group.dataset.provider=provider;group.append(el('h2',provider.toUpperCase()));
+Object.values(data.accounts).filter(a=>a.provider===provider).forEach(a=>{const c=el('article',undefined,'card');const head=el('div',undefined,'cardhead');head.append(el('span',a.alias,'name'),el('span',labels[a.status]||a.status,'status'));c.append(head);
+a.windows.forEach(w=>{const row=el('div',undefined,'window');const bar=el('div',undefined,'usage-meter');const used=Math.max(0,Math.min(100,w.used_percent));bar.dataset.level=used<50?'low':used<80?'medium':used<90?'high':'critical';bar.setAttribute('role','meter');bar.setAttribute('aria-label','Used quota');bar.setAttribute('aria-valuemin','0');bar.setAttribute('aria-valuemax','100');bar.setAttribute('aria-valuenow',String(used));const fill=el('span',undefined,'usage-fill');fill.style.width=used+'%';bar.append(fill);row.append(el('span',w.label),bar,el('span',Math.round(w.used_percent)+'%'),el('span',reset(w.resets_at)));c.append(row)});
+if(a.source==='laptop')c.append(el('div','Laptop link · 5 min refresh','note'));
+if(a.fetched_at)c.append(el('div','Checked '+new Date(a.fetched_at*1000).toLocaleTimeString('en-GB'),'note'));
+if(a.status==='stale'&&a.last_success_at)c.append(el('div','Last success: '+new Date(a.last_success_at*1000).toLocaleString('en-US'),'note'));
+group.append(c)});container.append(group)}
+document.querySelector('#updated').textContent=data.updated_at?'Updated '+new Date(data.updated_at*1000).toLocaleTimeString('en-GB'):'Loading';
+paintStyle();
+}catch(e){document.querySelector('#updated').textContent='Server unavailable'}}
+update();refreshDisplay();setInterval(update,30000);setInterval(refreshDisplay,2000);
+</script></html>
+'''
diff --git a/token_tv/live.py b/token_tv/live.py
new file mode 100644
index 0000000..5909940
--- /dev/null
+++ b/token_tv/live.py
@@ -0,0 +1,234 @@
+"""Live account dashboard and stock-firmware image publisher."""
+import argparse
+import hashlib
+import json
+import os
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from token_tv.device import FILES, PhotoDisplay
+from token_tv.display import STYLES, render_page
+from token_tv.web_assets import HTML, ASSETS, asset
+from token_tv.sources import load_config
+from token_tv.state import UsageStore
+
+
+def write_json(path, data):
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")))
+ os.chmod(temporary, 0o600)
+ temporary.replace(path)
+
+
+class DisplayPreferences:
+ def __init__(self, config_path, config):
+ self.path = Path(config_path)
+ self.config = dict(config)
+ self.style = config.get('display_style', 'pixel')
+ self.applied_style = None
+ self.status = 'queued' if config.get('device_url') else 'preview_only'
+ self.lock = threading.Lock()
+ self.changed = threading.Event()
+
+ def snapshot(self):
+ with self.lock:
+ return {'style': self.style, 'applied_style': self.applied_style,
+ 'status': self.status, 'styles': list(STYLES)}
+
+ def set_style(self, style):
+ if style not in STYLES:
+ raise ValueError('Unknown display style')
+ with self.lock:
+ updated = dict(load_config(self.path), display_style=style)
+ write_json(self.path, updated)
+ self.config = updated
+ self.style = style
+ self.status = 'queued' if self.config.get('device_url') else 'preview_only'
+ self.changed.set()
+
+ def delivered(self, style, success):
+ with self.lock:
+ if success:
+ self.applied_style = style
+ self.status = ('queued' if style != self.style else 'ok' if success else 'error')
+
+
+def handler(store, preferences=None):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ return
+
+ def do_GET(self):
+ url = urlparse(self.path)
+ path = url.path
+ snapshot = store.snapshot()
+ display = preferences.snapshot() if preferences else {'style': 'pixel', 'status': 'preview_only', 'styles': list(STYLES)}
+ snapshot['display'] = display
+ content_type = "application/json; charset=utf-8"
+ if path == "/":
+ body = HTML.encode()
+ content_type = "text/html; charset=utf-8"
+ elif path in ASSETS:
+ body, content_type = asset(path)
+ elif path == "/snapshot":
+ body = json.dumps(snapshot, ensure_ascii=False, separators=(",", ":")).encode()
+ elif path.startswith("/snapshot/") and path[10:] in snapshot["accounts"]:
+ body = json.dumps(snapshot["accounts"][path[10:]], ensure_ascii=False, separators=(",", ":")).encode()
+ elif path in ("/frame/0.jpg", "/frame/1.jpg"):
+ style = parse_qs(url.query).get('style', [display['style']])[0]
+ if style not in STYLES:
+ self.send_error(400, 'Unknown display style')
+ return
+ body = render_page(snapshot, int(path[7]), style)
+ content_type = "image/jpeg"
+ elif path == '/display':
+ body = json.dumps(display).encode()
+ elif path == "/health":
+ body = json.dumps({"status": "ok", "updated_at": snapshot["updated_at"]}).encode()
+ else:
+ self.send_error(404)
+ return
+ self.reply(200, body, content_type)
+
+ def reply(self, status, body, content_type='application/json; charset=utf-8'):
+ self.send_response(status)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("X-Content-Type-Options", "nosniff")
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ if urlparse(self.path).path != '/display/style':
+ self.send_error(404)
+ return
+ if preferences is None:
+ self.send_error(409, 'Display settings unavailable')
+ return
+ origin = self.headers.get('Origin')
+ if origin and (urlparse(origin).scheme not in ('http', 'https') or urlparse(origin).netloc != self.headers.get('Host')):
+ self.send_error(403, 'Origin mismatch')
+ return
+ try:
+ length = int(self.headers.get('Content-Length', '0'))
+ if not 0 < length <= 1024 or self.headers.get('Content-Type', '').split(';')[0] != 'application/json':
+ raise ValueError('Invalid JSON request')
+ data = json.loads(self.rfile.read(length))
+ if not isinstance(data, dict) or set(data) != {'style'} or data['style'] not in STYLES:
+ raise ValueError('Unknown display style')
+ preferences.set_style(data['style'])
+ except (ValueError, UnicodeError):
+ self.send_error(400, 'Choose a supported display style')
+ return
+ except OSError:
+ self.send_error(500, 'Could not save display choice')
+ return
+ self.reply(200, json.dumps(preferences.snapshot()).encode())
+ return Handler
+
+
+def main():
+ parser = argparse.ArgumentParser(description="TokenTV live account display")
+ parser.add_argument("--config", required=True, help="Credential-free account metadata")
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=8787)
+ parser.add_argument("--once", action="store_true")
+ parser.add_argument("--output", help="Write a normalized snapshot rather than stdout")
+ parser.add_argument("--state-dir", default=".runtime")
+ parser.add_argument("--restore-display", action="store_true")
+ args = parser.parse_args()
+ config = load_config(args.config)
+ if config.get("font"):
+ os.environ["TOKEN_TV_FONT"] = config["font"]
+ state_dir = Path(args.state_dir)
+ device = PhotoDisplay(config["device_url"]) if config.get("device_url") else None
+ backup_path = state_dir / "display-original.json"
+ if args.restore_display:
+ if not device or not backup_path.is_file():
+ parser.error("A display and its original state backup are required")
+ device.restore(json.loads(backup_path.read_text()))
+ print("Original display selection restored.")
+ return
+ store = UsageStore(config["accounts"])
+ preferences = DisplayPreferences(args.config, config)
+ interval = max(60, int(config.get("poll_seconds", 300)))
+ stopping = threading.Event()
+ original = None
+ activated = False
+
+ def cycle(refresh=True):
+ nonlocal original, activated
+ if refresh:
+ store.refresh()
+ snapshot = store.snapshot()
+ style = preferences.snapshot()['style']
+ if not args.once and device:
+ receipts = []
+ phase = "backup"
+ try:
+ if original is None:
+ original = json.loads(backup_path.read_text()) if backup_path.is_file() else device.capture()
+ if not backup_path.is_file():
+ write_json(backup_path, original)
+ phase = "upload"
+ for page, name in enumerate(FILES):
+ jpeg = render_page(snapshot, page, style)
+ (state_dir / name).write_bytes(jpeg)
+ receipts.append(dict(device.upload(name, jpeg), sha256=hashlib.sha256(jpeg).hexdigest()))
+ if not activated:
+ phase = "activate"
+ device.activate(original)
+ activated = True
+ write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "uploads": receipts})
+ preferences.delivered(style, True)
+ except (OSError, ValueError, KeyError) as error:
+ write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "status": "error", "phase": phase,
+ "uploads": receipts, "http_status": getattr(error, "code", None)})
+ preferences.delivered(style, False)
+ snapshot['display'] = preferences.snapshot()
+ write_json(state_dir / "snapshot.json", snapshot)
+ if args.output:
+ write_json(args.output, snapshot)
+
+ if args.once:
+ cycle()
+ if not args.output:
+ print(json.dumps(store.snapshot(), ensure_ascii=False, separators=(",", ":")))
+ return
+
+ def poll():
+ next_refresh = 0
+ while not stopping.is_set():
+ preferences.changed.clear()
+ refresh = time.monotonic() >= next_refresh
+ try:
+ cycle(refresh)
+ except Exception:
+ # Never serialize exception text, which may include auth material.
+ print("TokenTV poll failed; retained previous snapshot.", flush=True)
+ if refresh:
+ next_refresh = time.monotonic() + interval
+ preferences.changed.wait(max(0, next_refresh - time.monotonic()))
+
+ thread = threading.Thread(target=poll, daemon=True)
+ thread.start()
+ try:
+ with ThreadingHTTPServer((args.host, args.port), handler(store, preferences)) as server:
+ print(f"TokenTV live listening at http://{args.host}:{args.port}", flush=True)
+ server.serve_forever()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ stopping.set()
+ preferences.changed.set()
+ thread.join(timeout=2)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/token_tv/sources.py b/token_tv/sources.py
new file mode 100644
index 0000000..aad0788
--- /dev/null
+++ b/token_tv/sources.py
@@ -0,0 +1,295 @@
+"""Use credentials in their owning CLI homes; export only approved fields."""
+import json
+import os
+import queue
+import re
+import subprocess
+import threading
+import time
+from pathlib import Path
+from urllib.error import HTTPError
+from urllib.request import Request, urlopen
+
+from token_tv.usage import normalize_claude, normalize_codex, normalize_grok, timestamp, window
+from token_tv.display import STYLES
+
+
+class SourceError(Exception):
+ def __init__(self, code):
+ self.code = code
+ super().__init__(code)
+
+
+def scoped_env(provider, root):
+ env = dict(os.environ)
+ for key in ("OPENAI_API_KEY", "CODEX_API_KEY", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN",
+ "GROK_OAUTH_TOKEN", "GROK_API_KEY", "XAI_API_KEY", "GROK_AUTH_TOKEN", "CLAUDECODE"):
+ env.pop(key, None)
+ variable = {"claude": "CLAUDE_CONFIG_DIR", "codex": "CODEX_HOME", "grok": "GROK_HOME"}[provider]
+ env[variable] = str(root)
+ if provider == "claude":
+ env["CLAUDE_SECURESTORAGE_CONFIG_DIR"] = str(root)
+ return env
+
+
+class RPC:
+ def __init__(self, command, env):
+ self.process = subprocess.Popen(command, env=env, stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
+ text=True, bufsize=1)
+ self.messages = queue.Queue()
+ self.sequence = 0
+ def read():
+ for line in self.process.stdout:
+ try:
+ self.messages.put(json.loads(line))
+ except ValueError:
+ continue
+ self.messages.put(None)
+ self.reader = threading.Thread(target=read, daemon=True)
+ self.reader.start()
+
+ def call(self, method, params=None, timeout=25):
+ self.sequence += 1
+ identifier = self.sequence
+ self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": identifier,
+ "method": method, "params": params or {}}) + "\n")
+ self.process.stdin.flush()
+ deadline = time.monotonic() + timeout
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise SourceError("timeout")
+ try:
+ reply = self.messages.get(timeout=remaining)
+ except queue.Empty:
+ raise SourceError("timeout") from None
+ if reply is None:
+ raise SourceError("cli_unavailable")
+ if reply.get("id") != identifier:
+ # This client never permits agent tool execution.
+ if "method" in reply and "id" in reply:
+ self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": reply["id"],
+ "error": {"code": -32601, "message": "Not supported"}}) + "\n")
+ self.process.stdin.flush()
+ continue
+ if "error" in reply:
+ error = reply["error"]
+ message = str(error.get("message", "")).lower()
+ code = "auth_required" if any(x in message for x in ("auth", "login", "sign in", "token")) else "rpc_error"
+ if error.get("code") == -32601:
+ code = "method_unavailable"
+ raise SourceError(code)
+ return reply.get("result") or {}
+
+ def close(self):
+ if self.process.poll() is None:
+ self.process.terminate()
+ try:
+ self.process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ self.process.kill()
+ self.process.wait()
+ for stream in (self.process.stdin, self.process.stdout):
+ stream.close()
+ self.reader.join(timeout=1)
+
+
+def load_config(path):
+ data = json.loads(Path(path).read_text())
+ if set(data) - {"accounts", "device_url", "poll_seconds", "font", "display_style"}:
+ raise ValueError("Unsupported configuration field")
+ if data.get('display_style', 'pixel') not in STYLES:
+ raise ValueError('Unknown display style')
+ seen = set()
+ allowed = {"key", "alias", "provider", "source_home", "email", "snapshot_file", "fallback_snapshot_file", "refresh_with_cli"}
+ for account in data.get("accounts", []):
+ if set(account) - allowed:
+ raise ValueError("Only credential-free account metadata is allowed")
+ if account.get("provider") not in ("claude", "codex", "grok"):
+ raise ValueError("Unknown provider")
+ key = account.get("key", "")
+ if not re.fullmatch(r"[a-z0-9_-]{1,48}", key) or key in seen:
+ raise ValueError("Account keys must be unique")
+ if not isinstance(account.get("alias"), str) or not 1 <= len(account["alias"]) <= 32:
+ raise ValueError("Account alias is required")
+ if not account.get("email"):
+ raise ValueError("Expected account identity is required")
+ seen.add(key)
+ if not seen:
+ raise ValueError("At least one account is required")
+ return data
+
+
+def json_get(url, headers=None):
+ with urlopen(Request(url, headers=headers or {}), timeout=20) as response:
+ return json.load(response)
+
+
+def claude_payload(account):
+ root = Path(account["source_home"]).expanduser()
+ token = json.loads((root / ".credentials.json").read_text())["claudeAiOauth"]["accessToken"]
+ headers = {"Authorization": "Bearer " + token, "Accept": "application/json",
+ "User-Agent": "claude-code/2.1.287", "anthropic-beta": "oauth-2025-04-20"}
+ try:
+ profile = json_get("https://api.anthropic.com/api/oauth/profile", headers)
+ usage = json_get("https://api.anthropic.com/api/oauth/usage", headers)
+ except HTTPError as error:
+ if error.code != 401 or not account.get("refresh_with_cli"):
+ raise
+ # The CLI owns refresh/rotation. No manual refresh-token writes.
+ env = scoped_env("claude", root)
+ subprocess.run(["claude", "-p", "Reply only OK.", "--tools", "",
+ "--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"]
+ 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)
+ return profile, usage
+
+
+def email_from_profile(profile):
+ for item in (profile.get("account") or {}, profile):
+ for key in ("emailAddress", "email_address", "email"):
+ if isinstance(item.get(key), str):
+ return item[key]
+ return None
+
+
+def identity_matches(expected, actual):
+ return bool(actual and expected.strip().casefold() == actual.strip().casefold())
+
+
+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)
+ 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 {}
+ if identity.get("type") != "chatgpt":
+ raise SourceError("auth_required")
+ if not identity_matches(account["email"], identity.get("email")):
+ raise SourceError("identity_mismatch")
+ return rpc.call("account/rateLimits/read")
+ finally:
+ rpc.close()
+
+
+def grok_payload(account):
+ root = Path(account["source_home"]).expanduser()
+ if not (root / "auth.json").is_file():
+ 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)
+ try:
+ rpc.call("initialize", {"protocolVersion": 1, "clientCapabilities": {
+ "fs": {"readTextFile": False, "writeTextFile": False}, "terminal": False}})
+ try:
+ return rpc.call("_x.ai/billing", timeout=20)
+ except SourceError as error:
+ if error.code != "method_unavailable":
+ raise
+ return rpc.call("x.ai/billing", timeout=20)
+ finally:
+ rpc.close()
+
+
+def grok_identity(account):
+ data = json.loads((Path(account["source_home"]).expanduser() / "auth.json").read_text())
+ emails = set()
+ def scan(value):
+ if isinstance(value, dict):
+ if isinstance(value.get("email"), str):
+ emails.add(value["email"].strip().casefold())
+ for item in value.values():
+ if isinstance(item, (dict, list)):
+ scan(item)
+ elif isinstance(value, list):
+ for item in value:
+ scan(item)
+ scan(data)
+ if len(emails) != 1:
+ raise SourceError("identity_mismatch")
+ return emails.pop()
+
+
+def imported_row(account):
+ data = json.loads(Path(account["snapshot_file"]).expanduser().read_text())
+ row = data["accounts"][account["key"]]
+ if row.get("provider") != account["provider"] or row.get("alias") != account["alias"]:
+ raise SourceError("identity_mismatch")
+ fetched = timestamp(row.get("fetched_at"))
+ if fetched is None or fetched > time.time() + 60:
+ raise SourceError("invalid_snapshot")
+ allowed_status = {"ok", "quota_unavailable", "auth_required", "identity_mismatch", "error", "rate_limited", "stale"}
+ if row.get("status") not in allowed_status:
+ raise SourceError("invalid_snapshot")
+ clean = {"key": account["key"], "alias": account["alias"], "provider": account["provider"],
+ "status": row["status"], "windows": [], "fetched_at": fetched,
+ "identity_verified": row.get("identity_verified") is True, "source": "laptop"}
+ last_success = timestamp(row.get("last_success_at"))
+ if last_success and last_success <= fetched:
+ clean["last_success_at"] = last_success
+ for value in row.get("windows", []):
+ if value.get("label") not in {"5H", "WEEK", "WINDOW", "BUDGET"}:
+ continue
+ item = window(value["label"], value.get("used_percent"), value.get("resets_at"),
+ value.get("duration_minutes"))
+ if item:
+ clean["windows"].append(item)
+ if time.time() - fetched > 900:
+ clean["status"] = "stale"
+ clean["error_code"] = "laptop_offline"
+ return clean
+
+
+def fetch_account(account):
+ row = {"key": account["key"], "alias": account["alias"], "provider": account["provider"],
+ "status": "auth_required", "windows": [], "fetched_at": time.time(),
+ "identity_verified": False, "source": "mini"}
+ try:
+ if account.get("snapshot_file"):
+ return imported_row(account)
+ if account["provider"] == "claude":
+ profile, data = claude_payload(account)
+ if not identity_matches(account["email"], email_from_profile(profile)):
+ raise SourceError("identity_mismatch")
+ row["windows"] = normalize_claude(data)
+ row["identity_verified"] = True
+ elif account["provider"] == "codex":
+ row["windows"] = normalize_codex(codex_payload(account))
+ row["identity_verified"] = True
+ else:
+ if not identity_matches(account["email"], grok_identity(account)):
+ raise SourceError("identity_mismatch")
+ data = grok_payload(account)
+ row["windows"] = normalize_grok(data)
+ row["identity_verified"] = True
+ row["status"] = "ok" if row["windows"] else "quota_unavailable"
+ except SourceError as error:
+ row["status"] = error.code if error.code in {"auth_required", "identity_mismatch", "stale"} else "error"
+ row["error_code"] = error.code
+ except HTTPError as error:
+ row["status"] = {401: "auth_required", 403: "auth_required", 429: "rate_limited"}.get(error.code, "error")
+ row["error_code"] = "http_" + str(error.code)
+ except FileNotFoundError:
+ row["status"] = "auth_required"
+ except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
+ row["status"] = "error"
+ row["error_code"] = "source_unavailable"
+ row["fetched_at"] = time.time()
+ if row["status"] not in {"ok", "quota_unavailable", "identity_mismatch"} and account.get("fallback_snapshot_file"):
+ try:
+ fallback = imported_row(dict(account, snapshot_file=account["fallback_snapshot_file"]))
+ fallback["mini_auth_status"] = row["status"]
+ return fallback
+ except (SourceError, OSError, ValueError, KeyError, TypeError):
+ pass
+ return row
diff --git a/token_tv/state.py b/token_tv/state.py
new file mode 100644
index 0000000..ccd9e30
--- /dev/null
+++ b/token_tv/state.py
@@ -0,0 +1,53 @@
+"""Polling owns provider requests; HTTP readers only see cached state."""
+import copy
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+from token_tv.sources import fetch_account
+
+
+class UsageStore:
+ def __init__(self, accounts, fetch=fetch_account):
+ self.accounts = accounts
+ self.fetch = fetch
+ self.lock = threading.Lock()
+ self.updated_at = 0
+ self.rows = {a["key"]: {"key": a["key"], "alias": a["alias"], "provider": a["provider"],
+ "status": "loading", "windows": [], "fetched_at": 0,
+ "identity_verified": False, "source": "mini"}
+ for a in accounts}
+
+ def refresh(self):
+ with ThreadPoolExecutor(max_workers=min(4, len(self.accounts))) as executor:
+ rows = list(executor.map(self.fetch, self.accounts))
+ with self.lock:
+ for row in rows:
+ previous = self.rows[row["key"]]
+ if row["status"] in ("ok", "quota_unavailable"):
+ row["last_success_at"] = row["fetched_at"]
+ elif row["status"] != "identity_mismatch" and previous.get("windows") and previous.get("last_success_at"):
+ row["error_code"] = row.get("error_code", row["status"])
+ row["status"] = "stale"
+ row["windows"] = previous["windows"]
+ row["last_success_at"] = previous["last_success_at"]
+ row["identity_verified"] = previous.get("identity_verified", False)
+ self.rows[row["key"]] = row
+ self.updated_at = int(time.time())
+
+ def snapshot(self):
+ with self.lock:
+ rows = copy.deepcopy(self.rows)
+ updated = self.updated_at
+ now = time.time()
+ for row in rows.values():
+ if row["status"] == "ok" and now - row.get("last_success_at", row["fetched_at"]) > 900:
+ row["status"] = "stale"
+ row.setdefault("error_code", "snapshot_old")
+ by_label = {w["label"]: w for w in row["windows"]}
+ for prefix, label in (("session", "5H"), ("weekly", "WEEK")):
+ value = by_label.get(label, {})
+ row[prefix + "_percent"] = value.get("used_percent")
+ reset = value.get("resets_at")
+ row[prefix + "_reset_minutes"] = max(0, int((reset - now + 59) // 60)) if reset else None
+ return {"schema": 1, "updated_at": updated, "accounts": rows}
diff --git a/token_tv/themes.py b/token_tv/themes.py
new file mode 100644
index 0000000..1298388
--- /dev/null
+++ b/token_tv/themes.py
@@ -0,0 +1,501 @@
+"""Six LCD themes that match the web appearances; every reading stays live text.
+
+Each 240×240 frame shows one account per provider in three rows. Fonts are the
+bundled web fonts, gauges keep ten 10% cells, and each used-quota band is drawn as
+a two-tone gradient from its start colour to its tip (tokens.css lvl-*-2 → lvl-*).
+"""
+import functools
+import math
+import random
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFilter, ImageFont
+
+from token_tv.display import (
+ STATUS, account_label, mascot, overview_rows, primary_window, quota_period, time_left,
+)
+
+WEB = Path(__file__).with_name('web')
+SIZE = 240
+ROWS = (3, 82, 161)
+ROW_H = 76
+
+# (start, tip) per used-quota band: below 50, 50–79, 80–89, 90–100.
+BANDS = {
+ 'digital': (('#13b884', '#3dfcb0'), ('#6fd13a', '#c3f562'), ('#ff6a2b', '#ff9d45'), ('#e8243f', '#ff5a6a')),
+ 'neon': (('#00b894', '#2cf5b0'), ('#1f7bff', '#38d6ff'), ('#ff8a1f', '#ffc23d'), ('#ff2a4a', '#ff3d81')),
+ 'retro': (('#2aa84a', '#5ee06a'), ('#8fc93a', '#d3e84a'), ('#ff7a1f', '#ffab3d'), ('#d62b3c', '#ff5a5f')),
+ 'modern': (('#22c4a6', '#6ee7b7'), ('#2f8cff', '#79c0ff'), ('#f08a24', '#f6c453'), ('#e8455f', '#f7768e')),
+ 'sakura': (('#fbdde6', '#f2b8c9'), ('#f5bccb', '#e7899f'), ('#ea98ae', '#cf5679'), ('#d65a80', '#a3264b')),
+ 'hud': (('#14a874', '#35e0a0'), ('#1a7dff', '#3cc4ff'), ('#ff7a1a', '#ffb23f'), ('#e01e3c', '#ff4d6a')),
+}
+ACCENT = {
+ 'neon': {'claude': ('#ff8a2b', '#ffd23f'), 'codex': ('#22d3ee', '#4f7bff'), 'grok': ('#d946ef', '#8b5cf6')},
+ 'retro': {'claude': ('#ff9f43', '#ffcf6b'), 'codex': ('#3ee68b', '#9bffc8'), 'grok': ('#b388ff', '#e0d0ff')},
+ 'modern': {'claude': ('#f4a07a',) * 2, 'codex': ('#6ea8ff',) * 2, 'grok': ('#5ee0b5',) * 2},
+ 'sakura': {'claude': ('#cc6440',) * 2, 'codex': ('#6b4fa0',) * 2, 'grok': ('#34283a',) * 2},
+ 'hud': {'claude': ('#ff8a3d', '#ffb47a'), 'codex': ('#2fd4ff', '#8be9ff'), 'grok': ('#3ef29b', '#9dffcb')},
+}
+
+
[email protected]_cache(maxsize=None)
+def face(name, size, weight=None):
+ try:
+ loaded = ImageFont.truetype(str(WEB / name), size)
+ except OSError:
+ return ImageFont.load_default()
+ if weight is not None:
+ try:
+ loaded.set_variation_by_axes([weight])
+ except (OSError, ValueError, AttributeError):
+ pass
+ return loaded
+
+
+def rgb(color):
+ return tuple(int(color[i:i + 2], 16) for i in (1, 3, 5)) if isinstance(color, str) else tuple(color[:3])
+
+
+def mix(a, b, t):
+ a, b = rgb(a), rgb(b)
+ t = max(0.0, min(1.0, t))
+ return tuple(round(a[i] + (b[i] - a[i]) * t) for i in range(3))
+
+
+def band(theme, used):
+ return BANDS[theme][0 if used < 50 else 1 if used < 80 else 2 if used < 90 else 3]
+
+
+def reading(row):
+ value = primary_window(row)
+ used = max(0, min(100, value['used_percent'])) if value else None
+ period = quota_period(value) if value else STATUS.get(row['status'], 'NO DATA')
+ old = bool(value) and row['status'] != 'ok'
+ reset = time_left(value.get('resets_at')) if value else '--'
+ return used, period, old, reset
+
+
+def ghost(text):
+ """Unlit seven-segment cells: every lit glyph cell becomes 8."""
+ return ''.join(c if c in ' :' else '8' for c in text)
+
+
+class Canvas:
+ """Background, a blurred bloom layer and a crisp ink layer, composited once."""
+
+ def __init__(self, background):
+ self.base = Image.new('RGBA', (SIZE, SIZE), background)
+ self.ink = Image.new('RGBA', (SIZE, SIZE), (0, 0, 0, 0))
+ self.bloom = Image.new('RGBA', (SIZE, SIZE), (0, 0, 0, 0))
+ self.back = ImageDraw.Draw(self.base)
+ self.draw = ImageDraw.Draw(self.ink)
+ self.glow = ImageDraw.Draw(self.bloom)
+
+ def text(self, xy, text, font, fill, glow=None, anchor='la', **options):
+ try:
+ self.draw.text(xy, text, font=font, fill=fill, anchor=anchor, **options)
+ if glow:
+ self.glow.text(xy, text, font=font, fill=glow, anchor=anchor, **options)
+ except (KeyError, ValueError):
+ # Font features need libraqm; fall back to the default glyph forms.
+ options.pop('features', None)
+ self.draw.text(xy, text, font=font, fill=fill, anchor=anchor, **options)
+ if glow:
+ self.glow.text(xy, text, font=font, fill=glow, anchor=anchor, **options)
+
+ def spaced(self, xy, text, font, fill, tracking, anchor='la'):
+ x, y = xy
+ width = sum(self.draw.textlength(c, font=font) for c in text) + tracking * (len(text) - 1)
+ if anchor[0] == 'r':
+ x -= width
+ for c in text:
+ self.draw.text((x, y), c, font=font, fill=fill, anchor='l' + anchor[1])
+ x += self.draw.textlength(c, font=font) + tracking
+
+ def finish(self, blur=3):
+ out = self.base.copy()
+ if self.bloom.getbbox():
+ out.alpha_composite(self.bloom.filter(ImageFilter.GaussianBlur(blur)))
+ out.alpha_composite(self.bloom.filter(ImageFilter.GaussianBlur(blur * 2.5)))
+ out.alpha_composite(self.ink)
+ return out.convert('RGB')
+
+
[email protected]_cache(maxsize=None)
+def glyph(provider, size, color, stroke=None):
+ """Provider marks drawn at 4× and reduced for clean edges (burst, cube, ringed slash)."""
+ s = size * 4
+ image = Image.new('RGBA', (s, s), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(image)
+ width = round((stroke or max(1.6, size / 10)) * 4)
+ c = s / 2
+ if provider == 'claude':
+ reach = (0.49, 0.38, 0.46, 0.36, 0.48, 0.39, 0.47, 0.36, 0.49, 0.38, 0.46, 0.37)
+ for i, r in enumerate(reach):
+ a = math.radians(i * 30 + (4 if i % 2 else 0) - 90)
+ draw.line((c + math.cos(a) * s * 0.13, c + math.sin(a) * s * 0.13,
+ c + math.cos(a) * s * r, c + math.sin(a) * s * r), fill=color, width=width)
+ elif provider == 'codex':
+ k = s / 48
+ hexagon = [(24, 5), (40.5, 14.5), (40.5, 33.5), (24, 43), (7.5, 33.5), (7.5, 14.5), (24, 5)]
+ draw.line([(x * k, y * k) for x, y in hexagon], fill=color, width=width, joint='curve')
+ for end in ((7.5, 14.5), (40.5, 14.5), (24, 43)):
+ draw.line((24 * k, 24 * k, end[0] * k, end[1] * k), fill=color, width=width)
+ else:
+ r = s * 0.27
+ draw.ellipse((c - r, c - r, c + r, c + r), outline=color, width=width)
+ draw.polygon([(s * 0.1, s * 0.9), (s * 0.86, s * 0.12), (s * 0.9, s * 0.1), (s * 0.16, s * 0.9)], fill=color)
+ return image.resize((size, size), Image.Resampling.LANCZOS)
+
+
+def clock_mark(cv, center, r, color, width=1):
+ x, y = center
+ cv.draw.ellipse((x - r, y - r, x + r, y + r), outline=color, width=width)
+ cv.draw.line((x, y - r * 0.55, x, y, x + r * 0.45, y + r * 0.25), fill=color, width=width)
+
+
+def gauge(cv, box, used, colors, *, gap=3, shape='rect', radius=2, skew=0, track=(255, 255, 255, 30),
+ empty=(255, 255, 255, 70), stale=False, split=None, glow=False, shade=False, stepped=False):
+ """Ten 10% cells; the filled length samples one start→tip gradient of the band."""
+ x0, y0, x1, y1 = box
+ width, height = x1 - x0 + 1, y1 - y0 + 1
+ cell = (width - skew - 9 * gap) / 10
+ area = (width, height)
+ track_mask, fill_mask = Image.new('L', area, 0), Image.new('L', area, 0)
+ tm, fm = ImageDraw.Draw(track_mask), ImageDraw.Draw(fill_mask)
+
+ def outline(draw, i, fraction, fill, hollow=False):
+ a = i * (cell + gap)
+ b = a + cell * fraction
+ if shape == 'skew':
+ points = [(a + skew, 0), (b + skew, 0), (b, height - 1), (a, height - 1)]
+ draw.polygon(points, fill=None if hollow else fill, outline=fill if hollow else None)
+ elif shape == 'round':
+ draw.rounded_rectangle((a, 0, max(a + 1, b - 1), height - 1), radius=radius,
+ fill=None if hollow else fill, outline=fill if hollow else None)
+ else:
+ draw.rectangle((a, 0, max(a, b - 1), height - 1), fill=None if hollow else fill,
+ outline=fill if hollow else None)
+
+ for i in range(10):
+ outline(tm, i, 1, 255, hollow=used is None)
+ if used is not None and used / 10 - i > 0:
+ outline(fm, i, min(1.0, used / 10 - i), 255)
+ if used is None:
+ dots = Image.new('L', area, 0)
+ ImageDraw.Draw(dots).point([(x, y) for x in range(width) for y in range(height) if (x + y) % 3 == 0], fill=255)
+ track_mask = Image.composite(track_mask, Image.new('L', area, 0), dots)
+ cv.ink.paste(Image.new('RGBA', area, empty), (x0, y0), track_mask)
+ return
+ cv.ink.paste(Image.new('RGBA', area, track), (x0, y0), track_mask)
+ if not used:
+ return
+ full = math.floor(used / 10)
+ end = full * (cell + gap) + (used / 10 - full) * cell if used < 100 else width - skew
+ start, tip = colors
+ strip = Image.new('RGBA', area)
+ sd = ImageDraw.Draw(strip)
+ for x in range(width):
+ position = x if not stepped else (math.floor(x / (cell + gap)) + 0.5) * (cell + gap)
+ sd.line((x, 0, x, height), fill=mix(start, tip, position / max(1, end)) + (255,))
+ if stale:
+ for k in range(-height, width, 5):
+ fm.line((k, height, k + height, 0), fill=0, width=2)
+ if glow:
+ cv.bloom.paste(strip, (x0, y0), fill_mask)
+ cv.ink.paste(strip, (x0, y0), fill_mask)
+ if shade:
+ light = Image.new('RGBA', area, (255, 255, 255, 0))
+ ImageDraw.Draw(light).rectangle((0, 0, width, 1), fill=(255, 255, 255, 110))
+ ImageDraw.Draw(light).rectangle((0, height - 2, width, height), fill=(0, 0, 0, 80))
+ layer = Image.new('RGBA', (SIZE, SIZE), (0, 0, 0, 0))
+ layer.paste(light, (x0, y0), fill_mask)
+ cv.ink.alpha_composite(layer)
+ if split:
+ for i in range(10):
+ mid = x0 + i * (cell + gap) + cell / 2
+ cv.draw.rectangle((round(mid) - 1, y0, round(mid), y1), fill=split)
+
+
+def segment_time(reset):
+ """Seven segments cannot draw 'm': show under-a-day resets as a clock (18:11)."""
+ parts = reset.split()
+ if len(parts) == 2 and parts[0].endswith('h') and parts[1].endswith('m'):
+ return parts[0][:-1] + ':' + parts[1][:-1].zfill(2)
+ return reset
+
+
+def number_text(used):
+ return '--' if used is None else str(round(used))
+
+
+def render_digital(snapshot):
+ mint, dim, line, amber, unlit = '#7dffd0', '#4dbb92', '#22694f', '#ffcf5a', '#0d3326'
+ cv = Canvas('#020906')
+ 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]
+ 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')
+ cv.ink.alpha_composite(glyph(row['provider'], 15, mint), (11, y + 6))
+ cv.text((31, y + 3), account_label(row) + ' >', vt(22), mint, glow=(61, 252, 176, 90))
+ cv.text((229, y + 4), period + (' OLD' if old else ''), vt(20), amber if old else dim, anchor='ra')
+ if used is None:
+ cv.text((11, y + 31), '-- NO DATA', vt(26), dim)
+ else:
+ number = number_text(used)
+ cv.text((11, y + 32), ghost(number), seg(25), unlit)
+ cv.text((11, y + 32), number, seg(25), mint, glow=(61, 252, 176, 120))
+ x = 11 + cv.draw.textlength(number, font=seg(25)) + 3
+ cv.text((x, y + 38), '%', vt(24), mint)
+ if reset != '--':
+ clock = segment_time(reset)
+ cv.text((229, y + 28), 'RESETS IN', vt(16), dim, anchor='ra')
+ cv.text((229, y + 43), ghost(clock), seg(14), '#2a2108', anchor='ra')
+ cv.text((229, y + 43), clock, seg(14), amber, glow=(255, 190, 70, 120), anchor='ra')
+ gauge(cv, (11, y + 61, 229, y + 70), used, band('digital', used or 0), gap=3, track='#0b2a1f',
+ empty='#2a6b52', stale=old, split='#03100b', glow=True)
+ return cv.finish(blur=2)
+
+
+def render_neon(snapshot):
+ cv = Canvas('#05040c')
+ for y in range(4, SIZE, 8):
+ for x in range(4, SIZE, 8):
+ cv.back.point((x, y), fill='#120f24')
+ 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')
+ number = number_text(used)
+ cv.text((54, y + 19), number, ox(29), '#ffffff', glow=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)
+ return cv.finish(blur=3)
+
+
+def pixel_scene(cv, provider, top):
+ """A 2-px pixel landscape behind each Pixel Retro row (sunset / forest city / space)."""
+ rnd = random.Random({'claude': 11, 'codex': 23, 'grok': 37}[provider])
+ sky = {'claude': ('#2a1330', '#3a1834', '#4d1f36', '#652836', '#7f3335', '#9a4133'),
+ 'codex': ('#06171d', '#082027', '#0b2a2e', '#0e3434', '#113f39', '#15493e'),
+ 'grok': ('#0d0a28', '#120d33', '#170f3e', '#1c1349', '#211654', '#271a5f')}[provider]
+ d = cv.back
+ for i, color in enumerate(sky):
+ d.rectangle((6, top + 2 + i * 12, 233, top + 2 + (i + 1) * 12), fill=color)
+
+ def px(x, y, color, w=1, h=1):
+ d.rectangle((x * 2, top + y * 2, x * 2 + w * 2 - 1, top + y * 2 + h * 2 - 1), fill=color)
+
+ def disc(cx, cy, r, color):
+ for dy in range(-r, r + 1):
+ w = round(math.sqrt(r * r - dy * dy))
+ px(cx - w, cy + dy, color, 2 * w + 1)
+
+ if provider == 'claude':
+ disc(66, 12, 6, '#ff9e4f'); disc(66, 12, 4, '#ffc067')
+ for yy in (14, 16):
+ px(59, yy, sky[2], 15)
+ heights = [30 - round(5 * max(0, math.sin((x - 20) / 9)) + 2 * math.sin(x / 3)) for x in range(3, 117)]
+ for x, h in zip(range(3, 117), heights):
+ px(x, h, '#5a2236', 1, 37 - h)
+ for x in range(3, 117):
+ px(x, 33 - round(math.sin(x / 4)), '#371428', 1, 5)
+ elif provider == 'codex':
+ for _ in range(14):
+ px(rnd.randrange(20, 116), rnd.randrange(1, 12), '#9bffd2')
+ disc(66, 7, 3, '#d9ffe9'); disc(67, 6, 2, sky[0])
+ x = 40
+ while x < 116:
+ w, h = rnd.randrange(3, 6), rnd.randrange(6, 13)
+ px(x, 32 - h, '#0b3530', w, h + 5)
+ for wy in range(33 - h, 31, 2):
+ if rnd.random() > .5:
+ px(x + 1, wy, '#7dffb9')
+ x += w + 1
+ for p in range(3, 117, 3):
+ px(p, 33, '#05201a', 2, 5)
+ else:
+ for _ in range(40):
+ px(rnd.randrange(3, 116), rnd.randrange(1, 30), rnd.choice(('#efe6ff', '#b9a6ff')))
+ disc(66, 10, 5, '#8f6cf2'); disc(65, 9, 3, '#a98bff')
+ for i in range(-9, 10):
+ px(66 + i, 11 - round(i * .28), '#e2d6ff' if abs(i) < 5 else '#bca8ff')
+ for x in range(3, 117):
+ px(x, 33 - round(2 * abs(math.sin(x / 7))), '#120c33', 1, 6)
+
+
+def render_retro(snapshot):
+ outline_ink, cream = '#0a0d26', '#fff3d6'
+ cv = Canvas('#0a0f2c')
+ rnd = random.Random(5)
+ for _ in range(70):
+ 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]
+ a, a2 = ACCENT['retro'][row['provider']]
+ used, period, old, reset = reading(row)
+ pixel_scene(cv, row['provider'], y)
+ cv.back.rectangle((4, y, 235, y + ROW_H - 1), outline=outline_ink, width=2)
+ cv.back.rectangle((6, y + 2, 233, y + ROW_H - 3), outline=a, width=2)
+ for cx, cy in ((4, y), (234, y), (4, y + ROW_H - 2), (234, y + ROW_H - 2)):
+ cv.back.rectangle((cx, cy, cx + 1, cy + 1), fill='#0a0f2c')
+ cv.draw.rectangle((11, y + 8, 50, y + 47), fill=outline_ink, outline=a, width=2)
+ if row['provider'] == 'grok':
+ cv.draw.rectangle((16, y + 13, 45, y + 42), fill='#d9ccff')
+ mascot(cv.ink, row['provider'], (7, y + 4), pixel=True, size=32)
+ cv.text((57, y + 9), account_label(row), title(8), cream, stroke_width=1, stroke_fill=outline_ink)
+ cv.text((57, y + 22), number_text(used) + ('%' if used is not None else ''), title(16), cream,
+ stroke_width=2, stroke_fill=outline_ink)
+ cv.text((57, y + 41), period + (' OLD' if old else ''), title(8), '#ff9a9a' if old else '#b9d2ff', stroke_width=1, stroke_fill=outline_ink)
+ cv.draw.rectangle((153, y + 9, 228, y + 40), fill=outline_ink, outline=a, width=2)
+ cv.text((159, y + 14), 'RESET IN', title(8), '#a9bdf0')
+ cv.text((159, y + 27), reset.upper(), title(8), cream)
+ cv.draw.rectangle((10, y + 51, 229, y + 66), fill=outline_ink)
+ cv.draw.rectangle((12, y + 53, 227, y + 64), outline='#3a4fb0')
+ gauge(cv, (14, y + 55, 225, y + 62), used, band('retro', used or 0), gap=2, track='#19235f',
+ empty='#3a4ea8', stale=old, shade=True, stepped=True)
+ return cv.finish()
+
+
+def render_modern(snapshot):
+ cv = Canvas('#0b0e13')
+ for r in range(160, 0, -8):
+ cv.back.ellipse((200 - r, -60 - r, 200 + r, -60 + r), fill=mix('#0b0e13', '#1a2130', 1 - r / 160))
+ man = lambda s, w=600: face('manrope.ttf', s, w)
+ for index, row in enumerate(overview_rows(snapshot)):
+ y = ROWS[index]
+ a = ACCENT['modern'][row['provider']][0]
+ used, period, old, reset = reading(row)
+ for x in range(5, 235):
+ cv.back.line((x, y + 1, x, y + ROW_H - 2), fill=mix('#131820', a, max(0, .1 - (x - 5) / 1600)))
+ cv.draw.rounded_rectangle((4, y, 235, y + ROW_H - 1), radius=12, outline=mix('#222934', a, .28))
+ cv.back.rounded_rectangle((4, y, 235, y + ROW_H - 1), radius=12, outline=None)
+ cv.draw.rounded_rectangle((12, y + 10, 44, y + 42), radius=9, fill=mix('#0f1319', a, .14),
+ outline=mix('#0f1319', a, .3))
+ cv.ink.alpha_composite(glyph(row['provider'], 18, a), (19, y + 17))
+ cv.spaced((53, y + 11), account_label(row), man(8, 700), '#9ba5b3', 1.6)
+ cv.text((53, y + 58), period + (' · OLD' if old else ''), man(8, 600), '#f7768e' if old else '#7a8493', anchor='ls')
+ number = number_text(used)
+ cv.text((51, y + 18), number, man(30, 600), '#f4f6f9')
+ if used is not None:
+ x = 51 + cv.draw.textlength(number, font=man(30, 600)) + 1
+ cv.text((x, y + 29), '%', man(15, 600), '#f4f6f9')
+ cv.draw.line((158, y + 11, 158, y + 50), fill='#2f3744')
+ clock_mark(cv, (170, y + 18), 4, a, 1)
+ cv.spaced((228, y + 14), 'RESETS IN', man(7, 700), '#7a8493', 1.2, anchor='ra')
+ cv.text((228, y + 27), reset, man(14, 500), '#f4f6f9', anchor='ra')
+ gauge(cv, (12, y + 62, 228, y + 66), used, band('modern', used or 0), gap=3, shape='round', radius=2,
+ track='#232a35', empty='#3a4352', stale=old)
+ return cv.finish()
+
+
+def blossom(cv, cx, cy, r, petal='#f7b6c8', heart='#e0507f'):
+ for i in range(5):
+ a = math.radians(i * 72 - 90)
+ x, y = cx + math.cos(a) * r * .55, cy + math.sin(a) * r * .55
+ cv.draw.ellipse((x - r * .5, y - r * .5, x + r * .5, y + r * .5), fill=petal)
+ cv.draw.ellipse((cx - r * .22, cy - r * .22, cx + r * .22, cy + r * .22), fill=heart)
+
+
+def render_sakura(snapshot):
+ plum, mauve, pink = '#4a2433', '#8a6574', '#c2557a'
+ cv = Canvas('#fbeef2')
+ for r in range(150, 0, -6):
+ cv.back.ellipse((250 - r, -40 - r, 250 + r, -40 + r), fill=mix('#fbeef2', '#ffe1ea', 1 - r / 150))
+ for x, y, rot in ((18, 80, 20), (226, 158, -30), (120, 238, 10), (60, 158, 40)):
+ cv.back.ellipse((x - 3, y - 2, x + 3, y + 2), fill='#f4b3c6')
+ serif = lambda s, w=600: face('cormorant-garamond.woff2', s, w)
+ lining = {'features': ['lnum']}
+ shadow = Image.new('RGBA', (SIZE, SIZE), (0, 0, 0, 0))
+ for y in ROWS:
+ ImageDraw.Draw(shadow).rounded_rectangle((7, y + 4, 232, y + ROW_H), radius=14, fill=(166, 74, 108, 45))
+ cv.base.alpha_composite(shadow.filter(ImageFilter.GaussianBlur(4)))
+ for index, row in enumerate(overview_rows(snapshot)):
+ y = ROWS[index]
+ a = ACCENT['sakura'][row['provider']][0]
+ used, period, old, reset = reading(row)
+ cv.back.rounded_rectangle((5, y, 234, y + ROW_H - 2), radius=14, fill='#fffafc', outline='#ffffff')
+ cv.back.rounded_rectangle((12, y + 10, 44, y + 42), radius=10, fill='#fbe6ed', outline='#ffffff')
+ cv.ink.alpha_composite(glyph(row['provider'], 18, a), (19, y + 17))
+ cv.text((52, y + 6), account_label(row), serif(15, 700), plum)
+ cv.text((51, y + 17), number_text(used), serif(31, 600), plum, **lining)
+ if used is not None:
+ x = 51 + cv.draw.textlength(number_text(used), font=serif(31, 600)) + 1
+ cv.text((x, y + 30), '%', serif(17, 600), plum)
+ cv.draw.ellipse((147, y + 13, 165, y + 31), fill='#fbe1ea')
+ clock_mark(cv, (156, y + 22), 5, pink, 1)
+ cv.spaced((228, y + 12), 'RESETS IN', face('manrope.ttf', 7, 700), mauve, 1.1, anchor='ra')
+ cv.text((228, y + 21), reset, serif(17, 600), plum, anchor='ra', **lining)
+ cv.spaced((228, y + 52), period + (' OLD' if old else ''), face('manrope.ttf', 7, 700), '#a3264b' if old else mauve, 1.4, anchor='rs')
+ gauge(cv, (12, y + 60, 227, y + 65), used, band('sakura', used or 0), gap=3, shape='round', radius=3,
+ track='#f5e3e9', empty='#e7c2cf', stale=old)
+ blossom(cv, 226, 8, 9)
+ blossom(cv, 214, 3, 6)
+ blossom(cv, 9, 236, 7)
+ return cv.finish()
+
+
+def render_hud(snapshot):
+ cv = Canvas('#03080e')
+ for g in range(0, SIZE, 12):
+ color = '#0b1a28' if g % 48 == 0 else '#06111b'
+ 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]
+ a, a2 = ACCENT['hud'][row['provider']]
+ used, period, old, reset = reading(row)
+ cut = 10
+ frame = [(4, y), (235 - cut, y), (235, y + cut), (235, y + ROW_H - 1), (4 + cut, y + ROW_H - 1), (4, y + ROW_H - 1 - cut)]
+ cv.back.polygon(frame, fill=mix('#06101a', a, .05))
+ cv.draw.polygon(frame, outline=mix(a, '#1b3b58', .45))
+ cv.glow.line(frame + [frame[0]], fill=rgb(a) + (150,), width=2)
+ cv.draw.line((8, y + 4, 8, y + 12), fill=a, width=2)
+ cv.draw.line((8, y + 4, 16, y + 4), fill=a, width=2)
+ cv.draw.line((231, y + ROW_H - 5, 231, y + ROW_H - 13), fill=a, width=2)
+ cv.draw.line((231, y + ROW_H - 5, 223, y + ROW_H - 5), fill=a, width=2)
+ cv.ink.alpha_composite(glyph(row['provider'], 19, a), (12, y + 8))
+ cv.bloom.alpha_composite(glyph(row['provider'], 19, a), (12, y + 8))
+ cv.text((38, y + 8), account_label(row), chakra(14), '#ffffff')
+ cv.text((228, y + 9), period + (' OLD' if old else ''), chakra(10, False), '#ff4d6a' if old else '#8fadc6', anchor='ra')
+ number = number_text(used)
+ cv.text((12, y + 25), number, chakra(30), '#ffffff', glow=rgb(a) + (110,))
+ if used is not None:
+ x = 12 + cv.draw.textlength(number, font=chakra(30)) + 2
+ cv.text((x, y + 37), '%', chakra(16), a, glow=rgb(a) + (200,))
+ cv.draw.line((150, y + 30, 150, y + 52), fill='#22476a')
+ cv.spaced((228, y + 30), 'RESETS IN', chakra(7, False), '#6c8aa5', 1.4, anchor='ra')
+ cv.text((228, y + 40), reset, chakra(17), '#ffffff', anchor='ra')
+ gauge(cv, (12, y + 60, 228, y + 68), used, band('hud', used or 0), gap=3, shape='skew', skew=4,
+ track='#0c1c2b', empty='#22476a', stale=old, glow=True)
+ return cv.finish(blur=2)
+
+
+RENDERERS = {'digital': render_digital, 'neon': render_neon, 'retro': render_retro,
+ 'modern': render_modern, 'sakura': render_sakura, 'hud': render_hud}
diff --git a/token_tv/usage.py b/token_tv/usage.py
new file mode 100644
index 0000000..bc0c2c5
--- /dev/null
+++ b/token_tv/usage.py
@@ -0,0 +1,70 @@
+"""Small, explicit usage windows. Missing measurements stay missing."""
+import math
+from datetime import datetime
+
+
+def timestamp(value):
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return int(value) if math.isfinite(value) and value > 0 else None
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return int(parsed.timestamp()) if parsed.tzinfo else None
+ except ValueError:
+ pass
+ return None
+
+
+def window(label, percent, reset=None, duration=None):
+ if isinstance(percent, bool) or not isinstance(percent, (int, float)):
+ return None
+ if not math.isfinite(percent) or percent < 0:
+ return None
+ if not isinstance(duration, int) or isinstance(duration, bool) or duration <= 0:
+ duration = None
+ return {"label": label, "used_percent": float(percent),
+ "resets_at": timestamp(reset), "duration_minutes": duration}
+
+
+def normalize_claude(data):
+ result = []
+ for key, label, duration in (("five_hour", "5H", 300), ("seven_day", "WEEK", 10080)):
+ value = data.get(key) or {}
+ item = window(label, value.get("utilization"), value.get("resets_at"), duration)
+ if item:
+ result.append(item)
+ return result
+
+
+def normalize_codex(data):
+ result = []
+ limits = data.get("rateLimits") or {}
+ for key in ("primary", "secondary"):
+ value = limits.get(key) or {}
+ duration = value.get("windowDurationMins")
+ if not isinstance(duration, int) or isinstance(duration, bool) or duration <= 0:
+ duration = None
+ label = {300: "5H", 10080: "WEEK"}.get(duration, "WINDOW")
+ item = window(label, value.get("usedPercent"), value.get("resetsAt"), duration)
+ if item:
+ result.append(item)
+ return result
+
+
+def normalize_grok(data):
+ config = data.get("config") or {}
+ percent = config.get("creditUsagePercent")
+ cycle = config.get("currentPeriod") or {}
+ reset = cycle.get("end") or config.get("billingPeriodEnd")
+ item = window("BUDGET", percent, reset)
+ if item:
+ return [item]
+ # CLI credits are a billing budget, not a fabricated web-message quota.
+ limit = (data.get("monthlyLimit") or {}).get("val")
+ used = ((data.get("usage") or {}).get("includedUsed") or {}).get("val")
+ if isinstance(limit, (int, float)) and limit > 0 and isinstance(used, (int, float)):
+ item = window("BUDGET", used / limit * 100,
+ (data.get("billingCycle") or {}).get("billingPeriodEnd"))
+ if item:
+ return [item]
+ return []
diff --git a/token_tv/web/app.js b/token_tv/web/app.js
new file mode 100644
index 0000000..203f828
--- /dev/null
+++ b/token_tv/web/app.js
@@ -0,0 +1,276 @@
+'use strict';
+/* TokenTV web dashboard. Every theme renders the same nodes; style.css composes them. */
+const THEMES = [
+ {id:'digital', name:'Digital Terminal', eyebrow:'', title:'AI USAGE DASHBOARD', note:''},
+ {id:'neon', name:'Neon Cyberpunk', eyebrow:'Today', title:'AI USAGE', note:''},
+ {id:'retro', name:'Pixel Retro', eyebrow:'', title:'AI PROVIDERS', note:'USAGE DASHBOARD'},
+ {id:'modern', name:'Modern Minimal', eyebrow:'AI providers', title:'Usage Overview', note:'Track your usage and reset times across providers.'},
+ {id:'sakura', name:'Sakura Blossom', eyebrow:'Dashboard', title:'AI Usage', note:'Three minds. More possibilities.'},
+ {id:'hud', name:'Sci-Fi HUD', eyebrow:'', title:'AI PROVIDER USAGE', note:'Real-time usage monitor'}
+];
+const STATUS = {ok:'Connected', loading:'Loading', auth_required:'Login needed', identity_mismatch:'Check identity', quota_unavailable:'Quota unavailable', stale:'OLD · Previous value', rate_limited:'Retry later', error:'Fetch failed'};
+const PROVIDERS = ['claude', 'codex', 'grok'];
+const COMPANIES = {claude:'ANTHROPIC', codex:'OPENAI', grok:'XAI'};
+const svgNS = 'http://www.w3.org/2000/svg';
+const $ = s => document.querySelector(s);
+const readPreference = (k, f) => {try {return JSON.parse(localStorage.getItem(k)) ?? f} catch {return f}};
+const savePreference = (k, v) => {try {localStorage.setItem(k, JSON.stringify(v))} catch {/* Private browsing may disallow storage. */}};
+let accountChoices = readPreference('tokentv.accounts', {});
+if (!accountChoices || typeof accountChoices !== 'object' || Array.isArray(accountChoices)) accountChoices = {};
+let snapshot = null, offline = false, polling = false, displayInfo = null, clockChoice = null, applying = false, clockError = false;
+const el = (tag, text, cls) => {const n = document.createElement(tag); if (text !== undefined) n.textContent = text; if (cls) n.className = cls; return n};
+function svgNode(tag, attrs) {const n = document.createElementNS(svgNS, tag); for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v); return n}
+const clamp = v => Math.max(0, Math.min(100, v));
+/* Unlit seven-segment cells behind Digital numerals: every glyph cell becomes 8. */
+const ghost = text => text.replace(/[^\s:]/g, '8');
+const pad = n => String(n).padStart(2, '0');
+function seeded(seed) {return () => {seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296}}
+
+/* Provider marks: vector glyphs for most themes, the project's pixel mascots for Pixel Retro. */
+function icon(provider) {
+ const s = svgNode('svg', {viewBox:'0 0 48 48', 'aria-hidden':'true', fill:'none', stroke:'currentColor', 'stroke-linecap':'round', 'stroke-linejoin':'round', class:'glyph'});
+ if (provider === 'claude') {
+ const reach = [19.5, 15, 18, 14, 19, 15.5, 18.5, 14, 19.5, 15, 18, 14.5];
+ reach.forEach((r, i) => s.append(svgNode('path', {d:`M24 ${24 - 6} V${24 - r}`, 'stroke-width':3.4, transform:`rotate(${i * 30 + (i % 2 ? 4 : 0)} 24 24)`})));
+ } else if (provider === 'codex') {
+ s.append(svgNode('path', {d:'M24 5 40.5 14.5V33.5L24 43 7.5 33.5V14.5Z', 'stroke-width':3.2}));
+ s.append(svgNode('path', {d:'M7.5 14.5 24 24 40.5 14.5M24 24V43', 'stroke-width':3.2}));
+ } else {
+ s.append(svgNode('circle', {cx:24, cy:24, r:12.5, 'stroke-width':3.4}));
+ s.append(svgNode('path', {d:'M5 43C17 33 31 19 43 5 34 19 21 32 5 43Z', fill:'currentColor', stroke:'currentColor', 'stroke-width':1.6}));
+ }
+ return s;
+}
+function mascot(provider) {const img = el('img', undefined, 'pixel-mascot'); img.src = `/assets/${provider}-pixel.png`; img.alt = ''; img.width = 32; img.height = 32; img.decoding = 'async'; return img}
+function clockGlyph() {
+ const s = svgNode('svg', {viewBox:'0 0 24 24', 'aria-hidden':'true', fill:'none', stroke:'currentColor', 'stroke-width':1.8, 'stroke-linecap':'round', class:'clock-icon'});
+ s.append(svgNode('circle', {cx:12, cy:12, r:9}), svgNode('path', {d:'M12 7.5V12l3 2'}));
+ const p = svgNode('svg', {viewBox:'0 0 9 9', 'aria-hidden':'true', 'shape-rendering':'crispEdges', class:'clock-pixel'});
+ for (const [x, y, w, h, c] of [[2,0,5,1,'o'],[1,1,1,1,'o'],[7,1,1,1,'o'],[0,2,1,5,'o'],[8,2,1,5,'o'],[1,7,1,1,'o'],[7,7,1,1,'o'],[2,8,5,1,'o'],[1,2,7,5,'f'],[2,1,5,1,'f'],[2,7,5,1,'f'],[4,2,1,3,'o'],[5,4,2,1,'o']])
+ p.append(svgNode('rect', c === 'o' ? {x, y, width:w, height:h, fill:'currentColor'} : {x, y, width:w, height:h, fill:'#fff3d6', class:'face'}));
+ const wrap = el('span', undefined, 'clock-mark'); wrap.setAttribute('aria-hidden', 'true'); wrap.append(s, p); return wrap;
+}
+
+/* Pixel Retro scenery on a 200×62 logical grid, anchored bottom-right. Sky objects sit
+ * near x≈138 so they fall between the title row and the score column. */
+function scene(provider) {
+ const W = 200, H = 62, rnd = seeded({claude:11, codex:23, grok:37}[provider]);
+ const s = svgNode('svg', {viewBox:`0 0 ${W} ${H}`, preserveAspectRatio:'xMaxYMax slice', 'shape-rendering':'crispEdges', class:'scene', 'aria-hidden':'true'});
+ const rect = (x, y, w, h, fill, cls) => {const r = svgNode('rect', {x, y, width:w, height:h, fill}); if (cls) r.setAttribute('class', cls); s.append(r)};
+ const bands = colors => colors.forEach((c, i) => rect(0, Math.floor(i * H / colors.length), W, Math.ceil(H / colors.length) + 1, c));
+ const ridge = (f, fill) => {let d = `M0 ${H}`; for (let x = 0; x < W; x += 2) d += `V${Math.round(f(x))}H${x + 2}`; s.append(svgNode('path', {d:d + `V${H}Z`, fill}))};
+ const disc = (cx, cy, r, fill) => {for (let dy = -r; dy <= r; dy++) {const w = Math.round(Math.sqrt(r * r - dy * dy)); rect(cx - w, cy + dy, 2 * w + 1, 1, fill)}};
+ const pine = (x, base, h, fill) => {for (let i = 0; i < h; i++) {const w = 1 + 2 * Math.floor(i / 2); rect(x - Math.floor(w / 2), base - h + i, w, 1, fill)} rect(x, base, 1, 2, fill)};
+ const stars = (n, x0, y1, colors) => {for (let i = 0; i < n; i++) rect(x0 + Math.floor(rnd() * (W - x0)), Math.floor(rnd() * y1), 1, 1, colors[i % colors.length], i % 3 ? '' : 'twinkle')};
+ if (provider === 'claude') {
+ bands(['#2a1330', '#3a1834', '#4d1f36', '#652836', '#7f3335', '#9a4133', '#b65231', '#cf6630']);
+ disc(138, 15, 9, '#ff9e4f'); disc(138, 15, 7, '#ffc067'); disc(138, 14, 4, '#ffe08f');
+ for (const y of [17, 20, 23]) rect(128, y, 21, 1, '#4d1f36');
+ for (const [x, y] of [[112, 24], [119, 21], [126, 27]]) {rect(x, y, 1, 1, '#2a1330'); rect(x + 1, y + 1, 1, 1, '#2a1330'); rect(x + 2, y, 1, 1, '#2a1330')}
+ ridge(x => 41 - 9 * Math.max(0, Math.sin((x - 40) / 18)) - 3 * Math.sin(x / 6) - (x > 150 ? 5 * Math.max(0, Math.sin((x - 150) / 10)) : 0), '#5a2236');
+ ridge(x => 49 - 3 * Math.sin(x / 9 + 1) - 2 * Math.sin(x / 4), '#371428');
+ for (const x of [152, 158, 163, 182, 188, 194]) pine(x, 52, 7 + (x % 3), '#24101e');
+ } else if (provider === 'codex') {
+ bands(['#06171d', '#082027', '#0b2a2e', '#0e3434', '#113f39', '#15493e', '#195443', '#1e6048']);
+ stars(30, 40, 26, ['#9bffd2', '#e6fff3']);
+ disc(137, 11, 5, '#d9ffe9'); disc(139, 10, 4, '#082027');
+ let x = 52;
+ while (x < W) {const w = 6 + Math.floor(rnd() * 7), h = 10 + Math.floor(rnd() * 13); rect(x, 52 - h, w, h + 10, '#0b3530'); for (let wy = 54 - h; wy < 50; wy += 3) for (let wx = x + 1; wx < x + w - 1; wx += 2) if (rnd() > .55) rect(wx, wy, 1, 1, rnd() > .7 ? '#e8ffa6' : '#7dffb9'); x += w + 2}
+ for (let p = 0; p < W; p += 5) pine(p + 2, 58, 6 + Math.floor(rnd() * 5), '#05201a');
+ for (let i = 0; i < 9; i++) rect(60 + Math.floor(rnd() * 138), 38 + Math.floor(rnd() * 12), 1, 1, '#c8ff8a', 'twinkle');
+ } else {
+ bands(['#0d0a28', '#120d33', '#170f3e', '#1c1349', '#211654', '#271a5f', '#2d1e6a', '#33226f']);
+ stars(80, 0, 46, ['#efe6ff', '#b9a6ff', '#ffffff']);
+ disc(140, 15, 8, '#8f6cf2'); disc(138, 13, 6, '#a98bff'); disc(136, 11, 2, '#cdbbff');
+ for (let i = -15; i <= 15; i++) rect(140 + i, 16 + Math.round(-i * .28), 1, 1, Math.abs(i) < 8 ? '#e2d6ff' : '#bca8ff');
+ disc(108, 26, 2, '#d9cff7');
+ ridge(x => 50 - 4 * Math.abs(Math.sin(x / 13)) - 2 * Math.sin(x / 5), '#120c33');
+ ridge(x => 56 - 2 * Math.abs(Math.sin(x / 8 + 2)), '#0a0722');
+ for (const [cx, cy] of [[120, 58], [150, 59], [184, 58]]) rect(cx, cy, 3, 1, '#1d1550');
+ }
+ return s;
+}
+/* The TokenTV cube mascot for the Pixel Retro banner (36×32 logical pixels). */
+function retroMascot() {
+ const s = svgNode('svg', {viewBox:'0 0 44 34', 'shape-rendering':'crispEdges', class:'mascot-art'});
+ const r = (x, y, w, h, fill, cls) => {const n = svgNode('rect', {x, y, width:w, height:h, fill}); if (cls) n.setAttribute('class', cls); s.append(n)};
+ const O = '#151238', C = '#fff1d6', D = '#e3c79c', N = '#1c2a63', M = '#7ff5c8', P = '#ff7aa8', Y = '#ffd86b';
+ r(15, 1, 3, 3, P); r(15, 1, 1, 1, '#ffd0e0'); r(16, 4, 1, 4, O);
+ r(5, 8, 22, 1, O); r(4, 9, 1, 16, O); r(27, 9, 1, 16, O); r(5, 25, 22, 1, O);
+ r(5, 9, 22, 16, C); r(25, 10, 2, 15, D); r(5, 23, 22, 2, D); r(6, 10, 4, 1, '#ffffff');
+ r(8, 11, 16, 10, O); r(9, 12, 14, 8, N); r(9, 12, 14, 1, '#25367a');
+ r(12, 14, 2, 1, M); r(11, 15, 1, 1, M); r(14, 15, 1, 1, M); r(18, 14, 2, 1, M); r(17, 15, 1, 1, M); r(20, 15, 1, 1, M);
+ r(14, 18, 4, 1, M); r(13, 17, 1, 1, M); r(18, 17, 1, 1, M); r(10, 17, 2, 1, P); r(20, 17, 2, 1, P);
+ r(1, 15, 3, 1, O); r(1, 16, 1, 5, O); r(2, 16, 2, 4, C); r(1, 21, 3, 1, O);
+ r(28, 13, 2, 2, O); r(29, 9, 2, 4, O); r(28, 5, 4, 1, O); r(27, 6, 1, 3, O); r(32, 6, 1, 3, O); r(28, 6, 4, 3, C); r(28, 9, 4, 1, O);
+ r(8, 26, 1, 4, O); r(9, 26, 4, 3, '#2a2f6a'); r(13, 26, 1, 4, O); r(8, 30, 6, 1, O);
+ r(18, 26, 1, 4, O); r(19, 26, 4, 3, '#2a2f6a'); r(23, 26, 1, 4, O); r(18, 30, 6, 1, O);
+ for (const [x, y, w, h] of [[36,2,2,1],[39,2,2,1],[35,3,7,2],[36,5,5,1],[37,6,3,1],[38,7,1,1]]) r(x, y, w, h, '#ff5d8f', 'beat');
+ for (const [x, y] of [[33, 13], [40, 18], [1, 3]]) {r(x, y - 1, 1, 3, Y, 'twinkle'); r(x - 1, y, 3, 1, Y, 'twinkle')}
+ return s;
+}
+function buildStarfield() {
+ const rnd = seeded(5), s = svgNode('svg', {viewBox:'0 0 480 300', preserveAspectRatio:'xMidYMid slice', 'shape-rendering':'crispEdges'});
+ for (let i = 0; i < 140; i++) {const big = i % 17 === 0, r = svgNode('rect', {x:Math.floor(rnd() * 480), y:Math.floor(rnd() * 300), width:big ? 2 : 1, height:big ? 2 : 1, fill:['#ffffff', '#b9c8ff', '#ffe9a8'][i % 3]}); if (i % 4 === 0) r.setAttribute('class', 'twinkle'); r.style.animationDelay = (-rnd() * 4).toFixed(2) + 's'; s.append(r)}
+ $('#starfield').append(s);
+}
+/* Sakura branch: tapered limbs, notched five-petal flowers and buds. */
+function buildBranch() {
+ const s = svgNode('svg', {viewBox:'0 0 620 440', preserveAspectRatio:'xMaxYMin meet'});
+ const defs = svgNode('defs', {}), g = svgNode('radialGradient', {id:'petal-fill', cx:'50%', cy:'100%', r:'105%'});
+ for (const [o, c] of [['0', '#fffafc'], ['.5', '#ffd9e4'], ['1', '#f59bb7']]) g.append(svgNode('stop', {offset:o, 'stop-color':c}));
+ defs.append(g); s.append(defs);
+ const limb = (d, w, c) => s.append(svgNode('path', {d, fill:'none', stroke:c, 'stroke-width':w, 'stroke-linecap':'round'}));
+ limb('M640 26C574 40 520 66 470 104', 15, '#5e3540'); limb('M470 104C420 142 372 170 314 196', 10, '#6c3d48'); limb('M314 196C268 217 236 236 196 266', 6, '#7a4752');
+ limb('M470 104C486 150 482 196 500 246', 6, '#6c3d48'); limb('M500 246C506 270 520 290 536 304', 3.5, '#7a4752');
+ limb('M396 152C372 120 344 100 312 82', 5, '#6c3d48'); limb('M560 52C566 84 586 102 610 116', 4, '#6c3d48'); limb('M260 220C246 196 226 186 202 182', 3, '#7a4752');
+ const flower = (x, y, r, rot) => {
+ const f = svgNode('g', {transform:`translate(${x} ${y}) rotate(${rot}) scale(${r / 22})`});
+ for (let i = 0; i < 5; i++) f.append(svgNode('path', {d:'M0 0C-7-4-11-14-7-21C-4-25-1-24 0-21C1-24 4-25 7-21C11-14 7-4 0 0Z', fill:'url(#petal-fill)', stroke:'#f2a7bd', 'stroke-width':.6, transform:`rotate(${i * 72})`}));
+ for (let i = 0; i < 9; i++) {const a = i * 40 * Math.PI / 180, l = 6 + (i % 3); f.append(svgNode('path', {d:`M0 0L${(Math.cos(a) * l).toFixed(1)} ${(Math.sin(a) * l).toFixed(1)}`, stroke:'#d84a7a', 'stroke-width':.8})); f.append(svgNode('circle', {cx:(Math.cos(a) * l).toFixed(1), cy:(Math.sin(a) * l).toFixed(1), r:.9, fill:'#f7c25a'}))}
+ f.append(svgNode('circle', {r:2.6, fill:'#e0507f'}));
+ s.append(f);
+ };
+ const bud = (x, y, rot) => {const b = svgNode('g', {transform:`translate(${x} ${y}) rotate(${rot})`}); b.append(svgNode('ellipse', {cx:0, cy:-5, rx:3.6, ry:5.5, fill:'#f48fb1'}), svgNode('path', {d:'M-3.5-1 0 3 3.5-1 0 1Z', fill:'#7a4752'})); s.append(b)};
+ for (const [x, y, r, rot] of [[590,44,23,10],[548,70,26,-14],[512,40,18,30],[468,112,25,4],[430,92,20,-30],[402,150,22,18],[356,170,24,-8],[318,124,19,26],[300,200,21,40],[262,214,18,-20],[228,244,20,12],[492,196,22,-12],[514,258,18,30],[544,300,15,-6],[600,112,17,22],[198,184,14,-24],[336,92,15,8]]) flower(x, y, r, rot);
+ for (const [x, y, rot] of [[196,268,-140],[310,80,-60],[612,118,40],[538,306,150],[452,64,-20],[248,200,-80]]) bud(x, y, rot);
+ $('#branch').append(s);
+}
+function buildPetals() {
+ const rnd = seeded(9), box = $('#petals');
+ for (let i = 0; i < 18; i++) {
+ const p = el('i');
+ p.style.cssText = `--x:${(rnd() * 100).toFixed(1)}vw;--drift:${(rnd() * 22 - 4).toFixed(1)}vw;--size:${(8 + rnd() * 9).toFixed(1)}px;--fall:${(14 + rnd() * 12).toFixed(1)}s;--sway:${(3 + rnd() * 3).toFixed(1)}s;--delay:${(-rnd() * 26).toFixed(1)}s;--turn:${Math.round(rnd() * 360)}deg`;
+ box.append(p);
+ }
+}
+
+function resetTime(epoch) {if (!Number.isFinite(epoch) || epoch <= 0) return '—'; let m = Math.ceil((epoch - Date.now() / 1000) / 60); if (m <= 0) return 'Awaiting reset'; return m >= 1440 ? `${Math.floor(m / 1440)}d ${Math.floor(m % 1440 / 60)}h` : `${Math.floor(m / 60)}h ${pad(m % 60)}m`}
+function period(w) {if (!w) return 'QUOTA'; return w.label === 'BUDGET' ? 'CLI BUDGET' : w.label === 'WEEK' ? 'WEEKLY' : w.label === '5H' ? '5-HOUR' : String(w.label || 'QUOTA')}
+function level(v) {return v < 50 ? 'low' : v < 80 ? 'medium' : v < 90 ? 'high' : 'critical'}
+function levelText(v) {return v >= 100 ? 'Limit reached' : v >= 90 ? 'Near limit' : v >= 80 ? 'High usage' : v >= 50 ? 'Moderate' : 'Low usage'}
+function gauge(value, label) {
+ const g = el('div', undefined, 'meter');
+ if (Number.isFinite(value)) {value = clamp(value); g.dataset.level = level(value); g.style.setProperty('--value', value + '%'); g.style.setProperty('--v', String(Math.max(1, value))); g.setAttribute('role', 'meter'); g.setAttribute('aria-label', label); g.setAttribute('aria-valuemin', '0'); g.setAttribute('aria-valuemax', '100'); g.setAttribute('aria-valuenow', String(value))}
+ else {g.classList.add('unknown-meter'); g.setAttribute('aria-label', label + ' unavailable')}
+ for (let i = 0; i < 10; i++) {const seg = el('span', undefined, 'meter-segment'), fill = el('span', undefined, 'meter-fill'); seg.style.setProperty('--i', String(i)); fill.style.setProperty('--fill', Number.isFinite(value) ? clamp((value - i * 10) * 10) + '%' : '0%'); seg.append(fill); g.append(seg)}
+ return g;
+}
+function stat(key, value, cls) {const s = el('div', undefined, 'stat' + (cls ? ' ' + cls : '')); s.append(el('span', key, 'stat-k'), typeof value === 'string' ? el('span', value, 'stat-v') : value); return s}
+
+function setTheme(theme) {
+ const config = THEMES.find(t => t.id === theme) || THEMES[3];
+ document.documentElement.dataset.theme = config.id; savePreference('tokentv.theme', config.id);
+ $('#eyebrow').textContent = config.eyebrow; $('#eyebrow').hidden = !config.eyebrow;
+ $('#page-title').textContent = config.title;
+ $('#intro-note').textContent = config.note; $('#intro-note').hidden = !config.note;
+ for (const b of document.querySelectorAll('[data-theme-choice]')) b.setAttribute('aria-pressed', String(b.dataset.themeChoice === config.id));
+}
+for (const t of THEMES) {
+ const b = el('button', undefined, 'theme-button'); b.type = 'button'; b.dataset.themeChoice = t.id; b.setAttribute('aria-pressed', 'false');
+ const sw = el('span', undefined, 'swatch'); sw.dataset.swatch = t.id; sw.setAttribute('aria-hidden', 'true'); sw.append(el('i'), el('i'), el('i'));
+ b.append(sw, el('span', t.name, 'theme-name')); b.onclick = () => setTheme(t.id); $('#themes').append(b);
+}
+setTheme(readPreference('tokentv.theme', 'modern'));
+
+function providerCard(provider, accounts) {
+ let a = accounts.find(x => x.key === accountChoices[provider]) || accounts[0];
+ if (!a) a = {key:provider, alias:provider.toUpperCase(), provider, status:'loading', windows:[]};
+ const prior = $(`.provider-card[data-provider="${provider}"] .more-windows`);
+ const stale = offline || a.status === 'stale';
+ const valid = (a.windows || []).filter(w => Number.isFinite(w.used_percent));
+ // A mismatched identity must not expose another person's quota as this account.
+ const windows = a.status === 'identity_mismatch' ? [] : valid;
+ const primary = windows.reduce((p, w) => !p || w.used_percent > p.used_percent ? w : p, null);
+ const value = primary ? clamp(primary.used_percent) : null;
+ const shell = el('div', undefined, 'card-shell'); shell.dataset.provider = provider;
+ const card = el('article', undefined, 'provider-card');
+ Object.assign(card.dataset, {provider, key:a.key, stale:String(stale), level:value === null ? 'unknown' : level(value)});
+ const art = el('div', undefined, 'card-art'); art.setAttribute('aria-hidden', 'true'); art.append(scene(provider));
+ const head = el('div', undefined, 'card-head'), logo = el('div', undefined, 'provider-icon'); logo.append(icon(provider), mascot(provider));
+ const name = el('div', undefined, 'provider-name'); name.append(el('h2', provider.toUpperCase(), 'provider-title'), el('span', COMPANIES[provider], 'company'));
+ const tabs = el('div', undefined, 'account-tabs'); tabs.setAttribute('role', 'group'); tabs.setAttribute('aria-label', provider.toUpperCase() + ' accounts');
+ for (const row of accounts) {const letter = (row.alias || '').split(' ').at(-1); const b = el('button', letter, 'account-tab'); b.type = 'button'; b.dataset.account = row.key; b.title = row.alias; b.setAttribute('aria-label', row.alias); b.setAttribute('aria-pressed', String(row.key === a.key)); b.onclick = () => {accountChoices[provider] = row.key; savePreference('tokentv.accounts', accountChoices); renderAccounts(); $(`[data-account="${row.key}"]`)?.focus()}; tabs.append(b)}
+ head.append(logo, name, tabs);
+ const reading = el('div', undefined, 'reading'), meta = el('div', undefined, 'reading-meta');
+ meta.append(el('span', period(primary) + ' USED', 'reading-label'));
+ if (primary) meta.append(el('span', stale ? 'OLD · Last known usage' : levelText(value), 'level-label'));
+ else meta.append(el('span', a.status === 'quota_unavailable' ? 'Connected. No quota reported.' : STATUS[a.status] || 'No reading available.', 'unknown-message'));
+ const num = el('div', value === null ? '—' : undefined, 'percentage');
+ if (value !== null) {const digits = el('span', String(Math.round(value)), 'pct-num'); digits.dataset.ghost = ghost(digits.textContent); num.append(digits, el('span', '%', 'percent-sign'))}
+ reading.append(meta, num);
+ const timer = el('div', undefined, 'timer'), until = el('span', primary ? resetTime(primary.resets_at) : '—', 'timer-value');
+ if (/^[\ddh ]+$/.test(until.textContent)) until.dataset.ghost = ghost(until.textContent);
+ timer.append(clockGlyph(), el('span', 'RESETS IN', 'timer-label'), until);
+ const row = el('div', undefined, 'gauge'); row.append(gauge(value, a.alias + ' ' + period(primary) + ' used quota'), el('span', value === null ? '—' : Math.round(value) + '%', 'gauge-value'));
+ card.append(art, head, reading, timer, row);
+ const others = windows.filter(w => w !== primary);
+ if (others.length) {
+ const details = el('details', undefined, 'more-windows'); details.open = prior?.open || false;
+ const named = period(others[0]) === 'CLI BUDGET' ? 'CLI budget' : period(others[0])[0] + period(others[0]).slice(1).toLowerCase();
+ details.append(el('summary', others.length === 1 ? `${named} window` : `${others.length} more windows`));
+ for (const w of others) {const line = el('div', undefined, 'window-detail'); line.append(el('span', period(w), 'window-name'), gauge(w.used_percent, a.alias + ' ' + period(w) + ' used quota'), el('span', Math.round(w.used_percent) + '%', 'window-percent'), el('span', resetTime(w.resets_at), 'window-timer')); details.append(line)}
+ card.append(details);
+ }
+ const checked = stale ? a.last_success_at : a.fetched_at;
+ 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'));
+ 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)));
+ $('#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);
+ $('#foot-reporting').textContent = `${reporting} / ${rows.length} reporting`;
+ if (focused) {const b = [...document.querySelectorAll('[data-account]')].find(b => b.dataset.account === focused); b?.focus({preventScroll:true})}
+}
+async function update() {
+ if (polling) return; polling = true;
+ try {
+ const r = await fetch('/snapshot', {cache:'no-store'}); if (!r.ok) throw Error();
+ const data = 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 = staleCount ? `${staleCount} stale · Live server` : 'Live from Mini';
+ $('#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.';
+ if (!snapshot) $('#providers').replaceChildren(el('p', 'No usage data received.', 'loading'));
+ } finally {polling = false; document.body.dataset.offline = String(offline); renderAccounts()}
+}
+function tick() {
+ const now = new Date(), t = $('#local-time');
+ const iso = t.querySelector('.date-iso'), time = t.querySelector('.time');
+ iso.textContent = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`; iso.dataset.ghost = '8888-88-88';
+ t.querySelector('.date-long').textContent = now.toLocaleDateString('en-US', {month:'short', day:'2-digit', year:'numeric'}).toUpperCase();
+ time.textContent = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`; time.dataset.ghost = '88:88:88';
+}
+$('#clock-zone').textContent = new Intl.DateTimeFormat('en-US', {timeZoneName:'short'}).formatToParts(new Date()).find(p => p.type === 'timeZoneName')?.value || 'Local';
+
+function showClock(show) {$('#clock-panel').hidden = !show; $('#clock-toggle').setAttribute('aria-expanded', String(show)); if (show) {refreshDisplay(true); $('#close-clock').focus()} else $('#clock-toggle').focus()}
+$('#clock-toggle').onclick = () => showClock($('#clock-panel').hidden); $('#close-clock').onclick = () => showClock(false);
+let lastImageStyle = null, lastImageAt = 0;
+function paintClock(forceImage = false) {
+ const style = clockChoice || displayInfo?.style;
+ $('#clock-style').disabled = applying || !displayInfo; $('#apply').disabled = applying || !displayInfo || (style === displayInfo.style && displayInfo.status !== 'error' && !clockError);
+ $('#apply').textContent = applying ? 'Sending image…' : 'Apply to clock'; $('#apply').dataset.state = applying ? 'loading' : clockError || displayInfo?.status === 'error' ? 'error' : displayInfo?.status === 'ok' ? 'success' : 'default';
+ $('#display-state').textContent = clockError ? 'Could not apply. Please retry.' : !displayInfo ? 'Clock status unavailable' : style !== displayInfo.style ? 'Preview only · Apply to send' : displayInfo.status === 'queued' ? 'Sending image…' : displayInfo.status === 'error' ? 'Clock upload failed. Please retry.' : displayInfo.status === 'preview_only' ? 'Preview only · No clock connected' : 'Image sent · ' + styleName(displayInfo.applied_style);
+ if (style && !$('#clock-panel').hidden && (forceImage || style !== lastImageStyle || Date.now() - lastImageAt > 30000)) {lastImageStyle = style; lastImageAt = Date.now(); $('#frame').src = '/frame/0.jpg?style=' + encodeURIComponent(style) + '&t=' + lastImageAt; $('#frame').alt = styleName(style) + ' live clock preview'}
+}
+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('/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)};
+$('#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)}};
+$('#frame').onerror = () => {$('#display-state').textContent = 'Clock preview unavailable. Reopen to retry.'};
+
+$('#mascot').append(retroMascot()); buildStarfield(); buildBranch(); buildPetals(); tick();
+update(); refreshDisplay(); setInterval(update, 30000); setInterval(tick, 1000); setInterval(() => {if (!$('#clock-panel').hidden) refreshDisplay()}, 5000);
diff --git a/token_tv/web/chakra-petch-500.woff2 b/token_tv/web/chakra-petch-500.woff2
new file mode 100644
index 0000000..a3d1af7
Binary files /dev/null and b/token_tv/web/chakra-petch-500.woff2 differ
diff --git a/token_tv/web/chakra-petch-700.woff2 b/token_tv/web/chakra-petch-700.woff2
new file mode 100644
index 0000000..725e356
Binary files /dev/null and b/token_tv/web/chakra-petch-700.woff2 differ
diff --git a/token_tv/web/chakra-petch-LICENSE.txt b/token_tv/web/chakra-petch-LICENSE.txt
new file mode 100644
index 0000000..9cee5a5
--- /dev/null
+++ b/token_tv/web/chakra-petch-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2018 The Chakra Petch Project Authors (https://github.com/m4rc1e/Chakra-Petch.git)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/cormorant-garamond-LICENSE.txt b/token_tv/web/cormorant-garamond-LICENSE.txt
new file mode 100644
index 0000000..507d70f
--- /dev/null
+++ b/token_tv/web/cormorant-garamond-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2015 the Cormorant Project Authors (github.com/CatharsisFonts/Cormorant)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/cormorant-garamond.woff2 b/token_tv/web/cormorant-garamond.woff2
new file mode 100644
index 0000000..b15b093
Binary files /dev/null and b/token_tv/web/cormorant-garamond.woff2 differ
diff --git a/token_tv/web/dseg-LICENSE.txt b/token_tv/web/dseg-LICENSE.txt
new file mode 100644
index 0000000..ad4c0bf
--- /dev/null
+++ b/token_tv/web/dseg-LICENSE.txt
@@ -0,0 +1,95 @@
+Copyright (c) 2017, keshikan (http://www.keshikan.net),
+with Reserved Font Name "DSEG".
+
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/dseg7-classic-bold.woff2 b/token_tv/web/dseg7-classic-bold.woff2
new file mode 100644
index 0000000..558eec4
Binary files /dev/null and b/token_tv/web/dseg7-classic-bold.woff2 differ
diff --git a/token_tv/web/index.html b/token_tv/web/index.html
new file mode 100644
index 0000000..501c096
--- /dev/null
+++ b/token_tv/web/index.html
@@ -0,0 +1,74 @@
+<!doctype html>
+<html lang="en" data-theme="modern">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<meta name="color-scheme" content="dark light">
+<title>TokenTV · AI usage</title>
+<link rel="icon" href="data:,">
+<link rel="stylesheet" href="/assets/style.css">
+<script src="/assets/app.js" defer></script>
+</head>
+<body>
+<a class="skip" href="#providers">Skip to usage</a>
+<div class="backdrop" aria-hidden="true">
+ <div class="atmosphere"></div>
+ <div class="glow glow-a"></div><div class="glow glow-b"></div><div class="glow glow-c"></div>
+ <div class="starfield" id="starfield"></div>
+ <div class="branch" id="branch"></div>
+ <div class="bokeh"><i></i><i></i><i></i><i></i></div>
+ <div class="petals" id="petals"></div>
+ <div class="sweep"></div>
+</div>
+<div class="shell">
+ <header class="topbar">
+ <a class="brand" href="/" aria-label="TokenTV home"><span class="brandmark" aria-hidden="true"></span><span class="brand-word">TOKEN<b>TV</b></span></a>
+ <div class="connection"><span class="status-dot" aria-hidden="true"></span><span id="connection">Connecting</span></div>
+ <button id="clock-toggle" class="control clock-toggle" type="button" aria-expanded="false" aria-controls="clock-panel">Clock display</button>
+ </header>
+ <nav class="theme-section" aria-label="Dashboard appearance">
+ <span class="section-label">Appearance</span>
+ <div id="themes" class="themes" role="group" aria-label="Web theme"></div>
+ </nav>
+ <div class="workspace">
+ <main class="screen" id="dashboard">
+ <header class="screen-head">
+ <div class="title-block">
+ <p class="eyebrow" id="eyebrow">AI providers</p>
+ <h1 id="page-title">Usage Overview</h1>
+ <p class="intro-note" id="intro-note">Track your usage and reset times across providers.</p>
+ </div>
+ <div class="mascot" id="mascot" aria-hidden="true"></div>
+ <dl class="summary">
+ <div class="summary-accounts"><dt>Accounts</dt><dd id="account-count">—</dd></div>
+ <div class="summary-reporting"><dt>Reporting</dt><dd id="reporting-count">—</dd></div>
+ <div class="summary-providers"><dt>Providers</dt><dd>3</dd></div>
+ <div class="summary-clock"><dt>Today</dt><dd id="local-time"><span class="zone" id="clock-zone">Local</span><span class="date-iso"></span><span class="date-long"></span><span class="time"></span></dd></div>
+ </dl>
+ </header>
+ <div id="notice" class="notice" role="status" hidden></div>
+ <section class="provider-list" id="providers" aria-label="Provider usage"><p class="loading">Loading your accounts…</p></section>
+ <footer class="screen-foot">
+ <div class="footer-meta">
+ <span id="foot-reporting">— reporting</span>
+ <span id="updated">Waiting for data</span>
+ <span>Refreshes every 5 min</span>
+ <span class="signal" id="signal" data-strength="0" aria-hidden="true"><i></i><i></i><i></i></span>
+ </div>
+ <div class="legend" aria-label="Used quota levels"><span class="section-label">Used quota</span><span><i data-level="low"></i>0–49%</span><span><i data-level="medium"></i>50–79%</span><span><i data-level="high"></i>80–89%</span><span><i data-level="critical"></i>90–100%</span></div>
+ </footer>
+ </main>
+ <aside id="clock-panel" class="clock-panel" aria-label="Physical clock" hidden>
+ <div class="aside-head"><div><p class="eyebrow">Physical display</p><h2>Your clock</h2></div><button class="control icon-control" id="close-clock" type="button" aria-label="Close clock panel">×</button></div>
+ <div class="device"><div class="lcd"><img id="frame" width="240" height="240" alt="Live clock preview"></div></div>
+ <label for="clock-style">Clock style</label>
+ <select id="clock-style" class="control"></select>
+ <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>
+ </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>
+</div>
+</body>
+</html>
diff --git a/token_tv/web/jersey-10-LICENSE.txt b/token_tv/web/jersey-10-LICENSE.txt
new file mode 100644
index 0000000..f83e6da
--- /dev/null
+++ b/token_tv/web/jersey-10-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2023 The Soft Type Project Authors (https://github.com/scfried/soft-type-jersey)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/jersey-10.woff2 b/token_tv/web/jersey-10.woff2
new file mode 100644
index 0000000..385029f
Binary files /dev/null and b/token_tv/web/jersey-10.woff2 differ
diff --git a/token_tv/web/manrope-LICENSE.txt b/token_tv/web/manrope-LICENSE.txt
new file mode 100644
index 0000000..793d053
--- /dev/null
+++ b/token_tv/web/manrope-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2018 The Manrope Project Authors (https://github.com/googlefonts/manrope)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/manrope.ttf b/token_tv/web/manrope.ttf
new file mode 100644
index 0000000..75274da
Binary files /dev/null and b/token_tv/web/manrope.ttf differ
diff --git a/token_tv/web/orbitron-LICENSE.txt b/token_tv/web/orbitron-LICENSE.txt
new file mode 100644
index 0000000..91ede45
--- /dev/null
+++ b/token_tv/web/orbitron-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2018 The Orbitron Project Authors (https://github.com/theleagueof/orbitron), with Reserved Font Name: "Orbitron"
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/orbitron.ttf b/token_tv/web/orbitron.ttf
new file mode 100644
index 0000000..1fc54ce
Binary files /dev/null and b/token_tv/web/orbitron.ttf differ
diff --git a/token_tv/web/oxanium-LICENSE.txt b/token_tv/web/oxanium-LICENSE.txt
new file mode 100644
index 0000000..38913c0
--- /dev/null
+++ b/token_tv/web/oxanium-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2019 The Oxanium Project Authors (https://github.com/sevmeyer/oxanium)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/oxanium.woff2 b/token_tv/web/oxanium.woff2
new file mode 100644
index 0000000..24648cb
Binary files /dev/null and b/token_tv/web/oxanium.woff2 differ
diff --git a/token_tv/web/press-start-2p-LICENSE.txt b/token_tv/web/press-start-2p-LICENSE.txt
new file mode 100644
index 0000000..22796df
--- /dev/null
+++ b/token_tv/web/press-start-2p-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2012 The Press Start 2P Project Authors ([email protected]), with Reserved Font Name "Press Start 2P".
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
\ No newline at end of file
diff --git a/token_tv/web/press-start-2p.ttf b/token_tv/web/press-start-2p.ttf
new file mode 100644
index 0000000..39adf42
Binary files /dev/null and b/token_tv/web/press-start-2p.ttf differ
diff --git a/token_tv/web/style.css b/token_tv/web/style.css
new file mode 100644
index 0000000..1b13d74
--- /dev/null
+++ b/token_tv/web/style.css
@@ -0,0 +1,842 @@
+@import url('/assets/tokens.css');
+/* TokenTV web. Shared rules hold structure and data semantics; each theme block
+ * below re-composes the same nodes after its reference image
+ * (docs/plans/2026-10-03-web-theme-redesign.md). */
+
+@font-face{font-family:'Manrope';src:url('/assets/manrope.ttf') format('truetype');font-weight:200 800;font-display:swap}
+@font-face{font-family:'VT323';src:url('/assets/vt323.woff2') format('woff2');font-display:swap}
+@font-face{font-family:'DSEG7 Classic';src:url('/assets/dseg7-classic-bold.woff2') format('woff2');font-weight:400 700;font-display:swap}
+@font-face{font-family:'Jersey 10';src:url('/assets/jersey-10.woff2') format('woff2');font-display:swap}
+@font-face{font-family:'Orbitron';src:url('/assets/orbitron.ttf') format('truetype');font-weight:400 900;font-display:swap}
+@font-face{font-family:'Oxanium';src:url('/assets/oxanium.woff2') format('woff2');font-weight:500 800;font-display:swap}
+@font-face{font-family:'Press Start 2P';src:url('/assets/press-start-2p.ttf') format('truetype');font-display:swap}
+@font-face{font-family:'Cormorant Garamond';src:url('/assets/cormorant-garamond.woff2') format('woff2');font-weight:500 700;font-display:swap}
+@font-face{font-family:'Chakra Petch';src:url('/assets/chakra-petch-500.woff2') format('woff2');font-weight:500;font-display:swap}
+@font-face{font-family:'Chakra Petch';src:url('/assets/chakra-petch-700.woff2') format('woff2');font-weight:700;font-display:swap}
+
+/* ── Base ─────────────────────────────────────────────────────────── */
+*,*::before,*::after{box-sizing:border-box}
+html{min-width:300px;background:var(--bg)}
+body{margin:0;min-height:100vh;background:var(--bg);color:var(--ink);font:400 14px/1.5 var(--font-body);-webkit-font-smoothing:antialiased}
+button,select{font:inherit;color:inherit}
+button{cursor:pointer}
+a{color:inherit}
+[hidden]{display:none!important}
+:focus-visible{outline:2px solid var(--focus);outline-offset:3px}
+button:active:not(:disabled){transform:translateY(1px)}
+.skip{position:fixed;left:12px;top:-80px;z-index:30;padding:10px 14px;background:var(--panel);color:var(--ink)}
+.skip:focus{top:10px}
+
+/* Theme atmospheres live behind everything and never affect layout. */
+.backdrop{position:fixed;inset:0;z-index:0;overflow:hidden;pointer-events:none}
+.backdrop>*{display:none}
+.shell{position:relative;z-index:1;max-width:1000px;margin:0 auto;padding:0 32px 56px}
+.shell:has(.clock-panel:not([hidden])){max-width:1360px}
+
+/* ── Top bar ──────────────────────────────────────────────────────── */
+.topbar{display:flex;align-items:center;gap:18px;min-height:78px}
+.brand{display:inline-flex;align-items:center;gap:12px;text-decoration:none;font:800 13px/1 var(--font-label);letter-spacing:.22em;color:var(--ink)}
+.brand b{font-weight:inherit;color:var(--ink-2)}
+.brandmark{position:relative;flex:none;width:24px;height:19px;border:2px solid currentColor;border-radius:5px}
+.brandmark::before{content:"";position:absolute;inset:3px;background:linear-gradient(var(--lvl-low),var(--lvl-low)) 0 0/70% 3px no-repeat,linear-gradient(var(--ink-3),var(--ink-3)) 0 6px/45% 3px no-repeat}
+.brandmark::after{content:"";position:absolute;left:6px;right:6px;bottom:-6px;height:2px;background:currentColor}
+.connection{margin-left:auto;display:flex;align-items:center;gap:9px;font:500 12px/1 var(--font-label);color:var(--ink-2)}
+.status-dot{flex:none;width:8px;height:8px;border-radius:50%;background:var(--lvl-low);box-shadow:0 0 0 3px color-mix(in srgb,var(--lvl-low) 24%,transparent)}
+body[data-offline=true] .status-dot{background:var(--lvl-critical);box-shadow:0 0 0 3px color-mix(in srgb,var(--lvl-critical) 24%,transparent)}
+.control{min-height:38px;padding:9px 16px;border:1px solid var(--line-2);border-radius:var(--radius-control);background:color-mix(in srgb,var(--panel) 82%,transparent);color:var(--ink);font:600 12px/1 var(--font-label);letter-spacing:.03em;transition:background .16s ease-out,border-color .16s ease-out,color .16s ease-out}
+.control:hover:not(:disabled){border-color:var(--ink-3)}
+.control:disabled{opacity:.45;cursor:default}
+select.control{appearance:none;padding-right:38px;background-image:linear-gradient(45deg,transparent 50%,var(--ink-2) 50%),linear-gradient(135deg,var(--ink-2) 50%,transparent 50%);background-position:calc(100% - 20px) 52%,calc(100% - 15px) 52%;background-size:5px 5px;background-repeat:no-repeat}
+
+/* ── Appearance picker: each tile previews its own theme. ─────────── */
+.theme-section{margin:2px 0 34px}
+.section-label{display:block;margin:0 0 10px;font:700 10px/1.2 var(--font-label);letter-spacing:.24em;text-transform:uppercase;color:var(--ink-3)}
+.themes{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:8px}
+.theme-button{display:grid;gap:9px;padding:6px 6px 10px;border:1px solid var(--line);border-radius:calc(var(--radius-control) + 4px);background:color-mix(in srgb,var(--panel) 72%,transparent);color:var(--ink-2);font:600 11.5px/1.25 var(--font-label);text-align:left;transition:border-color .16s ease-out,color .16s ease-out,background .16s ease-out}
+.theme-button:hover{color:var(--ink);border-color:var(--line-2)}
+.theme-button[aria-pressed=true]{color:var(--ink);border-color:var(--ink-2);box-shadow:0 0 0 1px var(--ink-2)}
+.theme-name{padding:0 4px}
+.swatch{position:relative;display:grid;align-content:center;gap:4px;height:42px;padding:0 10px;overflow:hidden;border-radius:calc(var(--radius-control) - 2px)}
+.swatch i{display:block;height:5px;border-radius:3px;background:var(--c,#fff)}
+.swatch i:nth-child(1){width:86%}.swatch i:nth-child(2){width:62%}.swatch i:nth-child(3){width:36%}
+.swatch[data-swatch=digital]{border-radius:0;background:#03100b;box-shadow:inset 0 0 0 1px #22694f}
+.swatch[data-swatch=digital] i{border-radius:0;--c:#5dffc4;-webkit-mask:repeating-linear-gradient(90deg,#000 0 5px,transparent 5px 7px);mask:repeating-linear-gradient(90deg,#000 0 5px,transparent 5px 7px)}
+.swatch[data-swatch=neon]{border-radius:12px;background:#07051a;box-shadow:inset 0 0 18px rgba(217,70,239,.28),inset 0 0 0 1px #2a2148}
+.swatch[data-swatch=neon] i:nth-child(1){background:#ffb13b;box-shadow:0 0 8px #ff8a2b}
+.swatch[data-swatch=neon] i:nth-child(2){background:#38dcf5;box-shadow:0 0 8px #22d3ee}
+.swatch[data-swatch=neon] i:nth-child(3){background:#e05cf2;box-shadow:0 0 8px #d946ef}
+.swatch[data-swatch=retro]{border-radius:0;background:#141d52;box-shadow:inset 0 0 0 2px #4a64c8,inset 0 0 0 4px #0a0d26}
+.swatch[data-swatch=retro] i{height:6px;border-radius:0;-webkit-mask:repeating-linear-gradient(90deg,#000 0 5px,transparent 5px 6px);mask:repeating-linear-gradient(90deg,#000 0 5px,transparent 5px 6px)}
+.swatch[data-swatch=retro] i:nth-child(1){--c:#ff9f43}.swatch[data-swatch=retro] i:nth-child(2){--c:#3ee68b}.swatch[data-swatch=retro] i:nth-child(3){--c:#b388ff}
+.swatch[data-swatch=modern]{border-radius:9px;background:linear-gradient(180deg,#1b212b,#11151c);box-shadow:inset 0 0 0 1px #2a3240}
+.swatch[data-swatch=modern] i{height:4px}
+.swatch[data-swatch=modern] i:nth-child(1){--c:#f4a07a}.swatch[data-swatch=modern] i:nth-child(2){--c:#6ea8ff}.swatch[data-swatch=modern] i:nth-child(3){--c:#5ee0b5}
+.swatch[data-swatch=sakura]{border-radius:12px;background:radial-gradient(circle at 92% 8%,#ffc9da 0 14%,transparent 40%),#fdf2f5;box-shadow:inset 0 0 0 1px #f0d0da}
+.swatch[data-swatch=sakura] i{--c:#e48aa6}
+.swatch[data-swatch=sakura]::after{content:"";position:absolute;right:9px;top:8px;width:9px;height:7px;border-radius:150% 0 150% 0;background:#f49ab5;transform:rotate(20deg)}
+.swatch[data-swatch=hud]{border-radius:0;background:linear-gradient(rgba(64,140,200,.16) 1px,transparent 1px) 0 0/100% 7px,#06101a;box-shadow:inset 0 0 0 1px #22476a;clip-path:polygon(0 0,calc(100% - 9px) 0,100% 9px,100% 100%,9px 100%,0 calc(100% - 9px))}
+.swatch[data-swatch=hud] i{border-radius:0;transform:skewX(-24deg);-webkit-mask:repeating-linear-gradient(90deg,#000 0 5px,transparent 5px 7px);mask:repeating-linear-gradient(90deg,#000 0 5px,transparent 5px 7px)}
+.swatch[data-swatch=hud] i:nth-child(1){--c:#ff8a3d}.swatch[data-swatch=hud] i:nth-child(2){--c:#2fd4ff}.swatch[data-swatch=hud] i:nth-child(3){--c:#3ef29b}
+
+/* ── Screen ───────────────────────────────────────────────────────── */
+.workspace{display:grid;grid-template-columns:minmax(0,1fr);gap:28px;align-items:start}
+.shell:has(.clock-panel:not([hidden])) .workspace{grid-template-columns:minmax(0,1fr) 320px}
+.screen{position:relative;min-width:0}
+.screen-head{position:relative;display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin:6px 0 28px}
+.title-block{min-width:0}
+.eyebrow{margin:0 0 12px;font:700 11px/1.2 var(--font-label);letter-spacing:.3em;text-transform:uppercase;color:var(--ink-2)}
+h1{margin:0;font:600 48px/1.04 var(--font-display);letter-spacing:-.03em;color:var(--ink);overflow-wrap:anywhere}
+.intro-note{margin:12px 0 0;font-size:15px;color:var(--ink-2)}
+.mascot{display:none}
+.summary{display:flex;align-items:center;gap:24px;margin:0;flex:none}
+.summary>div{display:grid;gap:6px}
+.summary dt{font:700 10px/1 var(--font-label);letter-spacing:.2em;text-transform:uppercase;color:var(--ink-3)}
+.summary dd{margin:0;font:600 22px/1 var(--font-num);font-variant-numeric:tabular-nums;color:var(--ink)}
+.summary .summary-providers,.summary .summary-clock{display:none}
+#local-time span{white-space:nowrap}
+#local-time .zone,#local-time .date-iso,#local-time .date-long{display:none}
+.notice{margin:0 0 18px;padding:12px 16px;border:1px dashed var(--lvl-critical);border-radius:12px;background:color-mix(in srgb,var(--lvl-critical) 9%,transparent);font-size:13px;color:var(--ink)}
+.loading{padding:40px 0;color:var(--ink-2)}
+
+/* ── Provider card: one node set, composed by each theme's grid. ─── */
+.provider-list{display:grid;gap:18px}
+.card-shell{display:contents}
+.card-shell,.provider-card{--accent:var(--claude);--accent-2:var(--claude-2)}
+.card-shell[data-provider=codex],.provider-card[data-provider=codex]{--accent:var(--codex);--accent-2:var(--codex-2)}
+.card-shell[data-provider=grok],.provider-card[data-provider=grok]{--accent:var(--grok);--accent-2:var(--grok-2)}
+.provider-card{position:relative;isolation:isolate;overflow:hidden;display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"head head" "reading timer" "gauge gauge" "more more" "foot foot";align-items:center;column-gap:28px;padding:24px 28px 0;border:1px solid var(--line);border-radius:var(--radius-card);background:var(--panel)}
+.card-art{position:absolute;inset:0;z-index:-1;display:none;pointer-events:none}
+.card-art .scene{display:none;position:absolute;inset:0;width:100%;height:100%}
+.card-head{grid-area:head;display:flex;align-items:center;gap:14px;min-width:0}
+.provider-icon{flex:none;display:grid;place-items:center;width:44px;height:44px;color:var(--accent)}
+.provider-icon .glyph{width:30px;height:30px;overflow:visible}
+.pixel-mascot{display:none;width:64px;height:64px;image-rendering:pixelated}
+.provider-name{display:flex;flex-direction:column;gap:6px;min-width:0}
+.provider-title{margin:0;font:700 18px/1 var(--font-display);letter-spacing:.08em;color:var(--ink)}
+.company{font:700 10px/1 var(--font-label);letter-spacing:.26em;color:var(--ink-3)}
+.account-tabs{display:flex;flex-wrap:wrap;gap:5px;margin-left:auto}
+.account-tab{min-width:34px;min-height:32px;padding:0 10px;border:1px solid var(--line-2);border-radius:var(--radius-control);background:transparent;color:var(--ink-2);font:700 11px/1 var(--font-label);letter-spacing:.06em;transition:color .16s ease-out,background .16s ease-out,border-color .16s ease-out}
+.account-tab:hover{color:var(--ink);border-color:var(--ink-3)}
+.account-tab[aria-pressed=true]{background:var(--ink);border-color:var(--ink);color:var(--bg)}
+.reading{grid-area:reading;display:flex;flex-direction:column;gap:8px;min-width:0;margin:20px 0 16px}
+.reading-meta{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 12px}
+.reading-label{font:700 10px/1.2 var(--font-label);letter-spacing:.22em;color:var(--ink-2)}
+.level-label{font:700 10px/1.2 var(--font-label);letter-spacing:.16em;text-transform:uppercase;color:var(--ink-3)}
+.unknown-message{font:500 12px/1.3 var(--font-label);color:var(--ink-2)}
+.percentage{font:600 64px/1 var(--font-num);letter-spacing:-.04em;font-variant-numeric:tabular-nums;white-space:nowrap;color:var(--ink)}
+.percent-sign{font-size:.46em;letter-spacing:0;margin-left:.05em}
+.timer{grid-area:timer;display:grid;grid-template-columns:auto auto;justify-content:start;align-items:center;gap:6px 12px;min-width:180px;padding-left:28px;border-left:1px solid var(--line)}
+.clock-mark{grid-row:1/3;display:grid;place-items:center;color:var(--accent)}
+.clock-icon{width:22px;height:22px}
+.clock-pixel{display:none;width:27px;height:27px}
+.timer-label{font:700 10px/1.2 var(--font-label);letter-spacing:.22em;color:var(--ink-3)}
+.timer-value{font:600 26px/1.05 var(--font-num);letter-spacing:-.02em;font-variant-numeric:tabular-nums;white-space:nowrap;color:var(--ink)}
+.gauge{grid-area:gauge;display:flex;align-items:center;gap:14px;min-width:0}
+.gauge-value{display:none;flex:none;min-width:4ch;text-align:right;font:600 12px/1 var(--font-num);font-variant-numeric:tabular-nums;color:var(--ink-2)}
+
+/* Gauge: ten 10% cells; fill colour is the used-quota band. */
+.meter{--gauge:var(--lvl-low);--gauge-2:var(--lvl-low-2);position:relative;flex:1;min-width:0;display:flex;gap:4px;height:12px}
+.meter[data-level=medium]{--gauge:var(--lvl-medium);--gauge-2:var(--lvl-medium-2)}
+.meter[data-level=high]{--gauge:var(--lvl-high);--gauge-2:var(--lvl-high-2)}
+.meter[data-level=critical]{--gauge:var(--lvl-critical);--gauge-2:var(--lvl-critical-2)}
+/* Cells sample one band gradient over the filled length (--i = cell, --v = value): lvl-*-2 at the start, the band colour at the tip. */
+.meter-segment{--t0:min(100%,calc(var(--i,0) * 1000% / var(--v,100)));--t1:min(100%,calc((var(--i,0) + 1) * 1000% / var(--v,100)));position:relative;flex:1;min-width:0;overflow:hidden;background:var(--track)}
+.meter-fill{--fill-grad:linear-gradient(90deg,color-mix(in srgb,var(--gauge) var(--t0),var(--gauge-2)),color-mix(in srgb,var(--gauge) var(--t1),var(--gauge-2)));display:block;height:100%;width:var(--fill);background:var(--fill-grad)}
+.unknown-meter .meter-segment{background:transparent;outline:1px dashed var(--line-2);outline-offset:-1px}
+.provider-card[data-stale=true] .meter{opacity:.62}
+.provider-card[data-stale=true] .meter-fill{background:repeating-linear-gradient(135deg,var(--gauge) 0 3px,transparent 3px 6px)!important}
+/* Continuous bars (Neon, Modern, Sakura) draw one fill on the meter itself. */
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .meter{gap:0;border-radius:999px;background:var(--track)}
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .meter-segment{background:none;overflow:visible}
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .meter-fill{display:none}
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .meter::before{content:"";position:absolute;left:0;top:0;bottom:0;width:var(--value,0%);border-radius:inherit;background:linear-gradient(90deg,var(--gauge-2),var(--gauge))}
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .unknown-meter{background:transparent;outline:1px dashed var(--line-2);outline-offset:-1px}
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .unknown-meter .meter-segment{outline:0}
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .provider-card[data-stale=true] .meter::before{background:repeating-linear-gradient(135deg,var(--gauge) 0 4px,transparent 4px 8px)!important;box-shadow:none!important}
+
+.more-windows{grid-area:more;margin:2px 0 14px;font:500 12px/1.4 var(--font-label);color:var(--ink-2)}
+.more-windows summary{display:inline-flex;align-items:center;gap:9px;width:fit-content;min-height:28px;cursor:pointer;list-style:none;font-size:10px;font-weight:700;letter-spacing:.16em;text-transform:uppercase}
+.more-windows summary::-webkit-details-marker{display:none}
+.more-windows summary::before{content:"+";display:grid;place-items:center;width:18px;height:18px;border:1px solid var(--line-2);border-radius:50%;font-size:12px;line-height:1;letter-spacing:0}
+.more-windows[open] summary::before{content:"−"}
+.window-detail{display:grid;grid-template-columns:96px minmax(0,1fr) 48px 96px;align-items:center;gap:14px;margin-top:10px}
+.window-name{font-size:10px;font-weight:700;letter-spacing:.16em;color:var(--ink-3)}
+.window-detail .meter{height:6px;gap:2px}
+.window-percent{text-align:right;font-family:var(--font-num);font-variant-numeric:tabular-nums;color:var(--ink)}
+.window-timer{text-align:right;font-variant-numeric:tabular-nums;color:var(--ink-2)}
+
+.card-foot{grid-area:foot;display:flex;flex-wrap:wrap;align-items:center;gap:6px 18px;margin:0 -28px;padding:13px 28px 14px;border-top:1px solid var(--line);font:500 11px/1.3 var(--font-label);color:var(--ink-3)}
+.stat{display:inline-flex;align-items:baseline;gap:7px;min-width:0}
+.stat-k{font-size:9px;font-weight:700;letter-spacing:.2em;text-transform:uppercase;color:var(--ink-3)}
+.stat-v{color:var(--ink-2)}
+.stat-status{margin-left:auto}
+.provider-card[data-stale=true] .row-status{color:var(--lvl-critical)}
+
+/* ── Screen footer, legend, help ──────────────────────────────────── */
+.screen-foot{display:grid;gap:14px;margin-top:26px}
+.footer-meta{display:flex;flex-wrap:wrap;align-items:center;gap:8px 22px;font:500 11px/1.3 var(--font-label);color:var(--ink-3)}
+#foot-reporting,.signal{display:none}
+.legend{display:flex;flex-wrap:wrap;align-items:center;gap:8px 18px;font:500 11px/1 var(--font-label);color:var(--ink-3)}
+.legend .section-label{margin:0 4px 0 0}
+.legend span{display:inline-flex;align-items:center;gap:7px}
+.legend i{display:block;width:22px;height:6px;border-radius:3px;background:linear-gradient(90deg,var(--lvl-low-2),var(--lvl-low))}
+.legend i[data-level=medium]{background:linear-gradient(90deg,var(--lvl-medium-2),var(--lvl-medium))}
+.legend i[data-level=high]{background:linear-gradient(90deg,var(--lvl-high-2),var(--lvl-high))}
+.legend i[data-level=critical]{background:linear-gradient(90deg,var(--lvl-critical-2),var(--lvl-critical))}
+.help{max-width:760px;margin-top:22px;font-size:12px;color:var(--ink-3)}
+.help summary{cursor:pointer;width:fit-content;color:var(--ink-2)}
+.help p{line-height:1.7}
+
+/* ── Clock panel: the physical TokenTV, framed like the device. ──── */
+.clock-panel{position:sticky;top:20px;padding:22px;border:1px solid var(--line);border-radius:var(--radius-card);background:var(--panel)}
+.aside-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:18px}
+.aside-head .eyebrow{margin-bottom:8px}
+.aside-head h2{margin:0;font:600 22px/1.1 var(--font-display);color:var(--ink)}
+.icon-control{display:grid;place-items:center;width:38px;height:38px;padding:0;font-size:20px;line-height:1}
+.device{width:fit-content;max-width:100%;margin:0 auto 20px;padding:14px;border-radius:22px;background:linear-gradient(155deg,#34373e,#16181c 58%,#0c0d10);box-shadow:inset 0 1px 0 rgba(255,255,255,.14),inset 0 -3px 8px rgba(0,0,0,.55),0 22px 34px -20px rgba(0,0,0,.9)}
+.lcd{width:240px;max-width:100%;border-radius:4px;overflow:hidden;background:#000;box-shadow:0 0 0 2px #050607}
+.lcd img{display:block;width:100%;height:auto;aspect-ratio:1;image-rendering:pixelated}
+.clock-panel label{display:block;margin-bottom:8px;font:700 10px/1 var(--font-label);letter-spacing:.2em;text-transform:uppercase;color:var(--ink-3)}
+.clock-panel select{width:100%;margin-bottom:10px}
+.primary{width:100%;margin-bottom:12px}
+[data-theme] .control.primary{background:var(--ink);border-color:var(--ink);color:var(--bg);font-weight:800;text-shadow:none}
+.primary:hover:not(:disabled){filter:brightness(1.08)}
+.primary[data-state=error]{border-style:dashed}
+#display-state,.quiet{margin:0 0 6px;font-size:12px;color:var(--ink-2)}
+.quiet{color:var(--ink-3)}
+
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) :is(.section-label,.level-label,.more-windows summary){text-transform:none;letter-spacing:.01em;font-size:12px;font-weight:600}
+:is([data-theme=neon],[data-theme=modern],[data-theme=sakura]) .level-label{font-family:var(--font-body);font-size:11px;font-weight:500;color:var(--ink-3)}
+
+/* ════════════════════════════════════════════════════════════════════
+ Digital Terminal — phosphor console: one ruled window, header bar with
+ live clock and block cursor, boxed panels, split-segment bars, amber timers.
+ ════════════════════════════════════════════════════════════════════ */
+[data-theme=digital] body{background:radial-gradient(1200px 700px at 50% -20%,#062519 0%,transparent 70%),var(--bg);text-shadow:0 0 7px rgba(93,255,196,.2)}
+[data-theme=digital] .atmosphere{display:block;position:absolute;inset:0;background:repeating-linear-gradient(180deg,rgba(125,255,208,.04) 0 1px,transparent 1px 3px)}
+[data-theme=digital] .sweep{display:block;position:absolute;left:0;right:0;top:-220px;height:220px;background:linear-gradient(180deg,transparent,rgba(93,255,196,.045),transparent);animation:sweep 10s linear infinite}
+[data-theme=digital] .topbar{margin-bottom:22px;border-bottom:1px solid var(--line)}
+[data-theme=digital] .brand{font:400 25px/1 var(--font-label);letter-spacing:.16em}
+[data-theme=digital] .brandmark{border-radius:0;border-width:1px}
+[data-theme=digital] .connection{font:400 20px/1 var(--font-label);letter-spacing:.08em;text-transform:uppercase}
+[data-theme=digital] .status-dot{border-radius:0;box-shadow:0 0 8px var(--lvl-low)}
+[data-theme=digital] .control{border-radius:0;background:transparent;font:400 20px/1 var(--font-label);letter-spacing:.1em;text-transform:uppercase}
+[data-theme=digital] .control:hover:not(:disabled){background:rgba(93,255,196,.08)}
+[data-theme=digital] .clock-toggle::before{content:"[ "}
+[data-theme=digital] .clock-toggle::after{content:" ]"}
+[data-theme=digital] .section-label{font:400 20px/1 var(--font-label);letter-spacing:.14em;color:var(--ink-3)}
+[data-theme=digital] .section-label::before{content:"> "}
+[data-theme=digital] .theme-button{border-radius:0;background:transparent;font:400 18px/1.05 var(--font-label);letter-spacing:.06em;text-transform:uppercase}
+[data-theme=digital] .theme-button[aria-pressed=true]{border-color:var(--ink);box-shadow:none;background:rgba(93,255,196,.07)}
+[data-theme=digital] .screen{padding:16px;border:1px solid var(--line-2);background:linear-gradient(180deg,rgba(61,252,176,.035),transparent 35%),var(--panel);box-shadow:0 0 0 1px #000,0 0 70px -14px rgba(61,252,176,.2),inset 0 0 120px rgba(61,252,176,.04)}
+[data-theme=digital] .screen-head{align-items:center;margin:0 0 16px;padding:16px 20px;border:1px solid var(--line-2)}
+[data-theme=digital] h1{font:400 42px/1 var(--font-display);letter-spacing:.06em;text-transform:uppercase}
+[data-theme=digital] h1::after{content:"";display:inline-block;width:.58em;height:1em;margin-left:.3em;vertical-align:-.14em;background:var(--ink);box-shadow:0 0 10px rgba(125,255,208,.6);animation:blink 1.06s steps(1) infinite}
+[data-theme=digital] .summary-accounts,[data-theme=digital] .summary-reporting{display:none}
+[data-theme=digital] .summary .summary-clock{display:block}
+[data-theme=digital] .summary-clock dt{display:none}
+[data-theme=digital] .summary dd{display:flex;align-items:baseline;gap:16px;font:700 17px/1 var(--font-num);letter-spacing:.04em}
+[data-theme=digital] #local-time .zone{font:400 24px/1 var(--font-body);letter-spacing:.06em}
+[data-theme=digital] #local-time .zone,[data-theme=digital] #local-time .date-iso{display:inline}
+[data-theme=digital] .provider-list{gap:16px}
+[data-theme=digital] .provider-card{grid-template-columns:200px minmax(0,1fr) auto;grid-template-areas:"head head head" "reading gauge timer" "more more more" "foot foot foot";column-gap:26px;padding:0 20px;border:1px solid var(--line-2);border-radius:0;background:var(--panel-2)}
+[data-theme=digital] .card-head{gap:14px;padding:16px 0 14px;border-bottom:1px solid var(--line)}
+[data-theme=digital] .provider-icon{width:30px;height:30px}
+[data-theme=digital] .provider-icon .glyph{width:26px;height:26px;filter:drop-shadow(0 0 4px rgba(125,255,208,.5))}
+[data-theme=digital] .provider-name{flex:1;flex-direction:row;align-items:baseline;justify-content:space-between;gap:16px}
+[data-theme=digital] .provider-title{font:400 50px/.9 var(--font-display);letter-spacing:.03em}
+[data-theme=digital] .provider-title::after{content:" >";font-size:.66em;vertical-align:.14em;color:var(--ink-2)}
+[data-theme=digital] .company{font:400 23px/1 var(--font-label);letter-spacing:.12em;color:var(--ink-2)}
+[data-theme=digital] .account-tabs{gap:0;margin-left:20px;border:1px solid var(--line-2)}
+[data-theme=digital] .account-tab{min-width:36px;min-height:30px;border:0;border-left:1px solid var(--line-2);border-radius:0;font:400 22px/1 var(--font-label)}
+[data-theme=digital] .account-tab:first-child{border-left:0}
+[data-theme=digital] .account-tab[aria-pressed=true]{background:var(--ink);color:var(--bg);text-shadow:none}
+[data-theme=digital] .reading{gap:8px;min-width:150px;margin:22px 0}
+[data-theme=digital] .reading-meta{display:contents}
+[data-theme=digital] .level-label,[data-theme=digital] .unknown-message{order:1}
+[data-theme=digital] .reading-label{order:-1;font:400 22px/1 var(--font-label);letter-spacing:.1em;color:var(--ink-2)}
+[data-theme=digital] .percentage{font:700 58px/1 var(--font-num);letter-spacing:0}
+[data-theme=digital] .percent-sign{font:400 .78em/1 var(--font-body);margin-left:.14em}
+[data-theme=digital] .level-label,[data-theme=digital] .unknown-message{font:400 20px/1.05 var(--font-label);letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3)}
+[data-theme=digital] .gauge .meter{height:54px;gap:6px;padding:5px;border:1px solid var(--line-2)}
+[data-theme=digital] .meter-segment::after{content:"";position:absolute;top:0;bottom:0;left:calc(50% - 3px);width:6px;background:var(--panel-2)}
+[data-theme=digital] .meter-fill{background:linear-gradient(180deg,rgba(255,255,255,.2),transparent 60%),var(--fill-grad);box-shadow:0 0 14px color-mix(in srgb,var(--gauge) 55%,transparent)}
+[data-theme=digital] .unknown-meter .meter-segment{outline-color:var(--line-2)}
+[data-theme=digital] .timer{align-self:stretch;align-content:center;grid-template-columns:1fr;gap:10px;min-width:190px;padding-left:26px}
+[data-theme=digital] .clock-mark{display:none}
+[data-theme=digital] .timer-label{font:400 22px/1 var(--font-label);letter-spacing:.1em;color:var(--ink-2)}
+[data-theme=digital] .timer-value:not([data-ghost]){font:400 46px/1 var(--font-body)}
+[data-theme=digital] .timer-value{font:700 34px/1 var(--font-num);letter-spacing:0;color:var(--amber);text-shadow:0 0 14px rgba(255,207,90,.4)}
+[data-theme=digital] .more-windows{margin:0 0 16px;font:400 21px/1.2 var(--font-label);letter-spacing:.06em}
+[data-theme=digital] .more-windows summary{font:400 21px/1 var(--font-label);letter-spacing:.08em}
+[data-theme=digital] .more-windows summary::before{content:"[+]";width:auto;height:auto;border:0;border-radius:0;font-size:21px}
+[data-theme=digital] .more-windows[open] summary::before{content:"[-]"}
+[data-theme=digital] .window-name{font-size:20px;font-weight:400}
+[data-theme=digital] .window-percent,[data-theme=digital] .window-timer{font:400 22px/1 var(--font-body)}
+[data-theme=digital] .window-detail .meter{height:12px;gap:3px}
+[data-theme=digital] .window-detail .meter-segment::after{display:none}
+[data-theme=digital] .card-foot{gap:8px 30px;margin:0 -20px;padding:14px 20px;border-top:1px solid var(--line);font:400 21px/1 var(--font-label);letter-spacing:.08em;text-transform:uppercase}
+[data-theme=digital] .stat{gap:12px}
+[data-theme=digital] .stat-k{font-size:21px;font-weight:400;letter-spacing:.08em}
+[data-theme=digital] .stat-status{padding-left:22px;border-left:1px solid var(--line)}
+[data-theme=digital] .screen-foot{gap:12px;margin-top:16px}
+[data-theme=digital] .footer-meta{gap:0;border:1px solid var(--line-2);font:400 22px/1 var(--font-label);letter-spacing:.08em;text-transform:uppercase;color:var(--ink)}
+[data-theme=digital] .footer-meta>span{padding:17px 20px;border-left:1px solid var(--line)}
+[data-theme=digital] .footer-meta>span:first-child{border-left:0}
+[data-theme=digital] #foot-reporting{display:block}
+[data-theme=digital] .signal{display:flex;align-self:stretch;align-items:flex-end;gap:4px;margin-left:auto;padding:13px 20px!important}
+[data-theme=digital] .signal i{width:8px;background:var(--ink);box-shadow:0 0 8px rgba(125,255,208,.5)}
+[data-theme=digital] .signal i:nth-child(1){height:45%}[data-theme=digital] .signal i:nth-child(2){height:72%}[data-theme=digital] .signal i:nth-child(3){height:100%}
+[data-theme=digital] .signal[data-strength="2"] i:nth-child(3),[data-theme=digital] .signal[data-strength="0"] i{background:var(--track);box-shadow:none}
+[data-theme=digital] .legend{padding:0 4px;font:400 19px/1 var(--font-label);letter-spacing:.08em;text-transform:uppercase}
+[data-theme=digital] .legend .section-label::before{content:none}
+[data-theme=digital] .legend i{width:22px;height:8px;border-radius:0}
+[data-theme=digital] .notice{border-radius:0;font:400 21px/1.25 var(--font-label);letter-spacing:.04em}
+[data-theme=digital] .clock-panel{border-color:var(--line-2);border-radius:0;background:var(--panel)}
+[data-theme=digital] .aside-head h2{font:400 36px/1 var(--font-display);letter-spacing:.06em;text-transform:uppercase}
+[data-theme=digital] .help{font:400 20px/1.4 var(--font-label)}
+[data-theme=digital] body{font-size:20px}
+[data-theme=digital] .eyebrow,[data-theme=digital] .clock-panel label{font:400 19px/1 var(--font-label);letter-spacing:.1em}
+[data-theme=digital] #display-state,[data-theme=digital] .quiet{font-size:19px}
+/* Seven-segment readouts keep their unlit 8-cells visible behind the lit digits. */
+[data-theme=digital] [data-ghost]{position:relative;z-index:0}
+[data-theme=digital] [data-ghost]::before{content:attr(data-ghost);position:absolute;left:0;top:0;z-index:-1;opacity:.11;text-shadow:none}
+
+/* ════════════════════════════════════════════════════════════════════
+ Neon Cyberpunk — black glass, gradient-lit rounded rims, icon wells,
+ white-hot numerals with provider bloom, sheen pill bars, clock rings.
+ ════════════════════════════════════════════════════════════════════ */
+[data-theme=neon] .atmosphere{display:block;position:absolute;inset:0;background:radial-gradient(rgba(255,255,255,.04) 1px,transparent 1.5px) 0 0/24px 24px}
+[data-theme=neon] .glow{display:block;position:absolute;border-radius:50%;filter:blur(80px)}
+[data-theme=neon] .glow-a{width:44vw;height:44vw;left:-16vw;top:6vh;background:radial-gradient(circle,#ff6a1a,transparent 68%);opacity:.24}
+[data-theme=neon] .glow-b{width:40vw;height:40vw;right:-14vw;top:28vh;background:radial-gradient(circle,#18b4ff,transparent 68%);opacity:.22}
+[data-theme=neon] .glow-c{width:52vw;height:38vw;left:22vw;bottom:-24vw;background:radial-gradient(circle,#c026d3,transparent 68%);opacity:.3}
+[data-theme=neon] .brand{font:800 14px/1 var(--font-display);letter-spacing:.24em}
+[data-theme=neon] .brand b{color:#8ff3ff;text-shadow:0 0 6px rgba(34,211,238,.9),0 0 18px rgba(34,211,238,.5)}
+[data-theme=neon] .brandmark{border-color:#7df0ff;box-shadow:0 0 12px rgba(34,211,238,.6),inset 0 0 8px rgba(34,211,238,.4)}
+[data-theme=neon] .control{border-color:#3a325f;background:rgba(17,13,36,.7)}
+[data-theme=neon] .clock-toggle{box-shadow:0 0 0 1px rgba(217,70,239,.3),0 0 20px -6px #d946ef}
+[data-theme=neon] .theme-button{border-radius:16px;background:rgba(14,11,30,.62);border-color:#241f42}
+[data-theme=neon] .theme-button[aria-pressed=true]{border-color:#c084fc;box-shadow:0 0 0 1px #c084fc,0 0 22px -6px #d946ef}
+[data-theme=neon] .screen-head{align-items:center;margin-bottom:30px}
+[data-theme=neon] .title-block{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px 20px}
+[data-theme=neon] h1{order:1;font:800 34px/1 var(--font-display);letter-spacing:.1em;color:#fff;text-shadow:0 0 22px rgba(255,255,255,.25)}
+[data-theme=neon] h1::before{content:"";display:inline-block;width:24px;height:24px;margin-right:16px;vertical-align:-1px;background:linear-gradient(#4f7bff,#4f7bff) 0 100%/6px 52% no-repeat,linear-gradient(#22d3ee,#22d3ee) 9px 100%/6px 78% no-repeat,linear-gradient(#a78bfa,#a78bfa) 18px 100%/6px 100% no-repeat;filter:drop-shadow(0 0 6px #22d3ee)}
+[data-theme=neon] .title-block .eyebrow{order:2;margin:0;font:600 13px/1 var(--font-display);letter-spacing:.34em;color:var(--ink-2)}
+[data-theme=neon] .summary{gap:0;padding:4px;border-radius:999px;background:rgba(16,13,34,.75);box-shadow:inset 0 0 0 1px #3a325f,0 0 26px -10px #d946ef}
+[data-theme=neon] .summary>div{grid-auto-flow:column;align-items:center;gap:10px;padding:10px 18px}
+[data-theme=neon] .summary>div+div{border-left:1px solid #2a2448}
+[data-theme=neon] .summary dt{order:2;font:600 10px/1 var(--font-display);letter-spacing:.22em;color:var(--ink-2)}
+[data-theme=neon] .summary dd{font:700 18px/1 var(--font-num);color:#fff}
+[data-theme=neon] .provider-list{gap:22px}
+[data-theme=neon] .provider-card{grid-template-columns:100px auto minmax(0,1fr) auto;grid-template-areas:"icon name tabs timer" "icon reading reading timer" "gauge gauge gauge gauge" "more more more more" "foot foot foot foot";column-gap:24px;padding:26px 30px 0;border:0;border-radius:26px;background:radial-gradient(120% 150% at 0% 0%,color-mix(in srgb,var(--accent) 15%,transparent),transparent 52%),linear-gradient(180deg,rgba(255,255,255,.04),rgba(255,255,255,.008)),var(--panel);box-shadow:0 0 30px -8px color-mix(in srgb,var(--accent) 60%,transparent),0 0 80px -26px color-mix(in srgb,var(--accent) 70%,transparent),inset 0 0 36px -14px color-mix(in srgb,var(--accent) 45%,transparent)}
+[data-theme=neon] .provider-card::before{content:"";position:absolute;inset:0;z-index:-1;border-radius:inherit;padding:1.5px;background:linear-gradient(115deg,var(--accent-2),var(--accent) 30%,color-mix(in srgb,var(--accent) 25%,transparent) 62%,var(--accent-2));-webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask-composite:exclude}
+[data-theme=neon] .card-head{display:contents}
+[data-theme=neon] .provider-icon{grid-area:icon;width:100px;height:100px;border-radius:24px;background:radial-gradient(circle at 30% 22%,color-mix(in srgb,var(--accent) 32%,transparent),transparent 72%),rgba(255,255,255,.03);box-shadow:inset 0 0 0 1.5px color-mix(in srgb,var(--accent) 75%,transparent),0 0 24px -4px color-mix(in srgb,var(--accent) 70%,transparent),inset 0 0 22px color-mix(in srgb,var(--accent) 28%,transparent)}
+[data-theme=neon] .provider-icon .glyph{width:52px;height:52px;color:color-mix(in srgb,var(--accent),#fff 18%);filter:drop-shadow(0 0 5px var(--accent)) drop-shadow(0 0 14px color-mix(in srgb,var(--accent) 70%,transparent))}
+[data-theme=neon] .provider-name{grid-area:name;align-self:end;gap:8px}
+[data-theme=neon] .provider-title{font:700 27px/1 var(--font-display);letter-spacing:.1em;color:#fff}
+[data-theme=neon] .company{font:600 9px/1 var(--font-display);letter-spacing:.3em;color:var(--ink-3)}
+[data-theme=neon] .account-tabs{grid-area:tabs;align-self:end;margin:0 0 2px 6px;gap:6px}
+[data-theme=neon] .account-tab{border-color:color-mix(in srgb,var(--accent) 38%,transparent);font:700 11px/1 var(--font-display);color:var(--ink-2)}
+[data-theme=neon] .account-tab:hover{border-color:var(--accent);color:#fff}
+[data-theme=neon] .account-tab[aria-pressed=true]{border-color:transparent;background:linear-gradient(135deg,var(--accent-2),var(--accent));color:#08060f;box-shadow:0 0 16px -2px var(--accent)}
+[data-theme=neon] .reading{grid-area:reading;gap:10px;margin:14px 0 0}
+[data-theme=neon] .reading-meta{order:-1}
+[data-theme=neon] .reading-label{font:600 10px/1 var(--font-display);letter-spacing:.3em;color:var(--ink-2)}
+[data-theme=neon] .level-label{font:600 9px/1 var(--font-display);letter-spacing:.2em}
+[data-theme=neon] .percentage{font:800 74px/1 var(--font-num);letter-spacing:.02em;color:#fff;text-shadow:0 0 2px #fff,0 0 14px color-mix(in srgb,var(--accent) 90%,transparent),0 0 36px color-mix(in srgb,var(--accent) 65%,transparent)}
+[data-theme=neon] .percent-sign{font-size:.5em;font-weight:600}
+[data-theme=neon] .timer{grid-area:timer;align-self:center;gap:6px 16px;min-width:210px;padding:4px 0 4px 30px;border-left-color:color-mix(in srgb,var(--accent) 34%,transparent)}
+[data-theme=neon] .clock-icon{width:48px;height:48px;padding:11px;border-radius:50%;box-shadow:inset 0 0 0 1.5px var(--accent),0 0 18px -2px var(--accent),inset 0 0 12px color-mix(in srgb,var(--accent) 40%,transparent)}
+[data-theme=neon] .timer-label{font:600 10px/1 var(--font-display);letter-spacing:.3em;color:var(--ink-2)}
+[data-theme=neon] .timer-value{font:700 29px/1.1 var(--font-num);letter-spacing:.02em;color:#fff;text-shadow:0 0 16px color-mix(in srgb,var(--accent) 70%,transparent)}
+[data-theme=neon] .gauge{gap:18px;margin:22px 0 20px}
+[data-theme=neon] .meter{height:18px;background:linear-gradient(180deg,rgba(0,0,0,.4),rgba(255,255,255,.04)),var(--track);box-shadow:inset 0 1px 3px rgba(0,0,0,.7),inset 0 0 0 1px rgba(255,255,255,.05)}
+[data-theme=neon] .meter::before{background:linear-gradient(90deg,var(--gauge-2),var(--gauge) 72%,color-mix(in srgb,var(--gauge),#fff 38%));box-shadow:0 0 12px color-mix(in srgb,var(--gauge) 85%,transparent),0 0 30px color-mix(in srgb,var(--gauge) 45%,transparent)}
+[data-theme=neon] .meter::after{content:"";position:absolute;left:3px;top:3px;bottom:3px;width:max(0px,calc(var(--value,0%) - 6px));border-radius:inherit;background:repeating-linear-gradient(115deg,rgba(255,255,255,.22) 0 7px,transparent 7px 19px);mix-blend-mode:overlay}
+[data-theme=neon] .gauge-value{display:block;font:700 14px/1 var(--font-num);color:var(--ink-2)}
+[data-theme=neon] .window-detail .meter{height:7px}
+[data-theme=neon] .window-detail .meter::after{display:none}
+[data-theme=neon] .card-foot{margin:0 -30px;padding:14px 30px 16px;border-top-color:color-mix(in srgb,var(--accent) 20%,transparent)}
+[data-theme=neon] .stat-k{display:none}
+[data-theme=neon] .stat:not(.stat-status)+.stat:not(.stat-status)::before{content:"·";margin-right:11px;color:var(--ink-3)}
+[data-theme=neon] .legend i{height:6px;box-shadow:0 0 8px currentColor}
+[data-theme=neon] .control.primary{border-color:#7df0ff;background:#22d3ee;color:#04030a;box-shadow:0 0 18px -4px #22d3ee}
+[data-theme=neon] .clock-panel{border-color:#3a325f;background:rgba(12,10,26,.88);box-shadow:0 0 40px -16px #d946ef}
+
+/* ════════════════════════════════════════════════════════════════════
+ Pixel Retro — 8-bit night: pixel banner with the TokenTV mascot,
+ stepped frames, a pixel scene per provider, project pixel mascots,
+ chunky three-tone HP blocks. Press Start 2P at 8px multiples.
+ ════════════════════════════════════════════════════════════════════ */
+[data-theme=retro] body{background:linear-gradient(180deg,#060a20,#0c1340 55%,#121b55)}
+[data-theme=retro] .starfield{display:block;position:absolute;inset:0}
+[data-theme=retro] .starfield svg{display:block;width:100%;height:100%}
+[data-theme=retro] .twinkle{animation:twinkle 3.6s steps(2,jump-none) infinite}
+[data-theme=retro] .brand{font:400 12px/1 var(--font-display);letter-spacing:.04em}
+[data-theme=retro] .brand b{color:#ffd86b}
+[data-theme=retro] .brandmark{border-radius:0;border-width:3px;width:26px;height:22px}
+[data-theme=retro] .connection{font:400 20px/1 var(--font-body)}
+[data-theme=retro] body{font-size:20px}
+[data-theme=retro] .status-dot{border-radius:0}
+[data-theme=retro] .control{margin:3px;border:0;border-radius:0;background:#24338a;color:var(--ink);font:400 10px/1 var(--font-display);letter-spacing:.02em;box-shadow:inset -3px -3px 0 #151f5e,inset 3px 3px 0 #4a62d0,0 0 0 3px var(--outline)}
+[data-theme=retro] .control:hover:not(:disabled){background:#2c3ea0}
+[data-theme=retro] .control:active:not(:disabled){transform:translateY(2px)}
+[data-theme=retro] .section-label{font:400 8px/1.4 var(--font-display);letter-spacing:.06em;color:var(--ink-2)}
+[data-theme=retro] .themes{gap:12px}
+[data-theme=retro] .theme-button{margin:3px;border:0;border-radius:0;background:#111a4a;font:400 20px/1 var(--font-body);box-shadow:0 0 0 3px var(--outline),inset 0 0 0 2px #2c3c8c}
+[data-theme=retro] .theme-button[aria-pressed=true]{background:#1e2c78;color:#ffd86b;box-shadow:0 0 0 3px #ffd86b,0 0 0 6px var(--outline)}
+[data-theme=retro] .screen-head{display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"title mascot" "summary mascot";align-items:center;gap:20px 24px;margin:16px 8px 40px;padding:30px 32px 28px;background:linear-gradient(180deg,#3148c2 0 50%,#2b40b2 50%);box-shadow:inset 0 -6px 0 #2236a0,inset 0 6px 0 #4a63d6,0 -4px 0 #8cb8ff,0 4px 0 #8cb8ff,-4px 0 0 #8cb8ff,4px 0 0 #8cb8ff,-4px -4px 0 var(--outline),4px -4px 0 var(--outline),-4px 4px 0 var(--outline),4px 4px 0 var(--outline),0 -8px 0 var(--outline),0 8px 0 var(--outline),-8px 0 0 var(--outline),8px 0 0 var(--outline),0 16px 0 rgba(0,0,0,.28)}
+[data-theme=retro] .screen-head::before{content:"";position:absolute;left:18px;bottom:10px;width:4px;height:4px;background:#5d79e0;box-shadow:4px 0 #5d79e0,8px 0 #5d79e0,12px 0 #5d79e0,16px 0 #5d79e0,20px 0 #5d79e0,24px 0 #5d79e0,28px 0 #5d79e0,32px 0 #5d79e0,4px -4px #5d79e0,8px -4px #5d79e0,12px -4px #5d79e0,16px -4px #5d79e0,20px -4px #5d79e0,24px -4px #5d79e0,8px -8px #5d79e0,12px -8px #5d79e0,16px -8px #5d79e0,20px -8px #5d79e0,44px 0 #4867d6,48px 0 #4867d6,52px 0 #4867d6,56px 0 #4867d6,60px 0 #4867d6,48px -4px #4867d6,52px -4px #4867d6,56px -4px #4867d6}
+[data-theme=retro] .title-block{grid-area:title}
+[data-theme=retro] h1{font:400 40px/1.15 var(--font-display);letter-spacing:.02em;color:var(--ink);text-shadow:4px 4px 0 var(--outline),-2px 0 0 var(--outline),2px 0 0 var(--outline),0 -2px 0 var(--outline),0 2px 0 var(--outline)}
+[data-theme=retro] h1::before{content:"";display:inline-block;width:36px;height:36px;margin-right:18px;vertical-align:-2px;background:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 9' shape-rendering='crispEdges'%3E%3Cpath fill='%230a0d26' d='M3 0h3v2h3v3H8v3H6V7H3v1H1V5H0V2h3z'/%3E%3Cpath fill='%23ffd86b' d='M4 0h1v2H4zM3 2h3v1H3zM1 3h7v1H1zM2 4h5v1H2zM2 5h2v1H2zM5 5h2v1H5zM2 6h1v1H2zM6 6h1v1H6z'/%3E%3Cpath fill='%23fff5c4' d='M4 1h1v1H4zM3 3h2v1H3z'/%3E%3C/svg%3E") center/contain no-repeat;image-rendering:pixelated}
+[data-theme=retro] .intro-note{display:flex;align-items:center;gap:14px;margin:18px 0 0 54px;font:400 12px/1 var(--font-display);letter-spacing:.12em;color:#b9d2ff;text-shadow:2px 2px 0 var(--outline)}
+[data-theme=retro] .intro-note::before,[data-theme=retro] .intro-note::after{content:"";width:10px;height:10px;flex:none;background:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 5 5' shape-rendering='crispEdges'%3E%3Cpath fill='%23ffd86b' d='M2 0h1v5H2zM0 2h5v1H0z'/%3E%3C/svg%3E") center/contain no-repeat;image-rendering:pixelated}
+[data-theme=retro] .mascot{display:block;grid-area:mascot;width:176px;margin:-14px -6px -18px 0}
+[data-theme=retro] .mascot svg{display:block;width:100%;height:auto}
+[data-theme=retro] .mascot .beat{animation:beat 1.2s steps(2,jump-none) infinite}
+[data-theme=retro] .summary{grid-area:summary;justify-self:start;gap:14px;margin-left:54px}
+[data-theme=retro] .summary>div{display:flex;align-items:center;gap:10px;padding:9px 12px;background:#1c2a7c;box-shadow:0 0 0 3px var(--outline),inset 0 0 0 2px #3a52c4}
+[data-theme=retro] .summary dt{font:400 8px/1 var(--font-display);letter-spacing:.04em;color:#a9c8ff}
+[data-theme=retro] .summary dd{font:400 12px/1 var(--font-display);color:#ffd86b}
+[data-theme=retro] .provider-list{gap:34px;padding:0 8px}
+[data-theme=retro] .card-art{display:block}
+[data-theme=retro] .card-art .scene{display:block}
+[data-theme=retro] .card-art::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,rgba(10,13,38,.62),rgba(10,13,38,.3) 34%,rgba(10,13,38,0) 60%)}
+[data-theme=retro] .provider-card{grid-template-columns:120px auto minmax(0,1fr) 230px;grid-template-areas:"icon name tabs reading" "icon gauge gauge timer" "more more more more" "foot foot foot foot";column-gap:22px;row-gap:18px;padding:22px 24px 0;border:0;border-radius:0;background:var(--panel);box-shadow:inset 0 0 0 3px color-mix(in srgb,var(--accent) 30%,var(--outline)),0 -4px 0 var(--accent),0 4px 0 var(--accent),-4px 0 0 var(--accent),4px 0 0 var(--accent),-4px -4px 0 var(--outline),4px -4px 0 var(--outline),-4px 4px 0 var(--outline),4px 4px 0 var(--outline),0 -8px 0 var(--outline),0 8px 0 var(--outline),-8px 0 0 var(--outline),8px 0 0 var(--outline),0 16px 0 rgba(0,0,0,.3)}
+[data-theme=retro] .card-head{display:contents}
+[data-theme=retro] .provider-icon{grid-area:icon;width:120px;height:120px;background:var(--outline);box-shadow:inset 0 0 0 4px var(--accent),inset 0 0 0 8px var(--outline),inset 0 0 0 10px color-mix(in srgb,var(--accent) 28%,var(--outline)),6px 6px 0 rgba(0,0,0,.35)}
+[data-theme=retro] .provider-card[data-provider=grok] .provider-icon{background:#d9ccff;box-shadow:inset 0 0 0 4px var(--accent),inset 0 0 0 8px var(--outline),inset 0 0 0 10px color-mix(in srgb,var(--accent) 28%,var(--outline)),inset 0 0 0 21px var(--outline),6px 6px 0 rgba(0,0,0,.35)}
+[data-theme=retro] .provider-icon .glyph{display:none}
+[data-theme=retro] .pixel-mascot{display:block}
+[data-theme=retro] .provider-name{grid-area:name;align-self:end;gap:12px}
+[data-theme=retro] .provider-title{font:400 28px/1 var(--font-display);letter-spacing:.02em;color:var(--ink);text-shadow:3px 3px 0 var(--outline),-2px 0 0 var(--outline),2px 0 0 var(--outline),0 -2px 0 var(--outline),0 2px 0 var(--outline)}
+[data-theme=retro] .company{font:400 8px/1 var(--font-display);letter-spacing:.1em;color:var(--ink-2);text-shadow:2px 2px 0 var(--outline)}
+[data-theme=retro] .account-tabs{grid-area:tabs;align-self:end;gap:10px;margin:0 0 3px 10px}
+[data-theme=retro] .account-tab{min-width:32px;min-height:32px;padding:0 8px;border:0;border-radius:0;background:#26358e;color:var(--ink-2);font:400 10px/1 var(--font-display);box-shadow:inset -3px -3px 0 #151f5e,inset 3px 3px 0 #4a62d0,0 0 0 3px var(--outline)}
+[data-theme=retro] .account-tab:hover{color:var(--ink)}
+[data-theme=retro] .account-tab[aria-pressed=true]{background:#ffd86b;color:#2b1a05;box-shadow:inset -3px -3px 0 #cf952a,inset 3px 3px 0 #fff3b8,0 0 0 3px var(--outline)}
+[data-theme=retro] .reading{grid-area:reading;align-self:stretch;align-items:flex-start;justify-content:center;gap:10px;margin:0;padding:14px 16px;background:var(--outline);box-shadow:inset 0 0 0 3px #3a4fb0,inset 0 0 0 5px var(--outline),6px 6px 0 rgba(0,0,0,.3)}
+[data-theme=retro] .reading-meta{order:-1;justify-content:flex-start;gap:6px 10px}
+[data-theme=retro] .reading-label,[data-theme=retro] .level-label{font:400 8px/1 var(--font-display);letter-spacing:.04em;color:var(--ink-2);text-shadow:2px 2px 0 var(--outline)}
+[data-theme=retro] .unknown-message{font:400 20px/1 var(--font-body);color:var(--ink-2);text-shadow:2px 2px 0 var(--outline)}
+[data-theme=retro] .percentage{font:400 40px/1 var(--font-num);letter-spacing:0;color:var(--ink);text-shadow:4px 4px 0 var(--outline),-2px 0 0 var(--outline),2px 0 0 var(--outline),0 -2px 0 var(--outline),0 2px 0 var(--outline)}
+[data-theme=retro] .percent-sign{font-size:.6em;margin-left:4px}
+[data-theme=retro] .gauge{align-self:stretch}
+[data-theme=retro] .meter{height:40px;align-self:center;gap:5px;padding:6px;background:var(--outline);box-shadow:inset 0 0 0 3px #4459c4,0 0 0 3px var(--outline),6px 6px 0 rgba(0,0,0,.3)}
+[data-theme=retro] .meter-segment{--tm:min(100%,calc((var(--i,0) + .5) * 1000% / var(--v,100)));background:#19235f;box-shadow:inset 0 -4px 0 rgba(0,0,0,.25)}
+[data-theme=retro] .meter-fill{background:linear-gradient(180deg,rgba(255,255,255,.42) 0 4px,transparent 4px calc(100% - 6px),rgba(0,0,0,.3) calc(100% - 6px)),color-mix(in srgb,var(--gauge) var(--tm),var(--gauge-2))}
+[data-theme=retro] .unknown-meter .meter-segment{background:#141b4d;outline:2px dotted #3a4ea8;outline-offset:-2px}
+[data-theme=retro] .timer{grid-area:timer;align-self:center;justify-self:stretch;min-width:0;padding:12px 16px;border:0;background:var(--outline);box-shadow:inset 0 0 0 3px var(--accent),inset 0 0 0 5px var(--outline),6px 6px 0 rgba(0,0,0,.3);gap:8px 12px}
+[data-theme=retro] .clock-icon{display:none}
+[data-theme=retro] .clock-pixel{display:block;color:#0a0d26}
+[data-theme=retro] .clock-pixel .face{fill:var(--accent-2)}
+[data-theme=retro] .timer-label{font:400 8px/1 var(--font-display);color:var(--ink-2)}
+[data-theme=retro] .timer-value{font:400 16px/1.1 var(--font-num);letter-spacing:0;color:var(--ink)}
+[data-theme=retro] .more-windows{margin:4px 0 16px;font:400 20px/1.2 var(--font-body);color:var(--ink-2);text-shadow:2px 2px 0 var(--outline)}
+[data-theme=retro] .more-windows summary{font:400 8px/1 var(--font-display);letter-spacing:.04em}
+[data-theme=retro] .more-windows summary::before{border-radius:0;border:2px solid var(--ink-2)}
+[data-theme=retro] .window-detail .meter{height:14px;padding:2px;gap:2px;box-shadow:0 0 0 2px var(--outline)}
+[data-theme=retro] .window-name,[data-theme=retro] .window-percent{font:400 8px/1 var(--font-display)}
+[data-theme=retro] .card-foot{margin:4px -24px 0;padding:12px 24px 13px;border-top:0;background:rgba(10,13,38,.66);font:400 20px/1 var(--font-body);color:var(--ink-2)}
+[data-theme=retro] .stat-k{font:400 8px/1 var(--font-display);letter-spacing:0;color:var(--ink-3)}
+[data-theme=retro] .stat-v{color:var(--ink)}
+[data-theme=retro] .screen-foot{margin-top:34px}
+[data-theme=retro] .footer-meta,[data-theme=retro] .legend{font:400 20px/1 var(--font-body);color:var(--ink-2)}
+[data-theme=retro] .legend .section-label{font:400 8px/1 var(--font-display)}
+[data-theme=retro] .legend i{width:16px;height:8px;border-radius:0;box-shadow:0 0 0 2px var(--outline)}
+[data-theme=retro] .notice{border:0;border-radius:0;background:#3a1430;box-shadow:0 0 0 3px #ff5a5f,0 0 0 6px var(--outline);font:400 20px/1.2 var(--font-body)}
+[data-theme=retro] .clock-panel{margin:8px;border:0;border-radius:0;background:#141d52;box-shadow:0 0 0 4px #8cb8ff,0 0 0 8px var(--outline)}
+[data-theme=retro] .aside-head h2{font:400 16px/1.2 var(--font-display)}
+[data-theme=retro] .eyebrow{font:400 8px/1.4 var(--font-display);letter-spacing:.06em}
+[data-theme=retro] .clock-panel label{font:400 8px/1 var(--font-display);letter-spacing:.04em}
+[data-theme=retro] .control.primary{background:#ffd86b;color:#2b1a05;box-shadow:inset -3px -3px 0 #cf952a,inset 3px 3px 0 #fff3b8,0 0 0 3px var(--outline)}
+[data-theme=retro] .help{font:400 20px/1.4 var(--font-body)}
+[data-theme=retro] #display-state,[data-theme=retro] .quiet{font-size:20px;line-height:1.1}
+
+/* ════════════════════════════════════════════════════════════════════
+ Modern Minimal — charcoal, quiet provider tints, generous numerals,
+ hairline timer column, slim continuous bars.
+ ════════════════════════════════════════════════════════════════════ */
+[data-theme=modern] body{background:radial-gradient(1100px 620px at 78% -12%,#1a2130 0%,transparent 62%),radial-gradient(900px 520px at -12% 34%,#141a24 0%,transparent 60%),var(--bg)}
+[data-theme=modern] .screen-head{align-items:flex-start;margin-bottom:34px}
+[data-theme=modern] h1{font:600 50px/1.02 var(--font-display);letter-spacing:-.035em}
+[data-theme=modern] .summary{align-self:center;gap:0;padding:6px;border:1px solid var(--line-2);border-radius:999px;background:rgba(255,255,255,.02)}
+[data-theme=modern] .summary>div{grid-auto-flow:column;align-items:baseline;gap:8px;padding:8px 16px}
+[data-theme=modern] .summary>div+div{border-left:1px solid var(--line-2)}
+[data-theme=modern] .summary dt{order:2;font:600 12px/1 var(--font-label);letter-spacing:0;text-transform:none;color:var(--ink-2)}
+[data-theme=modern] .summary dd{font:700 15px/1 var(--font-num)}
+[data-theme=modern] .provider-card{grid-template-columns:64px auto minmax(0,1fr) auto;grid-template-areas:"icon name tabs timer" "icon reading reading timer" "gauge gauge gauge timer" "more more more more" "foot foot foot foot";column-gap:24px;padding:28px 32px 0;border-color:color-mix(in srgb,var(--accent) 24%,var(--line));background:linear-gradient(135deg,color-mix(in srgb,var(--accent) 10%,transparent),transparent 46%),linear-gradient(180deg,rgba(255,255,255,.025),transparent 60%),var(--panel);box-shadow:inset 0 1px 0 rgba(255,255,255,.04),0 26px 50px -30px rgba(0,0,0,.8)}
+[data-theme=modern] .card-head{display:contents}
+[data-theme=modern] .provider-icon{grid-area:icon;align-self:start;width:64px;height:64px;border-radius:17px;background:color-mix(in srgb,var(--accent) 13%,#0f1319);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 24%,transparent)}
+[data-theme=modern] .provider-icon .glyph{width:32px;height:32px}
+[data-theme=modern] .provider-name{grid-area:name;flex-direction:row;align-items:baseline;gap:12px;align-self:end}
+[data-theme=modern] .provider-title{font:600 13px/1 var(--font-label);letter-spacing:.34em}
+[data-theme=modern] .company{font:600 9px/1 var(--font-label);letter-spacing:.24em}
+[data-theme=modern] .account-tabs{grid-area:tabs;align-self:end;justify-self:end;gap:0;margin:0 0 -6px;padding:3px;border:1px solid var(--line-2);border-radius:11px}
+[data-theme=modern] .account-tab{min-width:30px;min-height:26px;border:0;border-radius:8px;font-size:11px}
+[data-theme=modern] .account-tab[aria-pressed=true]{background:var(--ink);color:#0b0e13}
+[data-theme=modern] .reading{grid-area:reading;flex-direction:row;align-items:center;gap:18px;margin:10px 0 18px}
+[data-theme=modern] .reading-meta{order:2;flex-direction:column;align-items:flex-start;gap:6px}
+[data-theme=modern] .percentage{font:600 76px/1 var(--font-num);letter-spacing:-.05em}
+[data-theme=modern] .gauge{align-self:start;margin-bottom:24px}
+[data-theme=modern] .meter{height:9px}
+[data-theme=modern] .meter::before{background:linear-gradient(90deg,var(--gauge-2),var(--gauge))}
+[data-theme=modern] .timer{grid-area:timer;align-self:stretch;align-content:center;grid-template-columns:auto 1fr;gap:12px 12px;min-width:210px;margin:0 0 22px 8px;padding-left:34px;border-left-color:var(--line-2)}
+[data-theme=modern] .clock-mark{grid-row:2;grid-column:1}
+[data-theme=modern] .timer-label{grid-row:1;grid-column:1/-1;letter-spacing:.3em}
+[data-theme=modern] .timer-value{grid-row:2;grid-column:2;font:500 31px/1 var(--font-num)}
+[data-theme=modern] .card-foot{margin:0 -32px;padding:14px 32px 16px;border-top-color:color-mix(in srgb,var(--line) 70%,transparent)}
+[data-theme=modern] .stat-k{display:none}
+[data-theme=modern] .stat:not(.stat-status)+.stat:not(.stat-status)::before{content:"·";margin-right:11px;color:var(--ink-3)}
+
+/* ════════════════════════════════════════════════════════════════════
+ Sakura Blossom — blush paper, plum serif display, frosted cards, a
+ blossom branch with drifting petals, petal-patterned pink-ramp bars.
+ ════════════════════════════════════════════════════════════════════ */
+[data-theme=sakura] body{background:radial-gradient(900px 620px at 88% -8%,#ffe1ea 0%,transparent 62%),radial-gradient(760px 520px at -12% 108%,#f9d3df 0%,transparent 62%),linear-gradient(180deg,#fdf4f7,#fbecf1)}
+[data-theme=sakura] .branch{display:block;position:absolute;top:64px;right:-34px;width:min(600px,52vw)}
+[data-theme=sakura] .branch svg{display:block;width:100%;height:auto;filter:drop-shadow(0 6px 10px rgba(190,90,120,.12))}
+[data-theme=sakura] .bokeh{display:block;position:absolute;left:-90px;bottom:-90px;width:460px;height:360px;filter:blur(8px);opacity:.6}
+[data-theme=sakura] .bokeh i{position:absolute;border-radius:50%;background:radial-gradient(circle,#fff 0 16%,#f7bfd0 44%,transparent 70%)}
+[data-theme=sakura] .bokeh i:nth-child(1){left:40px;bottom:40px;width:170px;height:170px}
+[data-theme=sakura] .bokeh i:nth-child(2){left:180px;bottom:120px;width:110px;height:110px;opacity:.8}
+[data-theme=sakura] .bokeh i:nth-child(3){left:120px;bottom:-10px;width:130px;height:130px;opacity:.7}
+[data-theme=sakura] .bokeh i:nth-child(4){left:290px;bottom:40px;width:80px;height:80px;opacity:.6}
+[data-theme=sakura] .petals{display:block;position:absolute;inset:0}
+[data-theme=sakura] .petals i{position:absolute;left:var(--x);top:-4vh;width:var(--size);height:calc(var(--size)*.78);animation:fall var(--fall) linear var(--delay) infinite}
+[data-theme=sakura] .petals i::before{content:"";position:absolute;inset:0;border-radius:150% 0 150% 0;background:linear-gradient(135deg,#ffe9f0,#f4a2bb);box-shadow:inset -1px -1px 2px rgba(214,90,130,.25);opacity:.85;animation:sway var(--sway) ease-in-out var(--delay) infinite alternate}
+[data-theme=sakura] .brand{font:700 13px/1 var(--font-label);letter-spacing:.3em}
+[data-theme=sakura] .brandmark{border-radius:6px}
+[data-theme=sakura] .control{border-color:var(--line-2);background:rgba(255,255,255,.82);color:var(--ink);box-shadow:0 6px 16px -10px rgba(166,74,108,.4)}
+[data-theme=sakura] .connection{padding:8px 14px;border-radius:999px;background:rgba(255,255,255,.7)}
+[data-theme=sakura] .theme-button{border-radius:18px;border-color:rgba(255,255,255,.95);background:rgba(255,255,255,.9);box-shadow:0 8px 18px -14px rgba(166,74,108,.5)}
+[data-theme=sakura] .theme-button[aria-pressed=true]{border-color:#d9819f;box-shadow:0 0 0 1px #d9819f,0 10px 22px -14px rgba(166,74,108,.6)}
+[data-theme=sakura] .section-label{color:var(--ink-2)}
+[data-theme=sakura] .screen-head{align-items:flex-end;margin:22px 0 38px}
+[data-theme=sakura] .title-block{display:flex;flex-direction:column}
+[data-theme=sakura] h1{order:1;font:600 86px/.92 var(--font-display);letter-spacing:-.015em;color:var(--ink)}
+[data-theme=sakura] .title-block .eyebrow{order:2;margin:16px 0 0 4px;font:500 13px/1 var(--font-label);letter-spacing:.64em;color:var(--ink-2)}
+[data-theme=sakura] .intro-note{order:3;margin:16px 0 0 4px;font:500 14px/1.4 var(--font-label);letter-spacing:.12em;color:var(--ink-2)}
+[data-theme=sakura] .intro-note::after{content:"";display:block;width:96px;height:2px;margin-top:20px;background:linear-gradient(90deg,#e7899f,rgba(231,137,159,0))}
+[data-theme=sakura] .summary{flex-direction:column;align-items:flex-start;gap:9px;padding:6px 0 6px 24px;border-left:1px solid var(--line-2)}
+[data-theme=sakura] .summary>div{display:flex;flex-direction:row-reverse;justify-content:flex-end;align-items:baseline;gap:9px}
+[data-theme=sakura] .summary .summary-providers{display:flex}
+[data-theme=sakura] .summary .summary-clock{display:none}
+[data-theme=sakura] :is(.percentage,.timer-value,.summary dd,.window-percent,.window-timer,.gauge-value){font-variant-numeric:lining-nums tabular-nums}
+[data-theme=sakura] .summary dt{font:600 11px/1 var(--font-label);letter-spacing:.34em;color:var(--ink-2)}
+[data-theme=sakura] .summary dd{font:600 20px/1 var(--font-num);font-variant-numeric:lining-nums tabular-nums;color:var(--ink)}
+[data-theme=sakura] .provider-list{gap:20px}
+[data-theme=sakura] .provider-card{grid-template-columns:84px minmax(0,1fr) auto auto;grid-template-areas:"icon name reading timer" "icon tabs reading timer" "gauge gauge gauge gauge" "more more more more" "foot foot foot foot";column-gap:26px;padding:26px 32px 0;border:1px solid rgba(255,255,255,.95);border-radius:26px;background:linear-gradient(180deg,rgba(255,255,255,.86),rgba(255,246,249,.7));box-shadow:inset 0 1px 0 #fff,0 22px 44px -26px rgba(166,74,108,.42),0 2px 6px rgba(166,74,108,.06);backdrop-filter:blur(8px)}
+[data-theme=sakura] .card-head{display:contents}
+[data-theme=sakura] .provider-icon{grid-area:icon;width:84px;height:84px;border-radius:24px;background:linear-gradient(150deg,#fff,#fbe3eb);box-shadow:inset 0 0 0 1px rgba(255,255,255,.95),0 10px 20px -12px rgba(166,74,108,.45)}
+[data-theme=sakura] .provider-icon .glyph{width:42px;height:42px}
+[data-theme=sakura] .provider-name{grid-area:name;align-self:end;gap:10px}
+[data-theme=sakura] .provider-title{font:600 34px/.95 var(--font-display);letter-spacing:.07em;color:var(--ink)}
+[data-theme=sakura] .company{font:600 9px/1 var(--font-label);letter-spacing:.46em;color:var(--ink-2)}
+[data-theme=sakura] .account-tabs{grid-area:tabs;align-self:start;margin:12px 0 0;gap:6px}
+[data-theme=sakura] .account-tab{border-color:var(--line-2);background:rgba(255,255,255,.7);color:var(--ink-2)}
+[data-theme=sakura] .account-tab[aria-pressed=true]{background:var(--ink);border-color:var(--ink);color:#fff}
+[data-theme=sakura] .reading{grid-area:reading;align-items:center;gap:8px;margin:0;text-align:center}
+[data-theme=sakura] .reading-meta{order:2;flex-direction:column;align-items:center;gap:6px}
+[data-theme=sakura] .reading-label{font:600 9px/1 var(--font-label);letter-spacing:.42em}
+[data-theme=sakura] .level-label{font:600 9px/1 var(--font-label);letter-spacing:.24em;color:var(--ink-3)}
+[data-theme=sakura] .unknown-message{max-width:150px}
+[data-theme=sakura] .percentage{font:600 66px/.9 var(--font-num);letter-spacing:-.01em;font-variant-numeric:lining-nums tabular-nums;color:var(--ink)}
+[data-theme=sakura] .percent-sign{font-size:.56em}
+[data-theme=sakura] .timer{grid-area:timer;gap:6px 14px;min-width:200px;padding-left:28px;border-left-color:var(--line-2)}
+[data-theme=sakura] .clock-icon{width:50px;height:50px;padding:13px;border-radius:50%;background:#fbe1ea;color:#c2557a;stroke-width:1.6}
+[data-theme=sakura] .timer-label{font:600 9px/1 var(--font-label);letter-spacing:.34em;color:var(--ink-2)}
+[data-theme=sakura] .timer-value{font:600 32px/1 var(--font-num);letter-spacing:0;color:var(--ink)}
+[data-theme=sakura] .gauge{margin:24px 0 20px}
+[data-theme=sakura] .meter{height:18px;background:#f6e4ea;box-shadow:inset 0 1px 2px rgba(150,70,100,.16)}
+[data-theme=sakura] .meter::before{background:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 36 18'%3E%3Cg fill='%23fff' opacity='.55'%3E%3Cpath d='M9 9c-1.6-.4-2.4-2.3-1.2-3.4.6-.5 1.2-.3 1.2.4.1-.7.7-.9 1.2-.4 1.2 1.1.4 3-1.2 3.4z'/%3E%3Cpath d='M9 9c.5 1.6-.9 3.2-2.4 2.6-.7-.3-.8-1-.2-1.3-.7.3-1.2-.2-1.1-.8.3-1.5 2.3-1.7 3.7-.5z'/%3E%3Cpath d='M9 9c1.4-1.2 3.4-1 3.7.5.1.6-.4 1.1-1.1.8.6.3.5 1-.2 1.3-1.5.6-2.9-1-2.4-2.6z'/%3E%3C/g%3E%3Ccircle cx='27' cy='6' r='1.4' fill='%23fff' opacity='.45'/%3E%3C/svg%3E") 0 50%/36px 18px repeat-x,linear-gradient(90deg,var(--gauge-2),var(--gauge));box-shadow:0 2px 6px -2px color-mix(in srgb,var(--gauge) 60%,transparent)}
+[data-theme=sakura] .window-detail .meter::before{background:linear-gradient(90deg,var(--gauge-2),var(--gauge))}
+[data-theme=sakura] .more-windows summary::before{border-color:var(--line-2);color:var(--ink-2)}
+[data-theme=sakura] .card-foot{margin:0 -32px;padding:14px 32px 16px;border-top-color:var(--line)}
+[data-theme=sakura] .stat-k{display:none}
+[data-theme=sakura] .stat:not(.stat-status)+.stat:not(.stat-status)::before{content:"";display:inline-block;width:9px;height:9px;margin-right:10px;vertical-align:-1px;background:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cg fill='%23eaa2b7'%3E%3Ccircle cx='5' cy='2.3' r='2'/%3E%3Ccircle cx='7.6' cy='4.2' r='2'/%3E%3Ccircle cx='6.6' cy='7.3' r='2'/%3E%3Ccircle cx='3.4' cy='7.3' r='2'/%3E%3Ccircle cx='2.4' cy='4.2' r='2'/%3E%3C/g%3E%3Ccircle cx='5' cy='5' r='1.2' fill='%23fff'/%3E%3C/svg%3E") center/contain no-repeat}
+[data-theme=sakura] .screen-foot{margin-top:34px}
+[data-theme=sakura] .footer-meta{justify-content:center;letter-spacing:.24em;text-transform:uppercase;font-size:10px;color:var(--ink-2)}
+[data-theme=sakura] .footer-meta::before,[data-theme=sakura] .footer-meta::after{content:"";flex:0 1 90px;height:1px;background:var(--line-2)}
+[data-theme=sakura] .legend{justify-content:center}
+[data-theme=sakura] .legend i{height:7px}
+[data-theme=sakura] .notice{border-style:solid;border-color:#e7a3b8;background:rgba(255,255,255,.75);color:var(--ink)}
+[data-theme=sakura] .clock-panel{border:1px solid rgba(255,255,255,.95);background:rgba(255,255,255,.82);box-shadow:0 22px 44px -26px rgba(166,74,108,.42);backdrop-filter:blur(8px)}
+[data-theme=sakura] .aside-head h2{font:600 30px/1 var(--font-display)}
+[data-theme=sakura] .device{background:linear-gradient(155deg,#ffffff,#f1e8e4 60%,#e2d6d1);box-shadow:inset 0 1px 0 #fff,inset 0 -3px 8px rgba(120,80,70,.18),0 22px 34px -20px rgba(120,60,80,.5)}
+[data-theme=sakura] .control.primary{background:var(--ink);border-color:var(--ink);color:#fff}
+
+/* ════════════════════════════════════════════════════════════════════
+ Sci-Fi HUD — navy telemetry: cut-corner glowing frames, wide technical
+ type, header with date block, skewed segment bar, four-cell stat rail.
+ ════════════════════════════════════════════════════════════════════ */
+[data-theme=hud] body{background:radial-gradient(1100px 640px at 50% -14%,#0c2338 0%,transparent 62%),var(--bg)}
+[data-theme=hud] .atmosphere{display:block;position:absolute;inset:0;background:linear-gradient(rgba(64,140,200,.075) 1px,transparent 1px) 0 0/96px 96px,linear-gradient(90deg,rgba(64,140,200,.075) 1px,transparent 1px) 0 0/96px 96px,linear-gradient(rgba(64,140,200,.03) 1px,transparent 1px) 0 0/24px 24px,linear-gradient(90deg,rgba(64,140,200,.03) 1px,transparent 1px) 0 0/24px 24px;-webkit-mask:radial-gradient(ellipse at 50% 30%,#000 40%,transparent 85%);mask:radial-gradient(ellipse at 50% 30%,#000 40%,transparent 85%)}
+[data-theme=hud] .sweep{display:block;position:absolute;left:0;right:0;top:-2px;height:2px;background:linear-gradient(90deg,transparent,rgba(47,212,255,.35),transparent);box-shadow:0 0 18px rgba(47,212,255,.4);animation:sweep 7s linear infinite}
+[data-theme=hud] .brand{font:700 15px/1 var(--font-label);letter-spacing:.26em}
+[data-theme=hud] .brandmark{border-radius:0;border-color:var(--codex);box-shadow:0 0 8px rgba(47,212,255,.5)}
+[data-theme=hud] .connection{font:500 12px/1 var(--font-label);letter-spacing:.18em;text-transform:uppercase}
+[data-theme=hud] .control{border-radius:0;font:700 12px/1 var(--font-label);letter-spacing:.16em;text-transform:uppercase;clip-path:polygon(0 0,calc(100% - 10px) 0,100% 10px,100% 100%,10px 100%,0 calc(100% - 10px));background:linear-gradient(90deg,rgba(47,212,255,.12),rgba(47,212,255,.04));border-color:#2c5f86}
+[data-theme=hud] .section-label{letter-spacing:.34em}
+[data-theme=hud] .theme-button{border-radius:0;font:700 11px/1.2 var(--font-label);letter-spacing:.12em;text-transform:uppercase;clip-path:polygon(0 0,calc(100% - 12px) 0,100% 12px,100% 100%,12px 100%,0 calc(100% - 12px));background:rgba(6,16,26,.8)}
+[data-theme=hud] .theme-button[aria-pressed=true]{border-color:var(--codex);box-shadow:inset 0 0 0 1px var(--codex),inset 0 0 22px -8px var(--codex);color:#fff}
+[data-theme=hud] .screen-head{--cut:18px;isolation:isolate;align-items:center;margin:0 0 24px;padding:24px 30px;background:linear-gradient(90deg,#2c6a98,#1d4466 45%,#2c6a98);clip-path:polygon(0 0,calc(100% - var(--cut)) 0,100% var(--cut),100% 100%,var(--cut) 100%,0 calc(100% - var(--cut)))}
+[data-theme=hud] .screen-head::before{content:"";position:absolute;inset:1px;z-index:-1;background:linear-gradient(90deg,rgba(47,212,255,.07),transparent 42%),var(--panel);clip-path:polygon(0 0,calc(100% - var(--cut) + .4px) 0,100% calc(var(--cut) - .4px),100% 100%,calc(var(--cut) - .4px) 100%,0 calc(100% - var(--cut) + .4px))}
+[data-theme=hud] .screen-head::after{content:"";position:absolute;left:46%;bottom:14px;width:110px;height:12px;background:repeating-linear-gradient(-62deg,rgba(47,212,255,.45) 0 3px,transparent 3px 9px)}
+[data-theme=hud] h1{font:700 38px/1 var(--font-display);letter-spacing:.07em;color:#fff;text-shadow:0 0 18px rgba(47,212,255,.25)}
+[data-theme=hud] .intro-note{margin-top:12px;font:500 12px/1 var(--font-label);letter-spacing:.44em;text-transform:uppercase;color:var(--ink-2)}
+[data-theme=hud] .summary{gap:0}
+[data-theme=hud] .summary>div{gap:9px;padding:2px 22px;border-left:1px solid var(--line-2)}
+[data-theme=hud] .summary .summary-clock{display:grid}
+[data-theme=hud] .summary dt{font:500 10px/1 var(--font-label);letter-spacing:.3em}
+[data-theme=hud] .summary dd{font:700 20px/1 var(--font-num);letter-spacing:.04em}
+[data-theme=hud] #local-time{display:grid;gap:6px}
+[data-theme=hud] #local-time .date-long{display:block;font-size:17px}
+[data-theme=hud] #local-time .zone{display:block;order:3;font:500 10px/1 var(--font-label);letter-spacing:.3em;color:var(--ink-3)}
+[data-theme=hud] #local-time .time{font:500 12px/1 var(--font-label);letter-spacing:.22em;color:var(--ink-2)}
+[data-theme=hud] .provider-list{gap:24px}
+[data-theme=hud] .card-shell{display:block;filter:drop-shadow(0 0 7px color-mix(in srgb,var(--accent) 42%,transparent))}
+[data-theme=hud] .provider-card{--cut:22px;grid-template-columns:200px minmax(0,1fr) auto auto;grid-template-areas:"head head pct timer" "meta gauge gauge gauge" "more more more more" "foot foot foot foot";column-gap:28px;padding:24px 30px 0;border:0;border-radius:0;background:linear-gradient(90deg,var(--accent),color-mix(in srgb,var(--accent) 40%,#1b3b58) 34%,#1b3b58 62%,color-mix(in srgb,var(--accent) 70%,#1b3b58));clip-path:polygon(0 0,calc(100% - var(--cut)) 0,100% var(--cut),100% 100%,var(--cut) 100%,0 calc(100% - var(--cut)))}
+[data-theme=hud] .provider-card::before{content:"";position:absolute;inset:1.5px;z-index:-1;background:linear-gradient(90deg,color-mix(in srgb,var(--accent) 8%,transparent),transparent 48%),var(--panel);clip-path:polygon(0 0,calc(100% - var(--cut) + .6px) 0,100% calc(var(--cut) - .6px),100% 100%,calc(var(--cut) - .6px) 100%,0 calc(100% - var(--cut) + .6px))}
+[data-theme=hud] .card-art{display:block;inset:9px}
+[data-theme=hud] .card-art::before,[data-theme=hud] .card-art::after{content:"";position:absolute;width:16px;height:16px;border:2px solid var(--accent)}
+[data-theme=hud] .card-art::before{left:0;top:0;border-right:0;border-bottom:0}
+[data-theme=hud] .card-art::after{right:0;bottom:0;border-left:0;border-top:0}
+[data-theme=hud] .card-head{gap:18px}
+[data-theme=hud] .provider-icon{width:56px;height:56px}
+[data-theme=hud] .provider-icon .glyph{width:50px;height:50px;filter:drop-shadow(0 0 8px color-mix(in srgb,var(--accent) 70%,transparent))}
+[data-theme=hud] .provider-name{gap:9px}
+[data-theme=hud] .provider-title{font:700 36px/1 var(--font-display);letter-spacing:.06em;color:#fff}
+[data-theme=hud] .company{font:500 11px/1 var(--font-label);letter-spacing:.52em;color:var(--ink-2)}
+[data-theme=hud] .account-tabs{gap:6px;margin-left:14px}
+[data-theme=hud] .account-tab{min-width:36px;border-color:color-mix(in srgb,var(--accent) 40%,#22476a);border-radius:0;font:700 12px/1 var(--font-label);clip-path:polygon(0 0,calc(100% - 7px) 0,100% 7px,100% 100%,7px 100%,0 calc(100% - 7px))}
+[data-theme=hud] .account-tab[aria-pressed=true]{background:var(--accent);border-color:var(--accent);color:#03080e}
+[data-theme=hud] .reading{display:contents}
+[data-theme=hud] .percentage{grid-area:pct;justify-self:end;font:700 80px/1 var(--font-num);letter-spacing:-.01em;color:#fff;text-shadow:0 0 22px color-mix(in srgb,var(--accent) 45%,transparent)}
+[data-theme=hud] .percent-sign{font-size:.5em;color:var(--accent);text-shadow:0 0 12px var(--accent)}
+[data-theme=hud] .reading-meta{grid-area:meta;flex-direction:column;align-items:flex-start;gap:9px;align-self:stretch;justify-content:center;margin-top:22px;padding:18px 0;border-top:1px solid var(--line)}
+[data-theme=hud] .reading-label{font:500 11px/1 var(--font-label);letter-spacing:.34em;color:var(--ink-2)}
+[data-theme=hud] .level-label{font:700 15px/1 var(--font-num);letter-spacing:.08em;color:var(--ink)}
+[data-theme=hud] .unknown-message{font:500 13px/1.3 var(--font-label);color:var(--ink)}
+[data-theme=hud] .timer{grid-area:timer;grid-template-columns:1fr;gap:10px;min-width:170px;padding-left:28px;border-left-color:var(--line-2)}
+[data-theme=hud] .clock-mark{display:none}
+[data-theme=hud] .timer-label{font:500 11px/1 var(--font-label);letter-spacing:.34em;color:var(--ink-2)}
+[data-theme=hud] .timer-value{font:700 36px/1 var(--font-num);letter-spacing:.01em;color:#fff}
+[data-theme=hud] .gauge{gap:18px;align-self:stretch;margin-top:22px;padding:18px 0;border-top:1px solid var(--line)}
+[data-theme=hud] .meter{height:34px;gap:5px;padding:5px 8px;border:1px solid var(--line-2);background:rgba(0,0,0,.28)}
+[data-theme=hud] .meter-segment{transform:skewX(-20deg);background:var(--track)}
+[data-theme=hud] .meter-fill{background:linear-gradient(180deg,rgba(255,255,255,.26),transparent 62%),var(--fill-grad);box-shadow:0 0 12px color-mix(in srgb,var(--gauge) 60%,transparent)}
+[data-theme=hud] .gauge-value{display:block;min-width:5ch;font:700 20px/1 var(--font-num);color:var(--ink)}
+[data-theme=hud] .more-windows{margin:0 0 16px;font:500 13px/1.3 var(--font-label)}
+[data-theme=hud] .more-windows summary::before{border-radius:0}
+[data-theme=hud] .window-detail .meter{height:10px;padding:2px;gap:3px}
+[data-theme=hud] .card-foot{display:grid;grid-template-columns:repeat(4,minmax(0,1fr)) minmax(0,1.5fr);gap:0;margin:0 -30px;padding:0;border-top:1px solid var(--line)}
+[data-theme=hud] .stat{display:grid;gap:8px;padding:15px 22px 17px;border-left:1px solid var(--line)}
+[data-theme=hud] .stat:first-child{border-left:0;padding-left:30px}
+[data-theme=hud] .stat-k{display:block;font:500 10px/1 var(--font-label);letter-spacing:.3em;color:var(--ink-3)}
+[data-theme=hud] .stat-v{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:700 15px/1.1 var(--font-num);letter-spacing:.04em;text-transform:uppercase;color:var(--ink)}
+[data-theme=hud] .stat-status{margin:0}
+[data-theme=hud] .stat-status .stat-v{white-space:normal}
+[data-theme=hud] .screen-foot{margin-top:26px}
+[data-theme=hud] .footer-meta{font:500 11px/1 var(--font-label);letter-spacing:.2em;text-transform:uppercase}
+[data-theme=hud] #foot-reporting{display:block;color:var(--ink)}
+[data-theme=hud] .legend{font:500 11px/1 var(--font-label);letter-spacing:.12em;text-transform:uppercase}
+[data-theme=hud] .legend i{border-radius:0;transform:skewX(-20deg)}
+[data-theme=hud] .notice{border-radius:0;border-style:solid}
+[data-theme=hud] .clock-panel{border-radius:0;border-color:#2c5f86;background:rgba(6,16,26,.92);clip-path:polygon(0 0,calc(100% - 18px) 0,100% 18px,100% 100%,18px 100%,0 calc(100% - 18px))}
+[data-theme=hud] .control.primary{border-color:var(--codex);background:var(--codex);color:#03080e}
+[data-theme=hud] .aside-head h2{font:700 22px/1 var(--font-display);letter-spacing:.08em;text-transform:uppercase}
+
+/* Clipped HUD controls cannot show an outside outline; draw focus inside. */
+[data-theme=hud] :is(.control,.account-tab,.theme-button):focus-visible{outline:0!important;box-shadow:inset 0 0 0 2px var(--focus)}
+
+/* ── Responsive ───────────────────────────────────────────────────── */
+@media (max-width:1240px){
+ .shell:has(.clock-panel:not([hidden])){max-width:1000px}
+ .shell:has(.clock-panel:not([hidden])) .workspace{grid-template-columns:minmax(0,1fr)}
+ .clock-panel{position:static;order:-1;width:min(100%,360px)}
+}
+@media (max-width:900px){
+ .shell{padding:0 24px 48px}
+ .themes{grid-template-columns:repeat(3,minmax(0,1fr))}
+ .screen-head{flex-wrap:wrap;align-items:flex-start}
+ [data-theme=hud] .provider-card{grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"head head" "pct timer" "meta meta" "gauge gauge" "more more" "foot foot"}
+ [data-theme=hud] .percentage{justify-self:start;margin-top:18px}
+ [data-theme=hud] .timer{margin-top:18px}
+ [data-theme=hud] .reading-meta{flex-direction:row;flex-wrap:wrap;align-items:baseline;justify-content:flex-start;gap:8px 18px;padding:16px 0 0;margin-top:20px}
+ [data-theme=hud] .gauge{margin-top:0;border-top:0}
+ [data-theme=hud] .card-foot{grid-template-columns:repeat(3,minmax(0,1fr))}
+ [data-theme=hud] .stat{border-top:1px solid var(--line)}
+ [data-theme=hud] .stat:nth-child(4){border-left:0;padding-left:30px}
+ [data-theme=digital] .provider-card{grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"head head" "reading timer" "gauge gauge" "more more" "foot foot"}
+ [data-theme=digital] .gauge{margin-bottom:20px}
+ [data-theme=digital] .reading{margin-bottom:16px}
+ [data-theme=retro] .provider-card{grid-template-columns:96px minmax(0,1fr) 200px;grid-template-areas:"icon name reading" "icon tabs reading" "gauge gauge timer" "more more more" "foot foot foot"}
+ [data-theme=retro] .provider-icon{width:96px;height:96px}
+ [data-theme=retro] .provider-card[data-provider=grok] .provider-icon{box-shadow:inset 0 0 0 4px var(--accent),inset 0 0 0 8px var(--outline),inset 0 0 0 10px color-mix(in srgb,var(--accent) 28%,var(--outline)),inset 0 0 0 17px var(--outline),6px 6px 0 rgba(0,0,0,.35)}
+ [data-theme=retro] .pixel-mascot{width:48px;height:48px}
+ [data-theme=retro] .account-tabs{align-self:start;margin:4px 0 0}
+ [data-theme=sakura] .provider-card{grid-template-columns:72px minmax(0,1fr) auto;grid-template-areas:"icon name reading" "icon tabs reading" "timer timer timer" "gauge gauge gauge" "more more more" "foot foot foot"}
+ [data-theme=sakura] .provider-icon{width:72px;height:72px}
+ [data-theme=sakura] .timer{justify-self:start;margin-top:18px;padding-left:0;border-left:0}
+ [data-theme=neon] .provider-card{grid-template-columns:80px minmax(0,1fr) auto;grid-template-areas:"icon name timer" "icon tabs timer" "reading reading reading" "gauge gauge gauge" "more more more" "foot foot foot"}
+ [data-theme=neon] .provider-icon{width:80px;height:80px;border-radius:20px}
+ [data-theme=neon] .provider-icon .glyph{width:42px;height:42px}
+ [data-theme=neon] .account-tabs{align-self:start;margin:10px 0 0}
+ [data-theme=neon] .reading{margin-top:22px}
+ [data-theme=modern] .provider-card{grid-template-columns:56px minmax(0,1fr) auto;grid-template-areas:"icon name timer" "icon tabs timer" "reading reading reading" "gauge gauge gauge" "more more more" "foot foot foot"}
+ [data-theme=modern] .provider-icon{width:56px;height:56px}
+ [data-theme=modern] .account-tabs{align-self:start;margin:10px 0 0}
+ [data-theme=modern] .timer{margin:0}
+ [data-theme=modern] .reading{margin-top:20px}
+}
+@media (max-width:640px){
+ .shell{padding:0 16px 40px}
+ .topbar{flex-wrap:wrap;gap:10px 14px;min-height:0;padding:16px 0 14px}
+ .connection{order:3;width:100%;margin-left:0}
+ .clock-toggle{margin-left:auto}
+ .theme-section{margin-bottom:26px}
+ .themes{gap:6px}
+ .theme-button{padding:5px 5px 8px;font-size:10.5px}
+ .swatch{height:30px;padding:0 7px;gap:3px}
+ .swatch i{height:4px}
+ .screen-head{gap:16px;margin-bottom:22px}
+ h1{font-size:36px}
+ .summary{flex:1 1 100%;flex-wrap:wrap;gap:16px}
+ .provider-list{gap:14px}
+ .provider-card,
+ [data-theme] .provider-card{grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"head head" "reading timer" "gauge gauge" "more more" "foot foot";column-gap:14px;padding:18px 16px 0}
+ [data-theme] .card-head{display:flex;flex-wrap:wrap;gap:10px 12px}
+ [data-theme] .provider-icon{width:40px;height:40px;border-radius:12px}
+ [data-theme] .provider-icon .glyph{width:26px;height:26px}
+ [data-theme] .provider-name{flex-direction:column;align-items:flex-start;gap:5px}
+ [data-theme] .provider-title{font-size:19px}
+ [data-theme] .account-tabs{margin:0 0 0 auto;align-self:center}
+ [data-theme] .account-tab{min-width:34px;min-height:34px}
+ [data-theme] .reading{display:flex;flex-direction:column;align-items:flex-start;gap:6px;margin:16px 0 14px;text-align:left}
+ [data-theme] .reading-meta{display:flex;order:2;flex-direction:column;align-items:flex-start;gap:4px}
+ [data-theme] .percentage{grid-area:auto;justify-self:auto;margin:0;font-size:50px}
+ [data-theme] .timer{grid-template-columns:auto;min-width:0;margin:0;padding-left:14px;border-left:1px solid var(--line-2);gap:6px;align-self:center}
+ [data-theme] .clock-mark{display:none}
+ [data-theme] .timer-value{font-size:22px}
+ [data-theme] .gauge{margin:0 0 16px;padding:0;border:0}
+ [data-theme] .card-foot{display:flex;gap:6px 12px;margin:0 -16px;padding:12px 16px 13px}
+ [data-theme] .stat{display:inline-flex;padding:0;border:0}
+ [data-theme] .stat-k{display:none}
+ [data-theme] .stat:not(.stat-status)+.stat:not(.stat-status)::before{content:"·";margin-right:6px;color:var(--ink-3)}
+ [data-theme] .stat-status{margin-left:auto}
+ .window-detail{grid-template-columns:62px minmax(0,1fr) 38px 70px;gap:8px}
+ .footer-meta{gap:6px 14px}
+ [data-theme=digital] .screen{padding:10px}
+ [data-theme=digital] .control{padding:8px 10px;font-size:17px;letter-spacing:.04em}
+ [data-theme=digital] .brand{font-size:21px}
+ [data-theme=digital] .screen-head{flex-direction:column;align-items:flex-start;padding:14px}
+ [data-theme=digital] h1{font-size:32px}
+ [data-theme=digital] .summary dd{gap:10px;font-size:13px}
+ [data-theme=digital] .provider-card{padding:0 14px}
+ [data-theme=digital] .card-head{padding:12px 0}
+ [data-theme=digital] .provider-name{flex-direction:column}
+ [data-theme=digital] .provider-title{font-size:38px}
+ [data-theme=digital] .company{font-size:19px}
+ [data-theme=digital] .percentage{font-size:46px}
+ [data-theme=digital] .timer{padding-left:14px}
+ [data-theme=digital] .timer-value{font-size:26px}
+ [data-theme=digital] .timer-label,[data-theme=digital] .reading-label{font-size:19px}
+ [data-theme=digital] .gauge .meter{height:40px;gap:4px;padding:4px}
+ [data-theme=digital] .meter-segment::after{left:calc(50% - 2px);width:4px}
+ [data-theme=digital] .card-foot{margin:0 -14px;padding:12px 14px;font-size:19px}
+ [data-theme=digital] .stat-status{padding-left:0;border-left:0}
+ [data-theme=digital] .footer-meta{font-size:19px}
+ [data-theme=digital] .footer-meta>span{padding:12px 14px;border-left:0;border-top:1px solid var(--line);width:100%}
+ [data-theme=digital] .footer-meta>span:first-child{border-top:0}
+ [data-theme=digital] .signal{width:auto!important;height:46px}
+ [data-theme=neon] h1{font-size:26px}
+ [data-theme=neon] .summary{flex:0 1 auto;border-radius:18px}
+ [data-theme=neon] .summary>div{padding:8px 12px;gap:7px}
+ [data-theme=neon] .summary dt{letter-spacing:.14em}
+ [data-theme=neon] .provider-card{border-radius:22px}
+ [data-theme=neon] .provider-icon{border-radius:14px}
+ [data-theme=neon] .provider-title{font-size:20px}
+ [data-theme=neon] .percentage{font-size:54px}
+ [data-theme=neon] .timer{padding:0 0 0 14px}
+ [data-theme=neon] .gauge{margin:4px 0 18px}
+ [data-theme=neon] .card-foot{margin:0 -16px;padding:12px 16px 14px}
+ [data-theme=retro] .screen-head{grid-template-columns:minmax(0,1fr);grid-template-areas:"title" "summary";margin:12px 8px 34px;padding:22px 18px}
+ [data-theme=retro] .mascot{position:absolute;right:10px;top:-34px;width:88px;margin:0}
+ [data-theme=retro] h1{font-size:22px}
+ [data-theme=retro] h1::before{width:22px;height:22px;margin-right:10px}
+ [data-theme=retro] .intro-note{margin:14px 0 0;font-size:8px}
+ [data-theme=retro] .summary{margin:0;flex-wrap:wrap}
+ [data-theme=retro] .provider-list{gap:28px}
+ [data-theme=retro] .provider-card{padding:18px 16px 0}
+ [data-theme=retro] .provider-icon{width:56px;height:56px;box-shadow:inset 0 0 0 3px var(--accent),inset 0 0 0 6px var(--outline),4px 4px 0 rgba(0,0,0,.35)}
+ [data-theme=retro] .provider-card[data-provider=grok] .provider-icon{box-shadow:inset 0 0 0 3px var(--accent),inset 0 0 0 6px var(--outline),inset 0 0 0 9px var(--outline),4px 4px 0 rgba(0,0,0,.35)}
+ [data-theme=retro] .pixel-mascot{width:32px;height:32px}
+ [data-theme=retro] .provider-title{font-size:16px}
+ [data-theme=retro] .account-tabs{gap:8px;margin-right:4px}
+ [data-theme=retro] .account-tab{min-width:30px;min-height:30px}
+ [data-theme=retro] .percentage{font-size:32px}
+ [data-theme=retro] .timer{padding:10px 12px;box-shadow:inset 0 0 0 3px var(--accent),inset 0 0 0 5px var(--outline)}
+ [data-theme=retro] .timer-value{font-size:12px}
+ [data-theme=retro] .meter{height:30px;padding:4px;gap:3px}
+ [data-theme=retro] .card-foot{margin:4px -16px 0;padding:11px 16px 12px}
+ [data-theme=modern] h1{font-size:38px}
+ [data-theme=modern] .summary{border-radius:16px}
+ [data-theme=modern] .percentage{font-size:52px}
+ [data-theme=modern] .provider-title{font-size:12px;letter-spacing:.28em}
+ [data-theme=modern] .provider-name{flex-direction:column;gap:6px}
+ [data-theme=modern] .account-tabs{margin-left:auto}
+ [data-theme=sakura] .branch{width:86vw;opacity:.55;top:-30px;right:-40px}
+ [data-theme=sakura] h1{font-size:60px}
+ [data-theme=sakura] .title-block .eyebrow{letter-spacing:.5em}
+ [data-theme=sakura] .summary{padding-left:16px}
+ [data-theme=sakura] .provider-card{border-radius:22px}
+ [data-theme=sakura] .provider-icon{width:44px;height:44px;border-radius:14px}
+ [data-theme=sakura] .provider-title{font-size:26px}
+ [data-theme=sakura] .percentage{font-size:54px}
+ [data-theme=sakura] .clock-icon{width:auto;height:auto;padding:0;background:none}
+ [data-theme=sakura] .timer-value{font-size:24px}
+ [data-theme=sakura] .gauge{margin:2px 0 16px}
+ [data-theme=sakura] .card-foot{margin:0 -16px;padding:12px 16px 14px}
+ [data-theme=hud] .screen-head{padding:20px 18px}
+ [data-theme=hud] .screen-head::after{display:none}
+ [data-theme=hud] h1{font-size:24px}
+ [data-theme=hud] .intro-note{letter-spacing:.3em}
+ [data-theme=hud] .summary>div:first-child{padding-left:0;border-left:0}
+ [data-theme=hud] .summary{row-gap:14px}
+ [data-theme=hud] .summary>div{padding:0 14px}
+ [data-theme=hud] .provider-card{--cut:16px;padding:18px 16px 0}
+ [data-theme=hud] .provider-title{font-size:22px}
+ [data-theme=hud] .company{letter-spacing:.36em}
+ [data-theme=hud] .card-art{inset:6px}
+ [data-theme=hud] .percentage{font-size:54px}
+ [data-theme=hud] .timer-value{font-size:24px}
+ [data-theme=hud] .reading-meta{display:flex;margin:0;padding:0;border:0}
+ [data-theme=hud] .meter{height:26px}
+ [data-theme=hud] .card-foot{margin:0 -16px}
+}
+@media (max-width:400px){
+ .theme-button{font-size:10px}
+ .summary{flex-wrap:wrap}
+ [data-theme] .percentage{font-size:44px}
+ [data-theme=sakura] h1{font-size:50px}
+ [data-theme=sakura] .summary{border-left:0;padding-left:0}
+ [data-theme=retro] .percentage{font-size:24px}
+ [data-theme=retro] .provider-title{font-size:14px}
+ [data-theme=hud] .summary>div{padding:0 10px}
+}
+
+/* ── Motion ───────────────────────────────────────────────────────── */
+@keyframes blink{50%{opacity:0}}
+@keyframes sweep{to{transform:translateY(calc(100vh + 240px))}}
+@keyframes twinkle{50%{opacity:.2}}
+@keyframes beat{50%{transform:translateY(-1px)}}
+@keyframes fall{from{transform:translate3d(0,0,0)}to{transform:translate3d(var(--drift),112vh,0)}}
+@keyframes sway{from{transform:rotate(var(--turn)) translateX(-7px)}to{transform:rotate(calc(var(--turn) + 80deg)) translateX(7px)}}
+@media (prefers-reduced-motion:reduce){
+ *,*::before,*::after{animation:none!important;transition:none!important}
+ [data-theme=sakura] .petals i{top:calc(var(--x) * .8)}
+}
diff --git a/token_tv/web/vt323-LICENSE.txt b/token_tv/web/vt323-LICENSE.txt
new file mode 100644
index 0000000..bcb092f
--- /dev/null
+++ b/token_tv/web/vt323-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2011, The VT323 Project Authors ([email protected])
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/token_tv/web/vt323.woff2 b/token_tv/web/vt323.woff2
new file mode 100644
index 0000000..d85c9a3
Binary files /dev/null and b/token_tv/web/vt323.woff2 differ
diff --git a/token_tv/web_assets.py b/token_tv/web_assets.py
new file mode 100644
index 0000000..48cffb0
--- /dev/null
+++ b/token_tv/web_assets.py
@@ -0,0 +1,29 @@
+"""Explicitly allowlisted web resources; never expose runtime files."""
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+WEB = ROOT / 'web'
+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/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'),
+ '/assets/jersey-10.woff2': (WEB / 'jersey-10.woff2', 'font/woff2'),
+ '/assets/orbitron.ttf': (WEB / 'orbitron.ttf', 'font/ttf'),
+ '/assets/press-start-2p.ttf': (WEB / 'press-start-2p.ttf', 'font/ttf'),
+ '/assets/oxanium.woff2': (WEB / 'oxanium.woff2', 'font/woff2'),
+ '/assets/cormorant-garamond.woff2': (WEB / 'cormorant-garamond.woff2', 'font/woff2'),
+ '/assets/chakra-petch-500.woff2': (WEB / 'chakra-petch-500.woff2', 'font/woff2'),
+ '/assets/chakra-petch-700.woff2': (WEB / 'chakra-petch-700.woff2', 'font/woff2'),
+ '/assets/claude-pixel.png': (ROOT / 'assets' / 'claude-pixel.png', 'image/png'),
+ '/assets/codex-pixel.png': (ROOT / 'assets' / 'codex-pixel.png', 'image/png'),
+ '/assets/grok-pixel.png': (ROOT / 'assets' / 'grok-pixel.png', 'image/png'),
+}
+
+
+def asset(path):
+ entry = ASSETS.get(path)
+ return (entry[0].read_bytes(), entry[1]) if entry else None
diff --git a/tokens.css b/tokens.css
new file mode 100644
index 0000000..156dbd8
--- /dev/null
+++ b/tokens.css
@@ -0,0 +1,102 @@
+/* TokenTV appearance tokens — one block per web theme.
+ * Roles: ink = neutral text and numerals for every provider; claude/codex/grok mark
+ * identity only; lvl-* are the four used-quota bands (<50, 50–79, 80–89, 90–100).
+ * Each band is a gradient: lvl-*-2 starts the fill, lvl-* is its tip and legend colour. */
+:root {
+ --font-body: 'Manrope', system-ui, sans-serif;
+ --font-display: var(--font-body);
+ --font-num: var(--font-display);
+ --font-label: var(--font-body);
+ --bg: #0c0f14; --panel: #141922; --panel-2: #1a202b;
+ --ink: #f4f6f9; --ink-2: #9ba5b3; --ink-3: #7a8493;
+ --line: #232a35; --line-2: #313a48; --track: #232a35; --focus: #cfe0ff;
+ --claude: #f4a07a; --claude-2: #f4a07a;
+ --codex: #6ea8ff; --codex-2: #6ea8ff;
+ --grok: #5ee0b5; --grok-2: #5ee0b5;
+ --lvl-low: #6ee7b7; --lvl-medium: #79c0ff; --lvl-high: #f6c453; --lvl-critical: #f7768e;
+ --lvl-low-2: #22c4a6; --lvl-medium-2: #2f8cff; --lvl-high-2: #f08a24; --lvl-critical-2: #e8455f;
+ --radius-card: 22px; --radius-control: 10px;
+ color-scheme: dark;
+}
+
+/* Digital Terminal: single-weight phosphor console, amber timers. */
+:root[data-theme=digital] {
+ --font-body: 'VT323', 'DejaVu Sans Mono', monospace;
+ --font-num: 'DSEG7 Classic', 'VT323', monospace;
+ --bg: #020906; --panel: #03100b; --panel-2: #04140e;
+ --ink: #7dffd0; --ink-2: #4dbb92; --ink-3: #3a9a77;
+ --line: #164a37; --line-2: #22694f; --track: #0a2a1e; --focus: #c8ffe9;
+ --amber: #ffcf5a;
+ --claude: #7dffd0; --codex: #7dffd0; --grok: #7dffd0;
+ --lvl-low: #3dfcb0; --lvl-medium: #c3f562; --lvl-high: #ff9d45; --lvl-critical: #ff5a6a;
+ --lvl-low-2: #13b884; --lvl-medium-2: #6fd13a; --lvl-high-2: #ff6a2b; --lvl-critical-2: #e8243f;
+ --radius-card: 0; --radius-control: 0;
+}
+
+/* Neon Cyberpunk: black glass, white-hot numerals, provider bloom. */
+:root[data-theme=neon] {
+ --font-display: 'Orbitron', 'Manrope', sans-serif;
+ --font-num: 'Oxanium', 'Orbitron', sans-serif;
+ --bg: #05040c; --panel: #0b0918; --panel-2: #120f26;
+ --ink: #f7f5ff; --ink-2: #aaa4cc; --ink-3: #8580ad;
+ --line: #262143; --line-2: #3a325f; --track: #17142c; --focus: #f0d9ff;
+ --claude: #ff8a2b; --claude-2: #ffd23f;
+ --codex: #22d3ee; --codex-2: #4f7bff;
+ --grok: #d946ef; --grok-2: #8b5cf6;
+ --lvl-low: #2cf5b0; --lvl-medium: #38d6ff; --lvl-high: #ffc23d; --lvl-critical: #ff3d81;
+ --lvl-low-2: #00b894; --lvl-medium-2: #1f7bff; --lvl-high-2: #ff8a1f; --lvl-critical-2: #ff2a4a;
+ --radius-card: 26px; --radius-control: 999px;
+}
+
+/* Pixel Retro: 8-bit night, cream type, HP-bar bands. */
+:root[data-theme=retro] {
+ --font-body: 'Jersey 10', 'DejaVu Sans Mono', monospace;
+ --font-display: 'Press Start 2P', 'Jersey 10', monospace;
+ --bg: #0a0f2c; --panel: #141d52; --panel-2: #1b2766;
+ --ink: #fff3d6; --ink-2: #a9bdf0; --ink-3: #7286c6;
+ --line: #2c3c8c; --line-2: #4a64c8; --track: #0d1440; --focus: #ffe38a;
+ --outline: #0a0d26;
+ --claude: #ff9f43; --claude-2: #ffcf6b;
+ --codex: #3ee68b; --codex-2: #9bffc8;
+ --grok: #b388ff; --grok-2: #e0d0ff;
+ --lvl-low: #5ee06a; --lvl-medium: #d3e84a; --lvl-high: #ffab3d; --lvl-critical: #ff5a5f;
+ --lvl-low-2: #2aa84a; --lvl-medium-2: #8fc93a; --lvl-high-2: #ff7a1f; --lvl-critical-2: #d62b3c;
+ --radius-card: 0; --radius-control: 0;
+}
+
+/* Modern Minimal: charcoal, quiet tints, generous numerals. */
+:root[data-theme=modern] {
+ --bg: #0b0e13; --panel: #131820; --panel-2: #192029;
+ --ink: #f4f6f9; --ink-2: #98a2b1; --ink-3: #7a8493;
+ --line: #222934; --line-2: #2f3744;
+}
+
+/* Sakura Blossom: blush paper, plum ink, one pink ramp for the bands. */
+:root[data-theme=sakura] {
+ --font-display: 'Cormorant Garamond', Georgia, serif;
+ --font-num: 'Cormorant Garamond', Georgia, serif;
+ --bg: #fbeef2; --panel: #fffafc; --panel-2: #fff;
+ --ink: #4a2433; --ink-2: #7a5262; --ink-3: #8a6574;
+ --line: #f0d6df; --line-2: #e7c2cf; --track: #f5e3e9; --focus: #a83f63;
+ --claude: #cc6440; --claude-2: #cc6440;
+ --codex: #6b4fa0; --codex-2: #6b4fa0;
+ --grok: #34283a; --grok-2: #34283a;
+ --lvl-low: #f2b8c9; --lvl-medium: #e7899f; --lvl-high: #cf5679; --lvl-critical: #a3264b;
+ --lvl-low-2: #fbdde6; --lvl-medium-2: #f5bccb; --lvl-high-2: #ea98ae; --lvl-critical-2: #d65a80;
+ --radius-card: 26px; --radius-control: 999px;
+ color-scheme: light;
+}
+
+/* Sci-Fi HUD: navy telemetry, cut corners, wide technical type. */
+:root[data-theme=hud] {
+ --font-body: 'Chakra Petch', 'Manrope', sans-serif;
+ --bg: #03080e; --panel: #06101a; --panel-2: #0a1824;
+ --ink: #e9f4ff; --ink-2: #8fadc6; --ink-3: #6c8aa5;
+ --line: #142c44; --line-2: #22476a; --track: #0c1c2b; --focus: #9fe8ff;
+ --claude: #ff8a3d; --claude-2: #ffb47a;
+ --codex: #2fd4ff; --codex-2: #8be9ff;
+ --grok: #3ef29b; --grok-2: #9dffcb;
+ --lvl-low: #35e0a0; --lvl-medium: #3cc4ff; --lvl-high: #ffb23f; --lvl-critical: #ff4d6a;
+ --lvl-low-2: #14a874; --lvl-medium-2: #1a7dff; --lvl-high-2: #ff7a1a; --lvl-critical-2: #e01e3c;
+ --radius-card: 0; --radius-control: 0;
+}