Skip to content

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

Release 0.3.1: one command to start, and it keeps running

click6067-ship-ite55ce95de498
diff --git a/AGENTS.md b/AGENTS.md
index 5f373cd..1370fbf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -16,12 +16,14 @@ When the user says "Set up TokenTV for me":
1. Install: `python3 -m venv .venv && .venv/bin/pip install -e .` (Windows: `.venv\Scripts\pip install -e .`),
or with Node only: `npx token-tv demo`.
-2. Ask the user for the clock's IP address (shown on the clock's screen).
-3. Run `.venv/bin/token-tv start --device-url <ip>`. It finds the Claude, Codex and Grok CLIs that are already
- signed in, reads each account's email through the official login, asks the user to confirm, saves the
- config and opens the dashboard at http://127.0.0.1:8787. The user then presses Clock display → Apply.
+2. Run `.venv/bin/token-tv start` in a terminal the user can answer. It finds the Claude, Codex and Grok CLIs
+ that are already signed in, reads each account's email through the official login and asks the user to
+ confirm, looks for the clock on the Wi-Fi (or asks for the IP shown on the clock's screen; pass
+ `--device-url <ip>` if you know it), asks once whether to start with the computer, saves the config and
+ opens the dashboard at http://127.0.0.1:8787.
+3. `--only codex` limits it to the tools the user names; `--face pixel` picks another face (default arcade).
4. If it says nothing is signed in, tell the user to sign in to the CLI they use (e.g. `claude`, then /login)
- and run step 3 again. A second account of the same service: `.venv/bin/token-tv connect --account <key>`.
+ and run step 2 again. A second account of the same service: `.venv/bin/token-tv connect --account <key>`.
Verified on Linux with one SD_PRO clock. Mac and Windows hosts are untested; report what fails.
diff --git a/README.ko.md b/README.ko.md
index 09f0730..a1f75d4 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -8,12 +8,12 @@
<p align="center"><img src="docs/images/real-clock.jpg" alt="작은 책상 시계에 띄운 TokenTV"></p>
<p align="center"><img src="docs/images/arcade.gif" width="320" alt="움직이는 Arcade 화면(샘플 데이터): Clawd, Codex 구름, Grok, Copilot, Anti가 일하는 모습, 그림이 곧 게이지"></p>
-<p align="center"><img src="docs/images/clock-faces.png" alt="시계 화면 6종(샘플 데이터)"></p>
+<p align="center"><img src="docs/images/clock-faces.png" alt="시계 화면 몇 가지(샘플 데이터)"></p>
약 5달러 Wi-Fi 책상 시계에 Claude·Codex 사용 한도(그리고 Grok, CodexBar를 거쳐 Copilot·Antigravity)를 띄웁니다. 펌웨어는 그대로예요.
**새 화면 Arcade:** 캐릭터마다 그림이 곧 게이지인 움직이는 화면입니다. 드문 장면 몇 개는 그 순간이 실제로 찾아올 때만 열립니다.
**구경하기:** [라이브 데모](https://token-tv.vercel.app), `npx token-tv demo` 또는 `uvx token-tv demo`, 시계·로그인 없이 바로.
-**설치하기:** 이 저장소를 AI에게 주고 *"TokenTV 설정해줘"* 라고 하세요. AI는 [AGENTS.md](AGENTS.md)를 따릅니다.
+**설치하기:** Claude·Codex·Grok을 쓰는 컴퓨터에서 `npx token-tv start`(또는 `uvx token-tv start`) 한 줄이면 됩니다. 로그인된 도구와 같은 와이파이의 시계를 스스로 찾고, 컴퓨터를 다시 켜도 계속 돌며, 대시보드를 엽니다. [라이브 데모](https://token-tv.vercel.app)에서 화면과 도구를 고르면 명령을 만들어 줍니다. AI에게 이 저장소를 주고 *"TokenTV 설정해줘"* 라고 해도 됩니다([AGENTS.md](AGENTS.md)).
**내 화면 만들기:** 시계 없이 [Game Boy 예제](examples/gameboy)에서 시작해 AI에게 바꿔 달라고 하세요. [가이드](docs/clock-faces.md) · [공유하기](https://github.com/click6067-ship-it/token-tv/issues/new?template=share_a_face.md)
자세히: [설정](docs/setup.ko.md) · [호환 시계](docs/hardware-compatibility.md) · [CodexBar 연동](docs/codexbar.md) · [애플워치](docs/apple-watch.md) · [English](README.md)
**새 소식:** 새 화면과 지원 시계는 [릴리스](https://github.com/click6067-ship-it/token-tv/releases)로 나옵니다. 받아 보려면 Watch → Custom → Releases.
diff --git a/README.md b/README.md
index 1db9206..6a4b70a 100644
--- a/README.md
+++ b/README.md
@@ -8,12 +8,12 @@
<p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/real-clock.jpg" alt="TokenTV on a real tiny desk clock"></p>
<p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/arcade.gif" width="320" alt="The animated Arcade face (sample data): Clawd, the Codex cloud, Grok, Copilot and Anti at work, each picture also a gauge"></p>
-<p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/clock-faces.png" alt="Six clock faces (sample data)"></p>
+<p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/clock-faces.png" alt="Some of the clock faces (sample data)"></p>
Your Claude and Codex usage limits (plus Grok, and Copilot or Antigravity through CodexBar) on a ~$5 Wi-Fi desk clock. No firmware flashing.
**New: Arcade**, an animated face where each character's picture is also its gauge, with a few rare scenes that open only when their moment comes on your clock.
**Try it:** [live demo](https://token-tv.vercel.app), `npx token-tv demo` or `uvx token-tv demo`, no clock or login needed.
-**Set it up:** give this repo to your AI and say *"Set up TokenTV for me."* It follows [AGENTS.md](https://github.com/click6067-ship-it/token-tv/blob/main/AGENTS.md).
+**Set it up:** run `npx token-tv start` (or `uvx token-tv start`) on the computer where you use Claude, Codex or Grok. It finds your signed-in tools and the clock on your Wi-Fi, keeps running when the computer restarts, and opens your dashboard. Pick a face and tools on the [live demo](https://token-tv.vercel.app) and it writes the command for you. Or give this repo to your AI and say *"Set up TokenTV for me."* ([AGENTS.md](https://github.com/click6067-ship-it/token-tv/blob/main/AGENTS.md))
**Make your own face:** no clock needed, start from the [Game Boy example](https://github.com/click6067-ship-it/token-tv/tree/main/examples/gameboy) and ask your AI to change it. [Guide](https://github.com/click6067-ship-it/token-tv/blob/main/docs/clock-faces.md) · [Share it](https://github.com/click6067-ship-it/token-tv/issues/new?template=share_a_face.md)
Details: [how it works](https://github.com/click6067-ship-it/token-tv/blob/main/docs/stock-photo-display.md) · [setup](https://github.com/click6067-ship-it/token-tv/blob/main/docs/setup.md) · [compatible clocks](https://github.com/click6067-ship-it/token-tv/blob/main/docs/hardware-compatibility.md) · [CodexBar input](https://github.com/click6067-ship-it/token-tv/blob/main/docs/codexbar.md) · [Apple Watch](https://github.com/click6067-ship-it/token-tv/blob/main/docs/apple-watch.md) · [한국어](https://github.com/click6067-ship-it/token-tv/blob/main/README.ko.md)
**Updates:** new faces and supported clocks ship as [releases](https://github.com/click6067-ship-it/token-tv/releases). To get them, use Watch → Custom → Releases.
diff --git a/docs/setup.ko.md b/docs/setup.ko.md
index e99a24e..58a63bf 100644
--- a/docs/setup.ko.md
+++ b/docs/setup.ko.md
@@ -18,7 +18,20 @@ Grok은 CLI 예산 정보를 보여주는 실험적 기능입니다. 제작자
Python 3.10+와 사용할 공급자의 공식 CLI(`claude`, `codex`, `grok`)가 필요합니다.
```bash
-pipx install token-tv
+npx token-tv start # 또는 uvx token-tv start · 또는 pipx install token-tv && token-tv start
+```
+
+`start`는 로그인된 Claude·Codex·Grok CLI를 찾아 이메일을 확인받고, 같은 와이파이에서 시계를 찾고(못 찾으면
+시계가 켜질 때 화면에 나오는 주소를 묻습니다), 컴퓨터를 켤 때 자동으로 돌지 한 번 물은 뒤 대시보드
+http://127.0.0.1:8787 을 엽니다. 고를 수 있는 것: `--face pixel`(기본 `arcade`), `--only codex`(또는
+`claude,codex`), `--device-url 192.168.0.50`. [라이브 데모](https://token-tv.vercel.app)가 이 줄을 만들어 줍니다.
+`npx token-tv autostart off`(시작할 때와 같은 방식: `uvx token-tv ...`, `token-tv ...`)로 백그라운드 실행을 멈추고,
+`autostart on`으로 다시 켭니다. Windows에서는 off가 다음 부팅부터 적용되고, 지금 도는 것은 로그아웃할 때 멈춥니다. 공유기가 시계 주소를 바꿔도
+TokenTV가 다시 찾습니다.
+
+계정을 더 넣거나 직접 다루려면:
+
+```bash
token-tv demo # 로그인 없이 샘플 데이터로 모든 시계 화면을 렌더
token-tv setup # 공급자당 최대 3계정 이메일과 시계 IP만 묻고, 기존 설정은 덮어쓰지 않음
token-tv doctor --live # 지금 각 공급자에 조회해 빠진 CLI·로그인과 해결 명령을 안내
diff --git a/docs/setup.md b/docs/setup.md
index 6ddf637..893be5f 100644
--- a/docs/setup.md
+++ b/docs/setup.md
@@ -7,15 +7,29 @@ Everything that used to be in the README. Written for people and for AI coding a
Needs Python 3.10+ and the official CLI (`claude`, `codex` or `grok`) for each provider you use.
```bash
-pipx install token-tv # or: pip install --user token-tv
-token-tv demo # every clock face with sample data, no login
-token-tv setup # asks for emails (up to 3 per provider) and the clock IP
-token-tv doctor --live # asks each provider now; says what is missing and the fix
-token-tv run # dashboard at http://127.0.0.1:8787, drives the clock
+npx token-tv start # or: uvx token-tv start · or: pipx install token-tv && token-tv start
```
-`uvx token-tv demo` (uv) or `npx token-tv demo` (Node) runs it without installing. From a clone,
-`pip install .` gives the same `token-tv` command.
+`start` finds the Claude, Codex and Grok CLIs that are signed in and asks you to confirm each email, looks for
+the clock on your Wi-Fi (or asks for its address, shown on the clock's screen when it starts), asks once whether
+TokenTV should start with the computer and keep running, then opens the dashboard at http://127.0.0.1:8787.
+Choices on the command line: `--face pixel` (default `arcade`), `--only codex` (or `claude,codex`),
+`--device-url 192.168.0.50`. The [live demo](https://token-tv.vercel.app) writes this line for you.
+`npx token-tv autostart off` stops the background copy (`uvx token-tv ...` or `token-tv ...`, the way you
+started it); `autostart on` sets it up again. On Windows, off stops it from starting with the computer, and the copy
+running now stops when you sign out.
+If the router later gives the clock a new address, TokenTV finds it again on its own.
+
+More accounts or more control:
+
+```bash
+token-tv demo # every clock face with sample data, no login
+token-tv setup # asks for emails (up to 3 per provider) and the clock IP
+token-tv doctor --live # asks each provider now; says what is missing and the fix
+token-tv run # dashboard at http://127.0.0.1:8787, drives the clock
+```
+
+From a clone, `pip install .` gives the same `token-tv` command.
<p align="center"><img src="images/usage-examples.png" alt="Digital face at low, busy and near-limit usage (sample data)"></p>
diff --git a/package.json b/package.json
index bb0f1d5..0705518 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "token-tv",
- "version": "0.3.0",
+ "version": "0.3.1",
"description": "Your Claude, Codex, Grok, Copilot and Antigravity usage limits on a tiny Wi-Fi desk clock (launcher for the Python package)",
"license": "MIT",
"repository": {
diff --git a/pyproject.toml b/pyproject.toml
index c403463..1fe3ca4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "token-tv"
-version = "0.3.0"
+version = "0.3.1"
description = "Your AI usage limits on a $5 desk clock: Claude, Codex, Grok, Copilot and Antigravity on a 240x240 Wi-Fi clock"
readme = "README.md"
license = "MIT"
diff --git a/scripts/build_demo.py b/scripts/build_demo.py
index 8416956..03815d5 100644
--- a/scripts/build_demo.py
+++ b/scripts/build_demo.py
@@ -54,7 +54,7 @@ def build(out, site):
name = f"{style}.{'gif' if image[:4] == b'GIF8' else 'jpg'}" # Space is animated
(frames / name).write_bytes(image)
paths[style] = f'/frames/{name}'
- display = {'style': 'digital', 'applied_style': 'digital', 'status': 'preview_only', 'styles': list(STYLES), 'frames': paths}
+ display = {'style': 'arcade', 'applied_style': 'arcade', 'status': 'preview_only', 'styles': list(STYLES), 'frames': paths}
(out / 'demo-display.json').write_text(json.dumps(display))
(out / 'demo-themes.json').write_text(json.dumps(theme_payload()))
shutil.copy2(ROOT / 'docs' / 'images' / 'social-preview.png', out / 'og.png')
diff --git a/tests/test_autostart.py b/tests/test_autostart.py
new file mode 100644
index 0000000..5a9d3ae
--- /dev/null
+++ b/tests/test_autostart.py
@@ -0,0 +1,143 @@
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from token_tv import autostart
+
+
+class AutostartTests(unittest.TestCase):
+ """TokenTV keeps running after the terminal closes, and comes back with the computer."""
+ def setUp(self):
+ self.folder = Path(tempfile.mkdtemp())
+
+ def placed(self, kind):
+ names = {'systemd': 'token-tv.service', 'launchd': 'tokentv.plist', 'startup': 'TokenTV.vbs'}
+ return mock.patch.object(autostart, 'place', return_value=(self.folder / names[kind], kind))
+
+ def test_each_system_gets_an_entry_that_runs_start_for_this_config(self):
+ argv = ['/home/me/.local/pipx/venvs/token-tv/bin/python', '-m', 'token_tv', 'start', '--yes', '--no-browser',
+ '--config', '/home/me/.config/token-tv/config.json']
+ unit = autostart.entry(argv, 'systemd')
+ self.assertIn('ExecStart=/home/me/.local/pipx/venvs/token-tv/bin/python -m token_tv start --yes', unit)
+ self.assertIn('WantedBy=default.target', unit)
+ plist = autostart.entry(argv, 'launchd')
+ self.assertIn('<string>--no-browser</string>', plist)
+ self.assertIn('<key>RunAtLoad</key><true/>', plist)
+ vbs = autostart.entry(['C:\\Py\\pythonw.exe', '-m', 'token_tv', 'start', '--config', 'C:\\Users\\me\\config.json'],
+ 'startup', path='C:\\Program Files\\nodejs;C:\\Windows')
+ self.assertIn('shell.Run """C:\\Py\\pythonw.exe"" ""-m""', vbs)
+ self.assertIn(', 0, True', vbs) # hidden, and waits for it to end before starting it again
+ self.assertIn('Do While files.FileExists(WScript.ScriptFullName)', vbs)
+ self.assertIn('shell.Environment("Process")("PATH") = "C:\\Program Files\\nodejs;C:\\Windows"', vbs)
+ self.assertIn("' config: C:\\Users\\me\\config.json", vbs)
+ for text in (unit, plist, vbs):
+ self.assertIn(autostart.MARK, text)
+
+ def test_the_entry_keeps_this_terminals_path_and_restarts(self):
+ argv = ['/opt/py/bin/python', '-m', 'token_tv', 'start']
+ unit = autostart.entry(argv, 'systemd', path='/home/me/.nvm/versions/node/v24/bin:/mnt/c/Program Files/x:/usr/bin')
+ self.assertIn('Environment="PATH=/home/me/.nvm/versions/node/v24/bin:/mnt/c/Program Files/x:/usr/bin"', unit)
+ self.assertIn('Restart=always', unit) # waits out a copy running in a terminal, then takes over
+ self.assertIn('Environment="PATH=50%%"', autostart.entry(argv, 'systemd', path='50%'))
+ plist = autostart.entry(argv, 'launchd', path='/opt/homebrew/bin:/usr/bin')
+ self.assertIn('<key>PATH</key><string>/opt/homebrew/bin:/usr/bin</string>', plist)
+ self.assertIn('<key>KeepAlive</key><true/>', plist)
+
+ def test_a_missing_systemctl_leaves_nothing_behind(self):
+ with self.placed('systemd'), mock.patch('subprocess.run', side_effect=FileNotFoundError('systemctl')):
+ with self.assertRaises(OSError):
+ autostart.install(self.folder / 'config.json')
+ self.assertFalse((self.folder / 'token-tv.service').exists())
+ with self.placed('systemd'):
+ self.assertEqual(autostart.status(), 'off')
+
+ def test_a_failed_reinstall_puts_the_working_entry_back(self):
+ working = autostart.entry(['/old/python', '-m', 'token_tv', 'start'], 'systemd')
+ (self.folder / 'token-tv.service').write_text(working)
+ failed = mock.Mock(returncode=1, stdout='', stderr='no bus')
+ with self.placed('systemd'), mock.patch.object(autostart, 'run', return_value=failed):
+ with self.assertRaises(OSError):
+ autostart.install(self.folder / 'config.json')
+ self.assertEqual((self.folder / 'token-tv.service').read_text(), working)
+
+ def test_a_stop_that_fails_keeps_the_entry_so_off_can_be_tried_again(self):
+ (self.folder / 'token-tv.service').write_text(autostart.entry(['/py', '-m', 'token_tv', 'start'], 'systemd'))
+ failed = mock.Mock(returncode=1, stdout='', stderr='Failed to stop')
+ with self.placed('systemd'), mock.patch.object(autostart, 'run', return_value=failed):
+ with self.assertRaises(OSError):
+ autostart.remove()
+ self.assertEqual(autostart.status(), 'on')
+
+ def test_windows_off_ends_the_copy_running_now(self):
+ config = self.folder / 'config.json'
+ (self.folder / 'state').mkdir()
+ (self.folder / 'state' / 'live.pid').write_text('4242')
+ (self.folder / 'TokenTV.vbs').write_text(autostart.entry(['pythonw', '-m', 'token_tv', 'start', '--config', str(config)], 'startup'))
+ python = mock.Mock(returncode=0, stdout='"pythonw.exe","4242","Console","1","40,000 K"', stderr='')
+ with self.placed('startup'), mock.patch.object(autostart, 'run', return_value=python), mock.patch('os.kill') as kill:
+ self.assertIn('stopped', autostart.remove())
+ kill.assert_called_once_with(4242, autostart.signal.SIGTERM)
+ self.assertFalse((self.folder / 'TokenTV.vbs').exists())
+
+ def test_windows_off_never_ends_another_program_that_took_the_number(self):
+ config = self.folder / 'config.json'
+ (self.folder / 'state').mkdir()
+ (self.folder / 'state' / 'live.pid').write_text('4242')
+ (self.folder / 'TokenTV.vbs').write_text(autostart.entry(['pythonw', '-m', 'token_tv', 'start', '--config', str(config)], 'startup'))
+ other = mock.Mock(returncode=0, stdout='"notepad.exe","4242","Console","1","9,000 K"', stderr='')
+ with self.placed('startup'), mock.patch.object(autostart, 'run', return_value=other), mock.patch('os.kill') as kill:
+ self.assertIn('Task Manager', autostart.remove())
+ kill.assert_not_called()
+
+ def test_the_stop_command_is_the_one_this_person_can_run(self):
+ with mock.patch('sys.prefix', '/home/me/.cache/token-tv/venv'):
+ self.assertEqual(autostart.how(), 'npx token-tv')
+ with mock.patch('sys.prefix', '/home/me/.cache/uv/archive-v0/abc'):
+ self.assertEqual(autostart.how(), 'uvx token-tv')
+ with mock.patch('sys.prefix', '/home/me/.local/pipx/venvs/token-tv'):
+ self.assertEqual(autostart.how(), 'token-tv')
+
+ def test_on_status_off_with_systemd(self):
+ config = self.folder / 'config.json'
+ config.write_text('{}')
+ done = mock.Mock(returncode=0, stdout='', stderr='')
+ with self.placed('systemd'), mock.patch.object(autostart, 'run', return_value=done) as run:
+ self.assertEqual(autostart.status(), 'off')
+ autostart.install(config)
+ self.assertEqual(autostart.status(), 'on')
+ self.assertIn(['systemctl', '--user', 'enable', '--now', 'token-tv.service'], [c.args[0] for c in run.call_args_list])
+ self.assertIn(['systemctl', '--user', 'restart', 'token-tv.service'], [c.args[0] for c in run.call_args_list])
+ self.assertIn('stopped', autostart.remove())
+ self.assertEqual(autostart.status(), 'off')
+
+ def test_an_entry_written_by_something_else_is_left_alone(self):
+ foreign = self.folder / 'token-tv.service'
+ foreign.write_text('[Service]\nExecStart=/opt/mine\n')
+ with self.placed('systemd'), mock.patch.object(autostart, 'run') as run:
+ self.assertEqual(autostart.status(), 'other')
+ with self.assertRaises(OSError):
+ autostart.install(self.folder / 'config.json')
+ self.assertIn('leaving it alone', autostart.remove())
+ run.assert_not_called()
+ self.assertEqual(foreign.read_text(), '[Service]\nExecStart=/opt/mine\n')
+
+ def test_a_failed_systemctl_leaves_no_entry(self):
+ failed = mock.Mock(returncode=1, stdout='', stderr='Failed to connect to bus')
+ with self.placed('systemd'), mock.patch.object(autostart, 'run', return_value=failed):
+ with self.assertRaises(OSError) as raised:
+ autostart.install(self.folder / 'config.json')
+ self.assertIn('bus', str(raised.exception))
+ self.assertFalse((self.folder / 'token-tv.service').exists())
+
+ def test_uvx_throwaway_copy_is_started_through_uvx(self):
+ with mock.patch('sys.prefix', '/home/me/.cache/uv/archive-v0/abc123'), \
+ mock.patch('shutil.which', return_value='/home/me/.local/bin/uvx'):
+ argv = autostart.command('/tmp/config.json')
+ self.assertEqual(argv[:3], ['/home/me/.local/bin/uvx', 'token-tv', 'start'])
+ with mock.patch('sys.prefix', '/home/me/.local/pipx/venvs/token-tv'):
+ self.assertEqual(autostart.command('/tmp/config.json')[1:3], ['-m', 'token_tv'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_cli.py b/tests/test_cli.py
index ec3858e..2c60ebd 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -131,10 +131,10 @@ class CliTest(unittest.TestCase):
self.assertFalse(self.config.exists())
self.assertEqual(cli.device_address('http://10.0.0.9:8080/'), 'http://10.0.0.9:8080')
- def test_doctor_without_config_explains_setup(self):
+ def test_doctor_without_config_points_to_start(self):
code, _, err = run('doctor', '--config', str(self.config))
self.assertEqual(code, 1)
- self.assertIn('token-tv setup', err)
+ self.assertIn('token-tv start', err)
def test_demo_renders_every_face_from_sample_data(self):
code, out, _ = run('demo', '--out', str(self.tmp / 'demo'), '--scale', '2')
@@ -213,20 +213,153 @@ class ConnectGuardTest(unittest.TestCase):
self.assertIn('Keychain', out.getvalue())
+class PortTest(unittest.TestCase):
+ def test_another_program_on_8787_moves_the_dashboard_to_the_next_free_port(self):
+ import socket
+ with socket.socket() as taken:
+ try:
+ taken.bind(('127.0.0.1', 8787))
+ except OSError:
+ self.skipTest('8787 is in use here already')
+ taken.listen()
+ with mock.patch.object(cli, 'running', return_value=False):
+ port, already = cli.dashboard_port()
+ self.assertEqual((port, already), (8788, False))
+
+ def test_a_dashboard_already_answering_is_reused(self):
+ with mock.patch.object(cli, 'running', side_effect=lambda port: port == 8789):
+ with mock.patch('socket.socket.bind', side_effect=OSError):
+ self.assertEqual(cli.dashboard_port(), (8789, True))
+
+
class StartTest(unittest.TestCase):
def setUp(self):
self.config = Path(tempfile.mkdtemp()) / 'config.json'
- def start(self, *extra):
+ def start(self, *extra, emails=None, found=(), already=False):
from token_tv import live
+ emails = emails or {'claude': '[email protected]', 'codex': None}
with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/x'), \
mock.patch.object(cli, 'login_state', side_effect=lambda p, h: 'yes' if p != 'grok' else 'no'), \
- mock.patch('token_tv.sources.logged_in_email',
- side_effect=lambda p, h: {'claude': '[email protected]', 'codex': None}[p]) as detect, \
+ mock.patch('token_tv.sources.logged_in_email', side_effect=lambda p, h: emails.get(p)) as detect, \
+ mock.patch('token_tv.device.find_clocks', return_value=list(found)) as scan, \
+ mock.patch.object(cli, 'dashboard_port', return_value=(8787, already)), \
mock.patch.object(live, 'main') as run:
code, out, err = run_cli('start', '--config', str(self.config), '--yes', '--no-browser', *extra)
+ self.scan = scan
return code, out, err, detect, run
+ def test_finds_the_clock_on_the_wifi_and_defaults_to_arcade(self):
+ code, out, _, _, run = self.start(found=['http://192.168.219.105'])
+ self.assertEqual(code, 0)
+ data = json.loads(self.config.read_text())
+ self.assertEqual((data['device_url'], data['display_style']), ('http://192.168.219.105', 'arcade'))
+ self.assertIn('Found a clock at 192.168.219.105', out)
+ run.assert_called_once()
+
+ def test_no_clock_found_runs_the_dashboard_alone(self):
+ code, out, _, _, run = self.start()
+ self.assertEqual(code, 0)
+ self.assertNotIn('device_url', json.loads(self.config.read_text()))
+ self.assertIn('No clock found', out)
+
+ def test_an_address_given_is_not_searched_for(self):
+ self.start('--device-url', '192.168.0.50')
+ self.scan.assert_not_called()
+
+ def test_only_and_face_from_the_web_demo(self):
+ both = {'claude': '[email protected]', 'codex': '[email protected]'}
+ code, _, _, _, _ = self.start('--only', 'codex', '--face', 'pixel', '--device-url', '10.0.0.5', emails=both)
+ self.assertEqual(code, 0)
+ data = json.loads(self.config.read_text())
+ self.assertEqual([a['provider'] for a in data['accounts']], ['codex'])
+ self.assertEqual(data['display_style'], 'pixel')
+
+ def test_only_a_service_not_signed_in_says_which(self):
+ code, _, err, _, run = self.start('--only', 'codex')
+ self.assertEqual(code, 1)
+ self.assertIn('No signed-in Codex CLI', err)
+ run.assert_not_called()
+
+ def test_only_naming_more_than_is_signed_in_still_sets_up(self):
+ code, _, _, _, run = self.start('--only', 'claude,codex', '--device-url', '10.0.0.5') # only Claude signed in
+ self.assertEqual(code, 0)
+ self.assertEqual([a['provider'] for a in json.loads(self.config.read_text())['accounts']], ['claude'])
+ run.assert_called_once()
+
+ def test_already_running_still_refuses_a_conflicting_only_and_switches_the_face(self):
+ self.config.write_text(json.dumps({'accounts': [
+ {'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]', 'source_home': '~/.claude'}]}))
+ code, _, err, _, _ = self.start('--only', 'codex', already=True)
+ self.assertEqual(code, 1)
+ self.assertIn('claude as well', err)
+ with mock.patch.object(cli, 'show_face') as face:
+ code, out, _, _, _ = self.start('--face', 'neon', already=True)
+ self.assertEqual(code, 0)
+ face.assert_called_once_with(8787, 'neon')
+
+ def test_only_rejects_unknown_services(self):
+ code, _, err, _, _ = self.start('--only', 'gemini')
+ self.assertEqual(code, 1)
+ self.assertIn('--only takes', err)
+
+ def test_a_face_given_again_is_kept_in_the_existing_config(self):
+ self.saved_config('http://192.168.0.50')
+ code, _, _, _, run = self.start('--face', 'neon')
+ self.assertEqual(code, 0)
+ self.assertEqual(json.loads(self.config.read_text())['display_style'], 'neon')
+ run.assert_called_once()
+
+ def test_already_running_opens_it_and_starts_no_second_copy(self):
+ code, out, _, detect, run = self.start(already=True)
+ self.assertEqual(code, 0)
+ self.assertIn('already running', out)
+ self.assertFalse(self.config.exists())
+ run.assert_not_called()
+
+ def test_asked_once_to_start_with_the_computer(self):
+ from token_tv import autostart, live
+ for answer, background in (('y', True), ('n', False)):
+ self.config.unlink(missing_ok=True)
+ with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/x'), \
+ mock.patch.object(cli, 'login_state', return_value='yes'), \
+ mock.patch('token_tv.sources.logged_in_email', side_effect=lambda p, h: '[email protected]' if p == 'codex' else None), \
+ mock.patch('token_tv.device.find_clocks', return_value=[]), \
+ mock.patch.object(cli, 'dashboard_port', side_effect=[(8787, False), (8788, True)]), \
+ mock.patch('sys.stdin.isatty', return_value=True), \
+ mock.patch.object(cli, 'ask', side_effect=lambda prompt, default='': answer if 'computer' in prompt else 'y' if '[Y/n]' in prompt else ''), \
+ mock.patch.object(autostart, 'status', return_value='off'), \
+ mock.patch.object(autostart, 'install', return_value='Runs in the background now') as install, \
+ mock.patch.object(live, 'main') as run:
+ code, out, _ = run_cli('start', '--config', str(self.config), '--no-browser')
+ self.assertEqual(code, 0)
+ self.assertEqual(install.called, background, answer)
+ self.assertEqual(run.called, not background, answer)
+ if background:
+ self.assertIn('Dashboard: http://127.0.0.1:8788', out) # where the background copy answered
+
+ def test_a_background_copy_that_never_answers_is_reported(self):
+ from token_tv import autostart, live
+ self.saved_config('http://192.168.0.50')
+ with mock.patch.object(cli, 'dashboard_port', return_value=(8787, False)), \
+ mock.patch('sys.stdin.isatty', return_value=True), mock.patch.object(cli, 'ask', return_value='y'), \
+ mock.patch.object(autostart, 'status', return_value='off'), \
+ mock.patch.object(autostart, 'install', return_value='ok'), mock.patch.object(cli.time, 'sleep'), \
+ mock.patch.object(live, 'main') as run:
+ code, _, err = run_cli('start', '--config', str(self.config), '--no-browser')
+ self.assertEqual(code, 1)
+ self.assertIn('autostart status', err)
+ run.assert_not_called()
+
+ def test_only_on_an_existing_config_with_other_services_is_refused(self):
+ self.config.write_text(json.dumps({'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'}]}))
+ code, _, err, _, run = self.start('--only', 'codex')
+ self.assertEqual(code, 1)
+ self.assertIn('claude as well', err)
+ run.assert_not_called()
+
def test_detects_signed_in_email_and_runs(self):
code, out, _, detect, run = self.start('--device-url', '192.168.0.50')
self.assertEqual(code, 0)
diff --git a/tests/test_device.py b/tests/test_device.py
index e920283..4d628ae 100644
--- a/tests/test_device.py
+++ b/tests/test_device.py
@@ -535,3 +535,24 @@ class UltraTests(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+
+
+class FindClockTests(unittest.TestCase):
+ """The clock is found on the Wi-Fi, so nobody has to read its address off the screen."""
+ def test_only_clocks_answer_and_nothing_is_written(self):
+ sd_state, sd_calls = {"files": {"cat.jpg": b"CAT"}, "enabled": set(), "total": 3000000, "base": 1500000}, []
+ ultra_state, ultra_calls = {"theme": 1, "autoplay": 1, "i_i": 5, "img": "", "files": {}, "parts": []}, []
+ from token_tv.device import find_clocks
+ with serve(sd_pro_clock(sd_state, sd_calls)) as sd_pro, serve(ultra_clock(ultra_state, ultra_calls)) as ultra, \
+ serve(answering(404, b"")) as printer, serve(answering(200, b"<html>router</html>")) as router:
+ nobody = "http://127.0.0.1:9" # nothing listens there
+ found = find_clocks([sd_pro, printer, ultra, router, nobody], timeout=2)
+ self.assertEqual(found, [sd_pro, ultra])
+ self.assertTrue(all(method == "GET" for method, *_ in sd_calls + ultra_calls))
+ self.assertEqual({path for _, path in sd_calls}, {"/v.json", "/photo/list"})
+
+ def test_this_computers_network_is_searched(self):
+ from token_tv import device
+ with patch.object(device, "local_prefixes", return_value=["192.168.7"]), \
+ patch.object(device, "clock_model", side_effect=lambda url, timeout: "sdpro" if url.endswith(".42") else None):
+ self.assertEqual(device.find_clocks(), ["http://192.168.7.42"])
diff --git a/tests/test_live.py b/tests/test_live.py
index c94e0db..d470f0f 100644
--- a/tests/test_live.py
+++ b/tests/test_live.py
@@ -173,3 +173,24 @@ class LoopTimingTests(unittest.TestCase):
self.assertAlmostEqual(until_loop_end(shown, 101.0), 7.4) # 1 s in
self.assertAlmostEqual(until_loop_end(shown, 100.0 + 2 * 8.4), 0) # right at the end of the second loop
self.assertEqual(until_loop_end({'at': None, 'loop': None}, 5), 0)
+
+
+class RelocateTests(unittest.TestCase):
+ def test_a_clock_with_a_new_address_is_followed_only_when_it_is_the_one_clock(self):
+ from token_tv.live import relocate
+ old = 'http://192.168.0.50'
+ self.assertEqual(relocate(old, lambda: ['http://192.168.0.77']), 'http://192.168.0.77')
+ self.assertIsNone(relocate(old, lambda: [old])) # still there: just busy
+ self.assertIsNone(relocate(old, lambda: [])) # off
+ self.assertIsNone(relocate(old, lambda: ['http://192.168.0.77', 'http://192.168.0.78'])) # which one?
+
+
+class LockTests(unittest.TestCase):
+ def test_one_tokentv_per_config(self):
+ import subprocess, sys, tempfile
+ from token_tv.live import hold_lock
+ folder = Path(tempfile.mkdtemp())
+ self.assertTrue(hold_lock(folder))
+ other = subprocess.run([sys.executable, '-c', 'import sys; from pathlib import Path; from token_tv.live import hold_lock; '
+ 'sys.exit(0 if hold_lock(Path(sys.argv[1])) else 3)', str(folder)], capture_output=True)
+ self.assertEqual(other.returncode, 3) # a second process with the same config is refused
diff --git a/token_tv/__init__.py b/token_tv/__init__.py
index 6339498..474fa6f 100644
--- a/token_tv/__init__.py
+++ b/token_tv/__init__.py
@@ -1,2 +1,2 @@
"""TokenTV: AI usage limits on a tiny desk clock."""
-__version__ = "0.3.0"
+__version__ = "0.3.1"
diff --git a/token_tv/arcade.py b/token_tv/arcade.py
index be50650..00b3f99 100644
--- a/token_tv/arcade.py
+++ b/token_tv/arcade.py
@@ -1610,13 +1610,14 @@ RAINBOW = ((255, 90, 82), (255, 167, 38), (255, 213, 79), (102, 187, 106), (66,
# catch the eye of someone working next to the clock.
BURST = {'unique': ((176, 124, 255), (214, 166, 255), (242, 228, 255), (236, 226, 255)),
'legend': ((255, 170, 60), (255, 214, 107), (255, 244, 200), (255, 248, 230))} # rays..., the flash
-BURST_FRAMES = {'unique': 14, 'legend': 20}
+BURST_FRAMES = {'unique': 4, 'legend': 5}
+BURST_PACE = {'unique': 3.5, 'legend': 4} # their 14 and 20 steps at about four times the first pace (owner's pick)
def light_burst(draw, f, tier, night=False):
"""The cut-in: rays from the middle, a flash and a white core; at night only the coloured rays."""
rays, flash = BURST[tier][:3], BURST[tier][3]
- n, cx, cy = BURST_FRAMES[tier], SIZE * .42, SIZE * .58
+ f, n, cx, cy = f * BURST_PACE[tier], BURST_FRAMES[tier] * BURST_PACE[tier], SIZE * .42, SIZE * .58
grow = min(1, (f + 1) / 4) # the rays reach the edges in four frames
thin = 1 if f < n * .55 else max(0, (n - f) / (n * .45)) # then thin away
if 2 <= f < n * .5 and not night:
diff --git a/token_tv/autostart.py b/token_tv/autostart.py
new file mode 100644
index 0000000..4eb12a5
--- /dev/null
+++ b/token_tv/autostart.py
@@ -0,0 +1,188 @@
+"""Start TokenTV with the computer and keep it running, so the clock does not stop when a terminal closes.
+
+Linux: a systemd user service. macOS: a LaunchAgent. Windows: a hidden entry in the Startup folder. Each runs
+`token-tv start --yes --no-browser` for one config. Only files TokenTV wrote are ever replaced or removed.
+"""
+import os
+import shlex
+import shutil
+import signal
+import subprocess
+import sys
+from pathlib import Path
+
+MARK = 'Written by token-tv autostart'
+LABEL = 'io.github.click6067-ship-it.token-tv'
+
+
+def how():
+ """How this person runs TokenTV, for the commands TokenTV tells them: `npx token-tv`, `uvx token-tv` or
+ `token-tv`."""
+ prefix = Path(sys.prefix)
+ if throwaway():
+ return 'uvx token-tv'
+ if prefix.name == 'venv' and prefix.parent.name == 'token-tv': # the npx launcher's own copy
+ return 'npx token-tv'
+ return 'token-tv'
+
+
+def throwaway():
+ """Whether this is uvx's throwaway copy, which uv may clear."""
+ parts = Path(sys.prefix).parts
+ return 'uv' in parts and ('cache' in (p.lower() for p in parts) or any(p.startswith('archive-v') for p in parts))
+
+
+def log_hint():
+ _, kind = place()
+ return {'systemd': 'journalctl --user -u token-tv', 'launchd': '~/Library/Logs/token-tv.log',
+ 'startup': 'none on Windows'}[kind]
+
+
+def command(config):
+ """How the computer starts TokenTV: this same Python (a pipx, pip or npx install keeps it), or uvx when this
+ run is uvx's throwaway copy, which uv may clear."""
+ tail = ['start', '--yes', '--no-browser', '--config', str(Path(config).expanduser().resolve())]
+ if throwaway():
+ uvx = shutil.which('uvx')
+ if uvx:
+ return [uvx, 'token-tv', *tail]
+ python = Path(sys.executable)
+ if sys.platform == 'win32' and (python.parent / 'pythonw.exe').exists():
+ python = python.parent / 'pythonw.exe' # no console window
+ return [str(python), '-m', 'token_tv', *tail]
+
+
+def place():
+ """Where the entry lives on this computer, and its kind."""
+ if sys.platform == 'darwin':
+ return Path('~/Library/LaunchAgents').expanduser() / f'{LABEL}.plist', 'launchd'
+ if sys.platform == 'win32':
+ startup = Path(os.environ.get('APPDATA', '~')).expanduser() / 'Microsoft/Windows/Start Menu/Programs/Startup'
+ return startup / 'TokenTV.vbs', 'startup'
+ base = Path(os.environ.get('XDG_CONFIG_HOME') or '~/.config').expanduser()
+ return base / 'systemd/user/token-tv.service', 'systemd'
+
+
+def entry(argv, kind, path=None):
+ """The text of the entry that runs `argv`. It keeps this terminal's PATH, where the Claude, Codex and Grok CLIs
+ (and Node, for some) were found, and it starts again whenever it stops: a copy already running in a terminal
+ makes it wait, and it takes over once that copy is closed."""
+ path = os.environ.get('PATH', '') if path is None else path
+ if kind == 'systemd':
+ quoted = path.replace('%', '%%').replace('\\', '\\\\').replace('"', '\\"')
+ return (f'# {MARK}\n[Unit]\nDescription=TokenTV desk clock\nAfter=network-online.target\n\n'
+ f'[Service]\nEnvironment="PATH={quoted}"\nExecStart={shlex.join(argv).replace("%", "%%")}\n'
+ f'Restart=always\nRestartSec=30\n\n[Install]\nWantedBy=default.target\n')
+ if kind == 'launchd':
+ args = ''.join(f'<string>{xml(a)}</string>' for a in argv)
+ log = xml(str(Path('~/Library/Logs/token-tv.log').expanduser()))
+ return (f'<?xml version="1.0" encoding="UTF-8"?>\n<!-- {MARK} -->\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST '
+ f'1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>'
+ f'<key>Label</key><string>{LABEL}</string><key>ProgramArguments</key><array>{args}</array>'
+ f'<key>EnvironmentVariables</key><dict><key>PATH</key><string>{xml(path)}</string></dict>'
+ f'<key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>30</integer>'
+ f'<key>StandardOutPath</key><string>{log}</string><key>StandardErrorPath</key><string>{log}</string>'
+ f'</dict></plist>\n')
+ # Windows: a hidden loop that runs TokenTV, waits for it to end, and runs it again until this file is gone.
+ line = ' '.join('""' + a.replace('"', '') + '""' for a in argv)
+ config = argv[argv.index('--config') + 1] if '--config' in argv else ''
+ return '\r\n'.join([
+ f"' {MARK}", f"' config: {config}",
+ 'Set shell = CreateObject("WScript.Shell")', 'Set files = CreateObject("Scripting.FileSystemObject")',
+ f'shell.Environment("Process")("PATH") = "{path.replace(chr(34), chr(34) * 2)}"',
+ 'Do While files.FileExists(WScript.ScriptFullName)', f' shell.Run "{line}", 0, True', ' WScript.Sleep 30000',
+ 'Loop', ''])
+
+
+def xml(text):
+ return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
+
+
+def ours(path):
+ try:
+ return MARK in path.read_text(errors='replace')
+ except OSError:
+ return False
+
+
+def run(argv):
+ """A system tool's result; a missing or hung tool reads as a failure, not an exception of another kind."""
+ try:
+ return subprocess.run(argv, capture_output=True, text=True, timeout=60)
+ except (OSError, subprocess.SubprocessError) as error:
+ return subprocess.CompletedProcess(argv, 1, '', f'{argv[0]}: {error}')
+
+
+def status():
+ """'on', 'off' or 'other' (an entry by that name that TokenTV did not write)."""
+ path, _ = place()
+ return 'off' if not path.exists() else 'on' if ours(path) else 'other'
+
+
+def install(config):
+ """Write the entry and start TokenTV now. Returns a line to show, or raises OSError with the reason."""
+ path, kind = place()
+ if path.exists() and not ours(path):
+ raise OSError(f'{path} exists and was not written by TokenTV; leaving it alone')
+ argv = command(config)
+ before = path.read_text() if path.exists() else None
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(entry(argv, kind))
+
+ def undo(reason): # put back what was there, so a failed try is not taken for a working entry
+ path.write_text(before) if before is not None else path.unlink()
+ raise OSError(reason)
+ if kind == 'systemd':
+ for step in (['systemctl', '--user', 'daemon-reload'], ['systemctl', '--user', 'enable', '--now', path.name],
+ ['systemctl', '--user', 'restart', path.name]):
+ done = run(step)
+ if done.returncode:
+ undo((done.stderr or done.stdout).strip() or 'systemctl failed')
+ elif kind == 'launchd':
+ domain = f'gui/{os.getuid()}'
+ run(['launchctl', 'bootout', domain, str(path)])
+ done = run(['launchctl', 'bootstrap', domain, str(path)])
+ if done.returncode:
+ undo((done.stderr or done.stdout).strip() or 'launchctl failed')
+ else:
+ try: # the same loop the next sign-in starts, started now
+ subprocess.Popen(['wscript.exe', str(path)], creationflags=getattr(subprocess, 'DETACHED_PROCESS', 0),
+ close_fds=True)
+ except OSError as error:
+ undo(str(error))
+ return f'TokenTV now runs in the background and starts with this computer. Stop it with: {how()} autostart off'
+
+
+def remove():
+ """Stop TokenTV and remove the entry. Returns a line to show; raises OSError, keeping the entry, if TokenTV
+ could not be stopped (so `off` can be tried again)."""
+ path, kind = place()
+ if not path.exists():
+ return 'TokenTV does not start with this computer.'
+ if not ours(path):
+ return f'{path} was not written by TokenTV; leaving it alone.'
+ if kind == 'systemd':
+ done = run(['systemctl', '--user', 'disable', '--now', path.name])
+ if done.returncode:
+ raise OSError((done.stderr or done.stdout).strip() or 'systemctl failed')
+ elif kind == 'launchd':
+ done = run(['launchctl', 'bootout', f'gui/{os.getuid()}', str(path)])
+ gone = 'No such process' in done.stderr or 'Could not find' in done.stderr # already stopped
+ if done.returncode and not gone:
+ raise OSError((done.stderr or done.stdout).strip() or 'launchctl failed')
+ text = path.read_text(errors='replace')
+ path.unlink()
+ if kind == 'systemd':
+ run(['systemctl', '--user', 'daemon-reload'])
+ if kind == 'startup': # the loop sees its file gone; the copy running now is ended by the number it left
+ config = next((line.split(':', 1)[1].strip() for line in text.splitlines() if line.startswith("' config:")), '')
+ pid_file = Path(config).parent / 'state' / 'live.pid' if config else None
+ try:
+ pid = int(pid_file.read_text())
+ shown = run(['tasklist', '/FI', f'PID eq {pid}', '/FO', 'CSV', '/NH']).stdout.lower()
+ if 'python' not in shown: # that number now belongs to another program, or to nothing
+ raise ValueError(pid)
+ os.kill(pid, signal.SIGTERM)
+ except (AttributeError, OSError, ValueError):
+ return 'TokenTV no longer starts with this computer; end pythonw.exe in Task Manager to stop it now.'
+ return 'TokenTV stopped and no longer starts with this computer.'
diff --git a/token_tv/cli.py b/token_tv/cli.py
index f6506cd..a8c4b9e 100644
--- a/token_tv/cli.py
+++ b/token_tv/cli.py
@@ -1,6 +1,7 @@
"""token-tv: set up, check, preview and run TokenTV.
- token-tv start find your signed-in CLIs, ask for the clock, run (the easy way)
+ token-tv start find your signed-in CLIs and the clock, keep it running (the easy way)
+ token-tv autostart start TokenTV with this computer (on), stop that (off), or check (status)
token-tv setup write a credential-free config (never overwrites one)
token-tv doctor check CLIs and login files (--live asks each provider)
token-tv demo render every clock face with sample data
@@ -15,6 +16,7 @@ import shutil
import sys
import time
from pathlib import Path
+from http.client import HTTPException
from urllib.parse import urlparse
PROVIDERS = {
@@ -113,7 +115,7 @@ def setup(args):
except ValueError as error:
print(error, file=sys.stderr)
return 1
- config = {'poll_seconds': 60, 'accounts': accounts, 'display_style': 'digital'}
+ config = {'poll_seconds': 60, 'accounts': accounts, 'display_style': 'arcade'}
if device:
config['device_url'] = device
try:
@@ -139,7 +141,7 @@ def read_config(path):
from token_tv.sources import load_config
path = Path(path).expanduser()
if not path.is_file():
- print(f'No config at {path}. Run: token-tv setup', file=sys.stderr)
+ print(f'No config at {path}. Run: token-tv start', file=sys.stderr)
return None
try:
return load_config(path)
@@ -239,14 +241,95 @@ def demo(args):
return 0
+PORTS = range(8787, 8797) # the dashboard's port: the first one free, when another program has 8787
+
+
+def running(port):
+ """Whether a TokenTV dashboard already answers on this port of this computer (in the background, say)."""
+ from urllib.request import ProxyHandler, build_opener
+ try:
+ with build_opener(ProxyHandler({})).open(f'http://127.0.0.1:{port}/display', timeout=2) as response:
+ return 'styles' in json.loads(response.read(65536))
+ except (OSError, ValueError, TypeError, HTTPException): # nothing there, or another program (ssh, say)
+ return False
+
+
+def dashboard_port():
+ """(port, True) where TokenTV already runs, else (the first free port, False), else (None, False)."""
+ import socket
+ for port in PORTS: # a copy already running anywhere first, whichever port it took
+ if running(port):
+ return port, True
+ for port in PORTS:
+ with socket.socket() as probe:
+ try:
+ probe.bind(('127.0.0.1', port))
+ except OSError:
+ continue
+ return port, False
+ return None, False
+
+
+def pick_clock(interactive):
+ """The clock's address: found on this Wi-Fi, chosen when there are several, else asked; '' = dashboard only."""
+ from token_tv.device import find_clocks
+ print('Looking for your clock on this Wi-Fi...', flush=True)
+ found = find_clocks()
+ if len(found) == 1:
+ print(f'Found a clock at {urlparse(found[0]).hostname}')
+ return found[0]
+ if found and interactive:
+ for n, url in enumerate(found, 1):
+ print(f' {n}. {urlparse(url).hostname}')
+ choice = ask('Which clock? Number', '1')
+ return found[int(choice) - 1] if choice.isdigit() and 1 <= int(choice) <= len(found) else found[0]
+ if found:
+ print(f'Found {len(found)} clocks; using {urlparse(found[0]).hostname} (pass --device-url to choose)')
+ return found[0]
+ if not interactive:
+ print('No clock found on this Wi-Fi: the dashboard runs without one (pass --device-url to add it).')
+ return ''
+ print('No clock found on this Wi-Fi. Its address shows on the clock screen when it starts.')
+ return ask('Clock address, e.g. 192.168.0.50 (blank = dashboard only)')
+
+
def start(args):
- """One command: find signed-in CLIs, confirm their emails, ask for the clock, then run."""
+ """One command: find signed-in CLIs and the clock, write the config, keep it running, open the dashboard."""
from token_tv.sources import logged_in_email
+ port, already = dashboard_port()
+ url = f'http://127.0.0.1:{port}'
+ only = [p.strip().lower() for p in (args.only or '').split(',') if p.strip()]
+ if set(only) - set(PROVIDERS):
+ print(f'--only takes {", ".join(PROVIDERS)}', file=sys.stderr)
+ return 1
path = Path(args.config).expanduser()
+ if already:
+ if path.exists():
+ config = read_config(path)
+ if config is None or refuses_only(path, config, only):
+ return 1
+ if args.face and config.get('display_style') != args.face:
+ show_face(port, args.face)
+ print(f'TokenTV is already running on this computer: {url}')
+ if only:
+ from token_tv import autostart
+ print(f'It reads its accounts when it starts: after changing them, restart it '
+ f'({autostart.how()} autostart off, then {autostart.how()} start).')
+ if not args.no_browser:
+ import webbrowser
+ webbrowser.open(url)
+ return 0
+ if port is None:
+ print(f'Ports {PORTS[0]}-{PORTS[-1]} are all taken on this computer; free one and run token-tv start again.',
+ file=sys.stderr)
+ return 1
interactive = not args.yes and sys.stdin.isatty()
- if not path.exists():
+ existed = path.exists()
+ if not existed:
accounts = []
for provider, (_, home, _, _) in PROVIDERS.items():
+ if only and provider not in only:
+ continue
if not cli_path(provider) or login_state(provider, home) == 'no':
continue
email = logged_in_email(provider, home)
@@ -258,12 +341,13 @@ def start(args):
'email': email, 'source_home': home})
print(f'{provider.title()}: {email}')
if not accounts:
- print('No signed-in Claude, Codex or Grok CLI found. Sign in to one (for example `claude`, then /login),\n'
+ wanted = ' or '.join(p.title() for p in only) if only else 'Claude, Codex or Grok'
+ print(f'No signed-in {wanted} CLI found. Sign in to one (for example `codex`, then log in),\n'
'or look around first with: token-tv demo', file=sys.stderr)
return 1
device = args.device_url
- if device is None and interactive:
- device = ask('Clock address shown on the clock screen, e.g. 192.168.0.50 (blank = dashboard only)')
+ if device is None:
+ device = pick_clock(interactive)
if device and not device.startswith(('http://', 'https://')):
device = 'http://' + device
try:
@@ -271,7 +355,7 @@ def start(args):
except ValueError as error:
print(error, file=sys.stderr)
return 1
- config = {'poll_seconds': 60, 'accounts': accounts, 'display_style': 'digital'}
+ config = {'poll_seconds': 60, 'accounts': accounts, 'display_style': args.face or 'arcade'}
if device:
config['device_url'] = device
path.parent.mkdir(parents=True, exist_ok=True)
@@ -295,17 +379,91 @@ def start(args):
f'and --device-url is only used when that file is created.\n'
f'To use {wanted}, change device_url in that file, then run token-tv start again.', file=sys.stderr)
return 1
+ if existed and refuses_only(path, config, only):
+ return 1
+ if args.face and config.get('display_style') != args.face: # the face picked on the web demo, kept from now on
+ config['display_style'] = args.face
+ path.write_text(json.dumps(config, indent=2) + '\n')
+ from token_tv import autostart
+ if interactive and autostart.status() == 'off' and \
+ ask('Start TokenTV with this computer and keep it running? [Y/n]', 'y').lower().startswith('y'):
+ try:
+ print(autostart.install(path))
+ except OSError as error:
+ print(f'Could not set that up ({error}); running here instead (Ctrl+C to stop).')
+ else:
+ for _ in range(60): # the background copy needs a moment to open its dashboard
+ port, up = dashboard_port()
+ if up:
+ break
+ time.sleep(.5)
+ if not up:
+ print(f'The background copy has not opened its dashboard after 30 seconds. Check it with: '
+ f'{autostart.how()} autostart status (its log: {autostart.log_hint()})', file=sys.stderr)
+ return 1
+ url = f'http://127.0.0.1:{port}'
+ if not args.no_browser:
+ import webbrowser
+ webbrowser.open(url)
+ print(f'Dashboard: {url}')
+ return 0
if not args.no_browser:
import threading
import webbrowser
- threading.Timer(1.5, webbrowser.open, ['http://127.0.0.1:8787']).start()
- print('Dashboard: http://127.0.0.1:8787 (Ctrl+C to stop)')
+ threading.Timer(1.5, webbrowser.open, [url]).start()
+ print(f'Dashboard: {url} (Ctrl+C to stop)')
from token_tv import live
- sys.argv = ['token-tv start', '--config', str(path), '--state-dir', str(path.parent / 'state')]
+ sys.argv = ['token-tv start', '--config', str(path), '--state-dir', str(path.parent / 'state'), '--port', str(port)]
live.main()
return 0
+def refuses_only(path, config, only):
+ """True, having said why, when a saved config shows services that --only leaves out: --only picks the services
+ when the config is made; it never quietly drops accounts from one."""
+ extra = sorted({a.get('provider') for a in config.get('accounts', [])} - set(only)) if only else []
+ if extra:
+ print(f'{path} already lists {", ".join(extra)} as well, and --only is only used when that file is made.\n'
+ f'To keep only {", ".join(only)}, remove the others from that file (or move it away and run this '
+ f'again), then run token-tv start.', file=sys.stderr)
+ return bool(extra)
+
+
+def show_face(port, face):
+ """Switch the TokenTV running on this computer to `face`, as its dashboard's own button does."""
+ from urllib.request import ProxyHandler, Request, build_opener
+ request = Request(f'http://127.0.0.1:{port}/display/style', data=json.dumps({'style': face}).encode(),
+ headers={'Content-Type': 'application/json'})
+ try:
+ build_opener(ProxyHandler({})).open(request, timeout=5).close()
+ print(f'The clock switches to {face}.')
+ except (OSError, HTTPException):
+ print(f'Could not switch the running TokenTV to {face}; pick it on its dashboard.', file=sys.stderr)
+
+
+def autostart_command(args):
+ from token_tv import autostart
+ if args.action == 'on':
+ if read_config(args.config) is None:
+ return 1
+ try:
+ print(autostart.install(Path(args.config).expanduser()))
+ except OSError as error:
+ print(f'Could not set it up: {error}', file=sys.stderr)
+ return 1
+ elif args.action == 'off':
+ try:
+ print(autostart.remove())
+ except OSError as error:
+ print(f'Could not stop it: {error}. Nothing was removed; try again.', file=sys.stderr)
+ return 1
+ else:
+ state = autostart.status()
+ print({'on': 'TokenTV starts with this computer.', 'off': 'TokenTV does not start with this computer.',
+ 'other': 'Another program owns the TokenTV entry; TokenTV leaves it alone.'}[state])
+ return 0
+
+
def passthrough(module, args, extra):
sys.argv = [f'token-tv {args.command}', '--config', str(Path(args.config).expanduser()), *extra]
if not {'-h', '--help'} & set(extra) and read_config(args.config) is None:
@@ -315,6 +473,7 @@ def passthrough(module, args, extra):
def main(argv=None):
+ from token_tv.display import STYLES
parser = argparse.ArgumentParser(prog='token-tv', description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest='command', metavar='command')
@@ -329,10 +488,14 @@ def main(argv=None):
help='give every account its own login home instead of reusing your existing CLI login')
s.add_argument('--device-url', help='clock address, e.g. http://192.168.0.50')
s.add_argument('--yes', action='store_true', help='do not ask; use only the flags given')
- st = commands.add_parser('start', parents=[config], help='find your signed-in CLIs, ask for the clock, and run')
- st.add_argument('--device-url', help='clock address, e.g. 192.168.0.50')
+ st = commands.add_parser('start', parents=[config], help='find your signed-in CLIs and the clock, and run')
+ st.add_argument('--device-url', help='clock address, e.g. 192.168.0.50 (default: found on this Wi-Fi)')
+ st.add_argument('--face', choices=STYLES, help='clock face (default: arcade)')
+ st.add_argument('--only', metavar='SERVICES', help='only these, comma-separated: claude,codex,grok')
st.add_argument('--yes', action='store_true', help='accept every signed-in account without asking')
st.add_argument('--no-browser', action='store_true', help='do not open the dashboard in a browser')
+ a = commands.add_parser('autostart', parents=[config], help='start TokenTV with this computer, or stop that')
+ a.add_argument('action', choices=('on', 'off', 'status'))
o = commands.add_parser('doctor', parents=[config], help='check CLIs and logins')
o.add_argument('--live', action='store_true', help='ask each provider now and compare the email; the CLI may refresh an expired login; prints status only')
d = commands.add_parser('demo', help='render every clock face with sample data')
@@ -359,7 +522,8 @@ def main(argv=None):
if args.command is None:
parser.print_help()
return 0
- return {'setup': setup, 'doctor': doctor, 'demo': demo, 'start': start}[args.command](args)
+ return {'setup': setup, 'doctor': doctor, 'demo': demo, 'start': start,
+ 'autostart': autostart_command}[args.command](args)
if __name__ == '__main__':
diff --git a/token_tv/device.py b/token_tv/device.py
index ff4d393..ba6abff 100644
--- a/token_tv/device.py
+++ b/token_tv/device.py
@@ -1,11 +1,18 @@
"""Confirmed SD_PRO photo API, plus the SmallTV-Ultra image API. Never flash or delete existing photographs."""
+import ipaddress
import json
+import re
+import socket
+import subprocess
+import sys
import time
import uuid
+from concurrent.futures import ThreadPoolExecutor
from http.client import HTTPException
+from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import quote, urlencode, urlparse
-from urllib.request import Request, urlopen
+from urllib.request import ProxyHandler, Request, build_opener, urlopen
FILES = ("tokentv.jpg", "tokentv.gif")
@@ -250,3 +257,84 @@ def open_display(base_url):
except (OSError, ValueError, AttributeError, HTTPException):
return display # model checked once at start; an Ultra offline at launch falls back to SD_PRO until restart
return UltraDisplay(base_url) if isinstance(model, str) and model.startswith("SmallTV-Ultra") else display
+
+
+def clock_model(base_url, timeout=3):
+ """'ultra' or 'sdpro' when a clock answers at `base_url`, else None. Read-only; an address where nothing answers
+ is asked once."""
+ opener = build_opener(ProxyHandler({})) # a clock is on this network, never behind a proxy
+
+ def get(path):
+ with opener.open(Request(base_url + path), timeout=timeout) as response:
+ return json.loads(response.read(65536))
+ try:
+ model = get("/v.json").get("m")
+ if isinstance(model, str) and model.startswith("SmallTV"):
+ return "ultra" if model.startswith("SmallTV-Ultra") else "sdpro"
+ except HTTPError:
+ pass # something answers there: an SD_PRO has no /v.json
+ except (OSError, ValueError, AttributeError, HTTPException):
+ return None
+ try:
+ listing = get("/photo/list")
+ if isinstance(listing.get("files"), list) and "total" in listing:
+ return "sdpro"
+ except (OSError, ValueError, AttributeError, HTTPException):
+ pass
+ return None
+
+
+def local_addresses():
+ """This computer's IPv4 addresses on every network it is on, as its own tools list them (a VPN may hold the
+ default route while the clock sits on the Wi-Fi). Under WSL, Windows' addresses too."""
+ found = []
+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ probe.connect(("192.0.2.1", 9)) # sends nothing: only picks the interface the default route is on
+ found.append(probe.getsockname()[0])
+ except OSError:
+ pass
+ finally:
+ probe.close()
+ tools = [["ipconfig"]] if sys.platform == "win32" else [["ip", "-4", "-o", "addr", "show"], ["ifconfig"]]
+ try:
+ if "microsoft" in Path("/proc/version").read_text().lower():
+ tools.append(["ipconfig.exe"])
+ except OSError:
+ pass
+ for tool in tools:
+ try:
+ shown = subprocess.run(tool, capture_output=True, timeout=10).stdout.decode(errors="replace")
+ except (OSError, subprocess.SubprocessError):
+ continue
+ pattern = r"IPv4[^\n]*?(\d+\.\d+\.\d+\.\d+)" if tool[0].startswith("ipconfig") else r"inet (?:addr:)?(\d+\.\d+\.\d+\.\d+)"
+ found += re.findall(pattern, shown)
+ return found
+
+
+def local_prefixes():
+ """The first three parts of this computer's private addresses: a clock on the same Wi-Fi is beside one.
+ Home networks first; at most four, so the search stays a few seconds."""
+ prefixes = []
+ for address in local_addresses():
+ try:
+ ip = ipaddress.ip_address(address)
+ except ValueError:
+ continue
+ if ip.is_private and not (ip.is_loopback or ip.is_link_local or address.startswith("0.")):
+ prefix = address.rsplit(".", 1)[0]
+ if prefix not in prefixes:
+ prefixes.append(prefix)
+ return sorted(prefixes, key=lambda p: (not p.startswith("192.168."), not p.startswith("10.")))[:4]
+
+
+def find_clocks(candidates=None, timeout=3):
+ """The addresses of the clocks that answer on this computer's networks, so nobody has to read one off the clock.
+ Every address of each local /24 is asked at once, read-only: a few seconds."""
+ if candidates is None:
+ candidates = [f"http://{prefix}.{n}" for prefix in local_prefixes() for n in range(1, 255)]
+ if not candidates:
+ return []
+ with ThreadPoolExecutor(max_workers=min(256, len(candidates))) as pool:
+ models = list(pool.map(lambda url: clock_model(url, timeout), candidates))
+ return [url for url, model in zip(candidates, models) if model]
diff --git a/token_tv/live.py b/token_tv/live.py
index dea4739..27c50c2 100644
--- a/token_tv/live.py
+++ b/token_tv/live.py
@@ -1,5 +1,6 @@
"""Live account dashboard and stock-firmware image publisher."""
import argparse
+import atexit
import dataclasses
import hashlib
import json
@@ -35,6 +36,39 @@ def until_loop_end(shown, now):
return 0 if wait > shown['loop'] - .1 else wait # right on time is no reason to wait a whole loop
+LOST_POLLS = 3 # polls in a row the clock does not answer before TokenTV looks for it on the network again
+RESCAN_SECONDS = 1800 # and then at most this often while it stays lost (a clock that is simply off)
+
+
+def relocate(current, find=None):
+ """The clock's new address when exactly one clock answers on this network and not at `current`, else None."""
+ if find is None:
+ from token_tv.device import find_clocks as find
+ found = find()
+ return found[0] if len(found) == 1 and found[0] != current else None
+
+
+LOCKS = [] # open lock files, held for the life of the process
+
+
+def hold_lock(state_dir):
+ """One TokenTV per config: two would both drive the clock and the same state files. False if one runs."""
+ state_dir.mkdir(parents=True, exist_ok=True)
+ handle = open(state_dir / "live.lock", "a+")
+ try:
+ if os.name == "nt":
+ import msvcrt
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ handle.close()
+ return False
+ LOCKS.append(handle)
+ return True
+
+
def write_json(path, data):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
@@ -87,6 +121,13 @@ class DisplayPreferences:
self.status = 'queued' if self.config.get('device_url') else 'preview_only'
self.changed.set()
+ def set_device(self, url):
+ """The clock moved to `url` (the router gave it a new address): kept in the config from now on."""
+ with self.lock:
+ updated = dict(load_config(self.path), device_url=url)
+ write_json(self.path, updated)
+ self.config = updated
+
def delivered(self, style, success):
with self.lock:
if success:
@@ -224,6 +265,12 @@ def main():
if config.get("font"):
os.environ["TOKEN_TV_FONT"] = config["font"]
state_dir = Path(args.state_dir)
+ if not (args.once or args.restore_display):
+ if not hold_lock(state_dir):
+ raise SystemExit("TokenTV is already running with this config on this computer.")
+ pid_file = state_dir / "live.pid"
+ pid_file.write_text(str(os.getpid())) # how `autostart off` ends it on Windows; gone again at exit
+ atexit.register(lambda: pid_file.unlink(missing_ok=True))
device = open_display(config["device_url"]) if config.get("device_url") else None
backup_path = state_dir / "display-original.json"
if args.restore_display:
@@ -257,12 +304,13 @@ def main():
streaks = {} # account key -> full periods in a row, at its last 'full'
shown = {'at': None, 'loop': None} # when the clock's GIF started, and its loop
+ lost = {'polls': 0, 'scanned': None} # polls in a row the clock did not answer, and when it was last looked for
def cycle(refresh=True, egg=None):
"""Read (if `refresh`), draw and upload; True once the clock has the picture. A new picture for a looping
face lands as the one on the clock finishes its loop, so the animation never jumps back mid-move; a
one-off's first picture goes at once."""
- nonlocal original, last_upload
+ nonlocal original, last_upload, device
delivered = False
if refresh:
store.refresh()
@@ -310,9 +358,27 @@ def main():
write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "uploads": receipts})
preferences.delivered(style, True)
delivered = True
+ lost['polls'] = 0
except (OSError, ValueError, KeyError, HTTPException) as error:
if isinstance(error, BackupMismatch):
print(mismatch_message(error, backup_path), flush=True)
+ if isinstance(error, (OSError, HTTPException)): # no answer, or another device answers there now
+ lost['polls'] += 1
+ if lost['polls'] >= LOST_POLLS and (lost['scanned'] is None or
+ time.monotonic() - lost['scanned'] > RESCAN_SECONDS):
+ lost['scanned'] = time.monotonic()
+ moved = relocate(device.base_url)
+ candidate = moved and open_display(moved)
+ try:
+ if candidate and original is not None:
+ candidate.check_backup(original) # the same kind of clock, or it is not ours
+ except BackupMismatch:
+ candidate = None
+ if candidate:
+ device = candidate
+ preferences.set_device(moved)
+ lost['polls'] = 0
+ print(f"TokenTV found the clock at its new address {moved}.", flush=True)
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)
diff --git a/token_tv/web/app.js b/token_tv/web/app.js
index 01126b8..ba218d7 100644
--- a/token_tv/web/app.js
+++ b/token_tv/web/app.js
@@ -256,9 +256,37 @@ function paintClock(forceImage = false) {
const style = clockChoice || displayInfo?.style;
$('#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 = 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);
+ $('#display-state').textContent = DEMO ? 'Demo · sample data' : 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);
+ paintSetup();
if (style && !$('#clock-panel').hidden && (forceImage || style !== lastImageStyle || Date.now() - lastImageAt > 30000)) {lastImageStyle = style; lastImageAt = Date.now(); $('#frame').src = DEMO ? displayInfo.frames?.[style] || `/frames/${encodeURIComponent(style)}.jpg` : '/frame/0.jpg?style=' + encodeURIComponent(style) + '&t=' + lastImageAt; $('#frame').alt = styleName(style) + ' live clock preview'}
}
+// On the demo: the one command that puts the face and tools picked here on a real clock.
+function setupCommand() {
+ const face = clockChoice || displayInfo?.style || 'arcade', parts = ['start'];
+ const picked = [...document.querySelectorAll('#get-it input[type=checkbox]:checked')].map(b => b.value);
+ const address = $('#get-address').value.trim().replace(/^https?:\/\//, '').replace(/\/+$/, '');
+ // An IPv4 address or a host name, with a port if any: letters, digits, dots, hyphens, so any shell takes it as is.
+ const valid = /^[A-Za-z0-9.-]+(:\d{1,5})?$/.test(address);
+ $('#get-address').setAttribute('aria-invalid', String(Boolean(address) && !valid));
+ if (STYLE_IDS.test(face) && face !== 'arcade') parts.push('--face', face);
+ if (picked.length && picked.length < 3) parts.push('--only', picked.join(','));
+ if (address && valid) parts.push('--device-url', address);
+ const problem = !picked.length ? 'Pick at least one tool' : address && !valid ? 'Check the clock address, e.g. 192.168.0.50' : '';
+ return {tail: parts.join(' '), problem};
+}
+const STYLE_IDS = /^[a-z][a-z0-9-]*$/;
+function paintSetup() {
+ if (!DEMO) return;
+ const {tail, problem} = setupCommand();
+ $('#get-command').textContent = problem || 'npx token-tv ' + tail;
+ $('#get-uvx').textContent = problem ? '—' : 'uvx token-tv ' + tail; $('#get-copy').disabled = Boolean(problem);
+}
+$('#get-copy').onclick = async () => {
+ const text = $('#get-command').textContent;
+ try {await navigator.clipboard.writeText(text); $('#get-copy').textContent = 'Copied'} catch {const range = document.createRange(); range.selectNodeContents($('#get-command')); getSelection().removeAllRanges(); getSelection().addRange(range); $('#get-copy').textContent = 'Press Ctrl+C'}
+ setTimeout(() => {$('#get-copy').textContent = 'Copy'}, 2000);
+};
+$('#get-it').oninput = paintSetup;
const styleName = s => s === 'retro' ? 'Pixel Retro' : s === 'retro-dual' ? 'Pixel Retro Dual' : s === 'hud' ? 'Sci-Fi HUD' : s ? s[0].toUpperCase() + s.slice(1) : 'Unknown';
let displayPolling = false;
async function refreshDisplay(forceImage = false) {if (displayPolling) return; displayPolling = true; try {const r = await fetch(DEMO ? '/demo-display.json' : '/display', {cache:'no-store'}); if (!r.ok) throw Error(); const data = await r.json(); const dirty = displayInfo && clockChoice !== displayInfo.style; displayInfo = data; if (!clockChoice || !dirty) clockChoice = data.style; const select = $('#clock-style'); if (!select.options.length) for (const s of data.styles) {const o = el('option', styleName(s)); o.value = s; select.append(o)} select.value = clockChoice; paintClock(forceImage); if (DEMO && themeData && !lastThumbFrames) {lastThumbFrames = true; paintThemes()}} catch {$('#display-state').textContent = 'Clock status unavailable'} finally {displayPolling = false}}
@@ -306,6 +334,7 @@ async function loadThemes() {try {const r = await fetch(DEMO ? '/demo-themes.jso
document.querySelectorAll('.theme-sort button').forEach(b => {b.onclick = () => {themeSort = b.dataset.sort; paintThemes()}});
$('#frame').onerror = () => {$('#display-state').textContent = 'Clock preview unavailable. Reopen to retry.'};
+if (DEMO) {$('#get-it').hidden = false; $('#apply').hidden = true; $('#clock-panel').hidden = false; $('#clock-toggle').setAttribute('aria-expanded', 'true')} // the demo opens on how to get it
$('#mascot').append(retroMascot()); buildStarfield(); tick();
update(); refreshDisplay(); loadThemes(); setInterval(update, 30000); setInterval(tick, 1000); setInterval(() => {if (!$('#clock-panel').hidden) refreshDisplay()}, 5000);
diff --git a/token_tv/web/index.html b/token_tv/web/index.html
index b978730..fecb6ba 100644
--- a/token_tv/web/index.html
+++ b/token_tv/web/index.html
@@ -64,6 +64,20 @@
<button class="control primary" id="apply" type="button" disabled>Apply to clock</button>
<p id="display-state" role="status">Loading clock status</p>
<p class="quiet">240 × 240 · The web appearance is separate from your clock style.</p>
+ <section id="get-it" class="get-it" aria-labelledby="get-it-title" hidden>
+ <div class="aside-head"><div><p class="eyebrow">Get it</p><h2 id="get-it-title">On your clock</h2></div></div>
+ <fieldset class="get-services"><legend>Your AI tools</legend>
+ <label><input type="checkbox" value="claude" checked> Claude</label>
+ <label><input type="checkbox" value="codex" checked> Codex</label>
+ <label><input type="checkbox" value="grok" checked> Grok</label>
+ </fieldset>
+ <label for="get-address">Clock address · optional</label>
+ <input id="get-address" class="control" placeholder="found on your Wi-Fi" autocomplete="off" spellcheck="false">
+ <p class="quiet">Paste this into a terminal on the computer where you use them:</p>
+ <div class="get-command"><code id="get-command">npx token-tv start</code><button id="get-copy" class="control primary" type="button">Copy</button></div>
+ <p class="quiet" id="get-note">It finds your signed-in tools and the clock, asks once to keep running when the computer starts, and opens your dashboard. No Node? <code id="get-uvx">uvx token-tv start</code></p>
+ <p class="quiet">The clock: a GeekMagic SmallTV (SD_PRO or Ultra), <a href="https://github.com/click6067-ship-it/token-tv/blob/main/docs/hardware-compatibility.md">which ones work</a>.</p>
+ </section>
</aside>
</div>
<section class="gallery" id="gallery" aria-labelledby="gallery-title">
diff --git a/token_tv/web/style.css b/token_tv/web/style.css
index 4b88d34..f8c807c 100644
--- a/token_tv/web/style.css
+++ b/token_tv/web/style.css
@@ -190,7 +190,7 @@ h1{margin:0;font:600 48px/1.04 var(--font-display);letter-spacing:-.03em;color:v
.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 label,.get-services legend{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}
@@ -198,6 +198,16 @@ h1{margin:0;font:600 48px/1.04 var(--font-display);letter-spacing:-.03em;color:v
.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)}
+.get-it{margin-top:18px;padding-top:16px;border-top:1px solid var(--line)}
+.get-services{display:flex;flex-wrap:wrap;gap:6px 14px;margin:0 0 12px;padding:0;border:0}
+.get-services legend{padding:0}
+.get-services label{display:flex;align-items:center;gap:6px;margin:0;font:600 13px/1 var(--font-label);letter-spacing:0;text-transform:none;color:var(--ink)}
+.get-it input.control{width:100%;margin-bottom:10px;font-weight:500;text-transform:none}
+.get-it input[aria-invalid=true]{border-color:var(--critical,#e5484d)}
+.get-command{display:grid;gap:8px;margin:4px 0 10px}
+.get-command code{padding:10px;border:1px solid var(--line-2);border-radius:var(--radius-control);background:var(--bg);color:var(--ink);font:500 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere;user-select:all}
+.get-it p code{font:500 11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--ink-2);overflow-wrap:anywhere}
+.get-it a{color:var(--ink-2)}
[data-theme=neon] :is(.section-label,.level-label,.more-windows summary){text-transform:none;letter-spacing:.01em;font-size:12px;font-weight:600}
[data-theme=neon] .level-label{font-family:var(--font-body);font-size:11px;font-weight:500;color:var(--ink-3)}
@@ -290,7 +300,7 @@ h1{margin:0;font:600 48px/1.04 var(--font-display);letter-spacing:-.03em;color:v
[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] .eyebrow,[data-theme=digital] .clock-panel label,[data-theme=digital] .get-services legend{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}
@@ -445,7 +455,7 @@ h1{margin:0;font:600 48px/1.04 var(--font-display);letter-spacing:-.03em;color:v
[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] .clock-panel label,[data-theme=retro] .get-services legend{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}