Skip to content

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

Release 0.3.3: Windows fixed, and Claude in the browser on a Mac (experimental)

click6067-ship-it5d7af3cf0ef6
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 0000000..8660ddc
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,76 @@
+name: Test
+
+# The tests, the npm launcher and a command TokenTV prints, on Linux, macOS and Windows: the author checks on Linux
+# only, so this is where a Mac or Windows break shows up first.
+
+on:
+ push:
+ branches: [main, "ci/**"]
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "22"
+ - if: runner.os == 'Linux'
+ run: sudo apt-get install -y -q fonts-dejavu-core
+ - run: python -m pip install -q Pillow
+ - run: python -B -m unittest discover -s tests
+
+ - name: The npm launcher from a packed copy, as `npx token-tv` runs it
+ run: |
+ npm pack --silent --pack-destination "$RUNNER_TEMP"
+ (cd "$RUNNER_TEMP" && mkdir npm && tar -xzf token-tv-*.tgz -C npm) # relative: Git Bash's tar takes D: for a host
+ node "$RUNNER_TEMP/npm/package/bin/token-tv.js" --version
+ node "$RUNNER_TEMP/npm/package/bin/token-tv.js" --version # the second run reuses the first's copy
+ if ls "$RUNNER_TEMP/npm/package" | grep -E '^build$|egg-info'; then echo "built inside the npm folder"; exit 1; fi
+
+ - name: A config in a folder with a space, and the command TokenTV prints for it
+ run: |
+ python -m pip install -q .
+ dir="$RUNNER_TEMP/Kim Minji"
+ token-tv setup --yes --codex-email [email protected] --config "$dir/config.json" | tee "$RUNNER_TEMP/setup.out"
+ next=$(sed -n 's/^Next: \(.*\) (separate.*/\1/p' "$RUNNER_TEMP/setup.out")
+ echo "running: $next"
+ eval "$next" > "$RUNNER_TEMP/next.out" 2>&1 || true # no login here: doctor says what is missing
+ cat "$RUNNER_TEMP/next.out"
+ if grep -q "No config at" "$RUNNER_TEMP/next.out"; then echo "the printed command lost the config path"; exit 1; fi
+ grep -q "[email protected]\|codex" "$RUNNER_TEMP/next.out"
+
+ - name: Sample faces render from the installed package
+ run: cd "$RUNNER_TEMP" && token-tv demo
+
+ - name: Start with the computer for real (a LaunchAgent on macOS, the Startup folder on Windows), then stop
+ if: runner.os != 'Linux'
+ run: |
+ cfg="$RUNNER_TEMP/Kim Minji/config.json"
+ token-tv autostart on --config "$cfg"
+ token-tv autostart status --config "$cfg" | tee "$RUNNER_TEMP/status.out"
+ grep -q "starts with this computer" "$RUNNER_TEMP/status.out"
+ url_file="$RUNNER_TEMP/Kim Minji/state/live.url"
+ for i in $(seq 1 60); do [ -s "$url_file" ] && curl -sf "$(cat "$url_file")/display" > "$RUNNER_TEMP/display.json" && break; sleep 2; done
+ cat "$RUNNER_TEMP/display.json"
+ grep -q '"status"' "$RUNNER_TEMP/display.json"
+ token-tv autostart off --config "$cfg"
+ sleep 5
+ if curl -sf "$(cat "$url_file" 2>/dev/null || echo http://127.0.0.1:8787)/display"; then echo "still running after off"; exit 1; fi
+ token-tv autostart status --config "$cfg" | grep -q "does not start"
diff --git a/README.ko.md b/README.ko.md
index c1e06ff..3a550cc 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -16,7 +16,7 @@
**필요한 것:**
- 컴퓨터와 같은 와이파이에 연결된 GeekMagic SmallTV 시계(SD_PRO 또는 Ultra, [호환 시계](docs/hardware-compatibility.md)).
-- Claude Code, Codex, Grok CLI 중 하나를 설치하고 로그인해 둔, 계속 켜 두는 컴퓨터. 브라우저에서 claude.ai나 chatgpt.com에 로그인한 것만으로는 안 됩니다. [Claude Code](https://code.claude.com/docs/ko/quickstart)나 Codex(`npm install -g @openai/codex`)를 설치해 같은 계정으로 로그인하세요.
+- Claude Code, Codex, Grok CLI 중 하나를 설치하고 로그인해 둔, 계속 켜 두는 컴퓨터. 브라우저에서 claude.ai나 chatgpt.com에 로그인한 것만으로는 안 됩니다. [Claude Code](https://code.claude.com/docs/ko/quickstart)나 Codex(`npm install -g @openai/codex`)를 설치해 같은 계정으로 로그인하세요. Mac이라면 브라우저의 Claude 로그인도 [CodexBar](docs/codexbar.md#claude-in-the-browser-only-on-a-mac-experimental)를 거쳐 쓸 수 있습니다(실험 단계).
- `npx`를 쓸 [Node](https://nodejs.org/). 다른 것은 필요 없습니다. Python이 필요하면 런처가 알아서 받아 옵니다.
Windows에서는 claude·codex가 로그인된 쪽(Windows 또는 WSL)에서 실행하세요. Node를 설치한 Windows에서 바로 돌리는 게 가장 간단하고, WSL은 마지막 터미널을 닫으면 곧 꺼집니다.
diff --git a/README.md b/README.md
index 8d7da91..e4bfcad 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ Your Claude and Codex usage limits (plus Grok, and Copilot or Antigravity throug
**What you need:**
- A GeekMagic SmallTV (SD_PRO or Ultra) on your Wi-Fi ([which ones work](https://github.com/click6067-ship-it/token-tv/blob/main/docs/hardware-compatibility.md)).
-- A computer that stays on, where Claude Code, Codex or the Grok CLI is installed and signed in. A claude.ai or chatgpt.com login in the browser is not enough: install [Claude Code](https://code.claude.com/docs/en/quickstart) or Codex (`npm install -g @openai/codex`) and sign in with the same account.
+- A computer that stays on, where Claude Code, Codex or the Grok CLI is installed and signed in. A claude.ai or chatgpt.com login in the browser is not enough: install [Claude Code](https://code.claude.com/docs/en/quickstart) or Codex (`npm install -g @openai/codex`) and sign in with the same account. On a Mac, Claude in the browser can do through [CodexBar](https://github.com/click6067-ship-it/token-tv/blob/main/docs/codexbar.md#claude-in-the-browser-only-on-a-mac-experimental) (experimental).
- [Node](https://nodejs.org/), for `npx`. Nothing else: the launcher brings its own Python if it needs one.
On Windows, run it on the side where your claude or codex is signed in: Windows itself with Node is simplest, and WSL stops soon after its last terminal closes.
diff --git a/docs/codexbar.md b/docs/codexbar.md
index e721534..2229db7 100644
--- a/docs/codexbar.md
+++ b/docs/codexbar.md
@@ -25,6 +25,23 @@ window, or the Gemini app's 5-hour and weekly limits); a config that still says
as Antigravity. Neither has been checked with a real account yet.
CodexBar's macOS app has not been tried.
+## Claude in the browser only, on a Mac (experimental)
+
+Signed in to claude.ai in the browser but no Claude Code? On a Mac, CodexBar can read that login's 5-hour and
+weekly limits from the browser (Safari, Chrome and its relatives, or Firefox), and TokenTV reads them from CodexBar.
+TokenTV itself never touches browser cookies. Nobody here has tried this on a real Mac yet: tell us how it goes.
+
+1. `brew install --cask codexbar`, open CodexBar and turn on Claude (usage source Auto or Web).
+2. In CodexBar: Settings > Advanced > Install CLI.
+3. In a terminal: `codexbar cookie refresh --provider claude --allow-keychain-prompt`, and allow the Keychain
+ prompt (for Safari, give the terminal Full Disk Access instead).
+4. Check `codexbar usage --provider claude --format json` shows a session and a weekly window.
+5. `npx token-tv start`: it finds CodexBar and sets up the account.
+
+What to know: the browser route uses claude.ai pages that are not a public API, so it can break until CodexBar
+catches up, and a Cloudflare check can block it. A Claude Free account has no 5-hour or weekly limit to show.
+There is no such route on Windows or Linux, and for ChatGPT in the browser CodexBar shows only Codex limits.
+
## Config
```json
diff --git a/package.json b/package.json
index 68d72e0..7c6b111 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "token-tv",
- "version": "0.3.2",
+ "version": "0.3.3",
"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 d83e61b..273fcc8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "token-tv"
-version = "0.3.2"
+version = "0.3.3"
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 03815d5..7a07fbf 100644
--- a/scripts/build_demo.py
+++ b/scripts/build_demo.py
@@ -32,19 +32,19 @@ def build(out, site):
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 = (WEB / 'index.html').read_text(encoding='utf-8')
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)
+ (out / 'index.html').write_text(html, encoding='utf-8')
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=(',', ':')))
+ (out / 'demo-snapshot.json').write_text(json.dumps(snapshot(), separators=(',', ':')), encoding='utf-8')
frames = out / 'frames'
frames.mkdir()
rendered = snapshot(time.time())
@@ -55,8 +55,8 @@ def build(out, site):
(frames / name).write_bytes(image)
paths[style] = f'/frames/{name}'
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()))
+ (out / 'demo-display.json').write_text(json.dumps(display), encoding='utf-8')
+ (out / 'demo-themes.json').write_text(json.dumps(theme_payload()), encoding='utf-8')
shutil.copy2(ROOT / 'docs' / 'images' / 'social-preview.png', out / 'og.png')
return sorted(str(p.relative_to(out)) for p in out.rglob('*') if p.is_file() and '.vercel' not in p.parts)
diff --git a/scripts/e2e_live.py b/scripts/e2e_live.py
index 7d7eba2..b5679e0 100644
--- a/scripts/e2e_live.py
+++ b/scripts/e2e_live.py
@@ -32,7 +32,7 @@ def main():
"quota_unavailable": sorted(k for k, row in snapshot["accounts"].items() if row["status"] == "quota_unavailable"),
"expected": len(snapshot["accounts"]), "all_authenticated": not pending, "updated_at": snapshot["updated_at"]}
if args.output:
- Path(args.output).write_text(json.dumps(result, indent=2))
+ Path(args.output).write_text(json.dumps(result, indent=2), encoding="utf-8")
print(json.dumps(result, indent=2))
if args.require_all and pending:
raise SystemExit(1)
diff --git a/scripts/update_theme_votes.py b/scripts/update_theme_votes.py
index 43477fc..6221045 100644
--- a/scripts/update_theme_votes.py
+++ b/scripts/update_theme_votes.py
@@ -62,7 +62,7 @@ def main():
print(text, end='')
return
temp = VOTES_PATH.with_suffix('.tmp')
- temp.write_text(text)
+ temp.write_text(text, encoding='utf-8')
temp.replace(VOTES_PATH)
print(f'Wrote {VOTES_PATH} ({sum(v["status"] == "fresh" for v in out["counts"].values())} counted now, attempt at {out["last_attempt_at"]})')
diff --git a/tests/test_antigravity.py b/tests/test_antigravity.py
index 175a9c9..a7a6df3 100644
--- a/tests/test_antigravity.py
+++ b/tests/test_antigravity.py
@@ -59,21 +59,21 @@ class AntigravityTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'config.json'
account = {'key': 'anti_a', 'alias': 'ANTI A', 'provider': 'antigravity', 'email': '[email protected]'}
- path.write_text(json.dumps({'accounts': [account]}))
+ path.write_text(json.dumps({'accounts': [account]}), encoding='utf-8')
with self.assertRaises(ValueError): # CodexBar owns the login
load_config(path)
- path.write_text(json.dumps({'accounts': [dict(account, codexbar_command='codexbar')]}))
+ path.write_text(json.dumps({'accounts': [dict(account, codexbar_command='codexbar')]}), encoding='utf-8')
loaded = load_config(path)['accounts'][0]
self.assertEqual(codexbar_entry([APP, AGY], loaded)[0], AGY) # its own entry by default
old = dict(account, provider='gemini', codexbar_command='codexbar', codexbar_provider='gemini')
- path.write_text(json.dumps({'accounts': [old]}))
+ path.write_text(json.dumps({'accounts': [old]}), encoding='utf-8')
loaded = load_config(path)['accounts'][0]
self.assertEqual(loaded['provider'], 'antigravity') # an old Gemini account is Anti now
self.assertEqual(codexbar_entry([APP, AGY], loaded)[0], APP)
older = dict(account, provider='gemini', codexbar_url='http://127.0.0.1:8080/usage?provider=gemini')
- path.write_text(json.dumps({'accounts': [older]}))
+ path.write_text(json.dumps({'accounts': [older]}), encoding='utf-8')
self.assertEqual(codexbar_entry([APP, AGY], load_config(path)['accounts'][0])[0], APP) # still its Gemini
- path.write_text(json.dumps({'accounts': [dict(account, codexbar_command='codexbar', codexbar_provider='cursor')]}))
+ path.write_text(json.dumps({'accounts': [dict(account, codexbar_command='codexbar', codexbar_provider='cursor')]}), encoding='utf-8')
with self.assertRaises(ValueError):
load_config(path)
@@ -96,11 +96,11 @@ class AntigravityTests(unittest.TestCase):
path = Path(directory) / 'snapshot.json'
row = {'provider': 'antigravity', 'alias': 'ANTI A', 'status': 'ok', 'fetched_at': time.time() - 30,
'windows': [w for w in normalize_codexbar(CLI)]}
- path.write_text(json.dumps({'accounts': {'anti_a': row}}))
+ path.write_text(json.dumps({'accounts': {'anti_a': row}}), encoding='utf-8')
account = {'key': 'anti_a', 'alias': 'ANTI A', 'provider': 'antigravity', 'snapshot_file': str(path)}
self.assertEqual([w['label'] for w in imported_row(account)['windows']], ['DAY'])
row.update(provider='codex', reset_credits={'count': 2, 'expires_at': 2_000_000_000})
- path.write_text(json.dumps({'accounts': {'anti_a': row}}))
+ path.write_text(json.dumps({'accounts': {'anti_a': row}}), encoding='utf-8')
self.assertEqual(imported_row(dict(account, provider='codex'))['reset_credits'], {'count': 2, 'expires_at': 2_000_000_000})
def test_old_names_keep_their_letter_and_full_counts_its_streak(self):
diff --git a/tests/test_autostart.py b/tests/test_autostart.py
index c988923..52062a8 100644
--- a/tests/test_autostart.py
+++ b/tests/test_autostart.py
@@ -1,3 +1,4 @@
+import sys
import tempfile
import unittest
from pathlib import Path
@@ -54,15 +55,15 @@ class AutostartTests(unittest.TestCase):
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)
+ (self.folder / 'token-tv.service').write_text(working, encoding='utf-8')
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)
+ self.assertEqual((self.folder / 'token-tv.service').read_text(encoding='utf-8'), 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'))
+ (self.folder / 'token-tv.service').write_text(autostart.entry(['/py', '-m', 'token_tv', 'start'], 'systemd'), encoding='utf-8')
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):
@@ -72,8 +73,8 @@ class AutostartTests(unittest.TestCase):
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'))
+ (self.folder / 'state' / 'live.pid').write_text('4242', encoding='utf-8')
+ (self.folder / 'TokenTV.vbs').write_text(autostart.entry(['pythonw', '-m', 'token_tv', 'start', '--config', str(config)], 'startup'), encoding='utf-8')
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())
@@ -83,8 +84,8 @@ class AutostartTests(unittest.TestCase):
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'))
+ (self.folder / 'state' / 'live.pid').write_text('4242', encoding='utf-8')
+ (self.folder / 'TokenTV.vbs').write_text(autostart.entry(['pythonw', '-m', 'token_tv', 'start', '--config', str(config)], 'startup'), encoding='utf-8')
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())
@@ -111,11 +112,12 @@ class AutostartTests(unittest.TestCase):
self.assertEqual(autostart.how(), 'token-tv')
with mock.patch('sys.prefix', '/proj/.venv'), mock.patch('shutil.which', return_value=None), \
mock.patch.object(autostart.Path, 'exists', return_value=True):
- self.assertEqual(autostart.how(), '/proj/.venv/bin/token-tv') # a venv not on PATH: its full path
+ folder = 'Scripts' if sys.platform == 'win32' else 'bin'
+ self.assertEqual(autostart.how(), str(Path('/proj/.venv') / folder / 'token-tv')) # a venv not on PATH: its full path
def test_on_status_off_with_systemd(self):
config = self.folder / 'config.json'
- config.write_text('{}')
+ config.write_text('{}', encoding='utf-8')
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')
@@ -128,14 +130,14 @@ class AutostartTests(unittest.TestCase):
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')
+ foreign.write_text('[Service]\nExecStart=/opt/mine\n', encoding='utf-8')
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')
+ self.assertEqual(foreign.read_text(encoding='utf-8'), '[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')
diff --git a/tests/test_catalog.py b/tests/test_catalog.py
index be13239..d4dcdcc 100644
--- a/tests/test_catalog.py
+++ b/tests/test_catalog.py
@@ -104,7 +104,7 @@ class CatalogTest(unittest.TestCase):
def test_corrupt_vote_file_means_unavailable_not_zero(self):
path = Path(tempfile.mkdtemp()) / 'votes.json'
- path.write_text('{"counts": ')
+ path.write_text('{"counts": ', encoding='utf-8')
votes = catalog.load_votes(path)
self.assertEqual(votes['counts'], {})
self.assertIsNone(votes['last_attempt_at'])
@@ -114,7 +114,7 @@ class CatalogTest(unittest.TestCase):
path.write_text(json.dumps({'last_attempt_at': 'yesterday', 'counts': {
'11': {'count': 5, 'status': 'fresh', 'fetched_at': 'not a time'}, # unreadable -> unavailable
'12': {'count': 5, 'status': 'fresh'}, # fresh without time -> unavailable
- '14': {'count': 7, 'status': 'stale'}}})) # old count, time unknown
+ '14': {'count': 7, 'status': 'stale'}}}), encoding='utf-8') # old count, time unknown
votes = catalog.load_votes(path)
self.assertIsNone(votes['last_attempt_at'])
themes = {t['id']: t for t in listed(votes=votes)['themes']}
@@ -131,7 +131,7 @@ class CatalogTest(unittest.TestCase):
self.assertEqual((mine['local'], mine['needs_update']), (True, False))
def test_bundled_catalog_matches_installed_faces(self):
- data = catalog.validate_catalog(json.loads(catalog.CATALOG_PATH.read_text()))
+ data = catalog.validate_catalog(json.loads(catalog.CATALOG_PATH.read_text(encoding='utf-8')))
self.assertLessEqual({t['id'] for t in data['themes']}, set(STYLES)) # a fork may add Local faces
# Existing public issues stay mapped; new faces have no voting issue yet.
self.assertEqual({t['id']: t['like_issue'] for t in data['themes']},
@@ -148,7 +148,7 @@ class CatalogTest(unittest.TestCase):
self.assertEqual({t['id'] for t in data['themes'] if t['local']}, set(STYLES))
def test_package_version_matches_pyproject(self):
- self.assertIn(f'version = "{__version__}"', (ROOT / 'pyproject.toml').read_text())
+ self.assertIn(f'version = "{__version__}"', (ROOT / 'pyproject.toml').read_text(encoding='utf-8'))
class RefreshTest(unittest.TestCase):
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 9575043..520ba80 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -2,6 +2,7 @@ import contextlib
import io
import json
import os
+import sys
import tempfile
import unittest
from pathlib import Path
@@ -29,16 +30,16 @@ class CliTest(unittest.TestCase):
code, out, _ = run('setup', '--config', str(self.config), '--yes',
'--claude-email', '[email protected]', '--device-url', 'http://10.0.0.9/')
self.assertEqual(code, 0)
- data = json.loads(self.config.read_text())
+ data = json.loads(self.config.read_text(encoding='utf-8'))
self.assertEqual(data['device_url'], 'http://10.0.0.9')
self.assertEqual(data['accounts'][0], {'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude',
'email': '[email protected]', 'source_home': '~/.claude'})
sources.load_config(self.config) # the daemon accepts what setup writes
- before = self.config.read_text()
+ before = self.config.read_text(encoding='utf-8')
code, _, err = run('setup', '--config', str(self.config), '--yes', '--codex-email', '[email protected]')
self.assertEqual(code, 1)
self.assertIn('never overwrites', err)
- self.assertEqual(self.config.read_text(), before)
+ self.assertEqual(self.config.read_text(encoding='utf-8'), before)
def test_setup_without_accounts_fails_and_writes_nothing(self):
code, _, err = run('setup', '--config', str(self.config), '--yes')
@@ -50,13 +51,13 @@ class CliTest(unittest.TestCase):
home = self.tmp / 'codex-home'
self.config.write_text(json.dumps({'accounts': [
{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex', 'email': '[email protected]',
- 'source_home': str(home)}]}))
+ 'source_home': str(home)}]}), encoding='utf-8')
with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/codex'):
code, out, _ = run('doctor', '--config', str(self.config))
self.assertEqual(code, 1)
self.assertIn('token-tv connect --config', out)
home.mkdir()
- (home / 'auth.json').write_text('{}') # existence only; doctor never opens it
+ (home / 'auth.json').write_text('{}', encoding='utf-8') # existence only; doctor never opens it
code, out, _ = run('doctor', '--config', str(self.config))
self.assertEqual(code, 0)
self.assertIn('not verified', out)
@@ -77,7 +78,7 @@ class CliTest(unittest.TestCase):
def test_doctor_never_calls_an_unchecked_keychain_ready(self):
self.config.write_text(json.dumps({'accounts': [
{'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]',
- 'source_home': str(self.tmp / 'empty')}]}))
+ 'source_home': str(self.tmp / 'empty')}]}), encoding='utf-8')
with mock.patch.object(cli, 'cli_path', return_value='/usr/bin/claude'), \
mock.patch.object(cli.sys, 'platform', 'darwin'):
code, out, _ = run('doctor', '--config', str(self.config))
@@ -87,7 +88,7 @@ class CliTest(unittest.TestCase):
def test_doctor_checks_codexbar_instead_of_a_login_file(self):
self.config.write_text(json.dumps({'accounts': [
{'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]',
- 'codexbar_command': str(self.tmp / 'missing-codexbar'), 'codexbar_source': 'oauth'}]}))
+ 'codexbar_command': str(self.tmp / 'missing-codexbar'), 'codexbar_source': 'oauth'}]}), encoding='utf-8')
code, out, _ = run('doctor', '--config', str(self.config))
self.assertEqual(code, 1)
self.assertIn('install the CodexBar CLI', out)
@@ -104,7 +105,7 @@ class CliTest(unittest.TestCase):
self.assertIn('live check ERROR', out)
def test_broken_config_gets_a_sentence_not_a_traceback(self):
- self.config.write_text('{"accounts": [')
+ self.config.write_text('{"accounts": [', encoding='utf-8')
for command in ('doctor', 'run'):
code, _, err = run(command, '--config', str(self.config))
self.assertEqual(code, 1)
@@ -114,7 +115,7 @@ class CliTest(unittest.TestCase):
code, out, _ = run('setup', '--config', str(self.config), '--yes',
'--codex-email', '[email protected]', '--codex-email', '[email protected]')
self.assertEqual(code, 0)
- a, b = json.loads(self.config.read_text())['accounts']
+ a, b = json.loads(self.config.read_text(encoding='utf-8'))['accounts']
self.assertEqual((a['key'], a['source_home']), ('codex_a', '~/.codex'))
self.assertEqual((b['key'], b['alias'], b['source_home']),
('codex_b', 'CODEX B', str(self.tmp / 'homes' / 'codex_b')))
@@ -123,7 +124,7 @@ class CliTest(unittest.TestCase):
def test_setup_isolate_never_points_at_the_everyday_home(self):
run('setup', '--config', str(self.config), '--yes', '--isolate', '--claude-email', '[email protected]')
- self.assertNotEqual(json.loads(self.config.read_text())['accounts'][0]['source_home'], '~/.claude')
+ self.assertNotEqual(json.loads(self.config.read_text(encoding='utf-8'))['accounts'][0]['source_home'], '~/.claude')
def test_bad_clock_address_is_rejected_before_writing(self):
for bad in ('ftp://clock', 'http://', 'http://clock/photo', 'http://clock:99999'):
@@ -134,7 +135,7 @@ class CliTest(unittest.TestCase):
self.assertEqual(cli.device_address('http://10.0.0.9:8080/'), 'http://10.0.0.9:8080')
code, _, _ = run('setup', '--config', str(self.config), '--yes', '--claude-email', '[email protected]',
'--device-url', '192.168.0.50') # a bare address, as start takes it
- self.assertEqual((code, json.loads(self.config.read_text())['device_url']), (0, 'http://192.168.0.50'))
+ self.assertEqual((code, json.loads(self.config.read_text(encoding='utf-8'))['device_url']), (0, 'http://192.168.0.50'))
def test_doctor_without_config_points_to_start(self):
code, _, err = run('doctor', '--config', str(self.config))
@@ -188,11 +189,11 @@ class ConnectGuardTest(unittest.TestCase):
from token_tv import connect
home = Path(tempfile.mkdtemp())
(home / '.codex').mkdir()
- (home / '.codex' / 'auth.json').write_text('{}')
+ (home / '.codex' / 'auth.json').write_text('{}', encoding='utf-8')
config = home / 'config.json'
config.write_text(json.dumps({'accounts': [{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex',
- 'email': '[email protected]', 'source_home': '~/.codex'}]}))
- with mock.patch.dict(os.environ, {'HOME': str(home)}), \
+ 'email': '[email protected]', 'source_home': '~/.codex'}]}), encoding='utf-8')
+ with mock.patch.dict(os.environ, {'HOME': str(home), 'USERPROFILE': str(home)}), \
mock.patch.object(connect.subprocess, 'run') as login, \
mock.patch.object(connect.sys, 'argv', ['connect', '--config', str(config), '--account', 'codex_a']):
out = io.StringIO()
@@ -206,7 +207,7 @@ class ConnectGuardTest(unittest.TestCase):
home = Path(tempfile.mkdtemp()) # no ~/.claude/.credentials.json at all
config = home / 'config.json'
config.write_text(json.dumps({'accounts': [{'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude',
- 'email': '[email protected]', 'source_home': '~/.claude'}]}))
+ 'email': '[email protected]', 'source_home': '~/.claude'}]}), encoding='utf-8')
with mock.patch.dict(os.environ, {'HOME': str(home)}), \
mock.patch.object(connect.sys, 'platform', 'darwin'), \
mock.patch.object(connect.subprocess, 'run') as login, \
@@ -223,11 +224,11 @@ class AddTest(unittest.TestCase):
from token_tv import connect
config = Path(tempfile.mkdtemp()) / 'config.json'
config.write_text(json.dumps({'accounts': [{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex',
- 'email': '[email protected]', 'source_home': '~/.codex'}]}))
+ 'email': '[email protected]', 'source_home': '~/.codex'}]}), encoding='utf-8')
with mock.patch.object(connect, 'main') as login:
code, out, _ = run('add', 'codex', '--email', '[email protected]', '--config', str(config))
self.assertEqual(code, 0)
- added = json.loads(config.read_text())['accounts'][1]
+ added = json.loads(config.read_text(encoding='utf-8'))['accounts'][1]
self.assertEqual((added['key'], added['alias'], added['email']), ('codex_b', 'CODEX B', '[email protected]'))
self.assertEqual(added['source_home'], str(config.parent / 'homes' / 'codex_b')) # the everyday login untouched
login.assert_called_once()
@@ -240,9 +241,9 @@ class ConfigWriteTest(unittest.TestCase):
def test_a_change_from_the_command_line_keeps_what_the_running_copy_saved_meanwhile(self):
config = Path(tempfile.mkdtemp()) / 'config.json'
stale = {'display_style': 'pixel', 'accounts': []}
- config.write_text(json.dumps(dict(stale, display_style='neon'))) # the dashboard switched to neon
+ config.write_text(json.dumps(dict(stale, display_style='neon')), encoding='utf-8') # the dashboard switched to neon
cli.save_clock(config, dict(stale), '192.168.0.9')
- saved = json.loads(config.read_text())
+ saved = json.loads(config.read_text(encoding='utf-8'))
self.assertEqual((saved['display_style'], saved['device_url']), ('neon', 'http://192.168.0.9'))
def test_printed_commands_carry_a_custom_config(self):
@@ -293,7 +294,7 @@ class StartTest(unittest.TestCase):
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())
+ data = json.loads(self.config.read_text(encoding='utf-8'))
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()
@@ -301,23 +302,23 @@ class StartTest(unittest.TestCase):
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.assertNotIn('device_url', json.loads(self.config.read_text(encoding='utf-8')))
self.assertIn('No clock found', out)
def test_started_again_by_hand_it_looks_for_the_clock_but_never_on_its_own(self):
self.start() # set up with no clock
- self.assertNotIn('device_url', json.loads(self.config.read_text()))
+ self.assertNotIn('device_url', json.loads(self.config.read_text(encoding='utf-8')))
self.start() # --yes, as the computer starts it: a lone clock on a shared Wi-Fi may be someone else's
self.scan.assert_not_called()
with mock.patch('sys.stdin.isatty', return_value=True), mock.patch('builtins.input', return_value=''):
code, out, _, _, _ = self.start(found=['http://192.168.0.77'], already=True, yes=False)
self.assertEqual(code, 0)
- self.assertEqual(json.loads(self.config.read_text())['device_url'], 'http://192.168.0.77')
+ self.assertEqual(json.loads(self.config.read_text(encoding='utf-8'))['device_url'], 'http://192.168.0.77')
self.assertIn('Found a clock at 192.168.0.77', out)
def test_an_https_address_is_kept_as_the_http_the_clock_speaks(self):
self.start('--device-url', 'https://192.168.0.50')
- self.assertEqual(json.loads(self.config.read_text())['device_url'], 'http://192.168.0.50')
+ self.assertEqual(json.loads(self.config.read_text(encoding='utf-8'))['device_url'], 'http://192.168.0.50')
def test_an_address_given_is_not_searched_for(self):
self.start('--device-url', '192.168.0.50')
@@ -327,10 +328,11 @@ class StartTest(unittest.TestCase):
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())
+ data = json.loads(self.config.read_text(encoding='utf-8'))
self.assertEqual([a['provider'] for a in data['accounts']], ['codex'])
self.assertEqual(data['display_style'], 'pixel')
+ @unittest.skipIf(sys.platform == 'win32', 'the stand-in codexbar is a script with a #! line')
def test_a_codexbar_user_is_set_up_from_what_codexbar_reads(self):
import os, stat, sys
folder = Path(tempfile.mkdtemp())
@@ -344,12 +346,12 @@ if provider == 'codex':
if provider == 'claude':
print(json.dumps([{{'provider': 'claude', 'error': {{'message': 'not signed in'}}}}])); sys.exit(1)
print(json.dumps([{{'provider': provider, 'usage': usage}}]))
-""")
+""", encoding='utf-8')
fake.chmod(fake.stat().st_mode | stat.S_IXUSR)
with mock.patch.dict(os.environ, {'PATH': f'{folder}{os.pathsep}{os.environ["PATH"]}'}):
code, out, _, _, run = self.start('--device-url', '10.0.0.5', emails={'claude': None, 'codex': None})
self.assertEqual(code, 0)
- accounts = json.loads(self.config.read_text())['accounts']
+ accounts = json.loads(self.config.read_text(encoding='utf-8'))['accounts']
self.assertEqual([(a['provider'], a['email'], a['codexbar_command']) for a in accounts],
[('codex', '[email protected]', 'codexbar'), ('copilot', 'not reported by CodexBar', 'codexbar'),
('antigravity', 'not reported by CodexBar', 'codexbar')])
@@ -362,6 +364,15 @@ print(json.dumps([{{'provider': provider, 'usage': usage}}]))
self.assertEqual(code, 1)
self.assertIn('install CodexBar', err)
+ def test_on_a_mac_a_browser_only_claude_user_is_told_about_codexbar(self):
+ with mock.patch('sys.platform', 'darwin'), mock.patch('shutil.which', return_value=None):
+ code, _, err, _, _ = self.start(emails={'claude': None, 'codex': None})
+ self.assertEqual(code, 1)
+ self.assertIn('Claude in the browser only, on a Mac', err)
+ with mock.patch('sys.platform', 'linux'), mock.patch('shutil.which', return_value=None):
+ _, _, err, _, _ = self.start(emails={'claude': None, 'codex': None})
+ self.assertNotIn('on a Mac', err)
+
def test_only_a_service_not_signed_in_says_which(self):
code, _, err, _, run = self.start('--only', 'codex')
self.assertEqual(code, 1)
@@ -371,12 +382,12 @@ print(json.dumps([{{'provider': provider, 'usage': usage}}]))
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'])
+ self.assertEqual([a['provider'] for a in json.loads(self.config.read_text(encoding='utf-8'))['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'}]}))
+ {'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]', 'source_home': '~/.claude'}]}), encoding='utf-8')
code, _, err, _, _ = self.start('--only', 'codex', already=True)
self.assertEqual(code, 1)
self.assertIn('claude as well', err)
@@ -408,7 +419,7 @@ print(json.dumps([{{'provider': provider, 'usage': usage}}]))
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')
+ self.assertEqual(json.loads(self.config.read_text(encoding='utf-8'))['display_style'], 'neon')
run.assert_called_once()
def test_already_running_opens_it_and_starts_no_second_copy(self):
@@ -466,7 +477,7 @@ print(json.dumps([{{'provider': provider, 'usage': usage}}]))
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'}]}))
+ {'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex', 'email': '[email protected]', 'source_home': '~/.codex'}]}), encoding='utf-8')
code, _, err, _, run = self.start('--only', 'codex')
self.assertEqual(code, 1)
self.assertIn('claude as well', err)
@@ -475,14 +486,14 @@ print(json.dumps([{{'provider': provider, 'usage': usage}}]))
def test_detects_signed_in_email_and_runs(self):
code, out, _, detect, run = self.start('--device-url', '192.168.0.50')
self.assertEqual(code, 0)
- data = json.loads(self.config.read_text())
+ data = json.loads(self.config.read_text(encoding='utf-8'))
self.assertEqual([(a['provider'], a['email']) for a in data['accounts']], [('claude', '[email protected]')])
self.assertEqual(data['device_url'], 'http://192.168.0.50') # bare IP is accepted
run.assert_called_once()
def test_existing_config_skips_detection(self):
self.config.write_text(json.dumps({'accounts': [{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex',
- 'email': '[email protected]', 'source_home': '~/.codex'}]}))
+ 'email': '[email protected]', 'source_home': '~/.codex'}]}), encoding='utf-8')
code, _, _, detect, run = self.start()
self.assertEqual(code, 0)
detect.assert_not_called()
@@ -491,7 +502,7 @@ print(json.dumps([{{'provider': provider, 'usage': usage}}]))
def saved_config(self, device_url):
config = {'device_url': device_url, 'accounts': [{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex',
'email': '[email protected]', 'source_home': '~/.codex'}]}
- self.config.write_text(json.dumps(config))
+ self.config.write_text(json.dumps(config), encoding='utf-8')
return config
def test_a_clock_address_given_later_is_kept_in_the_config(self):
@@ -500,11 +511,11 @@ print(json.dumps([{{'provider': provider, 'usage': usage}}]))
code, out, _, _, run = self.start('--device-url', '192.168.0.77')
self.assertEqual(code, 0)
self.assertIn('http://192.168.0.77', out)
- self.assertEqual(json.loads(self.config.read_text())['device_url'], 'http://192.168.0.77')
+ self.assertEqual(json.loads(self.config.read_text(encoding='utf-8'))['device_url'], 'http://192.168.0.77')
run.assert_called_once()
- self.config.write_text(json.dumps({'accounts': json.loads(self.config.read_text())['accounts']})) # no clock yet
+ self.config.write_text(json.dumps({'accounts': json.loads(self.config.read_text(encoding='utf-8'))['accounts']})) # no clock yet
code, _, _, _, run = self.start('--device-url', '10.0.0.9', already=True) # while one runs: it takes it up
- self.assertEqual((code, json.loads(self.config.read_text())['device_url']), (0, 'http://10.0.0.9'))
+ self.assertEqual((code, json.loads(self.config.read_text(encoding='utf-8'))['device_url']), (0, 'http://10.0.0.9'))
code, _, err, _, _ = self.start('--device-url', 'ftp://nope')
self.assertEqual(code, 1)
diff --git a/tests/test_codexbar.py b/tests/test_codexbar.py
index b077fc0..a027de3 100644
--- a/tests/test_codexbar.py
+++ b/tests/test_codexbar.py
@@ -18,7 +18,7 @@ FIXTURES = Path(__file__).parent / "fixtures" / "codexbar"
def fixture(name):
- return json.loads((FIXTURES / name).read_text())
+ return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
def ran(stdout, code=0):
@@ -64,7 +64,7 @@ class NormalizeTests(unittest.TestCase):
class FetchTests(unittest.TestCase):
def test_cli_command_line_and_row(self):
- stdout = (FIXTURES / "usage-claude-oauth.json").read_text()
+ stdout = (FIXTURES / "usage-claude-oauth.json").read_text(encoding="utf-8")
with patch("token_tv.sources.subprocess.run", return_value=ran(stdout)) as run:
row = fetch_account(CLAUDE)
command = run.call_args.args[0]
@@ -76,7 +76,7 @@ class FetchTests(unittest.TestCase):
self.assertFalse(row["identity_verified"])
def test_source_flag_is_omitted_unless_configured(self):
- stdout = (FIXTURES / "usage-codex.json").read_text()
+ stdout = (FIXTURES / "usage-codex.json").read_text(encoding="utf-8")
with patch("token_tv.sources.subprocess.run", return_value=ran(stdout)) as run:
row = fetch_account(CODEX)
self.assertNotIn("--source", run.call_args.args[0])
@@ -86,14 +86,14 @@ class FetchTests(unittest.TestCase):
def test_source_home_scopes_the_cli_home(self):
account = dict(CODEX, source_home="/explicit/codex-home")
with patch.dict("os.environ", {"OPENAI_API_KEY": "DO-NOT-INHERIT"}), \
- patch("token_tv.sources.subprocess.run", return_value=ran((FIXTURES / "usage-codex.json").read_text())) as run:
+ patch("token_tv.sources.subprocess.run", return_value=ran((FIXTURES / "usage-codex.json").read_text(encoding="utf-8"))) as run:
fetch_account(account)
env = run.call_args.kwargs["env"]
- self.assertEqual(env["CODEX_HOME"], "/explicit/codex-home")
+ self.assertEqual(env["CODEX_HOME"], str(Path("/explicit/codex-home")))
self.assertNotIn("OPENAI_API_KEY", env)
def test_reported_email_must_match(self):
- stdout = (FIXTURES / "usage-codex.json").read_text()
+ stdout = (FIXTURES / "usage-codex.json").read_text(encoding="utf-8")
with patch("token_tv.sources.subprocess.run", return_value=ran(stdout)):
row = fetch_account(dict(CODEX, email="[email protected]"))
self.assertEqual((row["status"], row["windows"]), ("identity_mismatch", []))
@@ -123,7 +123,7 @@ class FetchTests(unittest.TestCase):
self.assertEqual(store.snapshot()["accounts"]["claude_d"]["session_percent"], 8.0)
def test_failed_provider_keeps_no_numbers_and_no_message(self):
- stdout = (FIXTURES / "usage-claude-cli-error.json").read_text()
+ stdout = (FIXTURES / "usage-claude-cli-error.json").read_text(encoding="utf-8")
with patch("token_tv.sources.subprocess.run", return_value=ran(stdout, 1)):
row = fetch_account(dict(CLAUDE, codexbar_source="cli"))
self.assertEqual((row["status"], row["error_code"], row["windows"]), ("error", "codexbar_provider", []))
@@ -180,13 +180,13 @@ class FetchTests(unittest.TestCase):
self.assertEqual(row["status"], "identity_mismatch")
def test_provider_absent_from_output(self):
- with patch("token_tv.sources.subprocess.run", return_value=ran((FIXTURES / "usage-codex.json").read_text())):
+ with patch("token_tv.sources.subprocess.run", return_value=ran((FIXTURES / "usage-codex.json").read_text(encoding="utf-8"))):
row = fetch_account(CLAUDE)
self.assertEqual((row["status"], row["error_code"]), ("error", "codexbar_provider_missing"))
def test_store_and_clock_render_from_real_output(self):
- outputs = {"claude": (FIXTURES / "usage-claude-oauth.json").read_text(),
- "codex": (FIXTURES / "usage-codex.json").read_text()}
+ outputs = {"claude": (FIXTURES / "usage-claude-oauth.json").read_text(encoding="utf-8"),
+ "codex": (FIXTURES / "usage-codex.json").read_text(encoding="utf-8")}
def fake(command, **kwargs):
return ran(outputs[command[command.index("--provider") + 1]])
store = UsageStore([CLAUDE, CODEX])
@@ -206,7 +206,7 @@ class ConfigTests(unittest.TestCase):
base = {"key": "a", "alias": "A", "provider": "claude", "email": "[email protected]"}
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "config.json"
- path.write_text(json.dumps({"accounts": [dict(base, **account)]}))
+ path.write_text(json.dumps({"accounts": [dict(base, **account)]}), encoding="utf-8")
return load_config(path)
def test_accepts_cli_or_url_for_verified_providers(self):
diff --git a/tests/test_copilot.py b/tests/test_copilot.py
index c7596a2..a9503ad 100644
--- a/tests/test_copilot.py
+++ b/tests/test_copilot.py
@@ -29,10 +29,10 @@ class CopilotTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'config.json'
account = {'key': 'copilot_a', 'alias': 'COPILOT A', 'provider': 'copilot', 'email': '[email protected]'}
- path.write_text(json.dumps({'accounts': [account]}))
+ path.write_text(json.dumps({'accounts': [account]}), encoding='utf-8')
with self.assertRaises(ValueError):
load_config(path)
- path.write_text(json.dumps({'accounts': [dict(account, codexbar_command='codexbar')]}))
+ path.write_text(json.dumps({'accounts': [dict(account, codexbar_command='codexbar')]}), encoding='utf-8')
self.assertEqual(load_config(path)['accounts'][0]['provider'], 'copilot')
def test_every_face_draws_a_copilot_row_and_its_scene_moves(self):
diff --git a/tests/test_device.py b/tests/test_device.py
index b6d6847..f734cc6 100644
--- a/tests/test_device.py
+++ b/tests/test_device.py
@@ -509,7 +509,7 @@ class UltraTests(unittest.TestCase):
def test_mismatched_backup_is_kept_and_the_clock_is_not_touched(self):
with tempfile.TemporaryDirectory() as folder, serve(ultra_clock(self.state, self.calls)) as url:
backup = Path(folder) / "display-original.json"
- backup.write_text(json.dumps(SD_PRO_BACKUP))
+ backup.write_text(json.dumps(SD_PRO_BACKUP), encoding="utf-8")
saved = backup.read_bytes()
display = open_display(url)
# Live cycle: refuse before any capture, upload or new backup.
@@ -518,7 +518,7 @@ class UltraTests(unittest.TestCase):
# --restore-display: a clear message instead of a KeyError traceback.
config = Path(folder) / "config.json"
config.write_text(json.dumps({"device_url": url, "accounts": [
- {"key": "claude", "alias": "Claude", "provider": "claude", "email": "[email protected]"}]}))
+ {"key": "claude", "alias": "Claude", "provider": "claude", "email": "[email protected]"}]}), encoding="utf-8")
with patch("sys.argv", ["token-tv", "--config", str(config), "--state-dir", folder, "--restore-display"]):
with self.assertRaises(SystemExit) as stop:
live.main()
@@ -534,13 +534,13 @@ class UltraTests(unittest.TestCase):
backup = Path(folder) / "display-original.json"
display = open_display(url)
self.assertEqual(live.load_original(display, backup), ULTRA_BACKUP)
- self.assertEqual(json.loads(backup.read_text()), ULTRA_BACKUP)
+ self.assertEqual(json.loads(backup.read_text(encoding="utf-8")), ULTRA_BACKUP)
self.state["theme"] = 3
start = len(self.calls)
self.assertEqual(live.load_original(display, backup), ULTRA_BACKUP)
self.assertEqual(self.calls[start:], [])
# SD_PRO backups have no model key and keep working unchanged.
- backup.write_text(json.dumps(SD_PRO_BACKUP))
+ backup.write_text(json.dumps(SD_PRO_BACKUP), encoding="utf-8")
self.assertEqual(live.load_original(PhotoDisplay(url), backup), SD_PRO_BACKUP)
self.assertEqual(self.calls[start:], [])
diff --git a/tests/test_display_styles.py b/tests/test_display_styles.py
index 392e1a7..156e9b9 100644
--- a/tests/test_display_styles.py
+++ b/tests/test_display_styles.py
@@ -29,7 +29,7 @@ class DisplayStyleTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'config.json'
config = {'accounts': [account], 'display_style': 'pixel'}
- path.write_text(json.dumps(config))
+ path.write_text(json.dumps(config), encoding='utf-8')
prefs = DisplayPreferences(path, config)
server = ThreadingHTTPServer(('127.0.0.1', 0), handler(store, prefs))
thread = threading.Thread(target=server.serve_forever)
@@ -102,7 +102,7 @@ class DisplayStyleTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'config.json'
config = {'accounts': [{'key': 'a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]'}], 'display_style': 'unknown'}
- path.write_text(json.dumps(config))
+ path.write_text(json.dumps(config), encoding='utf-8')
with self.assertRaises(ValueError):
load_config(path)
diff --git a/tests/test_live.py b/tests/test_live.py
index 4266cf0..08bbf01 100644
--- a/tests/test_live.py
+++ b/tests/test_live.py
@@ -43,14 +43,14 @@ class LiveTests(unittest.TestCase):
def test_configuration_rejects_secret_fields(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.json"
- path.write_text(json.dumps({"accounts": [{"key": "a", "alias": "A", "provider": "claude", "password": "DO-NOT-USE"}]}))
+ path.write_text(json.dumps({"accounts": [{"key": "a", "alias": "A", "provider": "claude", "password": "DO-NOT-USE"}]}), encoding="utf-8")
with self.assertRaises(ValueError):
load_config(path)
def test_grok_owner_identity_must_match_expected_email(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "auth.json"
- path.write_text(json.dumps({"issuer::client": {"email": "[email protected]", "key": "NEVER-EXPORT", "refresh_token": "NEVER-EXPORT"}}))
+ path.write_text(json.dumps({"issuer::client": {"email": "[email protected]", "key": "NEVER-EXPORT", "refresh_token": "NEVER-EXPORT"}}), encoding="utf-8")
self.assertEqual(grok_identity({"source_home": directory}), "[email protected]")
account = {"key": "g", "alias": "G", "provider": "grok", "source_home": directory, "email": "[email protected]"}
with patch("token_tv.sources.grok_payload") as billing:
@@ -101,7 +101,7 @@ class LiveTests(unittest.TestCase):
path = Path(directory) / "bridge.json"
row = {"key": "a", "alias": "A", "provider": "claude", "status": "ok", "fetched_at": time.time(), "identity_verified": True,
"windows": [{"label": "WEEK", "used_percent": 31, "resets_at": None, "duration_minutes": 10080}]}
- path.write_text(json.dumps({"accounts": {"a": row}}))
+ path.write_text(json.dumps({"accounts": {"a": row}}), encoding="utf-8")
account = {"key": "a", "alias": "A", "provider": "claude", "email": "[email protected]", "source_home": str(Path(directory)/"absent"), "fallback_snapshot_file": str(path)}
actual = fetch_account(account)
self.assertEqual(actual["source"], "laptop")
@@ -260,8 +260,8 @@ class GuardTests(unittest.TestCase):
def test_a_lock_folder_it_cannot_write_is_no_reason_to_stop(self):
import contextlib, io, os, tempfile
from token_tv import live
- if hasattr(os, 'geteuid') and os.geteuid() == 0:
- self.skipTest('root writes anywhere')
+ if hasattr(os, 'geteuid') and os.geteuid() == 0 or os.name == 'nt':
+ self.skipTest('root writes anywhere, and Windows has no read-only folders')
folder = Path(tempfile.mkdtemp())
folder.chmod(0o555) # another account's folder, say
self.addCleanup(folder.chmod, 0o755)
diff --git a/tests/test_lockbox.py b/tests/test_lockbox.py
index a15eacb..c597270 100644
--- a/tests/test_lockbox.py
+++ b/tests/test_lockbox.py
@@ -37,7 +37,7 @@ class LockboxTests(unittest.TestCase):
lockbox.seal(salt, {'codex:crossed_70'}, content('jump'), chance=1, cooldown_days=7),
lockbox.seal(salt, {'codex:active'}, content('legendary', 'legend'), chance=1, cooldown_days=28),
lockbox.seal(salt, {'weekend=yes'}, content('maybe'), chance=.05, cooldown_days=7)]
- self.bundle.write_text(json.dumps({'salt': salt.hex(), 'boxes': boxes}))
+ self.bundle.write_text(json.dumps({'salt': salt.hex(), 'boxes': boxes}), encoding='utf-8')
self.rolls = []
self.box = lambda: lockbox.Lockbox(Path(self.dir.name) / 'history.json', self.bundle,
roll=lambda: self.rolls.pop(0) if self.rolls else 0.0)
@@ -51,7 +51,7 @@ class LockboxTests(unittest.TestCase):
return out
def test_the_bundle_says_nothing_readable_about_what_opens_a_box(self):
- text = self.bundle.read_text()
+ text = self.bundle.read_text(encoding='utf-8')
for word in ('hour', 'minute', 'jump', 'late', 'legendary', 'codex'):
self.assertNotIn(word, text)
@@ -117,7 +117,7 @@ class LockboxTests(unittest.TestCase):
salt = b'0123456789abcdef'
boxes = [lockbox.seal(salt, {'claude:idle'}, content('one', 'rare'), chance=.5, cooldown_days=3),
lockbox.seal(salt, {'codex:idle'}, content('two', 'rare'), chance=.5, cooldown_days=3)]
- self.bundle.write_text(json.dumps({'salt': salt.hex(), 'boxes': boxes}))
+ self.bundle.write_text(json.dumps({'salt': salt.hex(), 'boxes': boxes}), encoding='utf-8')
locks = self.box()
now = at(12)
data = snapshot(now, [('claude_a', 'A', 'claude', [('WEEK', 50, 3 * D)]), ('codex_a', 'B', 'codex', [('WEEK', 50, 3 * D)])])
@@ -196,8 +196,8 @@ class LockboxTests(unittest.TestCase):
locks.pick(self.data(at(10, 7)), at(10, 7))
check = locks.collection()['found'][0]['check']
config = Path(self.dir.name) / 'config.json'
- config.write_text(json.dumps({'display_style': 'arcade', 'accounts': [{'key': 'codex_a', 'alias': 'A', 'provider': 'codex'}]}))
- preferences = live.DisplayPreferences(config, json.loads(config.read_text()))
+ config.write_text(json.dumps({'display_style': 'arcade', 'accounts': [{'key': 'codex_a', 'alias': 'A', 'provider': 'codex'}]}), encoding='utf-8')
+ preferences = live.DisplayPreferences(config, json.loads(config.read_text(encoding='utf-8')))
store = UsageStore([{'key': 'codex_a', 'alias': 'A', 'provider': 'codex'}], fetch=lambda _: None)
replays = []
server = live.QuietServer(('127.0.0.1', 0), live.handler(store, preferences, locks, replays, threading.Event()))
@@ -221,8 +221,8 @@ class LockboxTests(unittest.TestCase):
check = locks.collection()['found'][0]['check']
config = Path(self.dir.name) / 'config.json'
config.write_text(json.dumps({'display_style': 'arcade', 'device_url': 'http://127.0.0.1:9',
- 'accounts': [{'key': 'codex_a', 'alias': 'A', 'provider': 'codex'}]}))
- preferences = live.DisplayPreferences(config, json.loads(config.read_text()))
+ 'accounts': [{'key': 'codex_a', 'alias': 'A', 'provider': 'codex'}]}), encoding='utf-8')
+ preferences = live.DisplayPreferences(config, json.loads(config.read_text(encoding='utf-8')))
store = UsageStore([{'key': 'codex_a', 'alias': 'A', 'provider': 'codex'}], fetch=lambda _: None)
replays = []
server = live.QuietServer(('127.0.0.1', 0), live.handler(store, preferences, locks, replays, threading.Event()))
@@ -284,9 +284,10 @@ class FactTests(unittest.TestCase):
def test_a_reading_brings_its_news(self):
readings = [(70, 1), (85, 1), (88, 0)] # a third and fourth reading follow
- def fetch(_):
+ start = time.time() - 600
+ def fetch(_): # a minute apart, as polls are: Windows' clock can give two quick readings the same time
used, count = readings.pop(0)
- return {'key': 'a', 'alias': 'A', 'provider': 'codex', 'status': 'ok', 'fetched_at': time.time(),
+ return {'key': 'a', 'alias': 'A', 'provider': 'codex', 'status': 'ok', 'fetched_at': start + 60 * (3 - len(readings)),
'windows': [{'label': 'WEEK', 'used_percent': used, 'resets_at': None}],
'reset_credits': {'count': count, 'expires_at': time.time() + 3600}}
store = UsageStore([{'key': 'a', 'alias': 'A', 'provider': 'codex'}], fetch=fetch)
@@ -334,6 +335,7 @@ class ReviewFixTests(unittest.TestCase):
found = lockbox.facts(data, lockbox.History(Path(directory) / 'h.json'), now)['copilot_a']
self.assertFalse({'copilot:idle', 'copilot:active'} & found)
+ @unittest.skipUnless(hasattr(time, 'tzset'), 'needs time.tzset, which Windows lacks')
def test_a_streak_counts_calendar_weeks_across_a_clock_change(self):
import os
saved = os.environ.get('TZ')
@@ -354,7 +356,7 @@ class ReviewFixTests(unittest.TestCase):
@unittest.skipUnless((Path(__file__).resolve().parents[1] / 'pyproject.toml').exists(), 'a source copy without packaging')
def test_the_bundle_is_packaged(self):
- self.assertIn('"*.bin"', (Path(__file__).resolve().parents[1] / 'pyproject.toml').read_text())
+ self.assertIn('"*.bin"', (Path(__file__).resolve().parents[1] / 'pyproject.toml').read_text(encoding='utf-8'))
class TimingTests(unittest.TestCase):
diff --git a/tests/test_web.py b/tests/test_web.py
index 99b6486..b3208e3 100644
--- a/tests/test_web.py
+++ b/tests/test_web.py
@@ -65,10 +65,10 @@ class ThemesEndpointTests(unittest.TestCase):
spec.loader.exec_module(module)
out = Path(tempfile.mkdtemp()) / 'site'
module.build(out, 'https://example.com')
- themes = json.loads((out / 'demo-themes.json').read_text())
+ themes = json.loads((out / 'demo-themes.json').read_text(encoding='utf-8'))
from token_tv.display import STYLES
self.assertEqual({t['id'] for t in themes['themes'] if t['installed']}, set(STYLES)) # adding a face needs no test edit
- html = (out / 'index.html').read_text()
+ html = (out / 'index.html').read_text(encoding='utf-8')
self.assertIn('data-demo', html)
self.assertIn('id="gallery"', html)
self.assertNotIn('★', html) # no star request in the demo bar
@@ -78,8 +78,8 @@ class GalleryTests(unittest.TestCase):
def setUp(self):
from pathlib import Path
web = Path(__file__).resolve().parents[1] / 'token_tv' / 'web'
- self.html = (web / 'index.html').read_text()
- self.js = (web / 'app.js').read_text()
+ self.html = (web / 'index.html').read_text(encoding='utf-8')
+ self.js = (web / 'app.js').read_text(encoding='utf-8')
def test_dashboard_has_visible_gallery_with_neutral_links(self):
panel_start = self.html.index('id="clock-panel"')
diff --git a/token_tv/__init__.py b/token_tv/__init__.py
index af67b0b..934de81 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.2"
+__version__ = "0.3.3"
diff --git a/token_tv/arcade.py b/token_tv/arcade.py
index 7caadd1..2a94e91 100644
--- a/token_tv/arcade.py
+++ b/token_tv/arcade.py
@@ -131,10 +131,10 @@ def gauge(draw, x, y, width, height, used, old=False):
@functools.lru_cache(maxsize=1)
def clawd_data():
"""Clawd's animations; the hidden scenes' own few, where this copy has them, from clawd-eggs.json."""
- data = json.loads((ASSETS / 'clawd.json').read_text())
+ data = json.loads((ASSETS / 'clawd.json').read_text(encoding='utf-8'))
extra = ASSETS / 'clawd-eggs.json'
if extra.exists():
- data.update(json.loads(extra.read_text()))
+ data.update(json.loads(extra.read_text(encoding='utf-8')))
return data
diff --git a/token_tv/autostart.py b/token_tv/autostart.py
index d7be038..9f3d86a 100644
--- a/token_tv/autostart.py
+++ b/token_tv/autostart.py
@@ -121,9 +121,14 @@ def xml(text):
return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
+def read(path):
+ data = path.read_bytes()
+ return data.decode('utf-16' if data[:2] in (b'\xff\xfe', b'\xfe\xff') else 'utf-8', errors='replace')
+
+
def ours(path):
try:
- return MARK in path.read_text(errors='replace')
+ return MARK in read(path)
except OSError:
return False
@@ -148,12 +153,14 @@ def install(config):
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
+ before = path.read_bytes() if path.exists() else None
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(entry(argv, kind))
+ # wscript reads a script as UTF-16 when it starts with a byte-order mark, else in the system's code page,
+ # which cannot hold every user name in a path; systemd and launchd read UTF-8.
+ path.write_text(entry(argv, kind), encoding='utf-16' if kind == 'startup' else 'utf-8')
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()
+ path.write_bytes(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],
@@ -197,7 +204,7 @@ def remove():
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')
+ text = read(path)
path.unlink()
if kind == 'systemd':
run(['systemctl', '--user', 'daemon-reload'])
@@ -205,7 +212,7 @@ def remove():
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())
+ pid = int(pid_file.read_text(encoding='utf-8'))
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)
diff --git a/token_tv/bridge.py b/token_tv/bridge.py
index 988d771..81572d0 100644
--- a/token_tv/bridge.py
+++ b/token_tv/bridge.py
@@ -13,7 +13,7 @@ p=pathlib.Path(sys.argv[1]).expanduser()
data=json.load(sys.stdin)
p.parent.mkdir(parents=True,exist_ok=True)
t=p.with_suffix('.tmp')
-t.write_text(json.dumps(data,ensure_ascii=False,separators=(',',':')))
+t.write_text(json.dumps(data,ensure_ascii=False,separators=(',',':')), encoding="utf-8")
os.chmod(t,0o600)
t.replace(p)
"""
diff --git a/token_tv/catalog.py b/token_tv/catalog.py
index a475b44..bccb37a 100644
--- a/token_tv/catalog.py
+++ b/token_tv/catalog.py
@@ -53,7 +53,7 @@ def validate_catalog(data):
def load_catalog(path=None):
- return validate_catalog(json.loads(Path(path or CATALOG_PATH).read_text()))
+ return validate_catalog(json.loads(Path(path or CATALOG_PATH).read_text(encoding='utf-8')))
def parse_time(text):
@@ -70,7 +70,7 @@ def load_votes(path=None):
A broken file, a bad count or an unreadable count time means unknown, never zero.
"""
try:
- data = json.loads(Path(path or VOTES_PATH).read_text())
+ data = json.loads(Path(path or VOTES_PATH).read_text(encoding='utf-8'))
counts = {}
for issue, value in data['counts'].items():
count, status, stamp = value.get('count'), value.get('status'), value.get('fetched_at')
diff --git a/token_tv/cli.py b/token_tv/cli.py
index 25a012f..f6c3991 100644
--- a/token_tv/cli.py
+++ b/token_tv/cli.py
@@ -137,7 +137,7 @@ def setup(args):
config['device_url'] = device
try:
path.parent.mkdir(parents=True, exist_ok=True)
- with open(path, 'x') as handle: # 'x' refuses to replace a file created meanwhile
+ with open(path, 'x', encoding='utf-8') as handle: # 'x' refuses to replace a file created meanwhile
json.dump(config, handle, indent=2)
handle.write('\n')
except OSError as error:
@@ -390,7 +390,11 @@ def start(args):
'copilot': ' Copilot: install CodexBar and sign it in (docs/codexbar.md)\n',
'antigravity': ' Antigravity: install CodexBar and sign it in (docs/codexbar.md)\n'}
codexbar = (' CodexBar: installed, but it reported no signed-in account (`codexbar usage --format json` '
- 'shows why)\n' if shutil.which('codexbar') else '')
+ 'shows why)\n' if shutil.which('codexbar') else
+ ' Claude in the browser only, on a Mac: CodexBar can read it for TokenTV (experimental):\n'
+ ' brew install --cask codexbar, open it, Settings > Advanced > Install CLI, then\n'
+ ' codexbar cookie refresh --provider claude --allow-keychain-prompt (docs/codexbar.md)\n'
+ if sys.platform == 'darwin' and (not only or 'claude' in only) else '')
print(f'No signed-in {wanted} CLI found on this computer:\n' + ''.join(f' {r}\n' for r in reasons) +
'TokenTV reads your limits through the official command-line tools; signing in on claude.ai or\n'
'chatgpt.com in a browser is not enough.\n' +
@@ -411,7 +415,7 @@ def start(args):
if device:
config['device_url'] = device
path.parent.mkdir(parents=True, exist_ok=True)
- with open(path, 'x') as handle:
+ with open(path, 'x', encoding='utf-8') as handle:
json.dump(config, handle, indent=2)
handle.write('\n')
print(f'Saved {path} (emails and paths only, no secrets).')
@@ -472,8 +476,8 @@ def codexbar_accounts(only, have, interactive):
def ask_codexbar(provider):
account = {'provider': provider, 'codexbar_command': 'codexbar'}
- if provider == 'claude':
- account['codexbar_source'] = 'oauth' # its default fails on Linux (docs/codexbar.md)
+ if provider == 'claude' and sys.platform != 'darwin':
+ account['codexbar_source'] = 'oauth' # its default fails on Linux; on a Mac it reads the browser first
try:
data = codexbar_payload(account)
except (SourceError, OSError, subprocess.SubprocessError):
@@ -517,9 +521,9 @@ def save_clock(path, config, address):
def update_config(path, **changes):
"""Write these keys into the config as it is on disk now: a running TokenTV may have just saved another key
(the face picked on its dashboard, say), and an older copy here must not undo it."""
- current = json.loads(path.read_text())
+ current = json.loads(path.read_text(encoding='utf-8'))
current.update(changes)
- path.write_text(json.dumps(current, indent=2) + '\n')
+ path.write_text(json.dumps(current, indent=2) + '\n', encoding='utf-8')
def refuses_only(path, config, only):
@@ -564,7 +568,7 @@ def add(args):
config.setdefault('accounts', []).append({
'key': key, 'alias': f'{args.provider.upper()} {letter}', 'provider': args.provider, 'email': email,
'source_home': str(path.parent / 'homes' / key)}) # its own login; the everyday one stays as it is
- path.write_text(json.dumps(config, indent=2) + '\n')
+ path.write_text(json.dumps(config, indent=2) + '\n', encoding='utf-8')
print(f'Added {args.provider.upper()} {letter} ({email}) to {path}.')
if args.no_login:
print(f'Sign it in later with: {cmd(f"connect --account {key}")}')
diff --git a/token_tv/device.py b/token_tv/device.py
index c803747..77c1d3f 100644
--- a/token_tv/device.py
+++ b/token_tv/device.py
@@ -60,7 +60,8 @@ class PhotoDisplay:
self.free = 0 # bytes free on the clock, likewise
self.listed_at = 0 # when the list was last read
self.held = {} # slot -> (sha256, bytes) of the GIF put there and seen to arrive whole
- self.last_used = {} # slot -> when it was last shown, so the one longest unused is written next
+ self.last_used = {} # slot -> the turn it was last shown in, so the one longest unused is written next
+ self.turns = 0 # a count, not a clock: Windows' clock can give two quick switches the same time
def request(self, path, data=None, headers=None):
# Straight to the clock: it is on this network, so a proxy set for the internet must not stand between.
@@ -178,7 +179,8 @@ class PhotoDisplay:
self.active, self.sizes = None, None
raise
self.active = name
- self.last_used[name] = time.monotonic()
+ self.turns += 1
+ self.last_used[name] = self.turns
def show(self, original, name, image, digest):
"""Put a picture on the clock and make it the one shown; returns receipts for what was sent."""
@@ -322,7 +324,7 @@ def local_addresses():
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():
+ if "microsoft" in Path("/proc/version").read_text(encoding="utf-8").lower():
tools.append(["ipconfig.exe"])
except OSError:
pass
diff --git a/token_tv/live.py b/token_tv/live.py
index 57c2cca..faf7c16 100644
--- a/token_tv/live.py
+++ b/token_tv/live.py
@@ -170,7 +170,7 @@ def write_json(path, data):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
- temporary.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")))
+ temporary.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")), encoding='utf-8')
os.chmod(temporary, 0o600)
temporary.replace(path)
@@ -178,7 +178,7 @@ def write_json(path, data):
def load_original(device, backup_path):
"""Return the clock's original state; save it first only if no backup exists yet."""
if backup_path.is_file():
- original = json.loads(backup_path.read_text())
+ original = json.loads(backup_path.read_text(encoding='utf-8'))
device.check_backup(original) # a backup from another kind of clock is kept and nothing is sent
return original
original = device.capture()
@@ -425,7 +425,7 @@ def main():
raise SystemExit(f"TokenTV cannot write its state folder {state_dir} ({error.strerror or error}).")
if not free:
try:
- where = (state_dir / "live.url").read_text().strip()
+ where = (state_dir / "live.url").read_text(encoding='utf-8').strip()
except OSError:
where = ''
raise SystemExit("TokenTV is already running with this config on this computer" +
@@ -442,8 +442,8 @@ def main():
raise SystemExit(f"Another TokenTV already drives the clock at {config['device_url']} "
f"(with another config). One clock takes one TokenTV.")
pid_file, url_file = state_dir / "live.pid", state_dir / "live.url"
- pid_file.write_text(str(os.getpid())) # how `autostart off` ends it on Windows; gone again at exit
- url_file.write_text(f"http://{'127.0.0.1' if args.host in ('0.0.0.0', '') else args.host}:{args.port}")
+ pid_file.write_text(str(os.getpid()), encoding='utf-8') # how `autostart off` ends it on Windows; gone again at exit
+ url_file.write_text(f"http://{'127.0.0.1' if args.host in ('0.0.0.0', '') else args.host}:{args.port}", encoding='utf-8')
atexit.register(lambda: (pid_file.unlink(missing_ok=True), url_file.unlink(missing_ok=True)))
# The clock's model is asked in the background, so a clock that hangs never keeps the dashboard from opening.
device = open_display(config["device_url"]) if config.get("device_url") and args.restore_display else None
@@ -451,7 +451,7 @@ def main():
if args.restore_display:
if not device or not backup_path.is_file():
parser.error("A display and its original state backup are required")
- original = json.loads(backup_path.read_text())
+ original = json.loads(backup_path.read_text(encoding='utf-8'))
try:
device.check_backup(original)
except BackupMismatch as error:
@@ -461,7 +461,7 @@ def main():
return
store = UsageStore(config["accounts"], min_fetch_seconds=MIN_FETCH_SECONDS)
try: # when each account last worked, from the last run
- store.restore(json.loads((state_dir / "snapshot.json").read_text()))
+ store.restore(json.loads((state_dir / "snapshot.json").read_text(encoding='utf-8')))
except (OSError, ValueError):
pass
preferences = DisplayPreferences(args.config, config)
diff --git a/token_tv/lockbox.py b/token_tv/lockbox.py
index d7d9e4c..e36c1ad 100644
--- a/token_tv/lockbox.py
+++ b/token_tv/lockbox.py
@@ -101,7 +101,7 @@ class History:
def __init__(self, path):
self.path = Path(path)
try:
- self.data = json.loads(self.path.read_text())
+ self.data = json.loads(self.path.read_text(encoding='utf-8'))
except (OSError, ValueError):
self.data = {}
self.data.setdefault('fired', {})
@@ -109,7 +109,7 @@ class History:
def save(self):
"""Write through a temporary file, so a crash mid-write keeps the old history."""
spare = self.path.with_suffix('.tmp')
- spare.write_text(json.dumps(self.data))
+ spare.write_text(json.dumps(self.data), encoding='utf-8')
os.replace(spare, self.path)
def observe(self, snapshot, now):
@@ -275,7 +275,7 @@ class Lockbox:
self.roll = roll
self.undo = None # what the last pick changed, until it is known to have played
try:
- loaded = json.loads(Path(bundle).read_text())
+ loaded = json.loads(Path(bundle).read_text(encoding='utf-8'))
self.salt, self.boxes = bytes.fromhex(loaded['salt']), {b['check']: b for b in loaded['boxes']}
except (OSError, ValueError, KeyError):
self.salt, self.boxes = b'', {}
diff --git a/token_tv/sources.py b/token_tv/sources.py
index e6f63ff..d7eab9f 100644
--- a/token_tv/sources.py
+++ b/token_tv/sources.py
@@ -112,7 +112,7 @@ class RPC:
def load_config(path):
- data = json.loads(Path(path).read_text())
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
if set(data) - {"accounts", "device_url", "poll_seconds", "font", "display_style"}:
raise ValueError("Unsupported configuration field")
if data.get('display_style', 'pixel') not in STYLES:
@@ -191,7 +191,7 @@ def claude_token(root):
"""Access token from the CLI home's file, or on macOS from the login Keychain (read only)."""
path = root / ".credentials.json"
if path.is_file() or sys.platform != "darwin":
- return json.loads(path.read_text())["claudeAiOauth"]["accessToken"]
+ return json.loads(path.read_text(encoding="utf-8"))["claudeAiOauth"]["accessToken"]
user = os.environ.get("USER") or "claude-code-user"
for service in keychain_services(root):
result = subprocess.run(["security", "find-generic-password", "-a", user, "-w", "-s", service],
@@ -375,7 +375,7 @@ def logged_in_email(provider, home, why=None):
def grok_identity(account):
- data = json.loads((Path(account["source_home"]).expanduser() / "auth.json").read_text())
+ data = json.loads((Path(account["source_home"]).expanduser() / "auth.json").read_text(encoding="utf-8"))
emails = set()
def scan(value):
if isinstance(value, dict):
@@ -394,7 +394,7 @@ def grok_identity(account):
def imported_row(account):
- data = json.loads(Path(account["snapshot_file"]).expanduser().read_text())
+ data = json.loads(Path(account["snapshot_file"]).expanduser().read_text(encoding="utf-8"))
row = data["accounts"][account["key"]]
provider = "antigravity" if row.get("provider") == "gemini" else row.get("provider") # from before Anti
if provider != account["provider"] or row.get("alias") != account["alias"]:
diff --git a/token_tv/web/index.html b/token_tv/web/index.html
index 3aabf57..b7c6342 100644
--- a/token_tv/web/index.html
+++ b/token_tv/web/index.html
@@ -43,7 +43,7 @@
<label><input type="checkbox" value="codex" checked> Codex</label>
<label><input type="checkbox" value="grok" checked> Grok</label>
</fieldset>
- <p class="quiet">On a computer that stays on, where Claude Code, Codex or the Grok CLI is signed in (a browser login is not enough), paste into a terminal:</p>
+ <p class="quiet">On a computer that stays on, where Claude Code, Codex or the Grok CLI is signed in (a browser login is not enough; on a Mac, <a href="https://github.com/click6067-ship-it/token-tv/blob/main/docs/codexbar.md#claude-in-the-browser-only-on-a-mac-experimental">CodexBar can read one</a>), paste into a terminal:</p>
<div class="get-command"><code id="get-command" aria-live="polite">npx token-tv start</code><button id="get-copy" class="control primary" type="button">Copy</button></div>
<p id="get-status" class="get-status" role="status" aria-live="polite"></p>
<label for="get-address">Clock address · optional</label>
diff --git a/token_tv/web_assets.py b/token_tv/web_assets.py
index bbf8d64..b89867b 100644
--- a/token_tv/web_assets.py
+++ b/token_tv/web_assets.py
@@ -3,7 +3,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parent
WEB = ROOT / 'web'
-HTML = (WEB / 'index.html').read_text()
+HTML = (WEB / 'index.html').read_text(encoding='utf-8')
ASSETS = {
'/assets/style.css': (WEB / 'style.css', 'text/css; charset=utf-8'),
'/assets/app.js': (WEB / 'app.js', 'text/javascript; charset=utf-8'),