Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.
Show the real clock and a live demo up front
click6067-ship-itf5b1110b86bc
diff --git a/README.ko.md b/README.ko.mdindex db6a099..79a2bf1 100644--- a/README.ko.md+++ b/README.ko.md@@ -1,6 +1,8 @@# TokenTV-[English README](README.md)+[English README](README.md) · [▶ 라이브 데모](https://token-tv.vercel.app)++여러 AI 계정의 사용량을 240×240 책상 시계와 브라우저에서 확인합니다.계정별 인증 홈을 분리하고, 실제 조회 실패와 오래된 값을 표시합니다.diff --git a/README.md b/README.mdindex 7cadc95..8955dc7 100644--- a/README.md+++ b/README.md@@ -1,103 +1,95 @@-# TokenTV+<h1 align="center">TokenTV</h1>-**A $5 AliExpress weather clock, turned into a live usage meter for your AI subscriptions.**--Claude · Codex · Grok — several accounts per provider — no firmware flashing.+<p align="center"><b>Your AI usage limits on a $5 desk clock</b><br>+Claude · Codex · Grok — multiple accounts — no firmware flashing</p><p align="center">- <img src="docs/images/clock-faces.gif" width="360" alt="TokenTV cycling through its clock faces (sample data)">+ <a href="https://token-tv.vercel.app"><img alt="Live demo" src="https://img.shields.io/badge/%E2%96%B6%20Live%20demo-token--tv.vercel.app-22d3ee?style=for-the-badge"></a>+ <a href="#quick-start"><img alt="Quick start" src="https://img.shields.io/badge/Quick%20start-Python%203.10%2B-7dffd0?style=for-the-badge"></a>+ <a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-9aa6b6?style=for-the-badge"></a></p>-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.----## 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.-- **Five clock faces:** Digital (seven-segment), Neon, Pixel Retro, Sci-Fi HUD and the- classic Pixel. Pick one from the web page.-- **A web dashboard** with four 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%.----## 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.+<p align="center"><img src="docs/images/real-clock.jpg" alt="TokenTV on a real $5 clock: Digital, Pixel Retro and Sci-Fi HUD faces"></p>-The stock-firmware photo API (`/theme/list`, `/photo/list`, `/photo/upload`) is verified-on the author's clock. Clones with other firmware are untested.+<p align="center"><a href="https://token-tv.vercel.app"><img src="docs/images/web-demo.png" alt="Web dashboard in four themes. Click to open the live demo"></a></p>-## 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.+<p align="center"><img src="docs/images/how-it-works.png" alt="Your CLI logins → TokenTV on your computer → a picture over Wi-Fi → the $5 clock"></p>## Quick start```bashgit clone https://github.com/click6067-ship-it/token-tv && cd token-tvpython3 -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+mkdir -p .runtime && cp config.example.json .runtime/config.json # your accounts + "device_url" of the clock+.venv/bin/python -m token_tv.live --config .runtime/config.json # dashboard: http://127.0.0.1:8787```-Open `http://127.0.0.1:8787/`. Under **Clock display**, choose a face and press-**Apply to clock**.+<details>+<summary><b>All five clock faces</b></summary>-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.+<br>-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+Pick one under **Clock display** in the dashboard, then press **Apply to clock**.+</details>-Early and built for one desk:+<details>+<summary><b>Hardware</b></summary>-- 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`.+- A GeekMagic **SmallTV**-style 240×240 Wi-Fi clock whose stock firmware has a photo album page.+ The author's cost ₩6,000 (about $5) on an AliExpress sale; prices vary.+- Any always-on machine on the same network with Python 3.10+ and the official CLIs you use.-Issues and pull requests are welcome, especially new providers, clock models and faces.+The stock photo API (`/theme/list`, `/photo/list`, `/photo/upload`) is verified on the author's+clock. Clones with other firmware are untested.+</details>-## Development+<details>+<summary><b>How usage is read</b></summary>++| Provider | Source | The number means |+|---|---|---|+| Claude | Claude Code CLI's own OAuth login (profile and usage) | Share of the 5-hour and weekly limits **used** |+| Codex | Official `codex app-server` account and rate-limit RPC | Share of each reported window **used** |+| Grok | Grok CLI billing RPC (experimental) | Share of the CLI **billing budget**, not web chat limits |++Every login is checked against the email you configured. The clock gets only a picture,+never a password, token or cookie. Polling runs every five minutes; old readings say OLD and+missing data shows a dash, never a fake 0%. Claude accounts with `refresh_with_cli: true` may+refresh an expired login through the CLI, which sends one tiny prompt.+</details>++<details>+<summary><b>Accounts, clock and restore</b></summary>++- `python3 -m token_tv.connect --config .runtime/config.json` logs each account in with its+ official CLI and keeps every account in its own CLI home.+- The config holds aliases, emails and CLI home paths only. Never put passwords, API keys or+ tokens in it.+- Add `"device_url": "http://<clock-ip>"` to drive the clock.+- To give the clock back its original photo and theme, stop TokenTV and run+ `python3 -m token_tv.live --config .runtime/config.json --restore-display`.+</details>++<details>+<summary><b>Status and contributing</b></summary>++Early and built for one desk: setup is a JSON file plus CLI logins, it is tested on Linux with+one clock, and it supports Claude, Codex and Grok. A new provider is one payload function in+`token_tv/sources.py`. Issues and pull requests for providers, clock models and faces are welcome.+</details>++<details>+<summary><b>Development</b></summary>```bashpython3 -B -m unittest discover -s tests -v+python3 scripts/build_demo.py --out site # the static live demo````scripts/test_web_browser.cjs` runs the browser checks with a local Playwright Chromium.--## License+</details>MIT, see [LICENSE](LICENSE). Bundled fonts keep their SIL Open Font License notices in-`token_tv/web/`.--[한국어 README](README.ko.md)+`token_tv/web/`. · [한국어](README.ko.md)diff --git a/docs/images/clock-faces.gif b/docs/images/clock-faces.gifdeleted file mode 100644index d74ffe4..0000000Binary files a/docs/images/clock-faces.gif and /dev/null differdiff --git a/docs/images/how-it-works.png b/docs/images/how-it-works.pngnew file mode 100644index 0000000..d8f2826Binary files /dev/null and b/docs/images/how-it-works.png differdiff --git a/docs/images/real-clock.jpg b/docs/images/real-clock.jpgnew file mode 100644index 0000000..b017da8Binary files /dev/null and b/docs/images/real-clock.jpg differdiff --git a/docs/images/social-preview.png b/docs/images/social-preview.pngnew file mode 100644index 0000000..5a86f85Binary files /dev/null and b/docs/images/social-preview.png differdiff --git a/docs/images/web-demo.png b/docs/images/web-demo.pngnew file mode 100644index 0000000..60636c3Binary files /dev/null and b/docs/images/web-demo.png differdiff --git a/docs/images/web-neon.png b/docs/images/web-neon.pngdeleted file mode 100644index 11ec9f1..0000000Binary files a/docs/images/web-neon.png and /dev/null differdiff --git a/docs/images/web-themes.png b/docs/images/web-themes.pngdeleted file mode 100644index 66babb8..0000000Binary files a/docs/images/web-themes.png and /dev/null differdiff --git a/scripts/build_demo.py b/scripts/build_demo.pynew file mode 100644index 0000000..ec3ab43--- /dev/null+++ b/scripts/build_demo.py@@ -0,0 +1,91 @@+"""Build the static TokenTV web demo: sample accounts and pre-rendered clock faces.++The output is plain files for any static host (the live demo runs on Vercel):+ python3 scripts/build_demo.py --out site --site-url https://example.com+"""+import argparse+import json+import shutil+import sys+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+from token_tv.display import STYLES, render_page # noqa: E402+from token_tv.web_assets import ASSETS, WEB # noqa: E402++REPO = 'https://github.com/click6067-ship-it/token-tv'+H, D = 3600, 86400+# key, alias, provider, [(window, used %, seconds until reset)]+SAMPLE = [+ ('claude_a', 'CLAUDE A', 'claude', [('WEEK', 86, 3 * D), ('5H', 41, 2 * H)]),+ ('claude_b', 'CLAUDE B', 'claude', [('5H', 52, 3 * H + 41 * 60), ('WEEK', 30, 5 * D)]),+ ('claude_c', 'CLAUDE C', 'claude', [('5H', 97, 38 * 60), ('WEEK', 64, 4 * D)]),+ ('codex_a', 'CODEX A', 'codex', [('5H', 34, 2 * H + 12 * 60)]),+ ('codex_b', 'CODEX B', 'codex', [('WEEK', 91, D + 4 * H)]),+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 61, 6 * D + 2 * H)]),+ ('grok_b', 'GROK B', 'grok', [('BUDGET', 18, 12 * D + 3 * H)]),+]+META = '''<meta name="description" content="Your AI usage limits on a $5 desk clock. Claude, Codex and Grok, several accounts, no firmware flashing.">+<meta property="og:title" content="TokenTV · Live demo">+<meta property="og:description" content="Your AI usage limits on a $5 desk clock. Claude · Codex · Grok · multiple accounts · no flashing.">+<meta property="og:image" content="{site}/og.png">+<meta property="og:url" content="{site}/">+<meta name="twitter:card" content="summary_large_image">'''+BAR = f'<div class="demo-bar">Live demo with sample data<a href="{REPO}">Get TokenTV on GitHub ★</a></div>'+++def snapshot(now=None):+ accounts = {}+ for key, alias, provider, windows in SAMPLE:+ row = {'key': key, 'alias': alias, 'provider': provider, 'status': 'ok', 'identity_verified': True,+ 'windows': [{'label': label, 'used_percent': used, 'resets_in': reset} for label, used, reset in windows]}+ if now is not None:+ row['fetched_at'] = row['last_success_at'] = now+ for window in row['windows']:+ window['resets_at'] = now + window['resets_in']+ accounts[key] = row+ return {'schema': 1, 'updated_at': now or 0, 'accounts': accounts}+++def build(out, site):+ out.mkdir(parents=True, exist_ok=True)+ for child in out.iterdir(): # keep the host's project link (.vercel)+ if child.name != '.vercel':+ shutil.rmtree(child) if child.is_dir() else child.unlink()+ html = (WEB / 'index.html').read_text()+ html = html.replace('<html lang="en" data-theme="digital">', '<html lang="en" data-theme="digital" data-demo>', 1)+ html = html.replace('<title>TokenTV · AI usage</title>', '<title>TokenTV · Live demo</title>\n' + META.format(site=site.rstrip('/')), 1)+ html = html.replace('<a class="skip" href="#providers">Skip to usage</a>', '<a class="skip" href="#providers">Skip to usage</a>\n' + BAR, 1)+ assert 'data-demo' in html and 'demo-bar' in html and 'og:image' in html, 'index.html markers changed'+ (out / 'index.html').write_text(html)+ assets = out / 'assets'+ assets.mkdir()+ for path, (file, _) in ASSETS.items():+ shutil.copy2(file, assets / path.rsplit('/', 1)[1])+ for notice in WEB.glob('*-LICENSE.txt'):+ shutil.copy2(notice, assets / notice.name)+ (out / 'demo-snapshot.json').write_text(json.dumps(snapshot(), separators=(',', ':')))+ display = {'style': 'digital', 'applied_style': 'digital', 'status': 'preview_only', 'styles': list(STYLES)}+ (out / 'demo-display.json').write_text(json.dumps(display))+ frames = out / 'frames'+ frames.mkdir()+ rendered = snapshot(time.time())+ for style in STYLES:+ (frames / f'{style}.jpg').write_bytes(render_page(rendered, style=style))+ shutil.copy2(ROOT / 'docs' / 'images' / 'social-preview.png', out / 'og.png')+ return sorted(str(p.relative_to(out)) for p in out.rglob('*') if p.is_file() and '.vercel' not in p.parts)+++def main():+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument('--out', default='site')+ parser.add_argument('--site-url', default='https://token-tv.vercel.app', help='absolute URL for link previews')+ args = parser.parse_args()+ files = build(Path(args.out), args.site_url)+ print(f'{len(files)} files in {args.out}')+++if __name__ == '__main__':+ main()diff --git a/token_tv/web/app.js b/token_tv/web/app.jsindex fb74e88..ed2ea3a 100644--- a/token_tv/web/app.js+++ b/token_tv/web/app.js@@ -15,6 +15,8 @@ const readPreference = (k, f) => {try {return JSON.parse(localStorage.getItem(k)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 = {};+// The static demo (scripts/build_demo.py) serves sample data and pre-rendered clock frames.+const DEMO = document.documentElement.hasAttribute('data-demo');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}@@ -196,14 +198,20 @@ function renderAccounts() {$('#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})}}+/* Demo data stores resets as seconds from now so the timers stay plausible on any day. */+function demoSnapshot(data) {+ const now = Date.now() / 1000;+ for (const a of Object.values(data.accounts)) {a.fetched_at = a.last_success_at = now; for (const w of a.windows) w.resets_at = now + w.resets_in}+ return {...data, updated_at: now};+}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();+ const r = await fetch(DEMO ? '/demo-snapshot.json' : '/snapshot', {cache:'no-store'}); if (!r.ok) throw Error();+ const data = DEMO ? demoSnapshot(await r.json()) : await r.json(); if (!data.accounts || !Number.isFinite(data.updated_at)) throw Error();snapshot = data; offline = false;const staleCount = Object.values(data.accounts).filter(a => a.status === 'stale').length;- $('#connection').textContent = staleCount ? `${staleCount} stale · Live server` : 'Live from Mini';+ $('#connection').textContent = DEMO ? 'Demo · sample data' : 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';@@ -227,14 +235,14 @@ $('#clock-toggle').onclick = () => showClock($('#clock-panel').hidden); $('#closlet 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);+ $('#clock-style').disabled = applying || !displayInfo; $('#apply').disabled = DEMO || 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'}+ $('#display-state').textContent = DEMO ? 'Demo · install TokenTV to drive a real clock' : 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 = DEMO ? `/frames/${encodeURIComponent(style)}.jpg` : '/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}}+async function refreshDisplay(forceImage = false) {if (displayPolling) return; displayPolling = true; try {const r = await fetch(DEMO ? '/demo-display.json' : '/display', {cache:'no-store'}); if (!r.ok) throw Error(); const data = await r.json(); const dirty = displayInfo && clockChoice !== displayInfo.style; displayInfo = data; if (!clockChoice || !dirty) clockChoice = data.style; const select = $('#clock-style'); if (!select.options.length) for (const s of data.styles) {const o = el('option', styleName(s)); o.value = s; select.append(o)} select.value = clockChoice; paintClock(forceImage)} catch {$('#display-state').textContent = 'Clock status unavailable'} finally {displayPolling = false}}$('#clock-style').onchange = e => {clockChoice = e.target.value; clockError = false; paintClock(true)};$('#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.'};diff --git a/token_tv/web/style.css b/token_tv/web/style.cssindex d5f6393..dac3cb6 100644--- a/token_tv/web/style.css+++ b/token_tv/web/style.css@@ -690,3 +690,10 @@ h1{margin:0;font:600 48px/1.04 var(--font-display);letter-spacing:-.03em;color:v@media (prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}++/* Static demo bar (scripts/build_demo.py only). */+.demo-bar{position:relative;z-index:2;display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:8px 14px;padding:9px 16px;border-bottom:1px solid var(--line);background:color-mix(in srgb,var(--panel) 90%,transparent);font:600 12px/1.3 var(--font-label);color:var(--ink-2)}+.demo-bar a{padding:6px 12px;border:1px solid var(--line-2);border-radius:var(--radius-control);color:var(--ink);text-decoration:none;white-space:nowrap}+.demo-bar a:hover{border-color:var(--ink-3)}+[data-theme=digital] .demo-bar{font-size:19px;font-weight:400;letter-spacing:.06em;text-transform:uppercase}+[data-theme=retro] .demo-bar{font-size:19px;font-weight:400}