Skip to content

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

Release 0.5.0: your pet knows what Claude Code is doing

click6067-ship-it7285f676d437
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
new file mode 100644
index 0000000..bf89ca3
--- /dev/null
+++ b/.claude-plugin/marketplace.json
@@ -0,0 +1,12 @@
+{
+ "name": "token-tv",
+ "description": "TokenTV: your AI usage limits and your agents' moments on a $5 desk clock",
+ "owner": { "name": "click6067-ship-it" },
+ "plugins": [
+ {
+ "name": "tokentv",
+ "source": "./claude-plugin",
+ "description": "Clawd on your TokenTV clock raises a hand while Claude Code waits for your permission, bows when a turn is done, and takes a pat or a snack (/tokentv pet, /tokentv snack)"
+ }
+ ]
+}
diff --git a/README.ko.md b/README.ko.md
index 03689f6..1f59304 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -16,11 +16,13 @@
**구경하기:** [라이브 데모](https://token-tv.vercel.app) 또는 `npx token-tv demo`, 시계·로그인 없이 바로.
**설치하기:** 계속 켜 두는 컴퓨터에서 `npx token-tv start`(또는 `uvx token-tv start`). 로그인된 도구와 같은 와이파이의 시계를 찾고, 백그라운드에서 계속 돌며, 대시보드를 엽니다. AI에게 *"TokenTV 설정해줘"* 라고 해도 됩니다([AGENTS.md](AGENTS.md)).
-**새 화면 Arcade:** 코딩하는 동안 봇들도 바삐 움직입니다. 예를 들어 Codex는 토큰을 쓰는 동안 코드 비를 뿌려 꽃을 키웁니다. 많이 쓸수록 꽃밭이 가득 찹니다. Clawd는 게임에서처럼 땅을 달리고, Grok은 로켓에 연료를 넣다가 쉴 때는 지구를 올려다봅니다. Copilot과 Anti는 새로 온 친구들입니다.
+**새 기능 Claude Code 모드:** Claude Code가 허락을 기다리면 Clawd가 손을 들고, 한 턴이 끝나면 인사합니다([설정 방법](https://github.com/click6067-ship-it/token-tv/blob/main/docs/claude-code-mod.md)).
+
+**새 화면 Arcade:** 코딩하는 동안 봇들도 바삐 움직입니다. 예를 들어 Codex는 토큰을 쓰는 동안 코드 비를 뿌려 꽃을 키웁니다. 많이 쓸수록 꽃밭이 가득 찹니다. Grok은 로켓에 연료를 넣다가 쉴 때는 지구를 올려다봅니다. Copilot과 Anti는 새로 온 친구들입니다.
<p align="center"><img src="docs/images/highlight-claude.gif" width="150" alt="브레이크댄스 추는 Clawd"> <img src="docs/images/highlight-codex.gif" width="150" alt="꽃밭에 코드 비를 뿌리는 Codex 구름"> <img src="docs/images/highlight-grok.gif" width="150" alt="옆 부스터가 떨어져 나간 Grok의 로켓"> <img src="docs/images/highlight-copilot.gif" width="150" alt="하늘에 하트를 그리는 Copilot"> <img src="docs/images/highlight-anti.gif" width="150" alt="무중력에 떠오른 Anti"></p>
-**저마다 다르게 반응합니다.** 한도가 리셋되면 축하하고, 얼마 안 남으면 누군가는 허둥대고 누군가는 초조해합니다. 남은 리셋권은 시계에 표시되고, 만료가 며칠 남으면 빨갛게 알려 줍니다.
-**그리고 비밀 장면이 몇 개 있습니다.** 어떤 건 정해진 시간에만, 어떤 건 봇이 정말 열심히 일한 뒤에만, 어떤 건 거의 나오지 않습니다. 한 번, 잠깐만 나오고, 무엇인지는 말하지 않겠습니다. 소스를 봐도 안 나옵니다. 봉인돼 있거든요. 얼마나 있는지는 [도감](https://token-tv.vercel.app/collection/)에서 볼 수 있습니다.
+**저마다 다르게 반응합니다.** 얼마 안 남으면 누군가는 허둥대고 누군가는 초조해합니다.
+**그리고 비밀 장면이 몇 개 있습니다.** 어떤 건 정해진 시간에만, 어떤 건 봇이 정말 열심히 일한 뒤에만, 어떤 건 거의 나오지 않습니다. 잠깐만 나오고, 무엇인지는 말하지 않겠습니다. 얼마나 있는지는 [도감](https://token-tv.vercel.app/collection/)에서 볼 수 있습니다.
숫자는 한눈에, 그리고 귀엽게. 새벽 3시에 혼자 코딩해도 봇들이 곁을 지킵니다. 누군가 커피를 타 줄지도 모르죠. 아이디어, 제안, PR 모두 환영입니다. *귀여움이 곧 기능입니다.*
diff --git a/README.md b/README.md
index e5c4333..5948835 100644
--- a/README.md
+++ b/README.md
@@ -16,11 +16,13 @@ Turn a ~$5 AliExpress clock (GeekMagic SmallTV) into a physical AI usage dashboa
**Try it:** [live demo](https://token-tv.vercel.app) or `npx token-tv demo`, no clock or login needed.
**Set it up:** run `npx token-tv start` (or `uvx token-tv start`) on a computer that stays on. It finds your signed-in tools and the clock on your Wi-Fi, keeps running in the background and opens your dashboard. Or tell your AI *"Set up TokenTV for me"* ([AGENTS.md](https://github.com/click6067-ship-it/token-tv/blob/main/AGENTS.md)).
+**New: Claude Code mode.** Clawd raises a hand when Claude Code needs you and bows when a turn ends ([set it up](https://github.com/click6067-ship-it/token-tv/blob/main/docs/claude-code-mod.md)).
+
**New: Arcade.** When you're coding, the bots get busy too. Codex, for example, rains code to grow flowers while it spends tokens: the more it spends, the fuller the garden. Grok refuels its rocket and, resting, gazes up at Earth, and Copilot and Anti are the newest friends.
<p align="center"><img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-claude.gif" width="150" alt="Clawd breakdancing"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-codex.gif" width="150" alt="The Codex cloud raining code on its flowers"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-grok.gif" width="150" alt="Grok's rocket losing a side booster"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-copilot.gif" width="150" alt="Copilot drawing a heart in the sky"> <img src="https://raw.githubusercontent.com/click6067-ship-it/token-tv/main/docs/images/highlight-anti.gif" width="150" alt="Anti floating in zero gravity"></p>
-**Each reacts in its own way.** with little left, one rushes and another frets.
-**And a few secret scenes.** Some come only at certain hours, some only after a bot has really worked, and some almost never. for a moment, and we're not telling you which. [The collection](https://token-tv.vercel.app/collection/) shows how much is out there.
+**Each reacts in its own way.** With little left, one rushes and another frets.
+**And a few secret scenes.** Some come only at certain hours, some only after a bot has really worked, and some almost never. Each lasts only a moment, and we're not telling you which. [The collection](https://token-tv.vercel.app/collection/) shows how much is out there.
Simple numbers at a glance, and cute while it's at it. Coding alone at 3 a.m.? Your bots are still up with you, and someone might even make you coffee. Ideas, suggestions and PRs are welcome. *Cuteness is a feature.*
diff --git a/claude-plugin/.claude-plugin/plugin.json b/claude-plugin/.claude-plugin/plugin.json
new file mode 100644
index 0000000..8e5570d
--- /dev/null
+++ b/claude-plugin/.claude-plugin/plugin.json
@@ -0,0 +1,11 @@
+{
+ "name": "tokentv",
+ "displayName": "TokenTV",
+ "version": "0.5.0",
+ "description": "Your TokenTV desk clock shows Clawd raising a hand while Claude Code waits for your permission, and a bow when a turn is done; /tokentv pet and /tokentv snack give Clawd a pat or a snack. Tells the TokenTV on this computer the moment's name, nothing else.",
+ "author": { "name": "click6067-ship-it" },
+ "homepage": "https://github.com/click6067-ship-it/token-tv",
+ "repository": "https://github.com/click6067-ship-it/token-tv",
+ "license": "MIT",
+ "keywords": ["tokentv", "desk clock", "smalltv", "pet", "permission prompt"]
+}
diff --git a/claude-plugin/README.md b/claude-plugin/README.md
new file mode 100644
index 0000000..618ae81
--- /dev/null
+++ b/claude-plugin/README.md
@@ -0,0 +1,18 @@
+# TokenTV for Claude Code
+
+While Claude Code waits for you to answer a permission prompt, Clawd on your
+[TokenTV](https://github.com/click6067-ship-it/token-tv) desk clock raises a hand (then hops, then holds up a
+sign); when a turn is done, it bows. `/tokentv pet` and `/tokentv snack` give it a pat or a snack, one loop of
+hearts or a cookie. Install it in Claude Code:
+
+```
+/plugin install tokentv --marketplace click6067-ship-it/token-tv
+```
+
+The mod tells the TokenTV running on this computer the moment's name and nothing else (`claude.ask`,
+`claude.answered`, `claude.end`, `claude.pet`, `claude.snack`): no prompt, command, path or id leaves it, nor the
+words typed after `/tokentv`. With no TokenTV running it does nothing.
+On Windows it sends nothing for now.
+The whole story, Codex's half and how to turn it off: [docs/claude-code-mod.md](../docs/claude-code-mod.md).
+
+Tests: `claude plugin test claude-plugin` (tested with Claude Code 2.1.289).
diff --git a/claude-plugin/hooks/hooks.json b/claude-plugin/hooks/hooks.json
new file mode 100644
index 0000000..64048e1
--- /dev/null
+++ b/claude-plugin/hooks/hooks.json
@@ -0,0 +1 @@
+{"modules": ["./register.ts"]}
diff --git a/claude-plugin/hooks/register.ts b/claude-plugin/hooks/register.ts
new file mode 100644
index 0000000..157c76c
--- /dev/null
+++ b/claude-plugin/hooks/register.ts
@@ -0,0 +1,276 @@
+// TokenTV's mod for Claude Code. While Claude Code waits for you to answer a permission prompt, Clawd on your
+// TokenTV clock raises a hand (then hops, then holds up a sign); when a turn is done, it bows. `/tokentv pet` and
+// `/tokentv snack` give Clawd a pat or a snack, one loop of hearts or munching.
+//
+// It tells the TokenTV running on this computer one of five names and nothing else: `claude.ask` (a permission
+// prompt is now waiting for you), `claude.answered` (you answered it, or it is over), `claude.end` (a turn ended),
+// `claude.pet` and `claude.snack` (the two commands). Prompts, commands, their words, paths and ids stay in this
+// file. TokenTV counts the waits of every session, so each session says once that its prompt opened and once that it
+// closed.
+//
+// Nothing here is awaited on Claude Code's path: the requests go out in the background, one after another so they
+// arrive in the order they happened, and when no TokenTV runs (or it does not answer) nothing happens at all. What
+// is below lives as long as the session (one per session).
+
+// TokenTV lets every wait go 30 minutes after the continuous wait began, at this ask or before it (its answer to the
+// ask says how long that wait had lasted: TokenTV-Wait-Age). An answer after that would close another, newer wait
+// there, so it is not sent; nor one that would come this close to it (it might land just after).
+const EXPIRE_MS = 30 * 60 * 1000
+const MARGIN_MS = 5000
+const KEEP = 256 // calls already answered, remembered so a late repeat of one is not a new wait
+const PATIENCE_MS = 2000 // the longest one request holds the next back (TokenTV answers in milliseconds)
+const STALE_MS = 5000 // a moment that could not go out within this is dropped: news, not history
+
+// `to` names the running TokenTV that counted the wait's ask; its answer goes to that one only, never to another
+// (one started since, which never saw the ask, would close a wait of someone else's). `sent` is the ask's own
+// request, which the answer waits for: TokenTV may count the ask however late it says so. `waited` is how long
+// TokenTV's continuous wait had lasted when it took the ask (ms; none from a TokenTV that does not say).
+type Wait = { agent: string | undefined; at: number; to?: string; sent?: Promise<unknown>; waited?: number }
+
+const waits = new Map<string, Wait>() // tool_use_id -> a prompt this session announced and has not closed
+const callers = new Map<string, string | undefined>() // tool_use_id -> the subagent making a call now, if one is
+const answered: string[] = []
+let interactive = true // false in `claude -p` and the SDK: nobody sits at a dialog there
+let mode: string | undefined // the permission mode, when Claude Code says it (auto mode's classifier asks no one)
+let lastTurn: string | undefined
+let queue: Promise<void> = Promise.resolve() // what is told goes out in the order it happened
+
+export function register(on: any) {
+ on('session.start', async ($: any, e: any, next: any) => {
+ interactive = e?.isInteractive !== false
+ try {
+ // `immediate`: a pat typed while Claude works goes at once, not after the turn (it touches nothing of it)
+ await $.command.register({ name: 'tokentv', description: 'Pet Clawd on your TokenTV clock, or give it a snack',
+ argumentHint: 'pet | snack', immediate: true })
+ } catch {}
+ return next(e)
+ })
+
+ // `/tokentv pet` and `/tokentv snack`: one name each to TokenTV, sent as the other moments are (in the
+ // background: the command never waits for it). Anything else after /tokentv sends nothing; its words go nowhere.
+ on('command.run', { command: 'tokentv' }, async ($: any, e: any) => {
+ const word = String(e?.args ?? '').trim().toLowerCase()
+ const moment = word === 'pet' ? 'claude.pet' : word === 'snack' ? 'claude.snack' : undefined
+ if (!moment) return { text: 'Try /tokentv pet or /tokentv snack.' }
+ if (await onWindows($)) return { text: 'On Windows the TokenTV mod sends nothing for now.' }
+ if (!(await findTokenTV($).catch(() => undefined))) {
+ return { text: 'No TokenTV is running on this computer: nothing was sent.' }
+ }
+ send($, moment)
+ return { text: word === 'pet' ? 'A pat for Clawd, on its way to TokenTV.' : 'A snack for Clawd, on its way to TokenTV.' }
+ })
+
+ // Read only for the permission mode (auto mode's classifier, not a person, settles what the rules leave open):
+ // as the session starts and again before each tool call, as Claude Code's settings hooks are told it.
+ on('classic.SessionStart', noteMode)
+ on('classic.PreToolUse', noteMode)
+
+ // The decision on a call, with Claude Code's verdict passed on untouched. `ask` with nobody else to decide it
+ // means the permission prompt is about to show: one wait, once per call however often it is seen.
+ on('tool.check', async ($: any, e: any, next: any) => {
+ const decided = await next(e)
+ try {
+ const id = e?.tool_use_id
+ if (asksYou(decided, id) && !waits.has(id) && !answered.includes(id)) {
+ const wait = { agent: e.agentId ?? callers.get(id), at: 0 }
+ waits.set(id, wait)
+ send($, 'claude.ask', wait)
+ }
+ } catch {}
+ return decided
+ })
+
+ // Your answer, as it happens: Claude Code draws the asked call's row again the moment you answer, running (you
+ // said yes) or with its result (you said no). Measured in Claude Code 2.1.289 (2026-11-01): the asked call's
+ // `isRunning` turns true in the first ToolGroup drawing after "Yes", while the tool.call around it settles only
+ // once the tool is done. Drawings come often: with no prompt open they are handed straight on, and none is changed.
+ on('ui.render', { component: ['ToolGroup', 'ToolUse'] }, async ($: any, e: any, next: any) => {
+ if (waits.size === 0) return next(e)
+ try {
+ const calls = e?.component === 'ToolGroup' ? e.props?.calls ?? [] : [e?.props] // a ToolUse row is one call
+ for (const call of calls) {
+ if (waits.has(call?.tool_use_id) && (call.isRunning === true || call.output != null)) {
+ answer($, call.tool_use_id)
+ }
+ }
+ } catch {}
+ return next(e)
+ })
+
+ // The permission check, your answer and the tool all happen inside `next`: once it is back, the prompt is over
+ // (the tool ran, or was refused, or the turn was cut short), if no drawing said so before. The call and its
+ // result pass through untouched.
+ on('tool.call', async ($: any, e: any, next: any) => {
+ const id = e?.tool_use_id
+ if (typeof id === 'string') callers.set(id, e.agentId) // tool.check carries it only from Claude Code 2.1.290
+ try {
+ return await next(e)
+ } finally {
+ callers.delete(id)
+ answer($, id)
+ }
+ })
+
+ // A turn's end closes its open prompts; the main turn's end, when it was not cut short, is a bow.
+ on('turn.complete', async ($: any, e: any, next: any) => {
+ try {
+ for (const [id, wait] of [...waits]) if (wait.agent === e?.agentId) answer($, id)
+ const id = e?.turnId
+ if (!e?.agentId && !e?.isAborted && (id === undefined || id !== lastTurn)) {
+ lastTurn = id
+ send($, 'claude.end')
+ }
+ } catch {}
+ return next(e)
+ })
+
+ on('session.end', async ($: any, e: any, next: any) => {
+ try {
+ for (const id of [...waits.keys()]) answer($, id) // sent as the rest are; TokenTV lets go of any left
+ } catch {}
+ return next(e)
+ })
+}
+
+async function noteMode($: any, e: any, next: any) {
+ if (typeof e?.permission_mode === 'string') mode = e.permission_mode
+ return next(e)
+}
+
+function asksYou(decided: any, id: unknown) {
+ if (!decided || decided.decision !== 'ask' || decided.decider) return false // a host program answers that one
+ if (typeof id !== 'string' || id === '' || !interactive || mode === 'dontAsk') return false
+ // In auto mode the classifier settles an ask, unless an ask rule or a PreToolUse hook asked for you.
+ return mode !== 'auto' || Boolean(decided.rule || decided.hook)
+}
+
+function answer($: any, id: unknown) {
+ if (typeof id !== 'string') return
+ const wait = waits.get(id)
+ if (!wait) return
+ waits.delete(id)
+ answered.push(id)
+ if (answered.length > KEEP) answered.shift()
+ send($, 'claude.answered', wait)
+}
+
+// In the background, never awaited by a hook: each moment waits for the one before it to be answered (or for
+// PATIENCE_MS), so TokenTV takes them in the order they happened; one held up past STALE_MS is dropped.
+function send($: any, moment: string, wait?: Wait) {
+ const asked = clockNow($)
+ asked.catch(() => {})
+ queue = queue.then(() => deliver($, moment, asked, wait)).catch(() => {})
+}
+
+async function deliver($: any, moment: string, asked: Promise<number>, wait?: Wait) {
+ if (wait && moment === 'claude.answered') {
+ // The ask's own request first: TokenTV may say late that it counted it. Not past STALE_MS: a TokenTV that
+ // never answers holds nothing up for long (and an ask it never confirmed is not answered).
+ if (wait.sent) await within($, wait.sent, STALE_MS)
+ if (wait.to === undefined) return // TokenTV never took the ask: nothing of it to close
+ const began = wait.at - (wait.waited ?? 0) // the continuous wait at TokenTV, which this ask joined
+ if ((await clockNow($)) - began >= EXPIRE_MS - MARGIN_MS) return // TokenTV has let this wait go by now
+ // An answer whose ask was counted goes however late, or the wait would stay on the clock.
+ } else if ((await clockNow($)) - (await asked) > STALE_MS) {
+ return
+ }
+ const place = await findTokenTV($)
+ if (!place) return
+ if (wait && moment === 'claude.answered' && wait.to !== place.id) return // another TokenTV run never saw the ask
+ const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ moment }),
+ socketPath: place.socket }
+ const sent = $.http.fetch(place.url, init).then((response: any) => {
+ if (!wait || moment !== 'claude.ask' || !response?.ok) return
+ wait.to = place.id
+ const waited = Number(response.headers?.['tokentv-wait-age']) // seconds; absent from an older TokenTV
+ if (Number.isFinite(waited) && waited >= 0) wait.waited = waited * 1000
+ })
+ const settled = sent.catch(() => {})
+ if (wait && moment === 'claude.ask') {
+ wait.at = await clockNow($)
+ wait.sent = settled
+ }
+ await within($, settled, PATIENCE_MS)
+}
+
+// `work`, or nothing after `ms`: the host's clock, else the runtime's own timer where there is one, else `work`.
+function within($: any, work: Promise<unknown>, ms: number) {
+ const later = () =>
+ typeof (globalThis as any).setTimeout === 'function'
+ ? new Promise((done) => (globalThis as any).setTimeout(done, ms))
+ : work
+ let timer: Promise<unknown>
+ try {
+ timer = Promise.resolve($.clock.sleep(ms)).catch(later)
+ } catch {
+ timer = later()
+ }
+ return Promise.race([work, timer])
+}
+
+async function clockNow($: any) {
+ try {
+ return await $.clock.now()
+ } catch {
+ return Date.now()
+ }
+}
+
+// Where the running TokenTV listens: its state folder beside the config `token-tv start` uses
+// (<XDG_CONFIG_HOME or ~/.config>/token-tv/state), or beside TOKEN_TV_CONFIG for another config. TokenTV writes its
+// address there while it runs (live.url) and, on Linux and macOS, a socket of its own (live.sock). A moment goes
+// only over that socket, where it meets no proxy and cannot be redirected anywhere else (Claude Code 2.1.289,
+// measured 2026-11-01: Content-Length, Host 127.0.0.1:port). Over TCP the same fetch takes a proxy set in its
+// environment, even to 127.0.0.1, and follows a redirect wherever it points, whatever its options say (measured the
+// same day): so with no socket nothing is sent, and a live.url alone, perhaps left from a TokenTV that stopped, its
+// port another program's now, is never tried. TokenTV makes no socket on Windows: there nothing is sent for now,
+// whatever the folder holds.
+async function onWindows($: any) {
+ return (await Promise.resolve().then(() => $.env.get('OS')).catch(() => undefined)) === 'Windows_NT'
+}
+
+async function findTokenTV($: any) {
+ if ((await $.env.get('OS')) === 'Windows_NT') return undefined
+ const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
+ const config = await $.env.get('TOKEN_TV_CONFIG')
+ let state: string | undefined
+ if (config) {
+ const path = /^~[\\/]/.test(config) && home ? home + config.slice(1) : config
+ const cut = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
+ state = (cut < 0 ? '' : path.slice(0, cut + 1)) + 'state'
+ } else {
+ const base = (await $.env.get('XDG_CONFIG_HOME')) || (home ? home + '/.config' : undefined)
+ state = base ? base + '/token-tv/state' : undefined
+ }
+ if (!state) return undefined
+ if (!absolute(state)) {
+ // Claude Code takes a socket only by an absolute path (2.1.289 refuses `./state/live.sock`): a relative one is
+ // made absolute from the folder the session started in, where the relative TOKEN_TV_CONFIG was set. Not the
+ // session's current folder, which follows a `cd` the model runs. With no absolute folder: nothing is sent.
+ const root = await Promise.resolve().then(() => $.session.root()).catch(() => undefined)
+ if (!absolute(root)) return undefined
+ state = root.replace(/[\\/]+$/, '') + '/' + state.replace(/^(\.[\\/])+/, '')
+ }
+ const text = await $.fs.read(state + '/live.url')
+ const url = loopback(text)
+ if (!url) return undefined
+ // Which run of TokenTV this is: it writes live.url anew each time it starts.
+ const stat = await $.fs.stat(state + '/live.url').catch(() => undefined)
+ const id = String(text).trim() + '@' + (stat?.mtimeMs ?? '')
+ const socket = state + '/live.sock'
+ if (!(await $.fs.exists(socket))) return undefined
+ return { url: url + '/moment', socket, id }
+}
+
+// A path from the root of a drive: /…, C:\… or C:/…, or \\server\share.
+function absolute(path: unknown): path is string {
+ return typeof path === 'string' && /^(\/|[A-Za-z]:[\\/]|\\\\)/.test(path)
+}
+
+// Only this computer: http to 127.0.0.1, localhost (sent as 127.0.0.1, never looked up) or [::1] with a port,
+// and nothing else. Any other address, a user, a path or a query: not ours to send to.
+function loopback(text: unknown) {
+ const found = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})$/.exec(String(text ?? '').trim())
+ if (!found || Number(found[2]) < 1 || Number(found[2]) > 65535) return undefined
+ return 'http://' + (found[1] === 'localhost' ? '127.0.0.1' : found[1]) + ':' + Number(found[2])
+}
diff --git a/claude-plugin/tests/register.test.ts b/claude-plugin/tests/register.test.ts
new file mode 100644
index 0000000..ba1556f
--- /dev/null
+++ b/claude-plugin/tests/register.test.ts
@@ -0,0 +1,738 @@
+import { expect, mock, test } from 'claude-code/testing'
+
+// A fake computer for the mod: a TokenTV state folder, a running TokenTV (or none) and Claude Code's own answers.
+// What the mod sends is caught at $.http.fetch; nothing leaves the test.
+const HOME = '/home/user'
+const STATE = HOME + '/.config/token-tv/state'
+const flush = () => new Promise((done) => setTimeout(done, 25))
+const DRAWN = { type: 'Text', props: {}, children: ['Bash(rm -rf build)'] }
+
+function computer(on: any, options: any = {}) {
+ const files: Record<string, string> = options.files ?? { [STATE + '/live.url']: 'http://127.0.0.1:8791' }
+ const stamps: Record<string, number> = options.stamps ?? {} // when each file was written (TokenTV's run)
+ const sockets: string[] = options.sockets ?? [STATE + '/live.sock']
+ const sent: any[] = []
+ const gates: Record<string, () => void> = {}
+ const verdicts: Record<string, any> = options.verdicts ?? {}
+ mock.env(on, options.env ?? { HOME })
+ // the kit hands paths over made absolute (a Windows path, here on another system, comes prefixed): by their end
+ const find = (path: string) => Object.keys(files).find((name) => path === name || path.endsWith('/' + name))
+ const socket = (path: string) => sockets.some((name) => path === name || path.endsWith('/' + name))
+ const reads: string[] = []
+ on('fs.read', ($: any, e: any) => {
+ reads.push(e.path)
+ return find(e.path) ? { value: files[find(e.path)!] } : { deny: 'ENOENT: no such file' }
+ })
+ on('fs.exists', ($: any, e: any) => ({ value: socket(e.path) || Boolean(find(e.path)) }))
+ on('fs.stat', ($: any, e: any) => {
+ const name = find(e.path)
+ return name ? { value: { kind: 'file', size: files[name].length, mtimeMs: stamps[name] ?? 1, isLink: false } }
+ : { deny: 'ENOENT: no such file' }
+ })
+ // the session's folder as Claude Code says it (`$.session.root()`, absolute; the kit has none of its own)
+ const root = 'root' in options ? options.root : '/work'
+ on('session.root', () => (root ? { value: root } : { deny: 'no folder' }))
+ const refused: any[] = []
+ on('http.fetch', options.fetch ?? (($: any, e: any) => {
+ if (e.init?.socketPath !== undefined && !/^\//.test(e.init.socketPath)) { // as Claude Code 2.1.289 refuses it
+ refused.push(e)
+ return { deny: 'socketPath takes an absolute path' }
+ }
+ sent.push(e)
+ return { value: { status: 204, ok: true, headers: {}, text: '' } }
+ }))
+ const calls: any[] = []
+ // Claude Code itself: a call waits inside next() for the check, the person and the tool, here until released
+ on('tool.call', async ($: any, e: any) => {
+ calls.push(e)
+ await new Promise<void>((done) => { gates[e.tool_use_id] = done })
+ return { result: 'ran ' + e.tool_use_id, context: ['for the model'] }
+ })
+ on('tool.check', ($: any, e: any) => verdicts[e.tool_use_id] ?? { decision: 'ask' })
+ on('ui.render', ($: any, e: any) => DRAWN) // Claude Code's own drawing of the row
+ on('turn.complete', () => ({ text: '' }))
+ on('session.start', () => ({ cwd: '/work' }))
+ on('session.end', () => ({ sessionId: 'session' }))
+ on('classic.SessionStart', () => ({}))
+ const registered: any[] = [] // the slash commands the mod offers, as Claude Code is asked to list them
+ on('command.register', ($: any, e: any) => {
+ registered.push(e)
+ return { value: { command: e.name } }
+ })
+ return { sent, refused, calls, reads, registered, release: (id: string) => gates[id]?.(),
+ moments: () => sent.map((s) => JSON.parse(s.init.body).moment) }
+}
+
+// A slash command as Claude Code runs it once the person typed `/tokentv <args>` (the words after the name in
+// `args`; left out for a bare `/tokentv`, as the kit does).
+const tokentv = ($: any, args?: string) => $.command.run(args === undefined ? { command: 'tokentv' } : { command: 'tokentv', args })
+
+// Claude Code drawing tool calls' rows, as it does the moment you answer a prompt: a ToolGroup with its calls in a
+// list, or a ToolUse row of one call (measured in 2.1.289: the asked call `isRunning` once you said yes).
+const row = (id: string, fields: any = {}) => ({ tool_use_id: id, tool: 'Bash', input: { command: 'rm -rf build' },
+ isRunning: false, isErrored: false, isInterrupted: false, ...fields })
+const group = ($: any, ...calls: any[]) => $.ui.render({ surface: 'terminal', component: 'ToolGroup', requestId: 'g1',
+ props: { calls, isActive: true, isExpanded: false } })
+const single = ($: any, call: any) => $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: call.tool_use_id,
+ props: call })
+
+// A tool call that needs your permission: the call starts, Claude Code checks it, and the prompt waits for you.
+async function prompt($: any, id: string, command = 'rm -rf build') {
+ const call = $.tool.call({ tool: 'Bash', command, tool_use_id: id })
+ call.catch(() => {}) // a call a test leaves waiting is let go with the test, not left a rejection nobody handles
+ await flush()
+ const verdict = await $.tool.check({ tool: 'Bash', input: { command }, tool_use_id: id })
+ await flush()
+ return { call, verdict }
+}
+
+const turn = (turnId: string, extra: any = {}) =>
+ ({ turnId, answer: 'done', durationMs: 1200, isAborted: false, usage: null, ...extra })
+
+test('a permission prompt is one claude.ask, and the end of that call is claude.answered', async ($: any, on: any) => {
+ const pc = computer(on)
+ const { call, verdict } = await prompt($, 't1')
+ expect(verdict).toEqual({ decision: 'ask' }) // Claude Code's verdict passes on untouched
+ expect(pc.moments()).toEqual(['claude.ask'])
+ pc.release('t1') // you answered and the tool ran
+ expect(await call).toEqual({ result: 'ran t1', context: ['for the model'] })
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered'])
+ expect(pc.sent[0].url).toBe('http://127.0.0.1:8791/moment')
+ expect(pc.sent[0].init).toEqual({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: '{"moment":"claude.ask"}',
+ socketPath: STATE + '/live.sock',
+ })
+})
+
+test('the hand comes down as you answer: the asked call drawn running, long before the tool is done',
+ async ($: any, on: any) => {
+ const pc = computer(on)
+ const { call } = await prompt($, 'y1')
+ const done = row('d1', { output: { stdout: '' } }) // a call before it, over already
+ expect(await group($, done, row('y1'))).toEqual(DRAWN) // the dialog is up: not answered yet
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask'])
+ expect(await group($, done, row('y1', { isRunning: true }))).toEqual(DRAWN) // "Yes": drawn untouched
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered'])
+ expect(await Promise.race([call, flush().then(() => 'still running')])).toBe('still running') // the tool runs on
+ await single($, row('y1', { isRunning: true }))
+ pc.release('y1')
+ await call
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered']) // once, however often drawn, not again at its end
+ })
+
+test('a "No" closes the prompt when its refusal is drawn, or else when the call ends', async ($: any, on: any) => {
+ const pc = computer(on)
+ const first = await prompt($, 'n1')
+ await single($, row('n1', { isErrored: true, output: 'The user refused this tool use' }))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered'])
+ pc.release('n1')
+ await first.call
+ const second = await prompt($, 'n2')
+ await group($, row('n2')) // drawn while the dialog is up, and never again
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered', 'claude.ask'])
+ pc.release('n2') // refused: the call ends with no tool run
+ await second.call
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered', 'claude.ask', 'claude.answered'])
+})
+
+test('a drawing of another call, or of any call with no prompt open, answers nothing and is drawn untouched',
+ async ($: any, on: any) => {
+ const pc = computer(on)
+ expect(await group($, row('x1', { isRunning: true }), row('x2', { output: 'ok' }))).toEqual(DRAWN)
+ expect(await single($, row('x3', { isRunning: true }))).toEqual(DRAWN)
+ await flush()
+ expect(pc.sent).toEqual([])
+ const { call } = await prompt($, 'mine')
+ expect(await group($, row('other', { isRunning: true }), row('mine'))).toEqual(DRAWN)
+ await single($, row('another', { output: 'ok' }))
+ await single($, row('mine', { output: null })) // waiting, its result none yet: no answer
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask'])
+ pc.release('mine')
+ await call
+ })
+
+test('no answer goes once TokenTV has let the wait go: the ask it joined began earlier there (TokenTV-Wait-Age)',
+ async ($: any, on: any) => {
+ const clock = mock.clock(on, { now: 1_000_000 })
+ const ages: Record<string, string> = { late: '1500', fresh: '0' } // how long TokenTV's wait had lasted, in s
+ let asked = ''
+ const pc = computer(on, {
+ fetch: ($: any, e: any) => {
+ const ask = named(e) === 'claude.ask'
+ pc.sent.push(e)
+ return { value: { status: 204, ok: true, headers: ask ? { 'tokentv-wait-age': ages[asked] } : {}, text: '' } }
+ },
+ })
+ asked = 'late' // another session's prompt had kept TokenTV waiting 25 minutes when this one joined
+ const late = await prompt($, 'late')
+ await clock.advance(8 * 60 * 1000) // TokenTV let the whole wait go 5 minutes ago
+ await group($, row('late', { isRunning: true }))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask'])
+ asked = 'fresh' // a new wait, this prompt its first
+ const fresh = await prompt($, 'fresh')
+ await clock.advance(8 * 60 * 1000)
+ await group($, row('fresh', { isRunning: true }))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.ask', 'claude.answered'])
+ pc.release('late')
+ pc.release('fresh')
+ await late.call
+ await fresh.call
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.ask', 'claude.answered'])
+ })
+
+// (A verdict of `ask` with `decider: 'host'`, a hosted session's program to answer, sends nothing either; the test
+// kit drops `decider` from a stubbed verdict, so only a real session shows it.)
+test('calls nobody is asked about send nothing: allowed, denied, another mod\'s query', async ($: any, on: any) => {
+ const pc = computer(on, {
+ verdicts: {
+ allowed: { decision: 'allow' },
+ denied: { decision: 'deny', reason: 'rule' },
+ },
+ })
+ for (const id of ['allowed', 'denied']) {
+ const { call } = await prompt($, id)
+ pc.release(id)
+ await call
+ }
+ await $.tool.check({ tool: 'Bash', input: { command: 'ls' } }) // another mod's query: no call, no prompt
+ await flush()
+ expect(pc.moments()).toEqual([])
+ })
+
+test('nothing is asked of anyone in a -p run, in dontAsk mode, or by auto mode\'s classifier', async ($: any, on: any) => {
+ const pc = computer(on)
+ await $.session.start({ surface: null, isInteractive: false, cwd: '/work' })
+ const first = await prompt($, 'p1')
+ pc.release('p1')
+ await first.call
+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })
+ for (const [mode, id] of [['dontAsk', 'd1'], ['auto', 'a1']]) {
+ await $.classic.SessionStart({ hook_event_name: 'SessionStart', permission_mode: mode, source: 'startup' })
+ const { call } = await prompt($, id)
+ pc.release(id)
+ await call
+ }
+ await flush()
+ expect(pc.moments()).toEqual([])
+})
+
+test('in auto mode an ask rule still puts the prompt to you', async ($: any, on: any) => {
+ const pc = computer(on, { verdicts: { r1: { decision: 'ask', rule: 'Bash(git push:*)' } } })
+ await $.classic.SessionStart({ hook_event_name: 'SessionStart', permission_mode: 'auto', source: 'startup' })
+ const { call } = await prompt($, 'r1', 'git push')
+ expect(pc.moments()).toEqual(['claude.ask'])
+ pc.release('r1')
+ await call
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered'])
+})
+
+test('the same prompt seen again is still one wait, and one answer closes it; a late repeat opens nothing',
+ async ($: any, on: any) => {
+ const pc = computer(on)
+ const { call } = await prompt($, 'same')
+ for (let k = 0; k < 9; k++) await $.tool.check({ tool: 'Bash', input: { command: 'rm -rf build' }, tool_use_id: 'same' })
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask'])
+ pc.release('same')
+ await call
+ await $.tool.check({ tool: 'Bash', input: { command: 'rm -rf build' }, tool_use_id: 'same' })
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered'])
+ })
+
+test('the end of a turn closes its open prompt, then bows; a turn cut short only closes it', async ($: any, on: any) => {
+ const pc = computer(on)
+ await prompt($, 'w1')
+ await $.turn.complete(turn('turn-1'))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered', 'claude.end'])
+ await prompt($, 'w2')
+ await $.turn.complete(turn('turn-2', { isAborted: true }))
+ await $.turn.complete(turn('turn-1')) // the same turn seen again: no second bow
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered', 'claude.end', 'claude.ask', 'claude.answered'])
+})
+
+test('a subagent\'s turn closes only its own prompts and is no bow', async ($: any, on: any) => {
+ const pc = computer(on, { verdicts: {} })
+ const main = await prompt($, 'main-1')
+ // the subagent's own prompt
+ const sub = $.tool.call({ tool: 'Bash', command: 'make', tool_use_id: 'sub-1', agentId: 'agent-7' })
+ await flush()
+ await $.tool.check({ tool: 'Bash', input: { command: 'make' }, tool_use_id: 'sub-1', agentId: 'agent-7' })
+ await flush()
+ await $.turn.complete(turn('sub-turn', { agentId: 'agent-7' }))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.ask', 'claude.answered'])
+ pc.release('main-1')
+ pc.release('sub-1')
+ await main.call
+ await sub
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.ask', 'claude.answered', 'claude.answered'])
+})
+
+test('closing the session closes its open prompts', async ($: any, on: any) => {
+ const pc = computer(on)
+ await prompt($, 'x1')
+ await prompt($, 'x2')
+ await $.session.end({ reason: 'prompt_input_exit' })
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.ask', 'claude.answered', 'claude.answered'])
+})
+
+test('an answer at or after the time TokenTV lets the wait go (30 minutes) is not sent', async ($: any, on: any) => {
+ const clock = mock.clock(on, { now: 1_000_000 })
+ const pc = computer(on)
+ const { call } = await prompt($, 'old')
+ await clock.advance(30 * 60 * 1000 - 5000) // five seconds before: it could land just after TokenTV let go
+ pc.release('old')
+ await call
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask'])
+})
+
+test('no TokenTV running: nothing is sent, and Claude Code goes on as before', async ($: any, on: any) => {
+ const pc = computer(on, { files: {}, sockets: [] })
+ const { call, verdict } = await prompt($, 'n1')
+ pc.release('n1')
+ expect(await call).toEqual({ result: 'ran n1', context: ['for the model'] })
+ expect(verdict).toEqual({ decision: 'ask' })
+ await $.turn.complete(turn('t'))
+ await flush()
+ expect(pc.sent).toEqual([])
+})
+
+test('only this computer\'s loopback address, over TokenTV\'s socket; anything else in live.url sends nothing',
+ async ($: any, on: any) => {
+ const files: Record<string, string> = {}
+ const pc = computer(on, { files })
+ const bad = ['http://example.com:8787', 'http://192.0.2.7:8787', 'http://[email protected]:8787',
+ 'http://[email protected]:8787', 'http://localhost.evil.example:8787', 'https://127.0.0.1:8787',
+ 'http://127.0.0.1:8787/moment', 'http://127.0.0.1:99999', 'http://127.0.0.1']
+ for (const url of bad) {
+ files[STATE + '/live.url'] = url
+ await $.turn.complete(turn(url))
+ await flush()
+ }
+ expect(pc.sent).toEqual([])
+ for (const [url, to] of [['http://localhost:8790', 'http://127.0.0.1:8790/moment'],
+ ['http://[::1]:8792', 'http://[::1]:8792/moment'], ['http://127.0.0.1:8793\n', 'http://127.0.0.1:8793/moment']]) {
+ files[STATE + '/live.url'] = url
+ await $.turn.complete(turn('ok ' + url))
+ await flush()
+ expect([pc.sent.at(-1).url, pc.sent.at(-1).init.socketPath]).toEqual([to, STATE + '/live.sock'])
+ }
+ })
+
+test('nothing goes anywhere but TokenTV\'s socket: a live.url alone sends nothing', async ($: any, on: any) => {
+ const pc = computer(on, { sockets: [] }) // live.url left by a TokenTV that stopped, its port maybe another's now
+ await prompt($, 'p1')
+ await $.turn.complete(turn('t'))
+ await flush()
+ expect(pc.sent).toEqual([])
+})
+
+const PLACES = { '/xdg/token-tv/state/live.url': 'http://127.0.0.1:8801', '/srv/tv/state/live.url': 'http://127.0.0.1:8802',
+ [HOME + '/tv2/state/live.url']: 'http://127.0.0.1:8803' }
+
+const SOCKETS = ['/xdg/token-tv/state/live.sock', '/srv/tv/state/live.sock', HOME + '/tv2/state/live.sock']
+
+for (const [env, url, socket] of [
+ [{ HOME, XDG_CONFIG_HOME: '/xdg' }, 'http://127.0.0.1:8801/moment', '/xdg/token-tv/state/live.sock'],
+ [{ HOME, XDG_CONFIG_HOME: '/xdg', TOKEN_TV_CONFIG: '/srv/tv/config.json' }, 'http://127.0.0.1:8802/moment', '/srv/tv/state/live.sock'],
+ [{ HOME, TOKEN_TV_CONFIG: '~/tv2/config.json' }, 'http://127.0.0.1:8803/moment', HOME + '/tv2/state/live.sock'],
+] as const) {
+ test(`TokenTV is found where it runs (${Object.keys(env).join(', ')})`, async ($: any, on: any) => {
+ const pc = computer(on, { env, files: PLACES, sockets: SOCKETS })
+ await $.turn.complete(turn('a'))
+ await flush()
+ expect(pc.sent.map((s) => [s.url, s.init.socketPath])).toEqual([[url, socket]])
+ })
+}
+
+// A relative TOKEN_TV_CONFIG: its state folder is in the folder the session started in, and the socket goes by its
+// absolute path (Claude Code 2.1.289 refuses a relative one, as the fake host here does).
+for (const [config, folder] of [['config.json', '/work/project/state'], ['./config.json', '/work/project/state'],
+ ['tv/config.json', '/work/project/tv/state']] as const) {
+ test(`TOKEN_TV_CONFIG=${config} is found beside it in the session's folder, by an absolute path`, async ($: any, on: any) => {
+ const pc = computer(on, { env: { HOME, TOKEN_TV_CONFIG: config }, root: '/work/project',
+ files: { [folder + '/live.url']: 'http://127.0.0.1:8806' }, sockets: [folder + '/live.sock'] })
+ await prompt($, 'c1')
+ await $.turn.complete(turn('c'))
+ await flush()
+ expect(pc.reads.filter((path: string) => path.includes('config.json'))).toEqual([])
+ expect(pc.refused).toEqual([])
+ expect(pc.sent.map((s) => [s.url, s.init.socketPath])).toEqual([
+ ['http://127.0.0.1:8806/moment', folder + '/live.sock'], ['http://127.0.0.1:8806/moment', folder + '/live.sock'],
+ ['http://127.0.0.1:8806/moment', folder + '/live.sock']])
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered', 'claude.end'])
+ })
+}
+
+for (const [label, root] of [['none', null], ['a relative one', 'work/project']] as const) {
+ test(`a relative TOKEN_TV_CONFIG with no absolute folder for the session (${label}) sends nothing`, async ($: any, on: any) => {
+ // (a TokenTV beside it wherever the kit looks, so only the rule keeps the moment back)
+ const pc = computer(on, { env: { HOME, TOKEN_TV_CONFIG: 'config.json' }, root,
+ files: { 'state/live.url': 'http://127.0.0.1:8806' }, sockets: ['state/live.sock'] })
+ await prompt($, 'c1')
+ await $.turn.complete(turn('c'))
+ await flush()
+ expect(pc.sent).toEqual([])
+ expect(pc.refused).toEqual([])
+ })
+}
+
+// Windows: nothing for now. TokenTV makes no socket there, and over TCP Claude Code's fetch takes a proxy set in its
+// environment and follows a redirect wherever it points, whatever its options say (2.1.289, measured): a moment's
+// name could leave this computer. Whatever the environment and the files say, nothing is sent; off Windows the same
+// folders are found and the moments go, so it is Windows alone that keeps them back.
+const PROXY = 'http://proxy.example:3128'
+const EVERYWHERE = { ...PLACES, [HOME + '/.config/token-tv/state/live.url']: 'http://127.0.0.1:8804',
+ 'C:/Users/u/.config/token-tv/state/live.url': 'http://127.0.0.1:8805',
+ 'C:\\work/tv\\state/live.url': 'http://127.0.0.1:8806' }
+const BESIDE = Object.keys(EVERYWHERE).map((url) => url.replace(/live\.url$/, 'live.sock')) // a socket by each
+
+for (const [label, env] of [
+ ['the folder token-tv start uses', {}],
+ ['HOME', { HOME }],
+ ['XDG_CONFIG_HOME', { HOME, XDG_CONFIG_HOME: '/xdg' }],
+ ['an absolute TOKEN_TV_CONFIG', { TOKEN_TV_CONFIG: '/srv/tv/config.json' }],
+ ['a relative TOKEN_TV_CONFIG', { TOKEN_TV_CONFIG: 'tv\\config.json' }],
+ ['NO_PROXY=127.0.0.1', { HTTP_PROXY: PROXY, NO_PROXY: '127.0.0.1' }],
+ ['NO_PROXY=*', { ALL_PROXY: PROXY, no_proxy: '*' }],
+] as const) {
+ for (const windows of [true, false]) {
+ const name = windows ? 'on Windows nothing is sent, whatever the environment and the files say'
+ : 'off Windows the same folders are found and the moments go'
+ test(`${name} (${label})`, async ($: any, on: any) => {
+ const fetched: any[] = []
+ const pc = computer(on, { env: { USERPROFILE: 'C:/Users/u', ...(windows ? { OS: 'Windows_NT' } : {}), ...env },
+ root: 'C:\\work', files: EVERYWHERE, sockets: BESIDE, fetch: ($: any, e: any) => {
+ fetched.push(e) // whatever it is: a moment, a check, to a socket or a port
+ return { value: { status: 204, ok: true, headers: {}, text: '' } }
+ } })
+ const { call } = await prompt($, 'w1')
+ await group($, row('w1', { isRunning: true }))
+ pc.release('w1')
+ await call
+ await $.turn.complete(turn('w'))
+ await prompt($, 'w2')
+ await $.session.end({ reason: 'prompt_input_exit' })
+ await flush()
+ expect(fetched.map((e) => (e.init?.body ? named(e) : 'a request naming no moment'))).toEqual(windows ? []
+ : ['claude.ask', 'claude.answered', 'claude.end', 'claude.ask', 'claude.answered'])
+ })
+ }
+}
+
+test('on Windows nothing goes to TokenTV\'s port either, whatever answers there', async ($: any, on: any) => {
+ // the folder as TokenTV leaves it on Windows (live.url, no socket), and on the port a server that answers any
+ // check as TokenTV once did (405, `TokenTV: moments`) and takes any moment
+ const fetched: any[] = []
+ computer(on, { env: { USERPROFILE: 'C:/Users/u', OS: 'Windows_NT' }, files: EVERYWHERE, sockets: [],
+ fetch: ($: any, e: any) => {
+ fetched.push(e)
+ return { value: e.init?.method === 'POST' ? { status: 204, ok: true, headers: {}, text: '' }
+ : { status: 405, ok: false, headers: { allow: 'POST', tokentv: 'moments' }, text: '' } }
+ } })
+ await prompt($, 'w1')
+ await $.turn.complete(turn('w'))
+ await flush()
+ expect(fetched).toEqual([])
+})
+
+const named = (e: any) => JSON.parse(e.init.body).moment
+
+test('a TokenTV that never answers holds nothing up; what it held back past five seconds is dropped, new ones go',
+ async ($: any, on: any) => {
+ const clock = mock.clock(on, { now: 1_000_000 })
+ const tried: string[] = []
+ let hang = true
+ computer(on, {
+ fetch: async ($: any, e: any) => {
+ tried.push(named(e))
+ if (hang) await clock.sleep(60_000) // longer than any call waits for
+ return { value: { status: 204, ok: true, headers: {}, text: '' } }
+ },
+ })
+ const started = Date.now()
+ await prompt($, 'h1')
+ for (const id of ['a', 'b']) await $.turn.complete(turn(id)) // closes h1, then two ends
+ await flush()
+ expect(Date.now() - started).toBeLessThan(1000) // the hooks never waited for a send
+ expect(tried).toEqual(['claude.ask']) // the next waits for an answer, two seconds at most
+ for (let k = 0; k < 5; k++) {
+ await clock.advance(2000)
+ await flush()
+ }
+ // h1's answer waited five seconds for TokenTV to confirm the ask, in vain: not sent. The ends, held up past
+ // five seconds by then, are dropped rather than sent late.
+ expect(tried).toEqual(['claude.ask'])
+ hang = false // TokenTV answers again (another one started, say): a new moment goes at once
+ await $.turn.complete(turn('c'))
+ await flush()
+ expect(tried).toEqual(['claude.ask', 'claude.end'])
+ })
+
+test('an answer whose ask TokenTV confirmed late still goes', async ($: any, on: any) => {
+ const clock = mock.clock(on, { now: 1_000_000 })
+ const tried: string[] = []
+ computer(on, {
+ fetch: async ($: any, e: any) => {
+ tried.push(named(e))
+ if (named(e) === 'claude.ask') await clock.sleep(3000) // slower than the two seconds the queue waits
+ return { value: { status: 204, ok: true, headers: {}, text: '' } }
+ },
+ })
+ await prompt($, 'late')
+ await $.turn.complete(turn('l', { isAborted: true })) // closes the prompt, no bow
+ await flush()
+ await clock.advance(2000)
+ await flush()
+ expect(tried).toEqual(['claude.ask']) // the answer waits for the ask's own answer
+ await clock.advance(1000)
+ await flush()
+ expect(tried).toEqual(['claude.ask', 'claude.answered'])
+})
+
+test('each moment waits for the one before it to be answered, so TokenTV takes them in order', async ($: any, on: any) => {
+ const clock = mock.clock(on, { now: 1_000_000 })
+ const tried: string[] = []
+ const pc = computer(on, {
+ fetch: async ($: any, e: any) => {
+ tried.push(named(e))
+ await clock.sleep(400)
+ return { value: { status: 204, ok: true, headers: {}, text: '' } }
+ },
+ })
+ await prompt($, 'o1')
+ await $.turn.complete(turn('o')) // its answer and its end, right after one another
+ await flush()
+ expect(tried).toEqual(['claude.ask'])
+ await clock.advance(400)
+ await flush()
+ expect(tried).toEqual(['claude.ask', 'claude.answered'])
+ await clock.advance(400)
+ await flush()
+ expect(tried).toEqual(['claude.ask', 'claude.answered', 'claude.end'])
+ pc.release('o1')
+})
+
+test('an answer goes only to the TokenTV that counted its ask, not to one started since', async ($: any, on: any) => {
+ const stamps: Record<string, number> = { [STATE + '/live.url']: 111 }
+ const pc = computer(on, { stamps })
+ const { call } = await prompt($, 'r1')
+ stamps[STATE + '/live.url'] = 222 // TokenTV restarted: it never saw that ask
+ pc.release('r1')
+ await call
+ await $.turn.complete(turn('r'))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.end'])
+})
+
+test('a failing TokenTV is quiet: the hooks go on, each moment is tried once, and an ask it never took is not answered',
+ async ($: any, on: any) => {
+ const tried: string[] = []
+ computer(on, { fetch: ($: any, e: any) => { tried.push(named(e)); return { deny: 'connection refused' } } })
+ const { call } = await prompt($, 'f1')
+ await $.turn.complete(turn('f'))
+ await flush()
+ expect(tried).toEqual(['claude.ask', 'claude.end'])
+ })
+
+test('prompts, commands, paths, outputs and ids never leave the mod', async ($: any, on: any) => {
+ const pc = computer(on)
+ const canaries = ['CANARY-PROMPT-7f3', 'CANARY-CMD-91c', 'CANARY-PATH-2ab', 'CANARY-SESSION-5d0', 'CANARY-OUT-e44',
+ 'CANARY-TOOLID-0c1', 'CANARY-TURN-b77', 'CANARY-AGENT-3f9']
+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work/CANARY-PATH-2ab' })
+ await $.classic.SessionStart({ hook_event_name: 'SessionStart', session_id: 'CANARY-SESSION-5d0', permission_mode: 'default',
+ cwd: '/work/CANARY-PATH-2ab', transcript_path: '/work/CANARY-PATH-2ab/t.jsonl', source: 'startup' })
+ const call = $.tool.call({ tool: 'Bash', command: 'cat /work/CANARY-PATH-2ab # CANARY-CMD-91c', tool_use_id: 'CANARY-TOOLID-0c1',
+ agentId: 'CANARY-AGENT-3f9' })
+ await flush()
+ await $.tool.check({ tool: 'Bash', input: { command: 'CANARY-CMD-91c', file_path: '/work/CANARY-PATH-2ab' },
+ tool_use_id: 'CANARY-TOOLID-0c1', agentId: 'CANARY-AGENT-3f9' })
+ pc.release('CANARY-TOOLID-0c1')
+ await call
+ await $.turn.complete(turn('CANARY-TURN-b77', { answer: 'CANARY-OUT-e44 CANARY-PROMPT-7f3' }))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered', 'claude.end'])
+ const everything = JSON.stringify(pc.sent)
+ for (const canary of canaries) expect(everything).not.toContain(canary)
+ for (const one of pc.sent) {
+ expect(Object.keys(JSON.parse(one.init.body))).toEqual(['moment'])
+ expect(Object.keys(one.init.headers)).toEqual(['content-type'])
+ }
+})
+
+test('the call, its arguments and its result pass through untouched, and only you answer the prompt',
+ async ($: any, on: any) => {
+ const pc = computer(on)
+ const { call } = await prompt($, 'u1', 'echo "untouched" && ls -la')
+ expect(await Promise.race([call, flush().then(() => 'still waiting')])).toBe('still waiting')
+ expect(pc.calls).toEqual([{ tool: 'Bash', command: 'echo "untouched" && ls -la', tool_use_id: 'u1' }])
+ pc.release('u1')
+ expect(await call).toEqual({ result: 'ran u1', context: ['for the model'] })
+ })
+
+test('a subagent\'s prompt is its own even when the check does not say whose it is', async ($: any, on: any) => {
+ const pc = computer(on)
+ const sub = $.tool.call({ tool: 'Bash', command: 'make', tool_use_id: 's1', agentId: 'agent-9' })
+ await flush()
+ await $.tool.check({ tool: 'Bash', input: { command: 'make' }, tool_use_id: 's1' }) // Claude Code 2.1.289
+ await $.turn.complete(turn('main-turn')) // the main turn's end leaves the subagent's prompt open
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.end'])
+ await $.turn.complete(turn('sub-turn', { agentId: 'agent-9' }))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.ask', 'claude.end', 'claude.answered'])
+ pc.release('s1')
+ await sub
+})
+
+// --- /tokentv pet and /tokentv snack (e5) ----------------------------------------------------------------------------
+
+test('/tokentv is one slash command, offered as the session starts, running at once mid-turn', async ($: any, on: any) => {
+ const pc = computer(on)
+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })
+ expect(pc.registered).toEqual([{ name: 'tokentv', description: 'Pet Clawd on your TokenTV clock, or give it a snack',
+ argumentHint: 'pet | snack', immediate: true }])
+ expect(pc.sent).toEqual([]) // offering it sends nothing
+})
+
+test('/tokentv pet and /tokentv snack each send their one name, and only that', async ($: any, on: any) => {
+ const pc = computer(on)
+ expect(await tokentv($, 'pet')).toEqual({ text: 'A pat for Clawd, on its way to TokenTV.' })
+ await flush()
+ expect(pc.moments()).toEqual(['claude.pet'])
+ expect(pc.sent[0].url).toBe('http://127.0.0.1:8791/moment')
+ expect(pc.sent[0].init).toEqual({ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: '{"moment":"claude.pet"}', socketPath: STATE + '/live.sock' })
+ expect(await tokentv($, ' Snack ')).toEqual({ text: 'A snack for Clawd, on its way to TokenTV.' })
+ await flush()
+ expect(pc.moments()).toEqual(['claude.pet', 'claude.snack'])
+ expect(pc.sent[1].init.body).toBe('{"moment":"claude.snack"}')
+})
+
+test('anything else after /tokentv sends nothing, and its words go nowhere', async ($: any, on: any) => {
+ const pc = computer(on)
+ const words = [undefined, '', 'pet CANARY-ARG-1a', 'snack now CANARY-ARG-2b', 'CANARY-ARG-3c', 'petting', 'pet\nsnack',
+ 'claude.pet', 'claude.ask', '{"moment":"claude.ask"}', 'constructor', '__proto__', 'toString', 'pet snack']
+ for (const args of words) {
+ expect(await tokentv($, args)).toEqual({ text: 'Try /tokentv pet or /tokentv snack.' })
+ }
+ await flush()
+ expect(pc.sent).toEqual([])
+ expect(pc.reads).toEqual([]) // not even a look for TokenTV
+ await tokentv($, 'pet') // and the command still works
+ await flush()
+ expect(pc.moments()).toEqual(['claude.pet'])
+ expect(JSON.stringify(pc.sent)).not.toContain('CANARY')
+})
+
+test('the session\'s prompts, paths and ids never leave with a pat or a snack', async ($: any, on: any) => {
+ const pc = computer(on)
+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work/CANARY-PATH-6e1' })
+ await $.classic.SessionStart({ hook_event_name: 'SessionStart', session_id: 'CANARY-SESSION-1f2', permission_mode: 'default',
+ cwd: '/work/CANARY-PATH-6e1', transcript_path: '/work/CANARY-PATH-6e1/t.jsonl', source: 'startup' })
+ await tokentv($, 'pet')
+ await tokentv($, 'snack')
+ await $.turn.complete(turn('CANARY-TURN-9a0', { answer: 'CANARY-OUT-4d2 CANARY-PROMPT-3c3' }))
+ await flush()
+ expect(pc.moments()).toEqual(['claude.pet', 'claude.snack', 'claude.end'])
+ for (const one of pc.sent) {
+ expect(Object.keys(JSON.parse(one.init.body))).toEqual(['moment'])
+ expect(Object.keys(one.init.headers)).toEqual(['content-type'])
+ }
+ expect(JSON.stringify(pc.sent)).not.toContain('CANARY')
+})
+
+test('every press goes as it is made: TokenTV, not the mod, drops one while another is to show', async ($: any, on: any) => {
+ const pc = computer(on)
+ for (const args of ['pet', 'pet', 'snack', 'pet']) await tokentv($, args)
+ await flush()
+ expect(pc.moments()).toEqual(['claude.pet', 'claude.pet', 'claude.snack', 'claude.pet']) // in order, nothing added
+})
+
+for (const [label, options] of [['none at all', { files: {}, sockets: [] }], ['a live.url with no socket', { sockets: [] }]] as const) {
+ test(`no TokenTV running (${label}): /tokentv sends nothing, and says so`, async ($: any, on: any) => {
+ const pc = computer(on, options)
+ expect(await tokentv($, 'pet')).toEqual({ text: 'No TokenTV is running on this computer: nothing was sent.' })
+ await flush()
+ expect(pc.sent).toEqual([])
+ })
+}
+
+test('on Windows /tokentv sends nothing, and says so', async ($: any, on: any) => {
+ const fetched: any[] = []
+ computer(on, { env: { USERPROFILE: 'C:/Users/u', OS: 'Windows_NT' }, files: EVERYWHERE, sockets: BESIDE,
+ fetch: ($: any, e: any) => { fetched.push(e); return { value: { status: 204, ok: true, headers: {}, text: '' } } } })
+ expect(await tokentv($, 'pet')).toEqual({ text: 'On Windows the TokenTV mod sends nothing for now.' })
+ expect(await tokentv($, 'snack')).toEqual({ text: 'On Windows the TokenTV mod sends nothing for now.' })
+ await flush()
+ expect(fetched).toEqual([])
+})
+
+test('a pat never waits for TokenTV: one that hangs holds each press up two seconds at most, and one held past five is dropped',
+ async ($: any, on: any) => {
+ const clock = mock.clock(on, { now: 1_000_000 })
+ const tried: string[] = []
+ let hang = true
+ computer(on, {
+ fetch: async ($: any, e: any) => {
+ tried.push(named(e))
+ if (hang) await clock.sleep(60_000)
+ return { value: { status: 204, ok: true, headers: {}, text: '' } }
+ },
+ })
+ const started = Date.now()
+ for (const args of ['pet', 'snack', 'pet', 'snack']) await tokentv($, args)
+ expect(Date.now() - started).toBeLessThan(1000) // each command answered at once
+ await flush()
+ expect(tried).toEqual(['claude.pet']) // the next waits for its answer, two seconds at most
+ await clock.advance(2000)
+ await flush()
+ expect(tried).toEqual(['claude.pet', 'claude.snack'])
+ await clock.advance(2000)
+ await flush()
+ expect(tried).toEqual(['claude.pet', 'claude.snack', 'claude.pet'])
+ await clock.advance(2000) // the last press is six seconds old by its turn: dropped, never sent late
+ await flush()
+ await clock.advance(2000)
+ await flush()
+ expect(tried).toEqual(['claude.pet', 'claude.snack', 'claude.pet'])
+ hang = false // TokenTV answers again: a fresh press goes at once
+ await tokentv($, 'snack')
+ await flush()
+ expect(tried).toEqual(['claude.pet', 'claude.snack', 'claude.pet', 'claude.snack'])
+ })
+
+test('a failing TokenTV is quiet: each press is tried once, and the next one still goes', async ($: any, on: any) => {
+ const tried: string[] = []
+ let refuse = true
+ computer(on, { fetch: ($: any, e: any) => {
+ tried.push(named(e))
+ return refuse ? { deny: 'connection refused' } : { value: { status: 500, ok: false, headers: {}, text: '' } }
+ } })
+ await tokentv($, 'pet')
+ await flush()
+ refuse = false // now it answers, with an error
+ await tokentv($, 'snack')
+ await flush()
+ expect(tried).toEqual(['claude.pet', 'claude.snack'])
+})
diff --git a/docs/claude-code-mod.md b/docs/claude-code-mod.md
new file mode 100644
index 0000000..5a0340f
--- /dev/null
+++ b/docs/claude-code-mod.md
@@ -0,0 +1,119 @@
+# Your agents' moments on the clock: Claude Code and Codex
+
+On the Arcade face, TokenTV's pets also show what your agents are doing right now:
+
+- **Claude Code waits for you.** When a permission prompt opens, Clawd raises a hand, with the readout
+ `NEEDS YOU`, and has the clock to itself (the other services' pets come back after). After 5 minutes unanswered
+ it hops; after 15 it holds up a sign. Once you answer (yes or no) or the turn ends, the usual face comes back,
+ even while the command you allowed is still running. After 30 minutes unanswered it gives up and
+ goes back to the usual face too. With several Claude Code sessions, the hand stays up while any one of them
+ waits, and the 30 minutes count from the first prompt of that wait: then every prompt still open is let go
+ together, and the next one to open starts a new wait at the raised hand.
+- **A turn is done.** When a Claude Code turn ends, Clawd bows once, with the readout `DONE`; when a Codex turn
+ ends, the Codex cloud bows. At most one bow a minute, Claude and Codex together: a turn that ends inside that
+ minute gets no bow, and none is saved for later. A waiting prompt always comes first.
+- **A pat or a snack.** Type `/tokentv pet` or `/tokentv snack` in Claude Code: Clawd shows hearts (`PETTED`) or
+ eats a cookie (`SNACKING`) for one loop. One at a time: a press while one is still to come or playing is dropped,
+ not saved for later, and so is one while Claude Code waits for you.
+- **A break.** Not from your agents but from your usage: after an hour of work on any of your accounts (an account
+ is at work while its usage rose in the last ten minutes) since the last ten minutes with none at work, the pets on
+ the clock drink a glass of water or stretch, one or the other, for one loop (`DRINKING`, `STRETCHING`). The next
+ hour counts from there. A waiting prompt comes first; the break follows it, unless you took a break meanwhile.
+ While an account at work cannot be read (rate limited, an outage), that time counts as neither work nor a break,
+ for up to an hour.
+
+Every change reaches the clock as the animation it is playing finishes its loop, never in the middle of one, and
+a moment that does not change the picture sends nothing to the clock.
+
+## Claude Code
+
+Install the TokenTV plugin (Claude Code 2.1.275 or later) in a Claude Code session:
+
+```
+/plugin install tokentv --marketplace click6067-ship-it/token-tv
+```
+
+or add the marketplace first and install from it: `/plugin marketplace add click6067-ship-it/token-tv`, then
+`/plugin install tokentv@token-tv`. To try a copy of this repository without installing:
+`claude --plugin-dir ./claude-plugin`.
+
+The plugin is a mod: a few lines of TypeScript that run inside Claude Code (`claude-plugin/hooks/register.ts`).
+It watches Claude Code's own permission decision for each tool call, how Claude Code draws that call (running, as
+soon as you said yes), the end of that call and the end of each turn, and changes none of them. It adds one slash
+command, `/tokentv`, with two words after it: `/tokentv pet` and `/tokentv snack` (they touch nothing of Claude's
+turn). Anything else after `/tokentv` sends nothing; the command says so, and says when no TokenTV is running on
+this computer. It finds the TokenTV running on this computer from TokenTV's state
+folder, beside the config that `token-tv start` uses
+(`~/.config/token-tv/state`, or under `XDG_CONFIG_HOME`); for another config, set `TOKEN_TV_CONFIG` to its path in
+the environment Claude Code runs in. Give it as an absolute path: a relative one like `config.json` is looked for
+in the folder the Claude Code session started in (and TokenTV's in the folder TokenTV started in), which is seldom
+the same place. With no TokenTV running it does nothing.
+
+On Windows the plugin installs, but the mod sends nothing for now (`/tokentv` says so). There TokenTV has no
+socket, and Claude Code's own requests over TCP follow a redirect wherever it points, whatever the mod asks
+(measured with Claude Code 2.1.289), so a moment's name could leave this computer. Codex's `token-tv notify` and
+everything else in TokenTV work on Windows as they do elsewhere.
+
+## Codex
+
+Codex runs a program of your choice when a turn ends. Add one line to `~/.codex/config.toml`, the one that
+matches how you run TokenTV:
+
+- installed with pip, pipx or uv tool: `notify = ["token-tv", "notify"]`
+- run with uvx: `notify = ["uvx", "token-tv", "notify"]`
+- run with npx: `notify = ["npx", "--yes", "token-tv", "notify"]`
+
+For another config, add its path: `notify = ["token-tv", "notify", "--config", "/path/to/config.json"]`. Codex
+takes one notify program; if you already have one, call `token-tv notify` from it with the same JSON argument.
+`token-tv notify` reacts only to `agent-turn-complete`, prints nothing and is done within two seconds. With npx,
+the very first run prepares TokenTV for about a minute; later runs are quick.
+
+## What is sent, and what is kept
+
+Only the moment's name, and only to the TokenTV on this computer: `claude.ask` (a prompt is waiting for you),
+`claude.answered` (you answered that prompt, or it is over), `claude.end` (a Claude Code turn ended),
+`claude.pet` and `claude.snack` (`/tokentv pet`, `/tokentv snack`) or `codex.end` (a Codex turn ended), as
+`{"moment": "<name>"}` in a `POST /moment`; the words you type after `/tokentv` are not sent, only the name. On
+Linux and macOS it goes only over TokenTV's own socket in its state folder (`live.sock`), where no proxy or redirect
+can take it anywhere else;
+with no socket there, nothing is sent. On Windows only `token-tv notify` sends: to TokenTV's port on `127.0.0.1`,
+through no proxy and following no redirect. Your prompts, commands, file paths, outputs and session ids never
+leave the mod or `token-tv notify`.
+
+TokenTV keeps the moments in memory only: nothing is logged, nothing is written to disk, and a restart forgets
+them. It takes moments only from this computer, by its own name, never from a web page. What goes to the clock
+is the picture, as for everything else TokenTV shows.
+
+## Turning it off
+
+- Claude Code: `/plugin disable tokentv` (or `/plugin uninstall tokentv`).
+- Codex: remove the `notify` line.
+- On any face other than Arcade, the moments are not shown.
+
+## Good to know
+
+- The mod sees your answer as Claude Code draws the call again (running, or refused). Where no such drawing names
+ the call (a desktop app older than that), the hand comes down when the call is over instead: after you approve a
+ long command there, it stays up until the command finishes.
+- In auto mode, Claude Code's classifier (not you) settles most calls, and those raise no hand; an ask rule or a
+ hook that asks you still does. Where an organization manages Claude Code, the mod cannot read the permission
+ mode, and auto mode's checks may briefly raise the hand.
+- With several Claude accounts on the clock, every Claude pet shows the moment: Claude Code does not say which
+ account a session uses.
+- TokenTV and the agents have to run on the same computer.
+- On Windows an old address left by a TokenTV that did not stop cleanly (ended from Task Manager, say) may name a
+ port another program holds now: `token-tv notify` sends it the name `codex.end`, which stays on this computer.
+
+## For developers
+
+The endpoint takes exactly `{"moment": "<name>"}` (JSON, at most 256 bytes), the name one of the six above, and
+answers `204` at once; anything else gets a `4xx` and changes nothing. Its `204` to a `claude.ask` says, in a
+`TokenTV-Wait-Age` header, how many seconds the wait that ask joined has lasted, so the mod sends no answer after
+TokenTV has let that wait go. A
+`GET /moment` is no moment (`405`, `Allow: POST`). A moment's request has 2 seconds to arrive whole, the
+dashboard's other requests 10; one that runs out is answered `408`, and a moment that came whole but late counts
+for nothing. The moments' rules are in `token_tv/moments.py` (time comes from
+`moments.CLOCK`, which tests replace with a fake clock; the break's hour from the readings' times on the wall clock,
+`time.time()`, and `moments.RANDOM` picks each break), the clock timing in `token_tv/live.py` (`sync_moments`;
+on an SD_PRO a loop is its GIF's pictures, each for its delay but at least `device_frame_ms`, 142 by default).
+Tests: `python3 -B -m unittest discover -s tests` and `claude plugin test claude-plugin`.
diff --git a/docs/hardware-compatibility.md b/docs/hardware-compatibility.md
index 2c9fd04..7e33fac 100644
--- a/docs/hardware-compatibility.md
+++ b/docs/hardware-compatibility.md
@@ -74,6 +74,12 @@ contributors' units ran; if an Ultra ever freezes on a picture, turn it off and
On the SD_PRO, leave TokenTV's `tokentv*.gif` files alone in the album while TokenTV runs: it switches them
itself, and one turned on by hand can be the next file TokenTV writes while the clock plays it.
+The SD_PRO shows each picture of a GIF for as long as the GIF asks, but never shorter than about 142 ms (on the
+author's unit: two films at 120 fps of pictures asking 70 ms, and a test GIF holding one picture for 3 s), so
+TokenTV times the end of each animation loop by its pictures' times that way, and a change lands as a loop ends. A
+unit whose shortest picture is longer or shorter can say so in the config: `"device_frame_ms": 150` (20 to 2000).
+The GIF itself stays as it is. On the Ultra, TokenTV times a loop as long as the GIF declares (not measured yet).
+
A new SmallTV-Ultra has no `/app.json` (it answers 404) until its theme is changed for the first time.
TokenTV then records that there was no saved theme, switches to the Photo Album as usual, and on restore
puts autoplay back but leaves the theme alone. Pick a theme on the clock's settings page afterwards if you
diff --git a/package.json b/package.json
index 50109dd..c8ab62e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "token-tv",
- "version": "0.4.1",
+ "version": "0.5.0",
"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 6d6d779..f819bc1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "token-tv"
-version = "0.4.1"
+version = "0.5.0"
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/tests/test_autostart.py b/tests/test_autostart.py
index 77f3c6d..97bba8e 100644
--- a/tests/test_autostart.py
+++ b/tests/test_autostart.py
@@ -1,3 +1,4 @@
+import os
import sys
import tempfile
import unittest
@@ -76,12 +77,56 @@ class AutostartTests(unittest.TestCase):
config = self.folder / 'config.json'
(self.folder / 'state').mkdir()
(self.folder / 'state' / 'live.pid').write_text('4242', encoding='utf-8')
+ (self.folder / 'state' / 'live.url').write_text('http://127.0.0.1:8787', 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=f'"C:\\Py\\pythonw.exe" -m token_tv start --yes --no-browser --config "{config}"', 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())
+ # ended outright, it could not take its address away itself: no agent goes on telling that port
+ self.assertFalse((self.folder / 'state' / 'live.url').exists())
+ self.assertFalse((self.folder / 'state' / 'live.pid').exists())
+
+ def test_windows_off_leaves_the_address_of_a_tokentv_started_meanwhile(self):
+ config, state = self.folder / 'config.json', self.folder / 'state'
+ state.mkdir()
+ (state / 'live.pid').write_text('4242', encoding='utf-8')
+ (state / 'live.url').write_text('http://127.0.0.1:8787', 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=f'"C:\\Py\\pythonw.exe" -m token_tv start --yes --no-browser --config "{config}"', stderr='')
+
+ def ended_and_another_started(pid, sig): # a new TokenTV starts the moment the old one is gone
+ (state / 'live.pid').write_text('5151', encoding='utf-8')
+ (state / 'live.url').write_text('http://127.0.0.1:8790', encoding='utf-8')
+ with self.placed('startup'), mock.patch.object(autostart, 'run', return_value=python), \
+ mock.patch('os.kill', side_effect=ended_and_another_started) as kill:
+ self.assertIn('stopped', autostart.remove())
+ kill.assert_called_once_with(4242, autostart.signal.SIGTERM)
+ self.assertEqual((state / 'live.pid').read_text(encoding='utf-8'), '5151') # the new one's, kept
+ self.assertEqual((state / 'live.url').read_text(encoding='utf-8'), 'http://127.0.0.1:8790')
+
+ def test_windows_off_leaves_the_files_of_a_tokentv_that_holds_the_lock(self):
+ # a new TokenTV that took the lock the moment the old one was gone, before writing its own number
+ state = self.folder / 'state'
+ state.mkdir()
+ (state / 'live.pid').write_text('4242', encoding='utf-8')
+ (state / 'live.url').write_text('http://127.0.0.1:8787', encoding='utf-8')
+ from token_tv.private_files import open_private
+ with open_private(state / 'live.lock') as held:
+ if os.name == 'nt':
+ import msvcrt
+ msvcrt.locking(held.fileno(), msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ with mock.patch.object(autostart, 'LOCK_WAIT', .2):
+ autostart.forget_ended_run(state, 4242)
+ self.assertTrue((state / 'live.pid').exists())
+ self.assertTrue((state / 'live.url').exists())
+ autostart.forget_ended_run(state, 4242) # once the lock is free, the ended run's files go
+ self.assertFalse((state / 'live.pid').exists())
+ self.assertFalse((state / 'live.url').exists())
def test_windows_off_never_ends_another_program_that_took_the_number(self):
config = self.folder / 'config.json'
@@ -92,6 +137,7 @@ class AutostartTests(unittest.TestCase):
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()
+ self.assertTrue((self.folder / 'state' / 'live.pid').exists()) # whatever runs, nothing of it is touched
def test_the_npm_launchers_own_uv_starts_it_with_the_computer(self):
env = {'TOKEN_TV_LAUNCHER': 'npx', 'TOKEN_TV_UVX': '/home/me/.cache/token-tv/uv/uvx'}
diff --git a/tests/test_breaks.py b/tests/test_breaks.py
new file mode 100644
index 0000000..e814165
--- /dev/null
+++ b/tests/test_breaks.py
@@ -0,0 +1,676 @@
+"""v2 phase 2, e6: after an hour of work (any account at work: its usage rose within state.ACTIVE_SECONDS, all of
+them together counted once) since the last break (BREAK with nobody at work) or the last reminder, the pets on the
+clock drink water or stretch, one of the two at random, for one loop at the end of the loop playing. A Claude wait
+outranks it: it plays after the wait if no break came meanwhile. Nothing piles up."""
+import io
+import sys
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run
+from test_moments import FakeClock, Rig, SyntheticTime, physical # noqa: E402
+from test_limit_warning import SyntheticWall # noqa: E402
+
+from token_tv import arcade, moments, state # noqa: E402
+from token_tv.moments import BREAK, BREAKS, WORK, Moments, Work, overlay # noqa: E402
+from token_tv.sample import D, H, snapshot # noqa: E402
+
+ACTIVE = state.ACTIVE_SECONDS
+NOW = int(time.mktime((2026, 11, 1, 14, 1, 0, 0, 0, -1))) # Sunday 2:01 pm wherever the tests run (the stage dims at night)
+PETS = ('claude', 'codex', 'grok', 'copilot', 'antigravity')
+
+
+class Picks:
+ """moments.RANDOM as a test sets it: each reminder's break in turn from `kinds`."""
+ def __init__(self, *kinds):
+ self.kinds, self.asked = list(kinds), 0
+
+ def choice(self, options):
+ self.asked += 1
+ kind = self.kinds.pop(0)
+ assert kind in options
+ return kind
+
+
+class WorkTests(unittest.TestCase):
+ """The hour of work, on the readings' own times (wall clock seconds here)."""
+ def setUp(self):
+ self.picks = Picks(*(['drink', 'stretch'] * 8))
+ patcher = mock.patch.object(moments, 'RANDOM', self.picks)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.w = Work(active=ACTIVE)
+
+ def rise(self, at, key='a', now=None):
+ self.w.observe({key: {'rose_at': at}}, at if now is None else now)
+
+ def work(self, start, end, every=60, key='a'):
+ """Rises every `every` seconds from `start` to `end`, each read as it happens."""
+ t = start
+ while t <= end:
+ self.rise(t, key)
+ t += every
+
+ def test_an_hour_of_work_makes_the_reminder_due_once_at_its_end(self):
+ self.work(0, WORK - 60)
+ self.w.advance(WORK - .001)
+ self.assertIsNone(self.w.due) # not a moment before
+ self.rise(WORK)
+ self.assertEqual(self.w.due, (WORK, 'drink'))
+ self.work(WORK + 60, 2 * WORK + 600) # an hour more without it shown: still that one reminder
+ self.assertEqual(self.w.due, (WORK, 'drink'))
+ self.assertEqual(self.picks.asked, 1)
+
+ def test_accounts_at_work_together_count_once_and_a_handover_keeps_the_hour(self):
+ for t in range(0, WORK, 60): # two at once, rising out of step
+ self.w.observe({'a': {'rose_at': t}, 'b': {'rose_at': t + 30}}, t + 30)
+ self.w.advance(WORK - .001)
+ self.assertIsNone(self.w.due) # no faster for two
+ self.w.advance(WORK)
+ self.assertEqual(self.w.due[0], WORK)
+ other = Work(active=ACTIVE)
+ for t in range(0, WORK // 2, 60):
+ other.observe({'a': {'rose_at': t}}, t)
+ for t in range(WORK // 2, WORK + 60, 60): # A stops, B goes on: no gap with nobody at work
+ other.observe({'a': {'rose_at': WORK // 2 - 60}, 'b': {'rose_at': t}}, t)
+ self.assertEqual(other.due[0], WORK)
+
+ def test_a_short_gap_keeps_the_work_done_and_adds_none(self):
+ self.work(0, 1800) # the last rise at 1800: at work until 1800 + ACTIVE
+ back = 1800 + ACTIVE + BREAK - 1 # a gap one second short of a break
+ self.work(back, back + 2 * WORK, every=60)
+ worked = 1800 + ACTIVE # done before the gap
+ self.assertEqual(self.w.due[0], back + WORK - worked) # not at wall WORK, and not a whole new hour
+
+ def test_a_break_starts_the_hour_over_at_exactly_its_length_not_a_moment_sooner(self):
+ edge = 1800 + ACTIVE # when the last account stopped counting as at work
+ for gap, starts_over in ((BREAK - .001, False), (BREAK, True)):
+ self.w = Work(active=ACTIVE)
+ self.work(0, 1800)
+ back = edge + gap
+ self.rise(back)
+ self.work(back + 60, back + 2 * WORK)
+ self.assertEqual(self.w.due[0], back + WORK if starts_over else back + WORK - edge, gap)
+
+ def test_a_rise_read_late_counts_its_work_and_ends_the_gap_before_a_break(self):
+ self.work(0, 1800)
+ edge = 1800 + ACTIVE
+ self.w.advance(edge + BREAK + 5) # looked at past what would be a break, before the reading came in
+ self.assertTrue(self.w.rested(edge + BREAK + 5))
+ late = edge + BREAK - .5 # the rise in that reading came just before
+ self.rise(late, now=edge + BREAK + 5)
+ self.assertFalse(self.w.rested(edge + BREAK + 5))
+ self.work(edge + BREAK + 60, edge + 3 * WORK)
+ self.assertAlmostEqual(self.w.due[0], late + WORK - edge, places=6) # the work before the gap kept
+
+ def test_a_rise_read_after_a_later_one_still_counts_for_when_it_was_measured(self):
+ self.rise(60, 'a')
+ self.rise(900, 'a') # A again at 900: on its own, a gap from 660 with nobody at work
+ self.rise(600, 'b', now=960) # B's rise at 600, read only at 960 (its snapshot written late, elsewhere)
+ self.work(960, WORK + 600, key='a')
+ self.assertEqual(self.w.due[0], 60 + WORK) # their work together is unbroken from 60: due an hour on
+ self.assertEqual(self.picks.asked, 1)
+
+ def test_a_rise_read_late_in_what_had_looked_like_a_break_keeps_the_hour(self):
+ self.work(0, 1800) # at work until 1800 + ACTIVE
+ edge = 1800 + ACTIVE
+ back = edge + BREAK + 100
+ self.work(back, back + 600) # back after what looks like a break: the hour started over at `back`
+ self.assertEqual(self.w.start, back)
+ self.rise(edge + BREAK / 2, 'b', now=back + 600) # but another account rose in that gap: read only now
+ self.assertEqual(self.w.start, 0) # no break after all
+ self.work(back + 660, back + 2 * WORK)
+ self.assertEqual(self.w.due[0], edge + BREAK / 2 + (WORK - edge)) # the work before the gap kept
+
+ def test_the_hour_is_the_same_whatever_order_its_rises_are_read_in(self):
+ import random
+ # A short gap, one that a single rise splits in two, an hour done, a real break, and another hour.
+ rises = sorted([(t, 'a') for t in range(0, 1500, 60)] + [(t, 'b') for t in range(2500, 3000, 100)] +
+ [(3600, 'd')] + [(t, 'c') for t in range(4300, 9000, 90)] + [(t, 'e') for t in range(11000, 14700, 60)])
+ states = []
+ for order in range(6):
+ picks = Picks(*(['drink', 'stretch'] * 8))
+ with mock.patch.object(moments, 'RANDOM', picks):
+ work, seen = Work(active=ACTIVE), list(rises)
+ if order: # each reading comes in up to a quarter of an hour late, in an order of its own
+ seen.sort(key=lambda rise: rise[0] + random.Random(f'{order}{rise}').uniform(0, 900))
+ now = 0
+ for at, key in seen:
+ now = max(now, at)
+ work.observe({key: {'rose_at': at}}, now)
+ if order == 0 and work.due and not states:
+ states.append(work.due) # (the first hour's reminder, read in order)
+ work.advance(14700)
+ states.append((work.due, picks.asked, work.start, round(work.credit, 6)))
+ self.assertEqual(states[0], (4160, 'drink')) # 2040 + 1000 + the gap's other side, 600, then 560 more
+ self.assertEqual(len(set(states[1:])), 1, states)
+ self.assertEqual(states[1], ((14600, 'stretch'), 2, 11000, 3700.0))
+
+ def test_rises_summed_up_after_hours_count_as_they_did(self):
+ long = Work(active=ACTIVE)
+ for t in range(0, 4 * WORK, 60): # four hours at work, the reminder never shown (no clock, say)
+ long.observe({'a': {'rose_at': t}}, t)
+ self.assertLess(len(long.rises), 2 * Work.KEEP // 60 + 20) # (the older rises summed up)
+ self.assertEqual(long.due, (WORK, 'drink')) # due since the first hour, that one reminder
+ long.shown(4 * WORK)
+ for t in range(4 * WORK + 60, 5 * WORK + 60, 60):
+ long.observe({'a': {'rose_at': t}}, t)
+ self.assertEqual(long.due, (5 * WORK, 'stretch')) # an hour from its showing
+
+ def fail(self, start, end, good, rose, key='a', status='stale', every=60):
+ """`key`'s readings failing every `every` seconds over [start, end): its last good one at `good`, its last
+ rise at `rose` (as a failed reading keeps them)."""
+ for t in range(start, end, every):
+ self.w.observe({key: {'status': status, 'rose_at': rose, 'last_success_at': good}}, t)
+
+ def test_an_account_at_work_whose_readings_fail_is_neither_at_work_nor_resting(self):
+ self.work(0, 1800) # at work until 1800 + ACTIVE
+ self.fail(1860, 3060, good=1800, rose=1800) # then twenty minutes of failed readings (rate limited, say)
+ self.assertFalse(self.w.rested(3060)) # no break counted through them
+ self.w.observe({'a': {'status': 'ok', 'rose_at': 3060, 'last_success_at': 3060}}, 3060) # in again, at work
+ self.assertEqual(self.w.start, 0) # the hour goes on
+ self.work(3120, 3 * WORK)
+ self.assertEqual(self.w.due[0], 3060 + WORK - (1800 + ACTIVE)) # and the time it failed was no work either
+
+ def test_an_account_idle_as_its_readings_began_to_fail_rests_meanwhile(self):
+ self.work(0, 1800)
+ for t in range(1860, 2700, 60): # readings in, no rise: idle from 1800 + ACTIVE
+ self.w.observe({'a': {'status': 'ok', 'rose_at': 1800, 'last_success_at': t}}, t)
+ self.fail(2700, 3120, good=2640, rose=1800, status='rate_limited')
+ self.w.observe({'a': {'status': 'ok', 'rose_at': 3120, 'last_success_at': 3120}}, 3120)
+ self.assertEqual(self.w.start, 3120) # a break all the same: the hour starts over
+
+ def test_readings_failing_past_an_hour_count_as_rest_after_it(self):
+ self.work(0, 1800)
+ self.fail(1860, 1800 + WORK + BREAK + 60, good=1800, rose=1800, status='error')
+ self.assertFalse(self.w.rested(1800 + WORK + BREAK - 1))
+ self.assertTrue(self.w.rested(1800 + WORK + BREAK)) # held for WORK, then BREAK of rest
+ self.w.observe({'a': {'status': 'ok', 'rose_at': 1800 + WORK + BREAK + 60}}, 1800 + WORK + BREAK + 60)
+ self.assertEqual(self.w.start, 1800 + WORK + BREAK + 60)
+
+ def test_a_rate_limited_account_at_work_holds_the_hour_through_the_store(self):
+ from token_tv.state import UsageStore
+ reading = {'status': 'ok', 'used': 10.0, 'at': 0}
+
+ def fetch(account):
+ ok = reading['status'] == 'ok'
+ return {'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex', 'status': reading['status'],
+ 'fetched_at': reading['at'], 'identity_verified': ok, 'source': 'mini',
+ 'windows': [{'label': '5H', 'used_percent': reading['used'], 'resets_at': reading['at'] + 4 * H}]
+ if ok else []}
+ store = UsageStore([{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex'}], fetch=fetch)
+
+ def read(t, status='ok', more=.01):
+ reading.update(status=status, at=NOW + t, used=reading['used'] + (more if status == 'ok' else 0))
+ with mock.patch.object(state, 'time', SyntheticWall(NOW + t)):
+ store.fetched.clear()
+ store.waits.clear() # (read again at once, whatever its back-off)
+ store.refresh()
+ self.w.observe(store.snapshot()['accounts'], NOW + t)
+ for t in range(0, 1860, 60):
+ read(t) # at work, its usage rising each minute (the first rise with the second reading)
+ for t in range(1860, 3060, 60):
+ read(t, 'rate_limited') # twenty minutes of 429s
+ self.assertEqual(store.snapshot()['accounts']['codex_a']['status'], 'stale')
+ for t in range(3060, 2 * WORK, 60):
+ read(t)
+ worked = 1800 + ACTIVE - 60 # before the 429s
+ self.assertEqual(self.w.due[0], NOW + 3060 + WORK - worked) # no break, and no work while it failed
+
+ def test_a_shown_reminder_starts_the_next_hour_where_it_went_on(self):
+ self.work(0, WORK)
+ self.assertEqual(self.w.due[0], WORK)
+ shown = WORK + 1300 # deferred (by a wait, say): the next hour counts from its showing, not its due time
+ self.work(WORK + 60, shown - 60)
+ self.w.shown(shown)
+ self.assertIsNone(self.w.due)
+ self.work(shown + 20, shown + 2 * WORK)
+ self.assertEqual(self.w.due, (shown + WORK, 'stretch')) # and its break picked anew
+
+ def test_a_break_lets_a_reminder_not_yet_shown_go_and_needs_a_new_hour(self):
+ self.work(0, WORK)
+ self.assertIsNotNone(self.w.due)
+ edge = WORK + ACTIVE
+ self.assertFalse(self.w.rested(edge + BREAK - .001))
+ self.assertTrue(self.w.rested(edge + BREAK)) # (not shown meanwhile)
+ self.rise(edge + BREAK + 30)
+ self.assertIsNone(self.w.due)
+ self.work(edge + BREAK + 90, edge + BREAK + 30 + WORK - 1)
+ self.assertIsNone(self.w.due)
+ self.rise(edge + BREAK + 30 + WORK)
+ self.assertEqual(self.w.due[0], edge + BREAK + 30 + WORK)
+
+ def test_only_a_rise_is_work(self):
+ for row in ({}, {'rose_at': None}, {'rose_at': True}, {'rose_at': float('nan')}, {'rose_at': 'x'}, 'x'):
+ self.w.observe({'a': row}, 100)
+ self.assertEqual((self.w.credit, self.w.last), (0.0, None))
+ self.rise(100)
+ for t in range(160, WORK + 1000, 60):
+ self.w.observe({'a': {'rose_at': 100}}, t) # the same rise read again and again: no more work
+ self.assertEqual(self.w.credit, ACTIVE)
+ self.assertIsNone(self.w.due)
+
+ def test_the_next_due_time_is_known_while_work_goes_on(self):
+ self.work(0, 600)
+ self.assertEqual(self.w.next_due(600), None) # (not reachable before this rise's activity ends)
+ self.work(660, WORK - ACTIVE)
+ self.assertEqual(self.w.next_due(WORK - ACTIVE), WORK)
+ self.assertIsNone(Work(active=ACTIVE).next_due(0))
+
+ def test_the_break_has_a_length_of_its_own(self):
+ with mock.patch.object(moments, 'BREAK', BREAK // 2): # the owner's number, apart from ACTIVE_SECONDS
+ self.work(0, 1800)
+ self.rise(1800 + ACTIVE + BREAK // 2)
+ self.work(1800 + ACTIVE + BREAK // 2 + 60, 1800 + 2 * WORK)
+ self.assertEqual(self.w.due[0], 1800 + ACTIVE + BREAK // 2 + WORK)
+ self.assertEqual(self.w.active, ACTIVE)
+
+
+class BreakStateTests(unittest.TestCase):
+ """The break among the moments, on moments.CLOCK, with the wall clock moving with it."""
+ def setUp(self):
+ self.clock = FakeClock()
+ self.wall0 = 1_800_000_000.0
+ for patcher in (mock.patch.object(moments, 'CLOCK', self.clock),
+ mock.patch.object(moments, 'time', SyntheticTime(self.clock, self.wall0)),
+ mock.patch.object(moments, 'RANDOM', Picks('stretch', 'drink', 'stretch'))):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.woken = []
+ self.m = Moments({'claude', 'codex'}, wake=lambda: self.woken.append(self.clock.t), active=ACTIVE)
+
+ def wall(self):
+ return self.wall0 + (self.clock.t - 10_000.0)
+
+ def work_until(self, t, every=60):
+ """A Codex account rising every `every` seconds (moments.CLOCK) up to `t`, each reading taken at once."""
+ while self.clock.t + every <= t:
+ self.clock.t += every
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}})
+
+ def test_after_an_hour_the_break_is_due_for_every_pet_once(self):
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}})
+ start = self.clock.t
+ self.assertIsNone(self.m.next_change()) # the hour is not reachable on this rise alone
+ self.work_until(start + WORK - 300)
+ self.assertEqual(self.m.next_change(), start + WORK) # it is now: TokenTV wakes for it, no reading needed
+ self.work_until(start + WORK - 1)
+ self.assertIsNone(self.m.wanted()[0])
+ self.clock.t = start + WORK
+ what, since, mark = self.m.wanted()
+ self.assertEqual((what, since, mark), (('break', 'stretch'), start + WORK, {'kind': 'stretch'}))
+ self.assertTrue(self.m.busy())
+ drawn = overlay(snapshot(NOW, [('claude_a', 'CLAUDE A', 'claude', [('WEEK', 40, 3 * D)]),
+ ('codex_a', 'CODEX A', 'codex', [('5H', 20, 2 * H)])]), what, mark)
+ self.assertEqual({key: row.get('moment') for key, row in drawn['accounts'].items()},
+ {'claude_a': {'kind': 'stretch'}, 'codex_a': {'kind': 'stretch'}})
+ for _ in range(5):
+ self.assertEqual(self.m.wanted()[0], ('break', 'stretch')) # the same choice however often looked at
+ self.m.shown(what, self.clock.t + 2)
+ self.assertEqual(self.m.wanted()[:2], (None, self.clock.t + 2)) # one loop, then the usual face
+ self.assertFalse(self.m.busy())
+
+ def test_a_wait_outranks_it_and_it_plays_after_the_wait(self):
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}})
+ start = self.clock.t
+ self.work_until(start + WORK - 120)
+ self.m.note('claude.ask')
+ self.work_until(start + WORK + 300)
+ self.assertEqual(self.m.wanted()[0], ('needs', 2)) # due meanwhile, but the wait is on the clock
+ self.m.note('claude.answered')
+ answered = self.clock.t
+ self.assertEqual(self.m.wanted()[:2], (('break', 'stretch'), answered)) # from the wait's end
+ self.m.shown(('break', 'stretch'), answered + 3)
+ self.work_until(answered + 3 + WORK - 60)
+ self.assertIsNone(self.m.wanted()[0])
+ self.work_until(answered + 3 + WORK + 60)
+ self.assertEqual(self.m.wanted()[0], ('break', 'drink')) # an hour from its showing
+
+ def test_a_break_while_the_wait_was_on_lets_it_go(self):
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}})
+ start = self.clock.t
+ self.work_until(start + WORK)
+ self.m.note('claude.ask')
+ last = self.clock.t
+ self.clock.t = last + ACTIVE + BREAK + 5 # nobody at work meanwhile
+ self.m.note('claude.answered')
+ self.assertIsNone(self.m.wanted()[0])
+ self.assertFalse(self.m.busy())
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}}) # work again
+ back = self.clock.t
+ self.work_until(back + WORK - 60)
+ self.assertIsNone(self.m.wanted()[0]) # a new hour from the work after the break
+ self.work_until(back + WORK)
+ self.assertEqual(self.m.wanted()[0], ('break', 'drink'))
+
+ def test_a_reading_that_makes_it_due_wakes_the_publisher(self):
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}})
+ start = self.clock.t
+ self.work_until(start + WORK - 30)
+ self.woken.clear()
+ self.clock.t = start + WORK + 30 # the next reading, late
+ self.assertTrue(self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}}))
+ self.assertEqual(self.woken, [self.clock.t])
+ self.assertEqual(self.m.wanted()[:2], (('break', 'stretch'), start + WORK))
+
+ def test_with_no_clock_to_show_it_on_the_break_stays_due_and_its_hour_counts_from_its_showing(self):
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}})
+ start = self.clock.t
+ self.work_until(start + WORK)
+ self.assertTrue(self.m.busy())
+ count = self.m.count
+ self.m.drop_bow() # another face, no clock, or the clock not answering, as it came due
+ self.assertEqual(self.m.count, count) # nothing changed:
+ self.assertEqual(self.m.wanted()[:2], (('break', 'stretch'), start + WORK)) # still due, the same break
+ self.work_until(start + WORK + 900) # a quarter of an hour more of work without a clock
+ self.m.drop_bow()
+ self.assertEqual(self.m.wanted()[:2], (('break', 'stretch'), start + WORK)) # that one reminder still, no other
+ shown = self.clock.t
+ self.m.shown(('break', 'stretch'), shown) # a clock takes it at last
+ self.work_until(shown + WORK - 60)
+ self.assertIsNone(self.m.wanted()[0])
+ self.work_until(shown + WORK + 60)
+ self.assertEqual(self.m.wanted()[0], ('break', 'drink')) # an hour from when it went on
+
+ def test_it_takes_nothing_from_the_bows_minute(self):
+ self.m.note('claude.end')
+ self.m.shown(('done', 'claude'), self.clock.t)
+ self.m.observe({'accounts': {'codex_a': {'provider': 'codex', 'rose_at': self.wall()}}})
+ start = self.clock.t
+ self.work_until(start + WORK)
+ self.assertEqual(self.m.wanted()[0], ('break', 'stretch'))
+ self.m.shown(('break', 'stretch'), self.clock.t)
+ self.assertFalse(self.m.cooling(self.clock.t)) # a break starts no bow's minute
+ self.m.note('claude.end')
+ self.assertEqual(self.m.wanted()[0], ('done', 'claude'))
+
+
+class BreakDrawingTests(unittest.TestCase):
+ def picture(self, provider, kind):
+ data = snapshot(NOW, [(f'{provider}_a', f"{arcade.SHORT_NAME.get(provider, provider.upper())} A", provider,
+ [('5H', 30, 2 * H)])])
+ data['accounts'][f'{provider}_a']['moment'] = {'kind': kind}
+ return arcade.render_arcade(data, NOW)
+
+ def test_every_pet_drinks_and_stretches_moving_through_one_loop(self):
+ water = (52, 140, 255) # the glass's water, the same for every pet
+ for provider in PETS:
+ stages = {}
+ for kind in BREAKS:
+ gif = Image.open(io.BytesIO(self.picture(provider, kind)))
+ shots = []
+ for n in range(gif.n_frames):
+ gif.seek(n)
+ shots.append(gif.convert('RGB').crop((0, 28, 240, 170)))
+ self.assertGreaterEqual(len({s.tobytes() for s in shots}), 10, (provider, kind)) # visibly moving
+ colours = set().union(*({c for _, c in s.getcolors(65536)} for s in shots))
+ self.assertEqual(water in colours, kind == 'drink', (provider, kind))
+ stages[kind] = shots
+ self.assertNotEqual(stages['drink'][len(stages['drink']) // 2].tobytes(),
+ stages['stretch'][len(stages['stretch']) // 2].tobytes())
+
+ def test_its_readout_says_which_break(self):
+ data = snapshot(NOW, [('grok_a', 'GROK A', 'grok', [('BUDGET', 30, 3 * D)])])
+ row = dict(data['accounts']['grok_a'], key='grok_a')
+ for kind, word in (('drink', 'DRINKING'), ('stretch', 'STRETCHING')):
+ moved = dict(row, moment={'kind': kind})
+ self.assertEqual(arcade.action_label(moved, arcade.scene_plan(moved, NOW), None, 0, 120), word)
+
+ def test_the_pets_that_would_be_on_the_clock_take_it_and_nobody_else_joins(self):
+ mark = {'kind': 'drink'}
+ accounts = [(f'{p}_a', f'{p.upper()} A', p, [('5H', 20 + 5 * k, 2 * H)]) for k, p in enumerate(PETS)]
+ data = snapshot(NOW, accounts)
+ for minute in range(0, 30, 6): # all idle, more than four: the four the rotation shows
+ at = NOW + minute * 60
+ usual = [row['key'] for row in arcade.shown_rows(data, at)]
+ self.assertEqual([row['key'] for row in arcade.shown_rows(overlay(data, ('break', 'drink'), mark), at)],
+ usual)
+ data['accounts']['codex_a']['active'] = True # one at work: it alone is on the clock, and takes the break
+ self.assertEqual([row['key'] for row in arcade.shown_rows(overlay(data, ('break', 'drink'), mark), NOW)],
+ ['codex_a'])
+
+ def test_one_picture_holds_every_pet_on_the_clock(self):
+ accounts = [('claude_a', 'CLAUDE A', 'claude', [('5H', 20, 2 * H)]), ('grok_a', 'GROK A', 'grok', [('BUDGET', 40, D)])]
+ data = overlay(snapshot(NOW, accounts), ('break', 'stretch'), {'kind': 'stretch'})
+ image = arcade.render_arcade(data, NOW)
+ self.assertEqual(image[:4], b'GIF8')
+ shots = arcade.arcade_frames(data, NOW)
+ labels = {arcade.action_label(row, arcade.scene_plan(row, NOW), None, 0, 60)
+ for row in arcade.shown_rows(data, NOW)}
+ self.assertEqual(labels, {'STRETCHING'})
+ self.assertEqual(len(shots), 60)
+
+
+class BreakTimingTests(unittest.TestCase):
+ """Through live.main on the fake SD_PRO, from the readings alone: an hour of a Codex account's work."""
+ def test_an_hour_of_work_brings_the_break_at_the_loops_end_then_the_usual_face_and_an_hour_more(self):
+ picks = Picks('drink', 'stretch')
+ patcher = mock.patch.object(moments, 'RANDOM', picks)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('5H', 20, 4 * H)]})
+ used = 20.0
+
+ def reading(n): # the n-th poll's reading, a little more used than the last
+ nonlocal used
+ used += .004 # (never enough to change the picture: only the break does)
+ rig.set('codex_a', '5H', used)
+ rig.write(rig.now() + rig.poll_at(n) - rig.clock.now())
+ rig.clock.to(rig.poll_at(n) + .5)
+
+ reading(1)
+ first_rise = rig.poll_at(1) # the baseline was read at t0; this is the first rise
+ n = 1
+ while rig.poll_at(n + 1) < first_rise + WORK:
+ n += 1
+ reading(n)
+ due = first_rise + WORK
+ self.assertNotEqual(rig.showing()[0], rig.picture(('break', 'drink'), snapshot=rig.held()))
+ before = rig.clock.now()
+ rig.set('codex_a', '5H', used + .004)
+ rig.write(rig.now() + due - rig.clock.now())
+ rig.clock.to(due - .001)
+ self.assertEqual([t for t in rig.switches(before) if t < due], []) # not a moment before the hour
+ boundary = rig.end_of_loop(due)
+ rig.clock.to(boundary + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('break', 'drink'), snapshot=rig.held()))
+ self.assertGreaterEqual(began, boundary)
+ self.assertLess(began, boundary + .25)
+ end = began + physical(image)
+ rig.clock.to(end + .3)
+ back, returned = rig.showing()
+ self.assertEqual(back, rig.picture(snapshot=rig.held())) # one loop of it, then the usual face
+ self.assertGreaterEqual(returned, end)
+ self.assertLess(returned, end + .25)
+ self.assertEqual(len(rig.switches(before)), 2) # its entry and the return, nothing else
+ self.assertEqual(picks.asked, 1)
+ # the next hour counts from the break's showing
+ n = max(k for k in range(n, n + 100) if rig.poll_at(k) <= rig.clock.now())
+ while rig.poll_at(n + 1) < began + WORK:
+ n += 1
+ reading(n)
+ self.assertEqual(picks.asked, 1)
+ self.assertEqual(rig.showing()[0], rig.picture(snapshot=rig.held()))
+ rig.set('codex_a', '5H', used + .004)
+ rig.write(rig.now() + began + WORK - rig.clock.now())
+ rig.clock.to(rig.end_of_loop(began + WORK) + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(('break', 'stretch'), snapshot=rig.held()))
+
+
+if __name__ == '__main__':
+ unittest.main()
+
+
+class ClaudeBreakTimingTests(unittest.TestCase):
+ """Claude's readings come at most every five minutes (state.MIN_FETCH_SECONDS): its rises still keep it at work
+ the whole hour, and its pet gets the break."""
+ def test_claude_alone_at_its_own_pace_of_readings(self):
+ patcher = mock.patch.object(moments, 'RANDOM', Picks('stretch'))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('claude',), wall=True, windows={'claude': [('5H', 30, 4 * H)]})
+ every = state.MIN_FETCH_SECONDS['claude']
+ used, k = 30.0, 0
+ while True:
+ k += 1
+ at = rig.t0 + k * every # a reading every five minutes, each a little higher
+ used += .01
+ rig.set('claude_a', '5H', used)
+ rig.write(rig.now() + at - rig.clock.now())
+ rig.clock.to(at + .5)
+ if k == 1:
+ first_rise = at
+ if at + every > first_rise + WORK:
+ break
+ self.assertTrue(rig.held()['accounts']['claude_a']['active'])
+ boundary = rig.end_of_loop(first_rise + WORK)
+ rig.clock.to(boundary + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('break', 'stretch'), snapshot=rig.held()))
+ self.assertGreaterEqual(began, boundary)
+ self.assertLess(began, boundary + .25)
+
+
+class BreakDuringOneOffTests(unittest.TestCase):
+ """The hour of work done while a hidden one-off's quiet aftermath plays: the break goes in at that loop's end,
+ not when the aftermath is over or at the next reading (time alone makes it due; TokenTV wakes for it)."""
+ def test_a_break_due_during_a_quiet_aftermath_goes_at_its_loops_end(self):
+ from PIL import Image as PILImage
+ from token_tv import live
+ from token_tv.lockbox import Box
+ patcher = mock.patch.object(moments, 'RANDOM', Picks('drink'))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('5H', 20, 4 * H)]})
+ stage = lambda colour: PILImage.new('RGB', (120, 71), colour) # noqa: E731
+ box = Box('Test', 'unique', 'codex_a', tuple(stage((200, 40, 40)) for _ in range(4)), 100,
+ after=(stage((40, 40, 200)), stage((40, 200, 40))))
+ opened = []
+
+ def pick(snap): # the box opens with the reading half a minute before the hour is done
+ if not opened and moments.CLOCK.now() >= rig.poll_at(60):
+ opened.append(moments.CLOCK.now())
+ return box
+ return None
+ patcher = mock.patch.object(live.Lockbox, 'pick', side_effect=pick)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ used = 20.0
+ for k in range(1, 61): # each reading measured half a minute before it is read: the hour ends between polls
+ used += .004
+ rig.set('codex_a', '5H', used)
+ rig.write(rig.now() + rig.poll_at(k) - 30 - rig.clock.now())
+ rig.clock.to(rig.poll_at(k) + .5)
+ due = rig.poll_at(1) - 30 + WORK
+ self.assertTrue(opened and opened[0] < due)
+ rig.clock.to(due - .001)
+ quiet, began = rig.showing() # the one-off's quiet loop, on since its event's loop ended
+ self.assertEqual(quiet, rig.picture(egg=__import__('dataclasses').replace(box, frames=box.after, after=(),
+ intro=False), snapshot=rig.held()))
+ boundary = rig.end_of_loop(due)
+ rig.clock.to(boundary + .3)
+ image, at = rig.showing()
+ self.assertEqual(image, rig.picture(('break', 'drink'), snapshot=rig.held()))
+ self.assertGreaterEqual(at, boundary)
+ self.assertLess(at, boundary + .25)
+
+
+class BreakSendFailureTests(unittest.TestCase):
+ """The break goes on, then the old picture fails to go off: the clock has shown it, so it does not come again.
+ The break's send fails: it is still due, and goes as the next loop ends; its hour counts from then."""
+ def test_a_break_the_clock_does_not_take_goes_at_the_next_loop_end_and_its_hour_counts_from_then(self):
+ from token_tv.device import PhotoDisplay
+ picks = Picks('drink', 'stretch')
+ patcher = mock.patch.object(moments, 'RANDOM', picks)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('5H', 20, 4 * H)]})
+ used = 20.0
+
+ def reading(k): # the k-th poll's reading, a little more used (never enough to change the picture)
+ nonlocal used
+ used += .004
+ rig.set('codex_a', '5H', used)
+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())
+ for k in range(1, 61):
+ reading(k)
+ rig.clock.to(rig.poll_at(k) + .5)
+ upload, refuse = PhotoDisplay.upload, []
+
+ def busy(self, name, image): # the clock refuses one send (the break's), then takes them again
+ if refuse:
+ refuse.clear()
+ raise OSError('the clock is busy')
+ return upload(self, name, image)
+ patcher = mock.patch.object(PhotoDisplay, 'upload', busy)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ refuse.append(True)
+ due = rig.poll_at(61) # the hour of work since the first rise (the first poll's) is done
+ reading(61)
+ normal = rig.showing()[0]
+ first = rig.end_of_loop(due)
+ rig.clock.to(first + .3)
+ self.assertEqual(refuse, []) # (the break's send was refused)
+ self.assertEqual(rig.showing()[0], normal) # the clock kept its picture
+ brk = rig.picture(('break', 'drink'), snapshot=rig.held())
+ nxt = first + physical(normal) # the next loop's end
+ rig.clock.to(nxt + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, brk) # the break, still due, as that loop ended
+ self.assertGreaterEqual(began, nxt - 1e-6) # (its own sum of the loop, to the last bit)
+ self.assertLess(began, nxt + .25)
+ self.assertEqual(picks.asked, 1)
+ k = 62
+ while rig.poll_at(k) < began + WORK:
+ reading(k)
+ rig.clock.to(rig.poll_at(k) + .5)
+ k += 1
+ self.assertEqual([image for _, image in rig.played].count(brk), 1) # once, and no other yet
+ self.assertEqual(picks.asked, 1)
+ reading(k)
+ rig.clock.to(rig.end_of_loop(began + WORK) + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(('break', 'stretch'), snapshot=rig.held())) # an hour on
+
+
+ def test_a_break_on_the_clock_is_not_played_again_after_a_lost_answer(self):
+ from token_tv.device import PhotoDisplay
+ patcher = mock.patch.object(moments, 'RANDOM', Picks('drink', 'stretch'))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('5H', 20, 4 * H)]})
+ used = 20.0
+ for k in range(1, 61):
+ used += .004
+ rig.set('codex_a', '5H', used)
+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())
+ rig.clock.to(rig.poll_at(k) + .5)
+ toggle, lose = PhotoDisplay.toggle, []
+
+ def flaky(self, category, key, value, enabled): # the old one's switch-off: done, its answer lost
+ toggle(self, category, key, value, enabled)
+ if lose and not enabled:
+ lose.clear()
+ raise OSError('answer lost')
+ patcher = mock.patch.object(PhotoDisplay, 'toggle', flaky)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ lose.append(True)
+ rig.set('codex_a', '5H', used + .004)
+ rig.write(rig.now() + rig.poll_at(61) - rig.clock.now())
+ rig.clock.to(rig.poll_at(61) + 30)
+ self.assertEqual(lose, []) # (the switch-off's answer was lost)
+ drawn = [image for _, image in rig.played]
+ brk = rig.picture(('break', 'drink'), snapshot=rig.held())
+ self.assertEqual(drawn.count(brk), 1) # it went on once
+ for k in range(62, 66): # the next readings: the usual face back, the break not again
+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())
+ rig.clock.to(rig.poll_at(k) + .5)
+ rig.clock.advance(30)
+ self.assertEqual([image for _, image in rig.played].count(brk), 1)
+ self.assertEqual(rig.showing()[0], rig.picture(snapshot=rig.held()))
diff --git a/tests/test_limit_warning.py b/tests/test_limit_warning.py
new file mode 100644
index 0000000..27d59ba
--- /dev/null
+++ b/tests/test_limit_warning.py
@@ -0,0 +1,436 @@
+"""v2 phase 2, x3: a window that, at its pace over the last RATE_WINDOW, would reach 100% in under HORIZON (and is
+still under 100%) blinks its battery beside SLOW, until the pace says otherwise or the window resets. The pet goes
+on as it was. The pace is each window's own, from its readings' own times."""
+import datetime
+import io
+import sys
+import time
+import unittest
+from fractions import Fraction
+from pathlib import Path
+from unittest import mock
+
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run
+from test_moments import Rig # noqa: E402
+
+from token_tv import arcade, moments, readout, sources, state # noqa: E402
+from token_tv.moments import WORK, overlay # noqa: E402
+from token_tv.sample import H, snapshot # noqa: E402
+from token_tv.state import HORIZON, RATE_WINDOW, UsageStore, running_out # noqa: E402
+
+LIMIT = 100
+NOW = int(time.mktime((2026, 11, 1, 14, 1, 0, 0, 0, -1))) # Sunday 2:01 pm wherever the tests run (the stage dims at night)
+T0 = 1_800_000_000 # the readings' clock in the history tests
+
+
+def linear(eta, final=70.0, at=T0, samples=4):
+ """A whole RATE_WINDOW of readings ending at `at` with `final` % used, rising at the pace that reaches LIMIT in
+ `eta` seconds; their times and values as (measured at, used %, resets at)."""
+ rate = Fraction(LIMIT - final) / Fraction(eta)
+ times = [at - RATE_WINDOW + Fraction(RATE_WINDOW) * k / (samples - 1) for k in range(samples)]
+ return [(float(t), float(Fraction(final) - rate * (at - t)), at + 3 * H) for t in times]
+
+
+class SyntheticWall:
+ """The time module with its wall clock stopped at `at`."""
+ def __init__(self, at):
+ self.at = at
+
+ def time(self):
+ return self.at
+
+ def __getattr__(self, name):
+ import time
+ return getattr(time, name)
+
+
+class Readings:
+ """A UsageStore read through its own refresh, its readings the test's: {key: [(label, used, resets_at)]} at `at`."""
+ def __init__(self, keys=('codex_a',)):
+ self.now, self.rows = T0, {}
+ accounts = [{'key': key, 'alias': key.upper(), 'provider': key.split('_')[0]} for key in keys]
+ self.store = UsageStore(accounts, fetch=self.fetch)
+
+ def fetch(self, account):
+ windows = self.rows[account['key']]
+ return {'key': account['key'], 'alias': account['alias'], 'provider': account['provider'], 'status': 'ok',
+ 'fetched_at': self.now, 'identity_verified': True, 'source': 'mini',
+ 'windows': [{'label': label, 'used_percent': used, 'resets_at': resets} for label, used, resets in windows]}
+
+ def read(self, at, **windows):
+ self.now = at
+ self.rows.update(windows)
+ self.store.refresh()
+ return {key: row['slow'] for key, row in self.store.snapshot()['accounts'].items()}
+
+
+class CachedReadings:
+ """A UsageStore reading one Codex account through CodexBar, whose reply is its cache: as old as CodexBar's own
+ measurement (`updatedAt`), OLD once that is over a quarter of an hour old. The replies are the test's."""
+ ACCOUNT = {'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex', 'email': '[email protected]',
+ 'codexbar_command': 'codexbar'}
+
+ def __init__(self, test):
+ self.wall = SyntheticWall(T0)
+ self.store = UsageStore([self.ACCOUNT])
+ self.reply = {}
+ for patcher in (mock.patch.object(sources, 'time', self.wall), mock.patch.object(state, 'time', self.wall),
+ mock.patch.object(sources, 'codexbar_payload', lambda account: [{'provider': 'codex', 'usage': {
+ 'updatedAt': self.reply['measured'], 'primary': {
+ 'usedPercent': self.reply['used'], 'windowMinutes': 300, 'resetsAt': self.reply['resets']}}}])):
+ patcher.start()
+ test.addCleanup(patcher.stop)
+
+ @staticmethod
+ def iso(at):
+ return datetime.datetime.fromtimestamp(at, datetime.timezone.utc).isoformat()
+
+ def read(self, at, used, resets, measured=None):
+ """The row after a reply at `at` of CodexBar's 5H window, `used` %, resetting at `resets`, as measured at
+ `measured` (default: just now)."""
+ self.wall.at = at
+ self.reply.update(measured=self.iso(at if measured is None else measured), used=used, resets=self.iso(resets))
+ self.store.refresh()
+ return self.store.snapshot()['accounts']['codex_a']
+
+ def at(self, when):
+ """The row as the dashboard and the clock see it at `when`, with no reply since."""
+ self.wall.at = when
+ return self.store.snapshot()['accounts']['codex_a']
+
+ def warned(self, test, resets):
+ """Four good readings over RATE_WINDOW, 40 % to 70 % by T0: running out (SLOW)."""
+ for at, used in ((T0 - 900, 40), (T0 - 600, 50), (T0 - 300, 60), (T0, 70)):
+ row = self.read(at, used, resets)
+ test.assertEqual((row['status'], row['slow']), ('ok', ['5H']))
+
+
+class ProjectionTests(unittest.TestCase):
+ def test_the_threshold_is_strict_and_exact(self):
+ for eta, warns in ((HORIZON / 2, True), (HORIZON * .99, True), (HORIZON, False), (HORIZON * 1.01, False),
+ (HORIZON * 2, False)):
+ readings = linear(eta)
+ self.assertEqual(running_out(readings), warns, eta)
+ (t0, u0, _), (t1, u1, _) = readings[0], readings[-1]
+ exact = (LIMIT - Fraction(u1)) * (Fraction(t1) - Fraction(t0)) / (Fraction(u1) - Fraction(u0))
+ self.assertEqual(exact < HORIZON, warns, (eta, float(exact))) # the oracle from the endpoints alone
+ flat = [(T0 - RATE_WINDOW + k * 300, 70.0, T0 + H) for k in range(4)]
+ self.assertFalse(running_out(flat))
+ self.assertFalse(running_out([(T0 - RATE_WINDOW, 99.0, T0 + H), (T0, 100.0, T0 + H)])) # at the limit
+ self.assertFalse(running_out([(T0 - RATE_WINDOW, 99.0, T0 + H), (T0, 104.0, T0 + H)])) # past it
+ self.assertFalse(running_out(linear(HORIZON / 4)[1:])) # less than a whole RATE_WINDOW: nothing to say
+ self.assertFalse(running_out(linear(HORIZON / 4)[-1:]))
+
+ def test_a_tie_in_the_decimals_read_is_a_tie(self):
+ # Readings such as 55.3 -> 70.2 over RATE_WINDOW reach the limit in just HORIZON, as written; the binary
+ # floats nearest them would make some a hair faster and warn.
+ for u0, u1 in ((55.3, 70.2), (77.05, 84.7), (70.9, 80.6), (49.9, 66.6), (70.0, 80.0)):
+ rise, left = Fraction(str(u1)) - Fraction(str(u0)), LIMIT - Fraction(str(u1))
+ self.assertEqual(left * RATE_WINDOW, rise * HORIZON, (u0, u1)) # (each is a tie at these numbers)
+ middle = round((u0 + u1) / 2, 3)
+ self.assertFalse(running_out([(T0 - RATE_WINDOW, u0, T0 + H), (T0 - RATE_WINDOW / 2, middle, T0 + H),
+ (T0, u1, T0 + H)]), (u0, u1))
+ store = Readings()
+ for at, used in ((T0 - RATE_WINDOW, u0), (T0 - RATE_WINDOW / 2, middle), (T0, u1)):
+ slow = store.read(at, codex_a=[('5H', used, T0 + H)])
+ self.assertEqual(slow, {'codex_a': []}, (u0, u1))
+ self.assertTrue(running_out([(T0 - RATE_WINDOW, 55.29, T0 + H), (T0, 70.2, T0 + H)])) # a hair faster: warns
+
+ def test_the_pace_is_the_whole_trailing_window_not_the_last_step_or_the_earlier_past(self):
+ recent = linear(HORIZON / 2)
+ steep = [(T0 - 3 * RATE_WINDOW, 1.0, T0 + 3 * H)] + recent # A: a long steep past
+ gentle = [(T0 - 3 * RATE_WINDOW, recent[0][1] - .1, T0 + 3 * H)] + recent # B: a gentle one
+ r = Fraction(LIMIT - 70) / (2 * HORIZON)
+ low = float(70 - r * RATE_WINDOW)
+ burst = [(T0 - RATE_WINDOW, low, T0 + H), (T0 - RATE_WINDOW / 3, low, T0 + H), (T0, 70.0, T0 + H)] # C
+ for name, readings, warns in (('A', steep, True), ('B', gentle, True), ('C', burst, False)):
+ store = Readings()
+ for at, used, resets in readings:
+ slow = store.read(at, codex_a=[('5H', used, resets)])
+ self.assertEqual(slow['codex_a'] == ['5H'], warns, name)
+
+ def test_more_or_fewer_readings_of_the_same_history_change_nothing(self):
+ for spacing in ([0, 1], [0, .2, .9, 1], [0, .5, .5, .5, 1], [0, .1, .3, .35, .6, .61, .95, 1]):
+ store = Readings()
+ for k in spacing:
+ at = T0 - RATE_WINDOW + RATE_WINDOW * k
+ used = 40 + 30 * k # one pace: 30% a RATE_WINDOW, so 30% left is one RATE_WINDOW off
+ slow = store.read(at, codex_a=[('5H', used, T0 + H)])
+ slow = store.read(at, codex_a=[('5H', used, T0 + H)]) # the same reading again: nothing new
+ self.assertEqual(slow, {'codex_a': ['5H']}, spacing)
+
+ def test_each_window_and_account_has_its_own_pace(self):
+ store = Readings(('codex_a', 'codex_b'))
+ hot = linear(HORIZON / 3)
+ for k, (at, used, resets) in enumerate(hot):
+ order = ('codex_b', 'codex_a') if k % 2 else ('codex_a', 'codex_b') # read in either order
+ for key in order:
+ windows = ([('5H', used, resets), ('WEEK', 30.0, T0 + 4 * 86400)] if key == 'codex_a'
+ else [('5H', 30.0 + k * .01, resets)])
+ slow = store.read(at, **{key: windows})
+ self.assertEqual(slow, {'codex_a': ['5H'], 'codex_b': []})
+
+ def test_a_reset_clears_the_warning_and_its_pace_starts_over(self):
+ for reset_value in (5.0, 90.0): # a new window lower, or one whose first reading is not lower
+ store = Readings()
+ for at, used, resets in linear(HORIZON / 3):
+ slow = store.read(at, codex_a=[('5H', used, resets)])
+ self.assertEqual(slow, {'codex_a': ['5H']})
+ new = T0 + 5 * H # a new reset time: a new window
+ slow = store.read(T0 + 60, codex_a=[('5H', reset_value, new)])
+ self.assertEqual(slow, {'codex_a': []}, reset_value) # neither the old growth nor the jump counts
+ for k in range(1, 20): # flat in the new window
+ slow = store.read(T0 + 60 + 60 * k, codex_a=[('5H', reset_value, new)])
+ self.assertEqual(slow, {'codex_a': []})
+ start, last = T0 + 60 * 20, reset_value
+ for k in range(16): # then a whole new history running out fast
+ last = reset_value + (100 - reset_value) * .9 * k / 15 if reset_value < 50 else 90 + .6 * k
+ slow = store.read(start + 60 * k, codex_a=[('5H', last, new)])
+ self.assertEqual(slow, {'codex_a': ['5H']}, reset_value)
+
+ def test_old_rises_age_out_with_flat_readings(self):
+ store = Readings()
+ readings = linear(HORIZON / 3, samples=16)
+ for at, used, resets in readings:
+ slow = store.read(at, codex_a=[('5H', used, resets)])
+ self.assertEqual(slow, {'codex_a': ['5H']})
+ at, used, resets = readings[-1]
+ seen = []
+ for k in range(1, 17):
+ seen.append(store.read(at + 60 * k, codex_a=[('5H', used, resets)])['codex_a'])
+ self.assertEqual(seen[-1], []) # a whole flat RATE_WINDOW later: no warning
+ cleared = seen.index([])
+ self.assertTrue(all(s == [] for s in seen[cleared:])) # once cleared, it stays so
+ # the oracle at the reading where it cleared: the whole window's rise over its own RATE_WINDOW
+ start = at + 60 * (cleared + 1) - RATE_WINDOW
+ before = max(r for r in readings if r[0] <= start)
+ after = min(r for r in readings + [(at + 60 * j, used, resets) for j in range(1, 17)] if r[0] > start)
+ begun = Fraction(before[1]) + (Fraction(after[1]) - Fraction(before[1])) * (start - Fraction(before[0])) / (
+ Fraction(after[0]) - Fraction(before[0]))
+ self.assertGreaterEqual((LIMIT - Fraction(used)) * RATE_WINDOW, (Fraction(used) - begun) * HORIZON)
+
+ def test_a_reading_grown_old_keeps_slow_till_the_last_good_one_is_horizon_old(self):
+ store = Readings()
+ for at, used, resets in linear(HORIZON / 3):
+ store.read(at, codex_a=[('5H', used, resets)])
+ for after, slow in ((state.STALE_SECONDS + 1, ['5H']), (HORIZON - 1, ['5H']), (HORIZON, [])):
+ with mock.patch.object(state, 'time', SyntheticWall(T0 + after)): # no new reading since: OLD
+ row = store.store.snapshot()['accounts']['codex_a']
+ self.assertEqual((row['status'], row['slow']), ('stale', slow), after)
+
+ def test_a_failed_reading_keeps_slow_and_readings_failing_past_the_horizon_let_it_go(self):
+ store = Readings()
+ for at, used, resets in linear(HORIZON / 3):
+ store.read(at, codex_a=[('5H', used, resets)])
+ failed = {'at': T0}
+ store.store.fetch = lambda account: {'key': account['key'], 'alias': account['alias'], 'provider': 'codex',
+ 'status': 'error', 'windows': [], 'fetched_at': failed['at']}
+ for after, slow in ((60, ['5H']), (HORIZON - 1, ['5H']), (HORIZON, [])):
+ failed['at'] = T0 + after
+ with mock.patch.object(state, 'time', SyntheticWall(T0 + after)):
+ store.store.fetched.clear() # (read again at once, whatever its back-off)
+ store.store.waits.clear()
+ store.store.refresh()
+ row = store.store.snapshot()['accounts']['codex_a']
+ self.assertEqual((row['status'], row['slow']), ('stale', slow), after) # OLD, SLOW as it was
+ store.store.fetch = store.fetch # a good reading again, no higher: its own pace says it, from its history
+ self.assertEqual(store.read(T0 + HORIZON + 60, codex_a=[('5H', 70.0, T0 + 3 * H)]), {'codex_a': []})
+
+ def test_an_old_copy_that_brings_a_new_window_lets_slow_go_and_the_old_copies_after_it_bring_none_back(self):
+ # Codex's review: CodexBar's cache, newer than the last good reading but read 16 minutes after it measured,
+ # brings the window that began at its reset, at 0 %; then old copies of it every minute for 45 minutes.
+ readings = CachedReadings(self)
+ readings.warned(self, T0 + 60)
+ row = readings.read(T0 + 1020, 0, T0 + 18060, measured=T0 + 60)
+ self.assertEqual((row['status'], row['windows'][0]['used_percent'], row['slow']), ('stale', 0, []))
+ for after in range(1080, 3721, 60):
+ row = readings.read(T0 + after, 0, T0 + 18060, measured=T0 + after - 960)
+ self.assertEqual((row['status'], row['slow']), ('stale', []), after)
+
+ def test_old_copies_of_the_same_window_keep_slow_only_till_the_last_good_reading_is_horizon_old(self):
+ readings = CachedReadings(self)
+ readings.warned(self, T0 + 2 * H)
+ for after in range(1020, HORIZON + 1, 60): # copies 16 minutes old, each newer than the last, a little higher
+ row = readings.read(T0 + after, 72, T0 + 2 * H + 30, measured=T0 + after - 960) # (its reset 30 s off)
+ self.assertEqual((row['status'], row['slow']), ('stale', ['5H'] if after < HORIZON else []), after)
+ readings = CachedReadings(self)
+ readings.warned(self, T0 + 2 * H)
+ readings.read(T0 + HORIZON - 60, 72, T0 + 2 * H, measured=T0 + HORIZON - 1020)
+ for after, slow in ((HORIZON - 1, ['5H']), (HORIZON, [])): # time alone, with no reply since
+ self.assertEqual(readings.at(T0 + after)['slow'], slow, after)
+
+ def test_an_old_copy_with_a_lower_use_or_another_reset_time_lets_slow_go(self):
+ for used, resets, slow in ((69.9, T0 + 2 * H, []), # lower: a correction
+ (75, T0 + 3 * H, []), # higher, but another window (its reset an hour off)
+ (70, T0 + 2 * H - 30, ['5H'])): # the same window, as high (its reset 30 s off)
+ readings = CachedReadings(self)
+ readings.warned(self, T0 + 2 * H)
+ row = readings.read(T0 + 1020, used, resets, measured=T0 + 60)
+ self.assertEqual((row['status'], row['slow']), ('stale', slow), (used, resets))
+ store = readings.store # and a failed reading after it keeps what that one kept
+ store.fetch = lambda account: {'key': account['key'], 'alias': account['alias'], 'provider': 'codex',
+ 'status': 'error', 'windows': [], 'fetched_at': T0 + 1080}
+ readings.wall.at = T0 + 1080
+ store.refresh()
+ self.assertEqual(store.snapshot()['accounts']['codex_a']['slow'], slow, (used, resets))
+
+
+class WarningDrawingTests(unittest.TestCase):
+ def pictures(self, slow, provider='codex', windows=(('5H', 84, 80 * 60), ('WEEK', 40, 4 * 86400)), **extra):
+ data = snapshot(NOW, [(f'{provider}_a', f'{provider.upper()} A', provider, list(windows))])
+ data['accounts'][f'{provider}_a'].update(active=True, slow=slow, **extra)
+ return arcade.arcade_frames(data, NOW), data
+
+ def test_the_battery_blinks_beside_slow_and_the_pet_goes_on_as_it_was(self):
+ warned, data = self.pictures(['5H'])
+ calm, _ = self.pictures([])
+ stage = lambda frame: frame.crop((0, 28, 240, 170)).tobytes() # noqa: E731
+ self.assertEqual([stage(f) for f in warned], [stage(f) for f in calm]) # the same pet, the same moves
+ case = lambda frame: {frame.getpixel((x, 196)) for x in range(26, 66)} # the 5H battery's top edge # noqa: E731
+ phases = [readout.WARN in case(frame) for frame in warned]
+ self.assertTrue(any(phases) and not all(phases)) # red, then not, inside the one GIF
+ self.assertFalse(any(readout.WARN in case(frame) for frame in calm))
+ week = lambda frame: {frame.getpixel((x, 217)) for x in range(26, 66)} # noqa: E731
+ self.assertFalse(any(readout.WARN in week(frame) for frame in warned)) # only the window running out
+ label = arcade.action_label(dict(data['accounts']['codex_a'], key='codex_a'),
+ arcade.scene_plan(data['accounts']['codex_a'], NOW), None, 0, 120)
+ self.assertEqual(label, 'SLOW')
+ words = warned[0].crop((70, 174, 230, 192))
+ self.assertIn(readout.WARN, {c for _, c in words.getcolors(65536)}) # SLOW in red
+
+ def test_a_wait_keeps_needs_you_and_the_battery_still(self):
+ data = snapshot(NOW, [('claude_a', 'CLAUDE A', 'claude', [('5H', 84, 80 * 60), ('WEEK', 40, 4 * 86400)])])
+ data['accounts']['claude_a'].update(slow=['5H'])
+ waiting = overlay(data, ('needs', 1), {'kind': 'needs', 'since': 0, 'level': 1})
+ row = dict(waiting['accounts']['claude_a'], key='claude_a')
+ self.assertEqual(arcade.action_label(row, arcade.scene_plan(row, NOW), None, 0, 120), 'NEEDS YOU')
+ frames = arcade.arcade_frames(waiting, NOW)
+ self.assertFalse(any(readout.WARN in {f.getpixel((x, 196)) for x in range(26, 66)} for f in frames))
+
+ def test_one_gif_of_it_needs_no_more_sends_to_keep_blinking(self):
+ frames, _ = self.pictures(['5H'])
+ image = arcade.encode(frames)
+ self.assertLess(len(image), arcade.BUDGET)
+ gif = Image.open(io.BytesIO(image))
+ self.assertGreater(gif.n_frames, 10) # the blink is in its pictures
+
+
+class WarningTimingTests(unittest.TestCase):
+ """Through live.main and the store's own readings: SLOW goes on once at a loop's end, stays without a send while
+ it holds, and goes off once, as the pace over the last RATE_WINDOW stops saying the window runs out."""
+ def test_slow_comes_on_once_holds_without_sends_and_goes_off_once(self):
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('5H', 60, 4 * H)]})
+ polls = RATE_WINDOW // rig.poll # a whole RATE_WINDOW of readings
+ used, k = 60.0, 0
+ for k in range(1, polls + 1): # 1.5% a minute: 17.5% left at the end is under 12 minutes away
+ used = 60 + 1.5 * k
+ rig.set('codex_a', '5H', used)
+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())
+ rig.clock.to(rig.poll_at(k) + .5)
+ self.assertEqual(rig.held()['accounts']['codex_a']['slow'], ['5H'])
+ rig.clock.to(rig.end_of_loop() + .3)
+ on, began = rig.showing()
+ self.assertEqual(on, rig.picture(snapshot=rig.held()))
+ frames = Image.open(io.BytesIO(on))
+ self.assertGreater(frames.n_frames, 1)
+ held = []
+ while True: # flat now: the pace over the window falls, reading by reading
+ k += 1
+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())
+ rig.clock.to(rig.poll_at(k) + .5)
+ held.append(rig.held()['accounts']['codex_a']['slow'])
+ if not held[-1]:
+ break
+ self.assertEqual(rig.switches(began + .001), []) # unchanged SLOW: nothing sent, nothing restarted
+ cleared = rig.poll_at(k)
+ self.assertLess(len(held), polls) # gone within a RATE_WINDOW of flat readings
+ boundary = rig.end_of_loop(cleared)
+ rig.clock.to(boundary + .3)
+ off, at = rig.showing()
+ self.assertEqual(off, rig.picture(snapshot=rig.held()))
+ self.assertNotEqual(off, on)
+ self.assertGreaterEqual(at, boundary)
+ self.assertLess(at, boundary + .25)
+ self.assertEqual(len(rig.switches(began + .001)), 1) # off once
+ for j in range(1, 4): # and flat readings after: nothing more
+ rig.write(rig.now() + rig.poll_at(k + j) - rig.clock.now())
+ rig.clock.to(rig.poll_at(k + j) + .5)
+ self.assertEqual(len(rig.switches(began + .001)), 1)
+
+ def test_one_failed_reading_keeps_slow_on_the_clock(self):
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('5H', 60, 4 * H)]})
+ polls = RATE_WINDOW // rig.poll
+ for k in range(1, polls + 1):
+ rig.set('codex_a', '5H', 60 + 1.5 * k)
+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())
+ rig.clock.to(rig.poll_at(k) + .5)
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.held()['accounts']['codex_a']['slow'], ['5H'])
+ rig.readings['codex_a']['status'] = 'error' # the next reading fails
+ rig.write(rig.now() + rig.poll_at(polls + 1) - rig.clock.now())
+ rig.clock.to(rig.poll_at(polls + 1) + .5)
+ row = rig.held()['accounts']['codex_a']
+ self.assertEqual((row['status'], row['slow']), ('stale', ['5H'])) # OLD, and still running out
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(snapshot=rig.held())) # on the clock so: SLOW does not drop
+ rig.readings['codex_a']['status'] = 'ok'
+ rig.set('codex_a', '5H', 60 + 1.5 * (polls + 2))
+ rig.write(rig.now() + rig.poll_at(polls + 2) - rig.clock.now())
+ rig.clock.to(rig.poll_at(polls + 2) + .5)
+ self.assertEqual(rig.held()['accounts']['codex_a']['slow'], ['5H']) # and the next good one says it again
+
+
+class WaitPriorityTests(unittest.TestCase):
+ """SLOW on the clock, then Claude asks for you while the hour of work comes due and presses come in: NEEDS YOU
+ keeps the readout, the presses are dropped, the warning goes on being worked out, and once you answer the break
+ plays, then the usual face with SLOW again as it still holds (v2p2-42)."""
+ def test_a_wait_over_slow_and_a_due_break(self):
+ patcher = mock.patch.object(moments, 'RANDOM', type('Pick', (), {'choice': lambda self, options: 'drink'})())
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('claude',), wall=True, windows={'claude': [('5H', 40, 4 * H)]})
+ every = state.MIN_FETCH_SECONDS['claude']
+
+ def reading(k, used):
+ rig.set('claude_a', '5H', used)
+ rig.write(rig.now() + rig.t0 + k * every - rig.clock.now())
+ rig.clock.to(rig.t0 + k * every + .5)
+
+ used = 40.0
+ for k in range(1, 14): # slowly for 45 minutes, then fast: SLOW by the hour
+ used += .2 if k <= 9 else 10
+ reading(k, used)
+ if k == 12:
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.held()['accounts']['claude_a']['slow'], ['5H'])
+ self.assertEqual(rig.showing()[0], rig.picture(snapshot=rig.held())) # the battery blinking, SLOW
+ asked = rig.t0 + 12 * every + 100
+ rig.clock.to(asked)
+ rig.say('claude.ask')
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(('needs', 1), snapshot=rig.held()))
+ rig.clock.advance(60)
+ rig.say('claude.pet')
+ due = rig.t0 + every + WORK # the first rise's hour, at the 13th reading
+ rig.clock.to(due + 50)
+ rig.say('claude.snack')
+ self.assertEqual(rig.held()['accounts']['claude_a']['slow'], ['5H']) # still worked out meanwhile
+ waiting = rig.picture(('needs', 1), snapshot=rig.held())
+ self.assertEqual(rig.showing()[0], waiting) # NEEDS YOU, not SLOW, not the break, not a treat
+ answered = rig.clock.now()
+ rig.say('claude.answered')
+ boundary = rig.end_of_loop(answered)
+ rig.clock.to(boundary + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('break', 'drink'), snapshot=rig.held())) # straight to the break
+ self.assertLess(began, boundary + .25)
+ rig.clock.to(began + rig.loop(image) + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(snapshot=rig.held())) # then SLOW again, as it holds
+ self.assertEqual(rig.held()['accounts']['claude_a']['slow'], ['5H'])
+ self.assertEqual(len(rig.switches(answered)), 2) # the break and the usual face: nothing between
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_live.py b/tests/test_live.py
index 223b834..f0dcca1 100644
--- a/tests/test_live.py
+++ b/tests/test_live.py
@@ -175,8 +175,24 @@ class LoopTimingTests(unittest.TestCase):
shown = {'at': 100.0, 'loop': 8.4}
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.assertAlmostEqual(until_loop_end(shown, 100.0 + 2 * 8.4 + .001), 8.399) # just after: that loop's end
+ self.assertAlmostEqual(until_loop_end(shown, 100.0 + 2 * 8.4 + .05), 8.35) # (no 'right on time' window)
+ self.assertAlmostEqual(until_loop_end(shown, 100.0), 8.4) # just gone on: its first loop whole
self.assertEqual(until_loop_end({'at': None, 'loop': None}, 5), 0)
+ def test_every_switch_is_timed_from_when_its_change_came_in(self):
+ from token_tv.live import LATE, switch_at
+ shown, loop = {'at': 100.0, 'loop': 2.0}, 2.0
+ end = 100.0 + 3 * loop # a loop's end
+ self.assertEqual(switch_at(shown, end - .001, end - .001), end) # just before an end: at it
+ self.assertEqual(switch_at(shown, end, end), end) # right at it: then
+ self.assertEqual(switch_at(shown, end + .001, end + .001), end + loop) # just after: that loop's end
+ self.assertEqual(switch_at(shown, end + .05, end + .05), end + loop)
+ self.assertEqual(switch_at(shown, end - .5, end + LATE - .001), end) # drawn as the loop ended: it still goes
+ self.assertEqual(switch_at(shown, end - .5, end + LATE + .001), end + loop) # past LATE: the next end
+ self.assertEqual(switch_at(shown, 100.0, 100.0), 100.0 + loop) # just gone on: its first loop whole
+ self.assertIsNone(switch_at({'at': None, 'loop': None}, 5, 5)) # nothing loops yet: at once
+
class RelocateTests(unittest.TestCase):
def test_a_clock_with_a_new_address_is_followed_only_when_it_is_the_one_clock(self):
diff --git a/tests/test_lockbox.py b/tests/test_lockbox.py
index d9bb5cc..c9a9937 100644
--- a/tests/test_lockbox.py
+++ b/tests/test_lockbox.py
@@ -96,6 +96,14 @@ class LockboxTests(unittest.TestCase):
box = locks.pick(self.data(saturday + 5 * week), saturday + 5 * week)
self.assertEqual(box.name, 'maybe') # 35 days on, past twice its share: sure
+ def test_overdue_odds_climb_to_sure_without_a_cliff(self):
+ self.assertEqual(lockbox.overdue(.1, .5), .1) # within its share: as it was
+ self.assertEqual(lockbox.overdue(.1, 1), .1)
+ self.assertAlmostEqual(lockbox.overdue(.1, 1.5), .55) # half a share late: half the rest
+ self.assertEqual(lockbox.overdue(.1, 2), 1.0) # twice its share: sure
+ steps = [lockbox.overdue(.1, 1 + k / 10) for k in range(11)]
+ self.assertEqual(steps, sorted(steps))
+
def test_the_odds_follow_how_often_a_situation_comes_about(self):
self.assertAlmostEqual(lockbox.odds(14, 14, 12, first=False), 1 / 12) # daily, one opening in twelve days
self.assertAlmostEqual(lockbox.odds(14, 14, 12, first=True), 2 / 12)
diff --git a/tests/test_mixed_run.py b/tests/test_mixed_run.py
new file mode 100644
index 0000000..40a1e18
--- /dev/null
+++ b/tests/test_mixed_run.py
@@ -0,0 +1,108 @@
+"""v2 phase 2, a mixed virtual run (v2p2-43): hours of two services' work with a short gap, a full break and a wait
+across the hour's end, pets and snacks with repeats, bows, through live.main on the fake SD_PRO. Every picture goes
+on at a real loop end of the one before it (its own pictures, each for its delay but at least 142 ms), the breaks
+come once an hour of work each and both kinds show, and nothing pressed or asked comes back later."""
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run
+from test_moments import Rig, physical # noqa: E402
+
+from token_tv import moments # noqa: E402
+from token_tv.moments import BREAK, WORK # noqa: E402
+from token_tv.sample import H # noqa: E402
+from token_tv.state import ACTIVE_SECONDS # noqa: E402
+
+APPLY_SLACK = .25
+
+
+class Picks:
+ def __init__(self, *kinds):
+ self.kinds = list(kinds)
+
+ def choice(self, options):
+ return self.kinds.pop(0)
+
+
+class MixedRunTests(unittest.TestCase):
+ def test_hours_of_mixed_work_and_moments(self):
+ patcher = mock.patch.object(moments, 'RANDOM', Picks('drink', 'stretch', 'drink', 'stretch'))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('claude', 'codex'), wall=True,
+ windows={'claude': [('5H', 20, 5 * H)], 'codex': [('5H', 20, 5 * H)]})
+ minute = lambda m: rig.t0 + 60 * m # noqa: E731
+ idle = set(range(70, 85)) | set(range(140, 165)) # a short gap, then a whole break with nobody at work
+ moments_at = {30: ['claude.pet', 'claude.pet', 'claude.snack'], 40: ['claude.end'], 41: ['claude.end'],
+ 55: ['claude.ask'], 64: ['claude.answered'], 100: ['claude.snack', 'claude.snack'],
+ 120: ['codex.end'], 121: ['claude.pet']}
+ used = {'claude_a': 20.0, 'codex_a': 20.0}
+ first_rise = None
+ for m in range(1, 231):
+ if m not in idle:
+ used['codex_a'] += .002 # (never enough to change the picture)
+ rig.set('codex_a', '5H', used['codex_a'])
+ if first_rise is None:
+ first_rise = minute(m)
+ if m % 5 == 0:
+ used['claude_a'] += .002
+ rig.set('claude_a', '5H', used['claude_a'])
+ rig.write(rig.now() + minute(m) - rig.clock.now())
+ rig.clock.to(minute(m) + .5)
+ for name in moments_at.get(m, []):
+ rig.say(name)
+ rig.clock.advance(.3)
+ rig.clock.advance(60)
+ played = rig.played
+ self.assertGreater(len(played), 10)
+ # every picture on at a real loop end of the one before it: its own pictures, counted from its own start
+ for (began, image), (then, _) in zip(played, played[1:]):
+ loop = physical(image)
+ loops = (then - began) / loop
+ k = max(1, int(loops))
+ self.assertTrue(began + k * loop <= then + 1e-6 < began + k * loop + APPLY_SLACK
+ or began + (k + 1) * loop <= then + 1e-6 < began + (k + 1) * loop + APPLY_SLACK,
+ (began - rig.t0, then - rig.t0, loop))
+ drawn = {} # which moment each played picture is, drawn independently from the readings TokenTV holds
+ held = rig.held()
+ for what in (('break', 'drink'), ('break', 'stretch'), ('treat', 'pet'), ('treat', 'snack'),
+ ('done', 'claude'), ('done', 'codex'), ('needs', 1)):
+ drawn[rig.picture(what, snapshot=held)] = what
+ seen = [(t - rig.t0, drawn.get(image)) for t, image in played if drawn.get(image)]
+ kinds = [what for _, what in seen]
+ self.assertIn(('break', 'drink'), kinds)
+ self.assertIn(('break', 'stretch'), kinds)
+ self.assertEqual([what for what in kinds if what[0] == 'treat'],
+ [('treat', 'pet'), ('treat', 'snack'), ('treat', 'pet')]) # one each time, repeats dropped
+ self.assertEqual([what for what in kinds if what[0] == 'done'], [('done', 'claude'), ('done', 'codex')])
+ breaks = [t + rig.t0 for t, what in seen if what[0] == 'break']
+ self.assertEqual(len(breaks), 3)
+ # an independent oracle of the hour of work, from the rises this test made (Codex's, every working minute)
+ rises = [minute(m) for m in range(1, 231) if m not in idle]
+
+ def due(start):
+ """When WORK of work since `start` is done: the union of [rise, rise + ACTIVE) after it."""
+ t, credit = start, 0.0
+ for r, nxt in zip(rises, rises[1:] + [float('inf')]):
+ if r + ACTIVE_SECONDS <= start:
+ continue
+ begin, end = max(r, start, t), min(r + ACTIVE_SECONDS, nxt)
+ if end > begin:
+ if credit + end - begin >= WORK:
+ return begin + WORK - credit
+ credit += end - begin
+ t = max(t, end)
+ return None
+ answered = minute(64)
+ self.assertLess(due(first_rise), answered) # the first hour came due while Claude waited (55-64 min)
+ self.assertTrue(answered <= breaks[0] < answered + 10) # so its break came at the wait's end, not before
+ self.assertTrue(due(breaks[0]) <= breaks[1] < due(breaks[0]) + 10) # an hour of work from its showing
+ back = min(r for r in rises if r > minute(140)) # the first rise after the break with nobody at work
+ self.assertGreaterEqual(back - (minute(139) + ACTIVE_SECONDS), BREAK)
+ self.assertTrue(due(back) <= breaks[2] < due(back) + 10) # a new hour from it: no credit from before
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_moments.py b/tests/test_moments.py
new file mode 100644
index 0000000..9031ca7
--- /dev/null
+++ b/tests/test_moments.py
@@ -0,0 +1,2030 @@
+"""v2: the agents' moments. The state machine (time injected), the endpoint, Codex's notify program, and when the
+clock gets each picture (a fake SD_PRO and a fake clock, through live.main itself)."""
+import http.client
+import io
+import json
+import os
+import signal
+import socket
+import subprocess
+import sys
+import threading
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+from urllib.parse import parse_qs, urlparse
+
+sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run
+from helpers import own_tmp, temp_dir
+from test_device import sd_pro_clock, serve, ultra_clock
+
+from token_tv import arcade, display, live, moments, readout, sources, state
+from token_tv.arcade import gif_seconds
+from token_tv.display import render_page
+from token_tv.moments import Moments, loop_end, overlay
+from token_tv.state import MIN_FETCH_SECONDS, UsageStore
+
+ROOT = Path(__file__).resolve().parent.parent
+FRAME_SD = .142 # the shortest an SD_PRO shows a picture, in seconds (live.DEVICE_FRAME_MS): the fake clock's own tick
+
+
+def physical(image, frame=FRAME_SD):
+ """How long an SD_PRO plays one loop of `image`: each of its pictures, as encoded, for the delay the GIF gives it
+ but at least `frame` seconds (m1), read from the GIF here, apart from live.loop_seconds. The sum is in whole ms,
+ as the GIF gives its delays: exact, so a loop's end here and TokenTV's agree to the last bit."""
+ from PIL import Image
+ source, total = Image.open(io.BytesIO(image)), 0
+ for n in range(source.n_frames):
+ source.seek(n)
+ total += max(source.info['duration'], frame * 1000)
+ return total / 1000
+
+
+class FakeClock:
+ """moments.CLOCK for tests: time moves only when the test moves it, and each wait that comes due on the way
+ runs in turn, so a jump to thirty minutes still passes five and fifteen."""
+ def __init__(self, start=10_000.0):
+ self.t = start
+ self.cond = threading.Condition()
+ self.sleepers = {} # thread -> (when its wait ends, the event that ends it sooner)
+ self.held = set() # usage readings a test holds up on purpose (their threads): no reason not to settle
+
+ def now(self):
+ with self.cond:
+ return self.t
+
+ def wait(self, event, seconds):
+ me = threading.get_ident()
+ with self.cond:
+ self.sleepers[me] = (self.t + max(0.0, seconds), event)
+ self.cond.notify_all()
+ try:
+ while not event.is_set() and self.t < self.sleepers[me][0]:
+ self.cond.wait(.002)
+ return event.is_set()
+ finally:
+ del self.sleepers[me]
+
+ def settle(self, timeout=20):
+ """Return once every waiting thread sleeps towards a time still to come (seen so a few times in a row), and
+ no usage reading is under way but those the test holds: TokenTV never waits for one, so it would land at
+ whatever time the test has moved on to."""
+ end, calm = time.monotonic() + timeout, 0
+ while time.monotonic() < end:
+ with self.cond:
+ quiet = bool(self.sleepers) and all(d > self.t and not e.is_set() for d, e in self.sleepers.values())
+ quiet = quiet and not any(thread.name == 'TokenTV reading' and thread not in self.held
+ for thread in threading.enumerate())
+ calm = calm + 1 if quiet else 0
+ if calm >= 4:
+ return
+ time.sleep(.004)
+ raise AssertionError('TokenTV did not settle')
+
+ def advance(self, seconds):
+ target = self.now() + seconds
+ while True:
+ self.settle()
+ with self.cond:
+ due = min((d for d, _ in self.sleepers.values()), default=target)
+ self.t = min(max(due, self.t), target)
+ self.cond.notify_all()
+ if self.t >= target:
+ break
+ self.settle()
+
+ def to(self, when):
+ self.advance(max(0.0, when - self.now()))
+
+ def bump(self, seconds):
+ """Move on by `seconds` now, as the real time something took (a test maps real waits onto this clock)."""
+ with self.cond:
+ self.t += seconds
+ self.cond.notify_all()
+
+
+class StateTests(unittest.TestCase):
+ def setUp(self):
+ self.clock = FakeClock()
+ patcher = mock.patch.object(moments, 'CLOCK', self.clock)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.woken = []
+ self.m = Moments({'claude', 'codex'}, wake=lambda: self.woken.append(self.clock.t))
+
+ def at(self, t):
+ self.clock.t = t
+
+ def test_a_wait_grows_more_insistent_and_is_let_go_after_thirty_minutes(self):
+ m, t0 = self.m, self.clock.t
+ self.assertTrue(m.note('claude.ask'))
+ what, since, mark = m.wanted()
+ self.assertEqual((what, since), (('needs', 1), t0))
+ self.assertEqual((mark['kind'], mark['level']), ('needs', 1))
+ self.assertEqual(m.next_change(), t0 + 300)
+ for t, level, since in ((59.999, 1, 0), (60, 1, 0), (299.999, 1, 0), (300, 2, 300), (899.999, 2, 300),
+ (900, 3, 900), (1799.999, 3, 900)):
+ self.at(t0 + t)
+ self.assertEqual(m.wanted()[:2], (('needs', level), t0 + since), t)
+ self.assertEqual(m.next_change(), t0 + 1800)
+ self.at(t0 + 1830) # looked at late: still due from the deadline itself
+ self.assertEqual(m.wanted()[:2], (None, t0 + 1800))
+ self.assertIsNone(m.next_change())
+
+ def test_waits_are_counted_across_sessions_and_keep_the_first_ones_age(self):
+ m, t0 = self.m, self.clock.t
+ m.note('claude.ask')
+ self.at(t0 + 10)
+ self.assertFalse(m.note('claude.ask')) # a second session waiting: the same picture
+ self.at(t0 + 20)
+ self.assertFalse(m.note('claude.answered')) # the first answered: the second still waits, as old as the first
+ self.at(t0 + 301)
+ self.assertEqual(m.wanted()[:2], (('needs', 2), t0 + 300))
+ self.assertTrue(m.note('claude.answered'))
+ self.assertEqual(m.wanted()[:2], (None, t0 + 301))
+ self.assertFalse(m.note('claude.answered')) # one answer too many (from a wait let go): never below none
+ self.at(t0 + 400)
+ m.note('claude.ask') # a new wait starts afresh
+ self.assertEqual((m.wanted()[:2], m.next_change()), ((('needs', 1), t0 + 400), t0 + 700))
+ self.assertEqual(len(self.woken), 3) # the first wait, its clearing, the new one
+
+ def test_an_expired_wait_is_forgotten_and_a_new_one_starts_at_the_hand(self):
+ m, t0 = self.m, self.clock.t
+ m.note('claude.ask')
+ m.note('claude.ask')
+ self.at(t0 + 1800)
+ self.assertIsNone(m.wanted()[0])
+ m.note('claude.ask')
+ self.assertEqual(m.wanted()[:2], (('needs', 1), t0 + 1800))
+ m.note('claude.answered')
+ self.assertIsNone(m.wanted()[0]) # the two let go are not counted any more
+
+ def test_the_waits_are_let_go_thirty_minutes_after_the_continuous_wait_began(self):
+ m, t0 = self.m, self.clock.t
+ m.note('claude.ask') # session A, never answered
+ self.at(t0 + 1700)
+ self.assertFalse(m.note('claude.ask')) # session B joins the wait: as old as A's
+ self.assertEqual(m.next_change(), t0 + 1800) # B's ask does not put it off
+ self.at(t0 + 1799.999)
+ self.assertEqual(m.wanted()[:2], (('needs', 3), t0 + 900))
+ self.at(t0 + 1800) # thirty minutes of waiting in all: both are let go, B's with A's
+ self.assertEqual(m.wanted()[:2], (None, t0 + 1800))
+ self.assertEqual((m.waits, m.next_change()), (0, None))
+ self.at(t0 + 1850)
+ self.assertFalse(m.note('claude.answered')) # B answered after all: none counted, nothing to close
+ self.at(t0 + 1900)
+ self.assertTrue(m.note('claude.ask')) # session C: a new wait, at the hand, as old as itself
+ self.assertEqual((m.wanted()[:2], m.next_change()), ((('needs', 1), t0 + 1900), t0 + 2200))
+ self.at(t0 + 1950)
+ self.assertTrue(m.note('claude.answered'))
+ self.assertEqual(m.wanted()[:2], (None, t0 + 1950))
+
+ def test_waits_never_answered_are_let_go_together_and_a_new_ask_starts_afresh(self):
+ m, t0 = self.m, self.clock.t
+ m.note('claude.ask')
+ self.at(t0 + 1200)
+ m.note('claude.ask') # neither is ever answered (the sessions were killed)
+ self.at(t0 + 3000) # looked at late: let go from the deadline itself
+ self.assertEqual(m.wanted()[:2], (None, t0 + 1800))
+ self.assertEqual(m.waits, 0)
+ m.note('claude.ask')
+ self.assertEqual(m.wanted()[:2], (('needs', 1), t0 + 3000)) # a new wait starts afresh
+ self.assertTrue(m.note('claude.answered')) # one answer closes it: the two let go are not counted
+ self.assertIsNone(m.wanted()[0])
+
+ def test_tokentvs_own_waits_look_again_at_the_time_every_few_seconds(self):
+ event = threading.Event()
+ began = time.monotonic()
+ self.assertFalse(moments.Clock().wait(event, .05))
+ self.assertGreaterEqual(time.monotonic() - began, .04)
+ event.set()
+ self.assertTrue(moments.Clock().wait(event, 30))
+
+ def test_the_clock_counts_the_time_the_computer_sleeps(self):
+ if sys.platform.startswith('linux') and hasattr(time, 'CLOCK_BOOTTIME'):
+ self.assertAlmostEqual(moments.Clock().now(), time.clock_gettime(time.CLOCK_BOOTTIME), delta=1)
+ elif sys.platform == 'darwin':
+ self.assertAlmostEqual(moments.Clock().now(), time.clock_gettime(time.CLOCK_MONOTONIC), delta=1)
+
+ def test_one_bow_in_any_rolling_minute_shared_by_claude_and_codex_none_queued(self):
+ m, t0 = self.m, self.clock.t
+ self.assertTrue(m.note('claude.end'))
+ self.assertEqual(m.wanted()[:2], (('done', 'claude'), t0))
+ self.assertFalse(m.note('codex.end')) # one is due already: dropped
+ self.at(t0 + 3)
+ m.shown(('done', 'claude'), t0 + 3) # it went on the clock: one loop, then the usual face
+ self.assertEqual(m.wanted()[:2], (None, t0 + 3))
+ for later in (20, 59.999):
+ self.at(t0 + 3 + later)
+ self.assertFalse(m.note('codex.end'))
+ self.assertFalse(m.note('claude.end'))
+ self.at(t0 + 3 + 60)
+ self.assertIsNone(m.wanted()[0]) # nothing comes back when the minute is up
+ self.assertTrue(m.note('codex.end'))
+ self.assertEqual(m.wanted()[:2], (('done', 'codex'), t0 + 63))
+
+ def test_a_wait_outranks_a_bow_and_nothing_put_off_comes_back(self):
+ m = self.m
+ m.note('claude.end')
+ m.note('claude.ask') # the bow not yet on the clock is dropped
+ self.assertEqual(m.wanted()[0], ('needs', 1))
+ self.assertFalse(m.note('codex.end'))
+ self.assertFalse(m.note('claude.end'))
+ m.note('claude.answered')
+ self.assertIsNone(m.wanted()[0])
+ self.assertIsNone(m.bowed) # and nothing dropped counts against the next bow
+ self.assertTrue(m.note('claude.end')) # a turn's end after its answer bows
+ self.assertEqual(m.wanted()[0], ('done', 'claude'))
+
+ def test_a_bow_with_no_clock_to_bow_on_is_dropped_and_holds_nothing_back(self):
+ m = self.m
+ m.note('claude.end')
+ m.drop_bow()
+ self.assertIsNone(m.wanted()[0])
+ self.assertTrue(m.note('codex.end'))
+
+ def test_moments_of_a_service_not_shown_are_ignored_and_cost_nothing(self):
+ m = Moments({'codex'})
+ for name in ('claude.ask', 'claude.answered', 'claude.end'):
+ self.assertFalse(m.note(name))
+ self.assertEqual((m.wanted()[0], m.next_change(), m.busy()), (None, None, False))
+ self.assertTrue(m.note('codex.end'))
+ self.assertEqual(m.wanted()[0], ('done', 'codex'))
+ for name in ('claude.Ask', 'claude', '', 'codex.ask', 'claude.ask '):
+ with self.assertRaises(ValueError):
+ m.note(name)
+
+ def test_the_moment_is_drawn_on_its_services_rows_only_and_adds_none(self):
+ snapshot = {'accounts': {'ca': {'provider': 'claude'}, 'cb': {'provider': 'claude'}, 'x': {'provider': 'codex'}}}
+ mark = {'kind': 'needs', 'since': 1.0, 'level': 2}
+ drawn = overlay(snapshot, ('needs', 2), mark)
+ self.assertEqual([k for k, row in drawn['accounts'].items() if row.get('moment')], ['ca', 'cb'])
+ self.assertNotIn('moment', snapshot['accounts']['ca']) # a copy, for drawing only
+ bow = overlay(snapshot, ('done', 'codex'), {'kind': 'done', 'at': 1.0})
+ self.assertEqual([k for k, row in bow['accounts'].items() if row.get('moment')], ['x'])
+ self.assertIs(overlay(snapshot, None, None), snapshot)
+ self.assertEqual(overlay({'accounts': {'x': {'provider': 'codex'}}}, ('needs', 1), mark)['accounts'],
+ {'x': {'provider': 'codex'}})
+
+ def test_a_change_goes_at_the_end_of_the_loop_playing_when_it_came(self):
+ shown = {'at': 100.0, 'loop': 4.2}
+ self.assertAlmostEqual(loop_end(shown, 101.05), 104.2)
+ self.assertAlmostEqual(loop_end(shown, 104.2), 104.2) # right at an end: that end
+ self.assertAlmostEqual(loop_end(shown, 104.21), 108.4) # just after: the next one, never mid-loop
+ self.assertAlmostEqual(loop_end(shown, 100.0), 104.2) # as a picture starts: its first loop plays out
+ self.assertAlmostEqual(loop_end(shown, 90.0), 104.2) # wanted before it went on: it still plays one loop
+ self.assertIsNone(loop_end({'at': None, 'loop': None}, 5))
+
+ def test_a_moment_joins_the_pets_on_the_clock_and_leaves_none_out(self):
+ def row(provider, **extra):
+ return dict({'provider': provider, 'alias': provider.upper(), 'status': 'ok', 'windows': []}, **extra)
+ waiting, bowing = {'kind': 'needs', 'since': 0, 'level': 1}, {'kind': 'done', 'at': 0}
+ shown = lambda accounts: [r['key'] for r in arcade.shown_rows({'accounts': accounts})] # noqa: E731
+ others = {'x': row('codex', active=True), 'g': row('grok'), 'p': row('copilot'), 'a': row('antigravity')}
+ # Claude waiting: its rows alone, the whole loop, however many services there are and whoever works
+ self.assertEqual(shown({'c': row('claude', moment=waiting), **others}), ['c'])
+ self.assertEqual(shown({'c': row('claude', moment=waiting), 'd': row('claude', moment=waiting), 'x': row('codex')}),
+ ['c', 'd'])
+ self.assertEqual(shown({'c': row('claude'), **others}), ['x']) # answered: back as before (Codex at work)
+ self.assertEqual(shown({'c': row('claude'), 'x': row('codex'), 'g': row('grok')}), ['c', 'x', 'g']) # all idle
+ # a bow shares the loop as ever: beside the working ones, or with every pet while all are idle
+ self.assertEqual(shown({'c': row('claude', moment=bowing), 'x': row('codex', active=True), 'g': row('grok')}),
+ ['c', 'x'])
+ self.assertEqual(shown({'c': row('claude'), 'x': row('codex', moment=bowing), 'g': row('grok')}), ['c', 'x', 'g'])
+
+ def test_needs_you_is_on_the_clock_the_whole_loop_beside_other_services(self):
+ claude = {'claude_a': {'provider': 'claude', 'alias': 'C', 'status': 'ok', 'windows': []}}
+ rows = dict(claude, **{p + '_a': {'provider': p, 'alias': p, 'status': 'ok', 'windows': []}
+ for p in ('codex', 'grok', 'copilot')})
+ mark = {'kind': 'needs', 'since': 0, 'level': 1}
+ frames = arcade.arcade_frames(overlay({'accounts': rows}, ('needs', 1), mark), 10_000)
+ alone = arcade.arcade_frames(overlay({'accounts': claude}, ('needs', 1), mark), 10_000)
+ # every frame of the loop is Clawd waiting, as if Claude were the only service on the clock
+ self.assertEqual(len(frames), len(alone))
+ self.assertEqual([k for k, (a, b) in enumerate(zip(frames, alone)) if a.tobytes() != b.tobytes()], [])
+
+ def test_a_bow_dips_once_a_loop_then_stands_proud(self):
+ def turns(providers, bowing):
+ """For each pet's turn in the loop: the frames, cut to where the pet is (for Codex, its cloud above the
+ garden, whose flowers lean on their own)."""
+ rows = {p + '_a': {'provider': p, 'alias': p, 'status': 'ok',
+ 'windows': [{'label': 'WEEK', 'used_percent': 50, 'resets_at': 10_000 + 86400}]}
+ for p in providers}
+ frames = arcade.arcade_frames(overlay({'accounts': rows}, ('done', bowing), {'kind': 'done', 'at': 0}), 10_000)
+ share = len(frames) // len(providers)
+ where = (0, 28, 240, 108) if bowing == 'codex' else (0, 28, 240, 170)
+ index = providers.index(bowing)
+ return [frame.crop(where).tobytes() for frame in frames[index * share:(index + 1) * share]]
+
+ def dips(turn):
+ """The runs of frames in which the pet is not as it stands at the end of its turn: (first, last)."""
+ runs, first = [], None
+ for k, frame in enumerate(turn + [turn[-1]]):
+ if frame != turn[-1] and first is None:
+ first = k
+ elif frame == turn[-1] and first is not None:
+ runs.append((first, k - 1))
+ first = None
+ return runs
+ four = ('claude', 'codex', 'grok', 'copilot')
+ for style in ('low', 'tilt'):
+ with mock.patch.object(arcade, 'BOW_STYLE', style):
+ for providers in (('claude',), ('claude', 'codex'), four):
+ turn = turns(providers, 'claude')
+ runs = dips(turn)
+ self.assertEqual(len(runs), 1, (style, providers, runs))
+ self.assertGreaterEqual(runs[0][1] - runs[0][0], 3, (style, providers)) # a dip, not a twitch
+ self.assertLess(runs[0][1], len(turn) - 3, (style, providers)) # then standing to the end
+ for providers in (('codex',), ('claude', 'codex'), four):
+ turn = turns(providers, 'codex')
+ runs = dips(turn)
+ self.assertEqual(len(runs), 1, (providers, runs))
+ self.assertGreaterEqual(runs[0][1] - runs[0][0], 3, providers)
+ self.assertLess(runs[0][1], len(turn) - 3, providers)
+
+ def test_each_bow_picks_one_of_the_two_at_random_and_keeps_it_while_it_plays(self):
+ rows = {'claude_a': {'provider': 'claude', 'alias': 'C', 'status': 'ok',
+ 'windows': [{'label': 'WEEK', 'used_percent': 50, 'resets_at': 10_000 + 86400}]}}
+
+ def loop(at):
+ frames = arcade.arcade_frames(overlay({'accounts': rows}, ('done', 'claude'), {'kind': 'done', 'at': at}),
+ 10_000)
+ return [frame.tobytes() for frame in frames]
+ drawn = {}
+ for style in arcade.BOW_STYLES:
+ with mock.patch.object(arcade, 'BOW_STYLE', style):
+ drawn[style] = loop(0)
+ self.assertNotEqual(drawn['low'], drawn['tilt'])
+ picked = [arcade.bow_style({'kind': 'done', 'at': 1000.0 + k * 61}) for k in range(40)]
+ self.assertEqual(set(picked), set(arcade.BOW_STYLES)) # both turn up
+ for at, style in ((1000.0 + k * 61, p) for k, p in enumerate(picked[:6])):
+ self.assertEqual(loop(at), drawn[style]) # the bow drawn is the one picked
+ self.assertEqual(loop(at), loop(at)) # and every drawing of it is the same picture
+
+ def test_the_hey_sign_rests_its_stick_on_clawds_head_however_high_the_hop(self):
+ from PIL import ImageChops
+ rows = {'claude_a': {'provider': 'claude', 'alias': 'C', 'status': 'ok',
+ 'windows': [{'label': 'WEEK', 'used_percent': 50, 'resets_at': 10_000 + 86400}]}}
+
+ def drawn(): # the scene of each frame of the loop, on the stage's own pixels (frames show it doubled)
+ mark = {'kind': 'needs', 'since': 0, 'level': 3}
+ return [frame.crop((0, 28, 240, 170)).resize((120, 71), 0)
+ for frame in arcade.arcade_frames(overlay({'accounts': rows}, ('needs', 3), mark), 10_000)]
+ frames = drawn()
+ with mock.patch.object(arcade, 'held_sign', lambda *args: None):
+ hopping = drawn() # Clawd, no sign
+ with mock.patch.object(arcade, 'place_clawd', lambda *args, **kwargs: None):
+ ground = drawn() # the scene alone
+ ends = set()
+ for k, (frame, clawd, bare) in enumerate(zip(frames, hopping, ground)):
+ sign = ImageChops.difference(frame, clawd)
+ end = sign.getbbox()[3] - 1 # the stick's last row: the sign's lowest
+ stick = [x for x in range(sign.width) if sign.getpixel((x, end)) != (0, 0, 0)]
+ on_clawd = lambda x, y: clawd.getpixel((x, y)) != bare.getpixel((x, y)) # noqa: E731
+ self.assertTrue(stick and all(on_clawd(x, end) for x in stick), k) # its end on Clawd's head
+ self.assertFalse(any(on_clawd(x, end - 1) for x in stick), k) # resting there, not pushed into it
+ ends.add(end)
+ self.assertGreater(len(ends), 3) # up and down with every hop
+
+ def test_the_waits_thresholds_are_the_drawings(self):
+ self.assertEqual(arcade.NEEDS_LEVELS, ((moments.SIGN, 3), (moments.HOP, 2), (0, 1)))
+ row = {'key': 'c', 'alias': 'C', 'provider': 'claude', 'status': 'ok', 'windows': [],
+ 'moment': {'kind': 'needs', 'since': 0, 'level': 2}}
+ self.assertEqual(arcade.scene_plan(row, 10_000)['moment']['level'], 2) # live.py's level, not the wall clock's
+
+
+def raw(port, data, timeout=4.0):
+ """Send raw bytes over loopback; (status or None, the whole answer, seconds until it closed)."""
+ began = time.monotonic()
+ with socket.create_connection(('127.0.0.1', port), timeout=timeout) as conn:
+ try:
+ conn.sendall(data)
+ except OSError:
+ pass
+ chunks = []
+ try:
+ while True:
+ chunk = conn.recv(65536)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ except OSError:
+ pass
+ answer = b''.join(chunks)
+ status = int(answer.split(b' ', 2)[1]) if answer.startswith(b'HTTP/') else None
+ return status, answer, time.monotonic() - began
+
+
+def dripped(connect, first, rest=b'', every=0, limit=6.0):
+ """A slow sender: `first` at once over a new connection (`connect()`), then `rest` a byte every `every` seconds.
+ (What TokenTV answered, seconds until it closed the connection: `limit` if it kept it open.)"""
+ conn = connect()
+ conn.settimeout(limit)
+ began, over = time.monotonic(), threading.Event()
+
+ def send():
+ try:
+ conn.sendall(first)
+ for k in range(len(rest)):
+ if over.wait(every):
+ return
+ conn.sendall(rest[k:k + 1])
+ except OSError:
+ pass
+ threading.Thread(target=send, daemon=True).start()
+ answer = b''
+ try:
+ while True:
+ chunk = conn.recv(4096)
+ if not chunk:
+ break
+ answer += chunk
+ except OSError: # reset, or still open at `limit`
+ pass
+ took = time.monotonic() - began
+ over.set()
+ conn.close()
+ return answer, took
+
+
+def post_bytes(port, body=b'{"moment":"claude.ask"}', host=None, headers=None, path='/moment', method='POST',
+ content_type='application/json', length=True):
+ lines = [f'{method} {path} HTTP/1.1']
+ if host is not False:
+ lines.append('Host: ' + (f'127.0.0.1:{port}' if host is None else host))
+ if content_type:
+ lines.append('Content-Type: ' + content_type)
+ if length is True:
+ lines.append(f'Content-Length: {len(body)}')
+ elif length is not False:
+ lines.append(f'Content-Length: {length}')
+ lines += [f'{k}: {v}' for k, v in (headers or [])]
+ return '\r\n'.join(lines).encode('latin-1') + b'\r\n\r\n' + body
+
+
+class EndpointTests(unittest.TestCase):
+ """POST /moment over loopback: what it takes, what it refuses, and that it answers fast whatever is sent."""
+ def setUp(self):
+ self.m = Moments({'claude', 'codex'})
+ self.serve(live.handler(UsageStore([]), agents=self.m))
+
+ def serve(self, handler):
+ server = live.QuietServer(('127.0.0.1', 0), handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+ self.port = server.server_port
+ return server
+
+ def send(self, **kwargs):
+ return raw(self.port, post_bytes(self.port, **kwargs))
+
+ def test_a_moment_is_taken_with_an_empty_204(self):
+ status, answer, took = self.send()
+ self.assertEqual(status, 204)
+ self.assertTrue(answer.endswith(b'\r\n\r\n')) # no body
+ self.assertNotIn(b'Access-Control', answer)
+ self.assertLess(took, 1)
+ self.assertEqual(self.m.wanted()[0], ('needs', 1))
+ for name in ('claude.answered', 'claude.end', 'codex.end'):
+ self.assertEqual(self.send(body=json.dumps({'moment': name}).encode())[0], 204)
+ self.assertEqual(self.m.wanted()[0], ('done', 'claude'))
+
+ def test_only_this_computers_names_and_a_plain_host_header(self):
+ for host in (f'127.0.0.1:{self.port}', f'localhost:{self.port}', f'[::1]:{self.port}', 'localhost'):
+ self.assertEqual(self.send(host=host)[0], 204, host)
+ self.assertEqual(self.m.waits, 4)
+ for host in ('evil.example', f'localhost.evil.example:{self.port}', f'127.0.0.1.evil.example:{self.port}',
+ 'mini.local', '192.168.0.20'):
+ status, answer, _ = self.send(host=host)
+ self.assertEqual(status, 403, host)
+ self.assertNotIn(host.encode(), answer)
+ for host in (False, '', '[::1', f'[email protected]:{self.port}', '127.0.0.1:80:80', '127.0.0.1 x'):
+ status, answer, _ = self.send(host=host)
+ self.assertTrue(400 <= status < 500, (host, status))
+ status, _, _ = self.send(headers=[('Host', 'evil.example')]) # two Host headers: which one?
+ self.assertEqual(status, 400)
+ self.assertEqual(self.m.waits, 4) # none of these changed anything
+ self.assertEqual(self.send()[0], 204) # and a valid one still works
+
+ def test_in_brackets_only_ipv6s_loopback_for_a_moment_and_for_the_dashboard_alike(self):
+ def get(host):
+ return raw(self.port, f'GET /display HTTP/1.1\r\nHost: {host}\r\n\r\n'.encode('latin-1'))[0]
+ for host in ('[::1]', f'[::1]:{self.port}'):
+ self.assertEqual(self.send(host=host)[0], 204, host)
+ self.assertEqual(get(host), 200, host)
+ for host in ('[127.0.0.1]', f'[127.0.0.1]:{self.port}', f'[127.0.0.1.]:{self.port}', f'[::2]:{self.port}',
+ f'[fe80::1]:{self.port}', '[evil]', '[localhost]', '[]', f'[::1]x:{self.port}', '[[::1]]'):
+ status, answer, _ = self.send(host=host)
+ self.assertTrue(400 <= status < 500, (host, status))
+ self.assertNotIn(host.encode(), answer)
+ self.assertEqual(get(host), 403, host)
+ self.assertEqual(self.m.waits, 2) # the two by [::1], nothing else
+
+ def test_a_tokentv_open_to_the_network_takes_moments_by_its_own_names_only(self):
+ m = Moments({'claude'})
+ self.serve(live.handler(UsageStore([]), agents=m, local_only=False,
+ names={'mini', 'mini.local', '192.168.0.20', 'desktop_ab'}))
+ self.assertEqual(self.send(host=f'mini:{self.port}')[0], 204)
+ self.assertEqual(self.send(host=f'other-host:{self.port}')[0], 403)
+ self.assertEqual(m.waits, 1)
+ self.assertEqual(self.send(host=f'DESKTOP_AB:{self.port}')[0], 204) # a Windows name may hold an underscore
+ self.assertEqual(raw(self.port, f'GET /display HTTP/1.1\r\nHost: DESKTOP_AB:{self.port}\r\n\r\n'.encode())[0], 200)
+ self.assertEqual(self.send(host=f'other_host:{self.port}')[0], 403)
+ self.assertEqual(m.waits, 2)
+
+ def test_an_ask_is_told_how_long_the_wait_it_joined_has_lasted(self):
+ clock = FakeClock()
+ patcher = mock.patch.object(moments, 'CLOCK', clock)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ age = lambda answer: [line for line in answer.split(b'\r\n') if line.lower().startswith(b'tokentv-wait-age:')] # noqa: E731
+ status, answer, _ = self.send()
+ self.assertEqual((status, age(answer)), (204, [b'TokenTV-Wait-Age: 0.0']))
+ clock.t += 1500
+ status, answer, _ = self.send() # another session's prompt joins the wait, 25 minutes in
+ self.assertEqual((status, age(answer)), (204, [b'TokenTV-Wait-Age: 1500.0']))
+ for name in ('claude.answered', 'claude.end', 'codex.end'):
+ self.assertEqual(age(self.send(body=json.dumps({'moment': name}).encode())[1]), [], name)
+ clock.t += 301 # the whole wait let go at its 30 minutes: the next prompt starts a new one
+ self.assertEqual(age(self.send()[1]), [b'TokenTV-Wait-Age: 0.0'])
+
+ def test_get_moment_is_no_moment(self):
+ def check(**kwargs):
+ return raw(self.port, post_bytes(self.port, method='GET', body=b'', content_type=None, length=False, **kwargs))
+
+ def head(answer):
+ return answer.split(b'\r\n\r\n')[0].lower().split(b'\r\n')[1:]
+ status, answer, took = check()
+ self.assertEqual(status, 405)
+ self.assertIn(b'allow: post', head(answer))
+ self.assertNotIn(b'tokentv', answer.lower()) # and it says nothing of whose endpoint this is
+ self.assertTrue(answer.endswith(b'\r\n\r\n')) # nothing more
+ self.assertLess(took, 1)
+ # refused as a moment is: another name, a web page, a query, no Host
+ for kwargs, code in (({'host': 'evil.example'}, 403), ({'headers': [('Origin', 'https://evil.example')]}, 403),
+ ({'path': '/moment?moment=claude.ask'}, 400), ({'host': False}, 400)):
+ status, answer, _ = check(**kwargs)
+ self.assertEqual(status, code, kwargs)
+ self.assertNotIn(b'tokentv', answer.lower(), kwargs)
+ self.assertIsNone(self.m.wanted()[0]) # none of it changed anything
+ status, answer, _ = self.send() # a moment is a 204, as ever
+ self.assertEqual(status, 204)
+ self.assertNotIn(b'tokentv:', answer.lower())
+ self.assertEqual(raw(self.port, f'GET /display HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\n\r\n'.encode())[0], 200)
+ self.assertEqual(check(path='/moment/')[0], 404)
+ self.serve(live.handler(UsageStore([]))) # a TokenTV without the moments: nobody's endpoint
+ status, answer, _ = check()
+ self.assertEqual(status, 404)
+ self.assertNotIn(b'tokentv', answer.lower())
+
+ def test_moments_come_only_from_this_computer(self):
+ a, b = socket.socketpair()
+ self.addCleanup(a.close)
+ self.addCleanup(b.close)
+ b.sendall(post_bytes(8787))
+ b.shutdown(socket.SHUT_WR)
+ server = mock.Mock()
+ handler = live.handler(UsageStore([]), agents=self.m)
+ handler(a, ('192.168.0.33', 51000), server) # from another computer on the network
+ self.assertIn(b' 403 ', b.recv(65536))
+ self.assertIsNone(self.m.wanted()[0])
+
+ def test_no_web_page_can_send_one(self):
+ for origin in ('https://evil.example', 'null', f'http://127.0.0.1:{self.port + 1}', 'http//127.0.0.1',
+ f'http://localhost:{self.port}'):
+ status, _, _ = self.send(headers=[('Origin', origin)])
+ self.assertEqual(status, 403, origin)
+ self.assertEqual(self.send(headers=[('Origin', f'http://127.0.0.1:{self.port}')])[0], 204) # its own page
+ status, answer, _ = raw(self.port, post_bytes(self.port, method='OPTIONS', body=b'', content_type=None, headers=[
+ ('Origin', 'https://evil.example'), ('Access-Control-Request-Method', 'POST')]))
+ self.assertEqual(status, 405)
+ self.assertNotIn(b'Access-Control-Allow', answer)
+ for kind, body in (('text/plain', b'{"moment":"claude.ask"}'), ('application/x-www-form-urlencoded', b'moment=claude.ask'),
+ ('multipart/form-data; boundary=x', b'--x\r\n\r\nclaude.ask\r\n--x--'), (None, b'{"moment":"claude.ask"}')):
+ self.assertEqual(self.send(body=body, content_type=kind)[0], 415, kind)
+ self.assertEqual(self.m.waits, 1)
+
+ def test_an_origin_that_does_not_even_parse_is_refused_like_a_foreign_one_without_a_traceback(self):
+ self.serve(live.handler(UsageStore([]), mock.Mock(), agents=self.m)) # with display settings, as TokenTV runs
+ said = io.StringIO()
+ with mock.patch('sys.stderr', said):
+ for origin in ('http://[::1', 'http://[evil', 'https://[', f'http://[::1]x:{self.port}',
+ f'http://[127.0.0.1:{self.port}'):
+ status, answer, _ = self.send(headers=[('Origin', origin)])
+ self.assertEqual(status, 403, origin)
+ self.assertNotIn(origin.encode(), answer)
+ for path, body in (('/display/style', b'{"style":"arcade"}'), ('/collection/replay', b'{"check":"x"}')):
+ status, answer, _ = self.send(path=path, body=body, headers=[('Origin', origin)])
+ self.assertEqual(status, 403, (path, origin))
+ self.assertNotIn(origin.encode(), answer)
+ self.assertEqual(said.getvalue(), '') # nothing went wrong in TokenTV, so nothing printed
+ self.assertIsNone(self.m.wanted()[0])
+ self.assertEqual(self.send()[0], 204) # and a valid one still works
+
+ def test_only_the_finite_names_and_nothing_beside_them(self):
+ hostile = ['<script>alert(1)</script>', '$(touch /tmp/x)', '../../etc/passwd']
+ bodies = [b'{"moment":"claude.asked"}', b'{"moment":""}', b'{"moment":"CLAUDE.ASK"}', b'{"moment":"Claude.ask"}',
+ b'{"moment":"claude.ask","prompt":"secret"}', b'{"moment":"claude.ask","session":"s1"}',
+ b'{"moment":1}', b'{"moment":null}', b'{"moment":["claude.ask"]}', b'["claude.ask"]',
+ b'[{"moment":"claude.ask"}]', b'"claude.ask"', b'{"moment":"claude.ask","moment":"claude.end"}',
+ b'{"moment":"claude.ask"', b'claude.ask', b'{"moment":"claude\xff.ask"}', b'\xfe\xff\x00{',
+ b'{"Moment":"claude.ask"}', b'{"moment":"claude.ask "}'] + \
+ [json.dumps({'moment': text}).encode() for text in hostile]
+ for body in bodies:
+ status, answer, _ = self.send(body=body)
+ self.assertEqual(status, 400, body)
+ for text in hostile + ['secret']:
+ self.assertNotIn(text.encode(), answer)
+ self.assertEqual(raw(self.port, post_bytes(self.port, method='GET', body=b''))[0], 405) # GET is no moment
+ self.assertEqual(self.send(path='/moment?moment=claude.ask')[0], 400)
+ self.assertEqual(self.send(path='/moment/')[0], 404)
+ self.assertIsNone(self.m.wanted()[0])
+ self.assertEqual(self.send()[0], 204) # a valid one afterwards still works
+
+ def test_oversized_or_broken_bodies_are_refused_before_they_are_read(self):
+ status, _, took = raw(self.port, post_bytes(self.port, body=b'{' + b' ' * (1 << 20) + b'}'))
+ self.assertEqual(status, 413)
+ self.assertLess(took, 2)
+ for length, code in (('1000000000', 413), ('257', 413), ('-5', 400), ('abc', 400), ('0', 400), ('+24', 400)):
+ status, _, took = raw(self.port, post_bytes(self.port, body=b'', length=length))
+ self.assertEqual(status, code, length)
+ self.assertLess(took, 2)
+ self.assertEqual(raw(self.port, post_bytes(self.port, length=False))[0], 400) # no length
+ body = b'{"moment":"claude.ask"}'
+ twice = post_bytes(self.port, body=body, headers=[('Content-Length', '5')])
+ self.assertEqual(raw(self.port, twice)[0], 400)
+ chunked = post_bytes(self.port, body=b'17\r\n' + body + b'\r\n0\r\n\r\n', length=False,
+ headers=[('Transfer-Encoding', 'chunked')])
+ self.assertEqual(raw(self.port, chunked)[0], 400)
+ both = post_bytes(self.port, body=body, headers=[('Transfer-Encoding', 'chunked')])
+ self.assertEqual(raw(self.port, both)[0], 400)
+ self.assertIsNone(self.m.wanted()[0])
+
+ def test_a_sender_that_stops_part_way_is_let_go_and_others_are_answered_meanwhile(self):
+ stalled = socket.create_connection(('127.0.0.1', self.port), timeout=5)
+ self.addCleanup(stalled.close)
+ whole = post_bytes(self.port, body=b'{"moment":"claude.end"}')
+ stalled.sendall(whole[:-10]) # the last ten bytes never come
+ began = time.monotonic()
+ status, _, took = self.send() # another client meanwhile
+ self.assertEqual(status, 204)
+ self.assertLess(took, 1)
+ conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=2)
+ conn.request('GET', '/display')
+ self.assertEqual(conn.getresponse().status, 200)
+ stalled.settimeout(4)
+ answer = b''
+ try:
+ while True:
+ chunk = stalled.recv(4096)
+ if not chunk:
+ break
+ answer += chunk
+ except OSError:
+ pass
+ self.assertLess(time.monotonic() - began, 2.5) # closed, not held open
+ self.assertIn(b' 408 ', answer) # it ran out of time
+ self.assertEqual(self.m.wanted()[0], ('needs', 1)) # the cut-short end never counted
+
+ def test_a_refused_sender_that_keeps_dripping_is_let_go_in_about_a_second(self):
+ conn = socket.create_connection(('127.0.0.1', self.port), timeout=5)
+ self.addCleanup(conn.close)
+ conn.sendall(post_bytes(self.port, body=b'', length='200', host='evil.example')) # refused at its Host
+ began = time.monotonic()
+ while time.monotonic() - began < 4:
+ try:
+ conn.sendall(b'x') # a byte every fifth of a second, for as long as it is let
+ except OSError:
+ break
+ time.sleep(.2)
+ self.assertLess(time.monotonic() - began, 2)
+
+ def test_a_moment_has_two_seconds_to_arrive_wherever_it_dawdles_and_a_late_one_gets_a_408(self):
+ tcp = lambda: socket.create_connection(('127.0.0.1', self.port), timeout=5) # noqa: E731
+ moment = post_bytes(self.port)
+ line = moment.split(b'\r\n')[0] + b'\r\n'
+ head = moment.split(b'\r\n\r\n')[0] + b'\r\n\r\n'
+ slow = {'stops in its headers': (tcp, moment[:30]),
+ 'drips its headers': (tcp, line, moment[len(line):], .15),
+ 'drips its body': (tcp, head, moment[len(head):], .6)}
+ got = {}
+ threads = [threading.Thread(target=lambda name, args: got.__setitem__(name, dripped(*args)), args=item)
+ for item in slow.items()]
+ for thread in threads:
+ thread.start()
+ time.sleep(.3)
+ status, _, took = self.send(body=b'{"moment":"claude.ask"}') # another client meanwhile
+ self.assertEqual(status, 204)
+ self.assertLess(took, 1)
+ for thread in threads:
+ thread.join(8)
+ for name, (answer, took) in got.items():
+ self.assertLess(took, live.READ_SECONDS + .6, name) # let go, not held
+ self.assertIn(b' 408 ', answer, name)
+ self.assertEqual(self.m.waits, 1) # only the client that sent its request in time
+
+ def test_a_moment_that_comes_whole_but_late_is_a_408_and_counts_for_nothing(self):
+ # Its first byte at once, the rest 8 s later in one go: while the first line is still coming it has the
+ # dashboard's 10 s, so the rest lands in one read and the headers and body are read from what came.
+ moment = post_bytes(self.port)
+ conn = socket.create_connection(('127.0.0.1', self.port), timeout=15)
+ self.addCleanup(conn.close)
+ conn.sendall(moment[:1])
+ time.sleep(8)
+ conn.sendall(moment[1:])
+ sent, answer = time.monotonic(), b''
+ try:
+ while chunk := conn.recv(65536):
+ answer += chunk
+ except OSError:
+ pass
+ self.assertTrue(answer.startswith(b'HTTP/'), answer)
+ self.assertEqual(int(answer.split(b' ', 2)[1]), 408)
+ self.assertLess(time.monotonic() - sent, 1) # answered as it came
+ self.assertEqual(self.m.waits, 0) # the sender gave up on it long ago: nothing counted
+ self.assertIsNone(self.m.wanted()[0])
+ self.assertEqual(self.send()[0], 204) # one in time is taken as ever
+ self.assertEqual(self.m.waits, 1)
+
+ def test_the_dashboards_other_requests_have_longer_so_a_slow_phone_is_answered(self):
+ preferences = mock.Mock()
+ preferences.snapshot.return_value = {'style': 'arcade', 'status': 'ok', 'styles': ['pixel', 'arcade']}
+ self.serve(live.handler(UsageStore([]), preferences, agents=self.m))
+
+ def late(head, rest, after):
+ """`head` at once, `rest` `after` seconds later, as a phone on poor Wi-Fi sends; (the answer, seconds
+ until it began)."""
+ conn = socket.create_connection(('127.0.0.1', self.port), timeout=15)
+ began, answered = time.monotonic(), None
+
+ def rest_later():
+ time.sleep(after)
+ try:
+ conn.sendall(rest)
+ except OSError:
+ pass
+ with conn:
+ conn.sendall(head)
+ threading.Thread(target=rest_later, daemon=True).start()
+ answer = b''
+ try:
+ while chunk := conn.recv(65536):
+ answered = answered or time.monotonic() - began
+ answer += chunk
+ except OSError:
+ pass
+ return answer, answered
+ host = f'Host: 127.0.0.1:{self.port}\r\n'.encode()
+ answer, _ = late(b'GET /display HTTP/1.1\r\n', host + b'\r\n', 3) # its headers three seconds late
+ self.assertIn(b' 200 ', answer)
+ body = b'{"style":"arcade"}'
+ style = (b'POST /display/style HTTP/1.1\r\n' + host + b'Content-Type: application/json\r\n' +
+ f'Content-Length: {len(body)}\r\n\r\n'.encode())
+ answer, _ = late(style, body, 2.3) # its body 2.3 s after the headers
+ self.assertIn(b' 200 ', answer)
+ preferences.set_style.assert_called_once_with('arcade')
+ with mock.patch.object(live, 'PAGE_SECONDS', 1.5): # even the dashboard's own time runs out at last
+ answer, took = late(style, body, 2.5)
+ self.assertIn(b' 408 ', answer) # a late body is no display choice that could not be saved
+ self.assertNotIn(b' 500 ', answer)
+ self.assertLess(took, 2.4) # answered as its time ran out, not when the body came
+ answer, took = late(b'GET /display HTTP/1.1\r\n', host + b'\r\n', 2.5)
+ self.assertIn(b' 408 ', answer)
+ answer, took = dripped(lambda: socket.create_connection(('127.0.0.1', self.port), timeout=5), b'')
+ self.assertEqual(answer, b'') # a connection that sends nothing is closed with nothing said
+ self.assertLess(took, 2.1)
+ preferences.set_style.assert_called_once() # only the one that came in time
+ self.assertEqual(self.send()[0], 204)
+
+ def test_a_display_choice_that_cannot_be_saved_is_said_so_without_a_traceback(self):
+ path = temp_dir(self) / 'config.json'
+ path.write_text(json.dumps({'accounts': [], 'display_style': 'pixel', 'from_a_newer_tokentv': 1}), encoding='utf-8')
+ self.serve(live.handler(UsageStore([]), live.DisplayPreferences(path, {'accounts': []}), agents=self.m))
+ said = io.StringIO()
+ with mock.patch('sys.stderr', said): # the config cannot be read back to save the choice into
+ status, answer, _ = self.send(path='/display/style', body=b'{"style":"arcade"}')
+ self.assertEqual(status, 500)
+ self.assertIn(b'Could not save display choice', answer)
+ self.assertEqual(said.getvalue(), '')
+ self.assertEqual(json.loads(path.read_text(encoding='utf-8'))['display_style'], 'pixel') # untouched
+
+ def test_what_the_server_could_not_take_never_comes_back_in_its_answer(self):
+ status, answer, _ = raw(self.port, b'FOO<b>X</b> /moment HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n')
+ self.assertEqual(status, 405)
+ self.assertNotIn(b'<b>', answer)
+ self.assertNotIn(b'FOO', answer)
+ status, answer, _ = raw(self.port, b'POST /moment HTTP/9<script>\r\n\r\n') # (answered as HTTP/0.9)
+ self.assertNotIn(b'<script>', answer)
+ self.assertIn(b'400', answer)
+ status, answer, _ = raw(self.port, post_bytes(self.port, method='PUT'))
+ self.assertEqual(status, 405)
+ self.assertIsNone(self.m.wanted()[0])
+
+ def test_twenty_at_once_cannot_wedge_it(self):
+ results = []
+
+ def one(body):
+ results.append(raw(self.port, post_bytes(self.port, body=body))[0])
+ threads = [threading.Thread(target=one, args=(b'{"moment":"claude.nope"}',)) for _ in range(10)]
+ threads += [threading.Thread(target=one, args=(b'{"moment":"claude.end"}',)) for _ in range(10)]
+ began = time.monotonic()
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(5)
+ self.assertLess(time.monotonic() - began, 2)
+ self.assertEqual(sorted(results), [204] * 10 + [400] * 10)
+ self.assertEqual(self.m.wanted()[0], ('done', 'claude')) # one bow; the other nine fell in its minute
+
+ def test_a_collection_replay_waits_for_no_agent_but_is_refused_while_one_needs_the_clock(self):
+ class Locks:
+ def collection(self):
+ return {'found': [{'check': 'box-1'}]}
+ prefs = mock.Mock()
+ prefs.snapshot.return_value = {'status': 'ok', 'applied_style': 'arcade', 'style': 'arcade'}
+ replays = []
+ self.serve(live.handler(UsageStore([]), prefs, Locks(), replays, threading.Event(), agents=self.m))
+ body = b'{"check":"box-1"}'
+ self.m.note('claude.ask')
+ status, answer, _ = raw(self.port, post_bytes(self.port, body=body, path='/collection/replay'))
+ self.assertEqual(status, 409)
+ self.assertIn(b'Claude Code is waiting for you', answer)
+ self.m.note('claude.answered')
+ self.m.note('claude.end')
+ self.assertEqual(raw(self.port, post_bytes(self.port, body=body, path='/collection/replay'))[0], 409)
+ self.assertEqual(replays, [])
+ self.m.drop_bow()
+ self.assertEqual(raw(self.port, post_bytes(self.port, body=body, path='/collection/replay'))[0], 200)
+ self.assertEqual(replays, ['box-1'])
+
+ def test_the_dashboards_other_paths_still_answer(self):
+ conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=3)
+ conn.request('GET', '/display')
+ self.assertEqual(conn.getresponse().status, 200)
+
+
+def receiver(test, answer=b'HTTP/1.0 204 No Content\r\n\r\n', hold=0):
+ """(port, requests): a loopback TCP server recording each whole request it gets, answering `answer` after
+ `hold` seconds."""
+ got = []
+ listener = socket.socket()
+ listener.bind(('127.0.0.1', 0))
+ listener.listen(8)
+ test.addCleanup(listener.close)
+
+ def one(conn):
+ with conn:
+ conn.settimeout(3)
+ data = b''
+ try:
+ while b'\r\n\r\n' not in data:
+ chunk = conn.recv(4096)
+ if not chunk:
+ break
+ data += chunk
+ head = data.split(b'\r\n\r\n', 1)[0].lower()
+ length = int(head.split(b'content-length:', 1)[1].split(b'\r\n', 1)[0]) if b'content-length:' in head else 0
+ while len(data.split(b'\r\n\r\n', 1)[-1]) < length:
+ chunk = conn.recv(4096)
+ if not chunk:
+ break
+ data += chunk
+ except (OSError, ValueError):
+ pass
+ got.append(data)
+ time.sleep(hold)
+ try:
+ conn.sendall(answer)
+ except OSError:
+ pass
+
+ def run():
+ while True:
+ try:
+ conn, _ = listener.accept()
+ except OSError:
+ return
+ threading.Thread(target=one, args=(conn,), daemon=True).start()
+ threading.Thread(target=run, daemon=True).start()
+ return listener.getsockname()[1], got
+
+
+class SocketTests(unittest.TestCase):
+ """The same endpoint on TokenTV's own socket (Linux and macOS), and the sender Codex's notify uses."""
+ def setUp(self):
+ self.dir = temp_dir(self)
+ self.m = Moments({'claude', 'codex'})
+
+ def receiver(self, answer=b'HTTP/1.0 204 No Content\r\n\r\n', hold=0):
+ """A loopback TCP server that records each request it is sent, and answers `answer` after `hold` seconds."""
+ return receiver(self, answer, hold)
+
+ @unittest.skipUnless(hasattr(socket, 'AF_UNIX') and os.name != 'nt', 'a Unix socket')
+ def test_a_moment_over_tokentvs_own_socket(self):
+ state = self.dir / 'state'
+ state.mkdir()
+ path = state / 'live.sock'
+ server = live.MomentSocket(str(path), live.handler(UsageStore([]), agents=self.m, moments_only=True))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+ port, got = self.receiver() # the TCP address in live.url: never used while the socket is there
+ (state / 'live.url').write_text(f'http://127.0.0.1:{port}', encoding='utf-8')
+ self.assertTrue(moments.post(state, 'claude.end'))
+ self.assertEqual((self.m.wanted()[0], got), (('done', 'claude'), []))
+ conn = socket.socket(socket.AF_UNIX)
+ conn.connect(str(path))
+ conn.sendall(b'GET /snapshot HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n')
+ self.assertIn(b' 404 ', conn.recv(4096)) # the socket serves moments, nothing else
+ conn.close()
+ conn = socket.socket(socket.AF_UNIX)
+ conn.connect(str(path))
+ conn.sendall(b'GET /moment HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n')
+ answer = conn.recv(4096)
+ self.assertIn(b' 405 ', answer) # no moment, as on the port
+ self.assertIn(b'allow: post', answer.lower())
+ self.assertNotIn(b'tokentv', answer.lower())
+ conn.close()
+ stalled = socket.socket(socket.AF_UNIX)
+ stalled.connect(str(path))
+ stalled.sendall(b'POST /moment HTTP/1.1\r\nHost: 127.0.0.1') # and stops in its headers
+ stalled.settimeout(5)
+ began = time.monotonic()
+ try:
+ while stalled.recv(4096):
+ pass
+ except OSError:
+ pass
+ self.assertLess(time.monotonic() - began, 3) # let go, not held
+ stalled.close()
+
+ def unix():
+ conn = socket.socket(socket.AF_UNIX)
+ conn.connect(str(path))
+ return conn
+ moment = b'POST /moment HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: 23\r\n\r\n'
+ for first, rest, every in ((b'', moment + b'{"moment":"claude.ask"}', .15), (moment, b'{"moment":"claude.ask"}', .6)):
+ answer, took = dripped(unix, first, rest, every) # a byte now and then, never in time
+ self.assertLess(took, live.READ_SECONDS + .6)
+ self.assertNotIn(b' 204 ', answer)
+ self.assertEqual(self.m.wanted()[0], ('done', 'claude')) # neither counted
+ path.unlink() # gone: TokenTV stopped, and an old address is no reason to send anywhere
+
+ @unittest.skipUnless(hasattr(socket, 'AF_UNIX') and os.name != 'nt', 'a Unix socket')
+ def test_a_stale_socket_is_no_reason_to_try_the_port(self):
+ state = self.dir / 'state'
+ state.mkdir()
+ dead = socket.socket(socket.AF_UNIX)
+ dead.bind(str(state / 'live.sock')) # left by a TokenTV that ended without its cleanup
+ dead.close()
+ port, got = self.receiver()
+ (state / 'live.url').write_text(f'http://127.0.0.1:{port}', encoding='utf-8')
+ self.assertFalse(moments.post(state, 'codex.end'))
+ time.sleep(.1)
+ self.assertEqual(got, [])
+
+ @unittest.skipUnless(hasattr(socket, 'AF_UNIX') and os.name != 'nt', 'a Unix socket')
+ def test_without_tokentvs_socket_nothing_goes_to_the_port_in_live_url(self):
+ state = self.dir / 'state'
+ state.mkdir()
+ port, got = self.receiver() # a TokenTV that stopped left its address; another program may have the port now
+ (state / 'live.url').write_text(f'http://127.0.0.1:{port}', encoding='utf-8')
+ self.assertFalse(moments.post(state, 'codex.end'))
+ time.sleep(.1)
+ self.assertEqual(got, [])
+
+ @mock.patch.object(moments, 'WINDOWS', True) # the port, as on Windows: http.client follows no redirect, no proxy
+ def test_the_sender_goes_only_to_this_computers_address_and_never_follows_or_proxies(self):
+ state = self.dir / 'state'
+ state.mkdir()
+ elsewhere, followed = self.receiver() # where the redirect points, on this computer: a follow would land here
+ port, got = self.receiver(answer=f'HTTP/1.0 307 Temporary Redirect\r\nLocation: http://127.0.0.1:{elsewhere}/stolen'
+ f'\r\n\r\n'.encode())
+ sink, caught = self.receiver()
+ with mock.patch.dict(os.environ, {'HTTP_PROXY': f'http://127.0.0.1:{sink}', 'http_proxy': f'http://127.0.0.1:{sink}',
+ 'ALL_PROXY': f'http://127.0.0.1:{sink}', 'NO_PROXY': ''}):
+ for bad in ('http://example.com:80', 'http://192.0.2.7:8787', f'http://[email protected]:{port}',
+ f'http://[email protected]:{port}', f'http://localhost.evil.example:{port}',
+ f'https://127.0.0.1:{port}', f'http://127.0.0.1:{port}/x', 'http://127.0.0.1:0', ''):
+ (state / 'live.url').write_text(bad, encoding='utf-8')
+ self.assertFalse(moments.post(state, 'codex.end'), bad)
+ (state / 'live.url').write_text(f'http://localhost:{port}\n', encoding='utf-8') # as TokenTV writes it
+ self.assertFalse(moments.post(state, 'codex.end')) # a redirect is no answer, and is not followed
+ time.sleep(.1)
+ self.assertEqual(len(got), 1)
+ self.assertEqual(followed, []) # no redirect followed
+ self.assertEqual(caught, []) # no proxy
+ head, body = got[0].split(b'\r\n\r\n', 1)
+ self.assertEqual(body, b'{"moment": "codex.end"}')
+ self.assertIn(f'Host: 127.0.0.1:{port}'.encode(), head)
+ self.assertTrue(head.startswith(b'POST /moment HTTP/1.1'))
+
+ @unittest.skipUnless(hasattr(socket, 'AF_UNIX') and os.name != 'nt', 'a Unix socket')
+ def test_the_sender_follows_no_redirect_from_the_socket_either(self):
+ state = self.dir / 'state'
+ state.mkdir()
+ elsewhere, followed = self.receiver() # where the redirect points, on this computer: a follow would land here
+ listener = listen_as_tokentv(self, state) # on TokenTV's socket, something that redirects
+
+ def redirect():
+ conn, _ = listener.accept()
+ with conn:
+ conn.recv(65536)
+ conn.sendall(f'HTTP/1.0 307 Temporary Redirect\r\nLocation: http://127.0.0.1:{elsewhere}/stolen\r\n\r\n'
+ .encode())
+ threading.Thread(target=redirect, daemon=True).start()
+ (state / 'live.url').write_text('http://127.0.0.1:8787', encoding='utf-8')
+ self.assertFalse(moments.post(state, 'codex.end')) # a redirect is no answer
+ time.sleep(.1)
+ self.assertEqual(followed, [])
+
+ @mock.patch.object(moments, 'WINDOWS', True)
+ def test_the_sender_gives_up_quickly_on_a_tokentv_that_does_not_answer(self):
+ state = self.dir / 'state'
+ state.mkdir()
+ port, got = self.receiver(hold=5)
+ (state / 'live.url').write_text(f'http://127.0.0.1:{port}', encoding='utf-8')
+ began = time.monotonic()
+ self.assertFalse(moments.post(state, 'codex.end', timeout=.8))
+ self.assertLess(time.monotonic() - began, 1.5)
+ self.assertFalse(moments.post(self.dir / 'nowhere', 'codex.end')) # no TokenTV at all
+
+ @unittest.skipUnless(hasattr(socket, 'AF_UNIX') and os.name != 'nt', 'a Unix socket')
+ def test_the_sender_gives_up_quickly_on_a_socket_that_does_not_answer(self):
+ state = self.dir / 'state'
+ state.mkdir()
+ hang = socket.socket(socket.AF_UNIX)
+ hang.bind(str(state / 'live.sock'))
+ hang.listen(1) # takes the connection, never answers
+ self.addCleanup(hang.close)
+ (state / 'live.url').write_text('http://127.0.0.1:8787', encoding='utf-8')
+ began = time.monotonic()
+ self.assertFalse(moments.post(state, 'codex.end', timeout=.8))
+ self.assertLess(time.monotonic() - began, 1.5)
+
+
+def tokentv_at(test, state, agents):
+ """The moment endpoint for the state folder `state`, as a running TokenTV has it: its port in live.url and, on
+ Linux and macOS, its own socket (live.sock)."""
+ server = live.QuietServer(('127.0.0.1', 0), live.handler(UsageStore([]), agents=agents))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ test.addCleanup(server.server_close)
+ test.addCleanup(server.shutdown)
+ (state / 'live.url').write_text(f'http://127.0.0.1:{server.server_port}', encoding='utf-8')
+ if not moments.WINDOWS:
+ unix = live.MomentSocket(str(state / 'live.sock'), live.handler(UsageStore([]), agents=agents, moments_only=True))
+ threading.Thread(target=unix.serve_forever, daemon=True).start()
+ test.addCleanup(unix.server_close)
+ test.addCleanup(unix.shutdown)
+ return server.server_port
+
+
+def listen_as_tokentv(test, state):
+ """A bare listener where TokenTV would be for `state` (its socket, or on Windows its port), taking connections."""
+ if moments.WINDOWS:
+ listener = socket.socket()
+ listener.bind(('127.0.0.1', 0))
+ (state / 'live.url').write_text(f'http://127.0.0.1:{listener.getsockname()[1]}', encoding='utf-8')
+ else:
+ (state / 'live.sock').unlink(missing_ok=True)
+ listener = socket.socket(socket.AF_UNIX)
+ listener.bind(str(state / 'live.sock'))
+ listener.listen(4)
+ test.addCleanup(listener.close)
+ return listener
+
+
+class NotifyTests(unittest.TestCase):
+ """`token-tv notify` as Codex runs it: a process, one JSON argument."""
+ def setUp(self):
+ self.dir = temp_dir(self)
+ self.home = self.dir / 'h' # short: a socket's path has a length limit (about 104 bytes on macOS)
+ self.state = self.home / '.config' / 'token-tv' / 'state'
+ self.state.mkdir(parents=True)
+ self.m = Moments({'codex'})
+ tokentv_at(self, self.state, self.m)
+
+ def notify(self, *args, env=None):
+ environment = {key: value for key, value in os.environ.items() if not key.startswith('TOKEN_TV')}
+ environment.update({'HOME': str(self.home), 'USERPROFILE': str(self.home), # Windows reads USERPROFILE
+ 'XDG_CONFIG_HOME': '', 'PYTHONPATH': str(ROOT), 'PYTHONDONTWRITEBYTECODE': '1'}, **(env or {}))
+ began = time.monotonic()
+ done = subprocess.run([sys.executable, '-m', 'token_tv', 'notify', *args], capture_output=True, env=environment,
+ cwd=str(self.dir), timeout=10)
+ return done, time.monotonic() - began
+
+ def files(self):
+ return sorted((str(p), p.stat().st_mtime_ns) for p in self.dir.rglob('*') if p.is_file())
+
+ def test_a_finished_turn_bows_and_nothing_of_it_is_printed_or_kept(self):
+ before = self.files()
+ event = {'type': 'agent-turn-complete', 'thread-id': 'CANARY-THREAD 9f', 'turn-id': 'CANARY-TURN 1',
+ 'cwd': '/home/u/CANARY-PATH', 'input-messages': ['CANARY-PROMPT "quoted"\nnew line $(touch pwned) `id`'],
+ 'last-assistant-message': 'CANARY-OUTPUT 한국어 ✓'}
+ done, took = self.notify(json.dumps(event, ensure_ascii=False))
+ self.assertEqual((done.returncode, done.stdout, done.stderr), (0, b'', b''))
+ self.assertLess(took, 2)
+ self.assertEqual(self.m.wanted()[0], ('done', 'codex'))
+ self.assertEqual(self.files(), before) # nothing written, the shell-looking text ran nothing
+ self.assertFalse((self.dir / 'pwned').exists())
+
+ def test_only_the_name_goes_out(self):
+ got = []
+ listener = listen_as_tokentv(self, self.state)
+
+ def accept():
+ conn, _ = listener.accept()
+ with conn:
+ conn.settimeout(3)
+ data = b''
+ while not data.endswith(b'}'):
+ chunk = conn.recv(4096)
+ if not chunk:
+ break
+ data += chunk
+ got.append(data)
+ conn.sendall(b'HTTP/1.0 204 No Content\r\n\r\n')
+ threading.Thread(target=accept, daemon=True).start()
+ done, _ = self.notify(json.dumps({'type': 'agent-turn-complete', 'turn-id': 'CANARY-77', 'cwd': '/CANARY-PATH'}))
+ self.assertEqual(done.returncode, 0)
+ time.sleep(.1)
+ self.assertEqual(len(got), 1)
+ self.assertNotIn(b'CANARY', got[0])
+ self.assertTrue(got[0].endswith(b'\r\n\r\n{"moment": "codex.end"}'))
+
+ def test_other_events_and_broken_arguments_do_nothing_quickly(self):
+ for args in ([json.dumps({'type': 'approval-requested'})], [json.dumps({'thread-id': 'x'})], ['"agent-turn-complete"'],
+ ['42'], ['-1'], ['{not json'], [], ['--weird'], ['[{"type": "agent-turn-complete"}]'],
+ [json.dumps({'type': 'Agent-Turn-Complete'})]):
+ done, took = self.notify(*args)
+ self.assertEqual((done.returncode, done.stdout, done.stderr), (0, b'', b''), args)
+ self.assertLess(took, 2)
+ self.assertIsNone(self.m.wanted()[0])
+ done, _ = self.notify(json.dumps({'type': 'agent-turn-complete'})) # the control
+ self.assertEqual(self.m.wanted()[0], ('done', 'codex'))
+
+ def test_no_tokentv_or_one_that_hangs_still_ends_within_two_seconds(self):
+ url = (self.state / 'live.url').read_text(encoding='utf-8')
+ (self.state / 'live.url').unlink()
+ done, took = self.notify(json.dumps({'type': 'agent-turn-complete'}))
+ self.assertEqual((done.returncode, done.stdout, done.stderr), (0, b'', b''))
+ self.assertLess(took, 2)
+ (self.state / 'live.url').write_text(url, encoding='utf-8')
+ listen_as_tokentv(self, self.state) # accepts, never answers
+ done, took = self.notify(json.dumps({'type': 'agent-turn-complete'}))
+ self.assertEqual((done.returncode, done.stdout, done.stderr), (0, b'', b''))
+ self.assertLess(took, 2)
+
+ def test_another_config_is_found_by_flag_or_by_environment(self):
+ other = self.dir / 'o'
+ (other / 'state').mkdir(parents=True)
+ (self.state / 'live.url').unlink()
+ tokentv_at(self, other / 'state', self.m)
+ self.notify('--config', str(other / 'config.json'), json.dumps({'type': 'agent-turn-complete'}))
+ self.assertEqual(self.m.wanted()[0], ('done', 'codex'))
+ self.m.drop_bow()
+ self.notify(json.dumps({'type': 'agent-turn-complete'}), env={'TOKEN_TV_CONFIG': str(other / 'config.json')})
+ self.assertEqual(self.m.wanted()[0], ('done', 'codex'))
+
+
+class StopTests(unittest.TestCase):
+ """TokenTV stopping: its address (live.url) and its socket (live.sock) go with it, so no agent goes on telling a
+ port another program may hold next."""
+ def test_a_tokentv_that_stops_takes_its_address_and_socket_away(self):
+ rig = Rig(self)
+ self.assertTrue((rig.state / 'live.url').exists())
+ self.assertEqual((rig.state / 'live.sock').exists(), not moments.WINDOWS)
+ rig.stop()
+ self.assertFalse((rig.state / 'live.url').exists())
+ self.assertFalse((rig.state / 'live.sock').exists())
+
+ @unittest.skipIf(os.name == 'nt', 'Windows ends a process outright: no program cleans up after that')
+ def test_asked_to_stop_as_systemd_and_launchd_ask_it_cleans_up_the_same(self):
+ folder = temp_dir(self)
+ home, state = folder / 'h', folder / 's'
+ home.mkdir()
+ readings = {'claude_a': {'alias': 'CLAUDE', 'provider': 'claude', 'status': 'ok', 'fetched_at': time.time(),
+ 'windows': [{'label': 'WEEK', 'used_percent': 30, 'resets_at': time.time() + 86400}]}}
+ (folder / 'readings.json').write_text(json.dumps({'accounts': readings}), encoding='utf-8')
+ config = {'accounts': [{'key': 'claude_a', 'alias': 'CLAUDE', 'provider': 'claude', 'email': '[email protected]',
+ 'snapshot_file': str(folder / 'readings.json')}], 'update_check': False}
+ (folder / 'config.json').write_text(json.dumps(config), encoding='utf-8')
+ environment = {key: value for key, value in os.environ.items() if not key.startswith('TOKEN_TV')}
+ # another HOME hides a per-user site-packages (Pillow): the child gets this process's import path
+ environment.update({'HOME': str(home), 'XDG_CONFIG_HOME': str(home / '.config'),
+ 'PYTHONPATH': os.pathsep.join([str(ROOT), *(p for p in sys.path if p)]),
+ 'PYTHONDONTWRITEBYTECODE': '1'})
+ out_path, err_path = folder / 'out.txt', folder / 'err.txt'
+ # Started for sure once it says it listens (its stop handler is in place by then), however loaded the
+ # machine; a free port another test took meanwhile is tried again with a new one.
+ for attempt in range(3):
+ with socket.socket() as probe:
+ probe.bind(('127.0.0.1', 0))
+ port = probe.getsockname()[1]
+ with open(out_path, 'wb') as out, open(err_path, 'wb') as err:
+ tokentv = subprocess.Popen([sys.executable, '-m', 'token_tv.live', '--config', str(folder / 'config.json'),
+ '--state-dir', str(state), '--port', str(port)], env=environment,
+ cwd=str(folder), stdout=out, stderr=err)
+ self.addCleanup(lambda child=tokentv: child.poll() is None and (child.kill(), child.wait()))
+ began = time.monotonic()
+ while b'TokenTV live listening' not in out_path.read_bytes() and tokentv.poll() is None:
+ self.assertLess(time.monotonic() - began, 60, err_path.read_bytes())
+ time.sleep(.05)
+ if tokentv.poll() is None:
+ break
+ self.assertIn(b'is in use', err_path.read_bytes()) # anything else is a real failure
+ self.assertIsNone(tokentv.poll(), err_path.read_bytes())
+ self.assertTrue((state / 'live.url').exists())
+ self.assertTrue((state / 'live.sock').exists())
+ status, answer, _ = raw(port, b'GET /moment HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n', timeout=15)
+ self.assertEqual(status, 405) # TokenTV, listening
+ self.assertIn(b'allow: post', answer.lower())
+ tokentv.send_signal(signal.SIGTERM)
+ tokentv.wait(timeout=60)
+ err = err_path.read_bytes()
+ self.assertEqual(tokentv.returncode, 0, err)
+ self.assertNotIn(b'Traceback', err)
+ self.assertFalse((state / 'live.url').exists())
+ self.assertFalse((state / 'live.sock').exists())
+
+
+class FrozenTime:
+ """The time module as the drawings see it: one fixed instant, so the same picture is the same bytes."""
+ def __init__(self, at):
+ self.at = at
+
+ def time(self):
+ return self.at
+
+ def __getattr__(self, name):
+ return getattr(time, name)
+
+
+class SyntheticTime:
+ """The time module with its wall clock (and, for the store, its monotonic one) moving with a FakeClock, from
+ `wall` when the clock read `start`: readings, the store's pace of fetching and the break's hour on the test's
+ clock."""
+ def __init__(self, clock, wall, monotonic=False):
+ self.clock, self.wall, self.start, self.fake_monotonic = clock, wall, clock.now(), monotonic
+
+ def time(self):
+ return self.wall + (self.clock.now() - self.start)
+
+ def monotonic(self):
+ return self.clock.now() if self.fake_monotonic else time.monotonic()
+
+ def __getattr__(self, name):
+ return getattr(time, name)
+
+
+class Rig:
+ """TokenTV itself (live.main) on a fake clock (moments.CLOCK) driving a fake SD_PRO, with fixed readings and
+ pictures drawn at one fixed instant. Uploads and toggles are logged at the fake time they reach the clock.
+
+ With `wall`, the wall clock moves with the fake one (TokenTV's, the store's and the readings' alike; the drawings
+ keep their fixed instant) and the readings are the test's to change: `windows` {provider: [(label, used %,
+ seconds to its reset)]}, then set() and write(). The first reading is taken as TokenTV starts (`t0`), the next
+ every `poll` seconds. `delay`: every send takes that long on the clock; `late`: the first one only (its picture,
+ and so its loop, goes on that much later); `switch_off`: turning a slot off takes that long (the animation holds
+ meanwhile, as for every request)."""
+ def __init__(self, test, providers=('claude',), state_dir=None, poll_seconds=None, frame_ms=None, wall=False,
+ windows=None, model='sdpro', delay=0, at=None, late=0, switch_off=0):
+ self.test = test
+ self.dir = temp_dir(test)
+ own_tmp(test) # the clock locks
+ self.clock = FakeClock()
+ self.model = model # the fake clock: an SD_PRO (its album's toggles), or an Ultra (one file, uploaded over)
+ self.frozen = FrozenTime(float(int(time.time() if at is None else at))) # (whole seconds, as the readings)
+ self.wall = SyntheticTime(self.clock, self.frozen.at) if wall else None
+ timed = ((mock.patch.object(module, 'time', self.wall) for module in (live, moments, sources))
+ if wall else (mock.patch.object(live, 'time', self.frozen),))
+ for patcher in (mock.patch.object(moments, 'CLOCK', self.clock),
+ *(mock.patch.object(module, 'time', self.frozen) for module in (arcade, readout, display)),
+ *timed,
+ *((mock.patch.object(state, 'time', SyntheticTime(self.clock, self.frozen.at, True)),) if wall else ()),
+ mock.patch.object(live.Lockbox, 'pick', return_value=None), # no hidden one-offs meanwhile
+ mock.patch.object(arcade, 'BOW_STYLE', 'low')): # one bow, so picture() draws the one sent
+ patcher.start()
+ test.addCleanup(patcher.stop)
+ self.calls, self.log = [], []
+ if model == 'ultra':
+ self.album = {'theme': 3, 'autoplay': 0, 'i_i': 0, 'parts': [], 'files': {}}
+ fake = ultra_clock(self.album, self.calls)
+ else:
+ self.album = {'files': {}, 'enabled': set(), 'total': 3_000_000, 'base': 0}
+ fake = sd_pro_clock(self.album, self.calls)
+ clock, log, state_of = self.clock, self.log, self.album
+
+ played = self.played = [] # (when, the bytes) of each picture as it was turned on
+ first = [late] if late else []
+
+ class Timed(fake):
+ def do_GET(self):
+ log.append((clock.now(), 'GET', self.path))
+ if switch_off and self.path.startswith('/photo/toggle') and self.path.endswith('state=0'):
+ clock.bump(switch_off) # (taken before the answer goes back)
+ super().do_GET()
+ if self.path.startswith('/photo/toggle') and self.path.endswith('state=1'):
+ name = parse_qs(urlparse(self.path).query)['name'][0]
+ if name.startswith('tokentv'):
+ played.append((clock.now(), state_of['files'].get(name)))
+
+ def do_POST(self):
+ log.append((clock.now(), 'POST', self.path))
+ took = delay + (first.pop() if first else 0)
+ if took: # a send that takes this long on the clock (the animation holds meanwhile)
+ clock.bump(took)
+ super().do_POST()
+ self.delay = delay
+ self.device = serve(Timed)
+ self.url = self.device.__enter__()
+ test.addCleanup(self.device.__exit__, None, None, None)
+ self.readings, accounts = {}, []
+ now = self.wall.time() if wall else time.time()
+ for k, provider in enumerate(providers):
+ key, alias = f'{provider}_a', provider.upper()
+ shown = (windows or {}).get(provider) or [('WEEK', 30 + 10 * k, 3 * 86400)]
+ self.readings[key] = {'alias': alias, 'provider': provider, 'status': 'ok', 'fetched_at': now,
+ 'windows': [{'label': label, 'used_percent': used, 'resets_at': now + left}
+ for label, used, left in shown]}
+ accounts.append({'key': key, 'alias': alias, 'provider': provider, 'email': f'{provider}@example.com',
+ 'snapshot_file': str(self.dir / 'readings.json')})
+ self.write(now)
+ self.config = {'accounts': accounts, 'device_url': self.url, 'display_style': 'arcade', 'update_check': False}
+ self.poll = poll_seconds or 60
+ if poll_seconds:
+ self.config['poll_seconds'] = poll_seconds
+ self.frame = FRAME_SD if frame_ms is None else frame_ms / 1000 # the fake SD_PRO's pace, set in the config too
+ if frame_ms is not None:
+ self.config['device_frame_ms'] = frame_ms
+ (self.dir / 'config.json').write_text(json.dumps(self.config), encoding='utf-8')
+ self.state = state_dir or self.dir / 'state'
+ self.start()
+
+ def start(self):
+ with socket.socket() as probe:
+ probe.bind(('127.0.0.1', 0))
+ self.port = probe.getsockname()[1]
+ ready = threading.Event()
+ box = {}
+ argv = ['--config', str(self.dir / 'config.json'), '--state-dir', str(self.state), '--port', str(self.port)]
+ self.thread = threading.Thread(target=live.main, args=(argv, lambda server: (box.update(server=server), ready.set())),
+ daemon=True)
+ self.t0 = self.clock.now() # TokenTV's first reading is taken as it starts
+ self.thread.start()
+ self.test.assertTrue(ready.wait(10))
+ self.server = box['server']
+ self.test.addCleanup(self.stop)
+ self.clock.settle()
+
+ def stop(self):
+ if self.thread.is_alive():
+ self.server.shutdown()
+ self.thread.join(5)
+
+ def now(self):
+ """The wall clock as TokenTV, the store and the readings see it."""
+ return self.wall.time() if self.wall else time.time()
+
+ def set(self, key, label, used):
+ """Change one window's used % in the readings (write() puts them where TokenTV reads them)."""
+ for window in self.readings[key]['windows']:
+ if window['label'] == label:
+ window['used_percent'] = used
+
+ def write(self, at=None):
+ """The readings as measured at `at` (default: now), where TokenTV reads them at its next poll."""
+ for row in self.readings.values():
+ row['fetched_at'] = self.now() if at is None else at
+ (self.dir / 'readings.json').write_text(json.dumps({'accounts': self.readings}), encoding='utf-8')
+
+ def poll_at(self, n):
+ """When TokenTV takes its `n`-th reading after the first (taken as it started, at t0)."""
+ return self.t0 + n * self.poll
+
+ def say(self, name):
+ conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=5)
+ conn.request('POST', '/moment', json.dumps({'moment': name}), {'Content-Type': 'application/json'})
+ status = conn.getresponse().status
+ self.test.assertEqual(status, 204)
+ self.clock.settle()
+
+ def uploads(self, since=None):
+ sent = '/doUpload?dir=/image/' if self.model == 'ultra' else '/photo/upload'
+ return [t for t, method, path in self.log if method == 'POST' and path == sent and (since is None or t >= since)]
+
+ def switches(self, since=None):
+ """When a picture was turned on (an activation), each of them since `since`."""
+ return [t for t, method, path in self.log if path.startswith('/photo/toggle') and path.endswith('state=1')
+ and (since is None or t >= since)]
+
+ def requests(self, since):
+ return [(t, method, path) for t, method, path in self.log if t >= since]
+
+ def showing(self):
+ """(the bytes the clock shows, when that picture went on: the time of the toggle that turned it on; on an
+ Ultra, its one file as last sent, and when that send ended)."""
+ if self.model == 'ultra':
+ return self.album['files']['tokentv.gif'], self.uploads()[-1] + self.delay
+ on = [name for name in self.album['enabled'] if name.startswith('tokentv')]
+ self.test.assertEqual(len(on), 1)
+ started = max(t for t, method, path in self.log if path.startswith('/photo/toggle') and f'name={on[0]}' in path
+ and path.endswith('state=1'))
+ return self.album['files'][on[0]], started
+
+ def loop(self, image):
+ """How long this fake clock plays one loop of `image`: an SD_PRO each picture for its delay but at least
+ `frame`; an Ultra as long as the delays say."""
+ return gif_seconds(image) if self.model == 'ultra' else physical(image, self.frame)
+
+ def end_of_loop(self, at=None):
+ """When the loop the clock plays at `at` (default: now) ends, from its picture's own start and frames."""
+ image, started = self.showing()
+ return loop_end({'at': started, 'loop': self.loop(image)}, self.clock.now() if at is None else at)
+
+ def picture(self, what=None, level=None, egg=None, reading=True, snapshot=None):
+ """The picture TokenTV should send for `what` (or the one-off `egg`), drawn here independently from the same
+ readings (or, with `reading` False, from none yet: every account still loading), or from `snapshot` (the
+ readings as TokenTV holds them, held(): who is at work comes from their history)."""
+ if snapshot is None:
+ store = UsageStore(self.config['accounts'], min_fetch_seconds=MIN_FETCH_SECONDS)
+ if reading:
+ store.refresh()
+ snapshot = store.snapshot()
+ mark = None if what is None else ({'kind': 'needs', 'since': 0, 'level': what[1]} if what[0] == 'needs'
+ else {'kind': 'done', 'at': 0} if what[0] == 'done' else {'kind': what[1]})
+ return render_page(overlay(snapshot, what, mark), 0, 'arcade', egg=egg)
+
+ def held(self):
+ """The readings as TokenTV holds them now: its dashboard's /snapshot."""
+ conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=5)
+ conn.request('GET', '/snapshot')
+ return json.loads(conn.getresponse().read())
+
+
+class ClockTimingTests(unittest.TestCase):
+ """When each moment reaches the clock: at the end of the loop it is playing, one upload per change, none for
+ the same again; a wait grows more insistent and is let go on time with nothing else happening."""
+ def assertAt(self, rig, when, what, since):
+ """One more upload at the loop's end `when` (within 250 ms), and the clock shows `what` since then."""
+ image, started = rig.showing()
+ self.assertEqual(image, rig.picture(what))
+ self.assertGreaterEqual(started, when - 1e-6) # (TokenTV sums the loop its own way, to the last bit)
+ self.assertLess(started, when + .25)
+ self.assertLessEqual(len(rig.uploads(since)), 1) # a picture the clock still holds needs only switching on
+ return started, physical(image)
+
+ def test_a_wait_comes_at_the_loops_end_then_hops_holds_a_sign_and_is_let_go(self):
+ rig = Rig(self)
+ normal, start = rig.showing()
+ self.assertEqual(normal, rig.picture())
+ loop = physical(normal)
+ rig.clock.advance(loop / 4)
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ rig.clock.to(start + loop - .001)
+ self.assertEqual(rig.requests(asked), []) # nothing interrupts the loop that is playing
+ rig.clock.to(start + loop + .3)
+ start, loop = self.assertAt(rig, start + loop, ('needs', 1), asked)
+ mark = rig.clock.now()
+ rig.say('claude.ask') # another session waits too: the same picture, nothing sent
+ rig.clock.to(asked + 299.999) # through the minute's reading of the usage: still nothing sent
+ self.assertEqual(rig.requests(mark), [])
+ for threshold, level in ((300, 2), (900, 3)):
+ due = loop_end({'at': start, 'loop': loop}, asked + threshold)
+ rig.clock.to(due + .3)
+ start, loop = self.assertAt(rig, due, ('needs', level), asked + threshold - 1)
+ rig.clock.advance(3 * loop)
+ self.assertEqual(rig.uploads(start + .01), []) # the same state loops on with no request
+ rig.say('claude.answered') # one of the two answered: still waiting
+ rig.clock.to(asked + 1799.999)
+ self.assertEqual(rig.showing()[0], rig.picture(('needs', 3)))
+ due = loop_end({'at': start, 'loop': loop}, asked + 1800)
+ rig.clock.to(due + .3)
+ self.assertAt(rig, due, None, asked + 1799) # thirty minutes after the wait began, the other's with it, no bow
+ self.assertLessEqual(len(rig.uploads(asked)), 4) # hand, hops, sign, the usual face: no more
+ rig.clock.advance(120)
+ image, _ = rig.showing()
+ self.assertEqual(image, rig.picture())
+
+ def test_an_answer_clears_the_wait_and_its_old_deadlines_do_nothing_later(self):
+ rig = Rig(self)
+ _, start = rig.showing()
+ rig.clock.advance(1)
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ rig.clock.advance(320) # through the hop
+ _, start = rig.showing()
+ rig.say('claude.answered')
+ answered = rig.clock.now()
+ loop = physical(rig.showing()[0])
+ due = loop_end({'at': start, 'loop': loop}, answered)
+ rig.clock.to(due + .3)
+ start, loop = self.assertAt(rig, due, None, answered)
+ rig.clock.to(asked + 1900) # past the old sign and let-go times
+ self.assertEqual(rig.uploads(start + .01), [])
+
+ def test_a_turns_end_bows_for_one_loop_and_bows_at_most_once_a_minute(self):
+ rig = Rig(self)
+ _, start = rig.showing()
+ loop = physical(rig.showing()[0])
+ rig.clock.advance(loop / 2)
+ ended = rig.clock.now()
+ rig.say('claude.end')
+ rig.clock.to(start + loop + .3)
+ bowed, bow_loop = self.assertAt(rig, start + loop, ('done', 'claude'), ended)
+ rig.clock.advance(1)
+ rig.say('claude.end') # inside the minute: dropped
+ rig.clock.to(bowed + bow_loop + .3)
+ image, back = rig.showing()
+ self.assertEqual(image, rig.picture()) # one loop of the bow, then the usual face, no second bow
+ self.assertGreaterEqual(back, bowed + bow_loop)
+ self.assertLess(back, bowed + bow_loop + .25)
+ self.assertLessEqual(len(rig.uploads(ended)), 2)
+ rig.say('codex.end') # no Codex here: nothing, and no minute used up
+ rig.clock.to(bowed + 59.9)
+ rig.say('claude.end')
+ rig.clock.advance(10)
+ self.assertEqual(rig.showing()[0], rig.picture())
+ rig.clock.to(bowed + 60.5)
+ rig.say('claude.end') # a fresh one after the minute bows again, at the next loop's end
+ rig.clock.to(rig.end_of_loop() + .1)
+ self.assertEqual(rig.showing()[0], rig.picture(('done', 'claude')))
+
+ def test_codex_bows_as_itself(self):
+ rig = Rig(self, providers=('claude', 'codex'))
+ _, start = rig.showing()
+ loop = physical(rig.showing()[0])
+ rig.clock.advance(1)
+ ended = rig.clock.now()
+ rig.say('codex.end')
+ rig.clock.to(start + loop + .3)
+ bowed, bow_loop = self.assertAt(rig, start + loop, ('done', 'codex'), ended)
+ self.assertNotEqual(rig.picture(('done', 'codex')), rig.picture(('done', 'claude')))
+ rig.clock.to(bowed + bow_loop + .3)
+ self.assertEqual(rig.showing()[0], rig.picture())
+
+ def test_a_wait_that_comes_during_a_bow_follows_it_and_a_waits_bow_is_dropped(self):
+ rig = Rig(self, providers=('claude', 'codex'))
+ _, start = rig.showing()
+ loop = physical(rig.showing()[0])
+ rig.say('codex.end')
+ rig.clock.to(start + loop + .3)
+ bowed, bow_loop = rig.showing()[1], physical(rig.showing()[0])
+ rig.clock.advance(bow_loop / 2)
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ rig.clock.to(bowed + bow_loop + .3)
+ self.assertAt(rig, bowed + bow_loop, ('needs', 1), asked) # at the bow's end, not before
+ rig.clock.advance(70)
+ rig.say('claude.end') # another session's turn ends while this one waits
+ rig.say('codex.end')
+ rig.clock.advance(20)
+ self.assertEqual(rig.showing()[0], rig.picture(('needs', 1)))
+ mark = rig.clock.now()
+ rig.say('claude.answered')
+ rig.clock.advance(20)
+ self.assertEqual(rig.showing()[0], rig.picture()) # no stale bow afterwards
+ self.assertLessEqual(len(rig.uploads(mark)), 1)
+
+ def test_states_superseded_before_the_loop_ends_never_show(self):
+ rig = Rig(self)
+ rig.clock.advance(.5)
+ mark = rig.clock.now()
+ rig.say('claude.ask')
+ rig.say('claude.answered')
+ rig.clock.to(rig.end_of_loop() + rig.end_of_loop() - mark) # two loop ends later
+ self.assertEqual(rig.requests(mark), []) # asked and answered within one loop: nothing at all
+ rig.clock.advance(.5)
+ mark = rig.clock.now()
+ due = rig.end_of_loop()
+ for _ in range(3):
+ rig.say('claude.ask')
+ rig.say('claude.answered')
+ rig.say('claude.ask')
+ rig.clock.to(due + .3)
+ self.assertAt(rig, due, ('needs', 1), mark) # only the last state, once, at that loop's end
+ rig.clock.advance(.5)
+ mark = rig.clock.now()
+ due = rig.end_of_loop()
+ rig.say('claude.answered')
+ rig.say('claude.end') # the turn's end right after its answer: the bow, with no flash of the hand
+ rig.clock.to(due + .3)
+ self.assertAt(rig, due, ('done', 'claude'), mark)
+
+ def test_a_change_due_while_a_new_reading_waits_for_the_loops_end_is_drawn_in(self):
+ rig = Rig(self, providers=('claude', 'codex'))
+ rig.clock.advance(1)
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ rig.clock.to(asked + 290)
+ readings = json.loads((rig.dir / 'readings.json').read_text(encoding='utf-8'))
+ readings['accounts']['codex_a']['windows'][0]['used_percent'] = 35 # Codex's reading changes (down: no work)
+ readings['accounts']['codex_a']['fetched_at'] = time.time()
+ (rig.dir / 'readings.json').write_text(json.dumps(readings), encoding='utf-8')
+ rig.clock.to(asked + 300) # the minute's poll took the new reading and waits for the loop's end: hop now due
+ due = rig.end_of_loop(asked + 300)
+ rig.clock.to(due + .3)
+ image, started = rig.showing()
+ self.assertEqual(image, rig.picture(('needs', 2))) # the hop, with the new reading, at that loop's end
+ self.assertLess(started, due + .25)
+ # one upload for the hop with the new reading; one more only if a loop ended between the poll and the hop
+ self.assertLessEqual(len(rig.uploads(asked + 290)), 2)
+
+ def test_a_slow_reading_holds_no_moment_back_and_is_drawn_once_it_is_in(self):
+ gate, slow, began, tokentvs = threading.Event(), threading.Event(), [], []
+ self.addCleanup(gate.set)
+ read = live.UsageStore.refresh
+
+ def refresh(store): # TokenTV's providers answer only when the test says so (the test's own at once)
+ tokentvs[:] = tokentvs or [store] # the first store to read is TokenTV's, as it starts
+ if slow.is_set() and store is tokentvs[0]:
+ began.append(moments.CLOCK.now())
+ moments.CLOCK.held.add(threading.current_thread())
+ gate.wait(30)
+ return read(store)
+ patcher = mock.patch.object(live.UsageStore, 'refresh', refresh)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, providers=('claude', 'codex'))
+ slow.set()
+ rig.clock.advance(61) # the minute's reading has begun, and does not come
+ self.assertEqual(len(began), 1)
+ rig.clock.advance(1)
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ due = rig.end_of_loop()
+ rig.clock.to(due + .3)
+ start, loop = self.assertAt(rig, due, ('needs', 1), asked) # on time, with the last reading
+ due = loop_end({'at': start, 'loop': loop}, asked + 300)
+ rig.clock.to(due + .3)
+ start, loop = self.assertAt(rig, due, ('needs', 2), asked + 299) # the hop on time too
+ answered = rig.clock.now()
+ rig.say('claude.answered')
+ due = rig.end_of_loop()
+ rig.clock.to(due + .3)
+ self.assertAt(rig, due, None, answered)
+ self.assertEqual(len(began), 1) # no second reading piled up behind the first
+ readings = json.loads((rig.dir / 'readings.json').read_text(encoding='utf-8'))
+ readings['accounts']['codex_a']['windows'][0]['used_percent'] = 25 # a flower less (down: no work)
+ readings['accounts']['codex_a']['fetched_at'] = time.time()
+ (rig.dir / 'readings.json').write_text(json.dumps(readings), encoding='utf-8')
+ before = rig.showing()[0]
+ gate.set() # the reading comes in at last
+ for thread in threading.enumerate():
+ if thread.name == 'TokenTV reading':
+ thread.join(5)
+ rig.clock.settle()
+ rig.clock.to(rig.end_of_loop() + .3)
+ image, _ = rig.showing()
+ self.assertNotEqual(image, before)
+ self.assertEqual(image, rig.picture()) # drawn once it is in, at the loop's end
+
+ def test_a_reading_that_never_comes_from_the_start_holds_back_no_moment_nor_its_escalation(self):
+ gate, began, tokentvs = threading.Event(), [], []
+ self.addCleanup(gate.set)
+ read = live.UsageStore.refresh
+
+ def refresh(store): # TokenTV's providers do not answer, from its very first reading (the test's own do)
+ tokentvs[:] = tokentvs or [store]
+ if store is tokentvs[0]:
+ began.append(moments.CLOCK.now())
+ moments.CLOCK.held.add(threading.current_thread())
+ gate.wait(60)
+ return read(store)
+ patcher = mock.patch.object(live.UsageStore, 'refresh', refresh)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self)
+ rig.clock.advance(10)
+ self.assertEqual(rig.uploads(), []) # no reading yet, nothing to show yet: the clock keeps what it had
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ image, start = rig.showing() # no loop of TokenTV's playing to wait for: at once, drawn from what it has
+ self.assertEqual(image, rig.picture(('needs', 1), reading=False))
+ self.assertLess(start - asked, .25)
+ loop = physical(image)
+ for threshold, level in ((300, 2), (900, 3)):
+ due = loop_end({'at': start, 'loop': loop}, asked + threshold)
+ rig.clock.to(due + .3)
+ image, start = rig.showing()
+ self.assertEqual(image, rig.picture(('needs', level), reading=False))
+ self.assertGreaterEqual(start, due) # at its loop's end, as ever
+ self.assertLess(start, due + .25)
+ loop = physical(image)
+ answered = rig.clock.now()
+ rig.say('claude.answered')
+ due = loop_end({'at': start, 'loop': loop}, answered)
+ rig.clock.to(due + .3)
+ image, start = rig.showing()
+ self.assertEqual(image, rig.picture(reading=False))
+ self.assertLess(start, due + .25)
+ self.assertEqual(len(began), 1) # one reading out, however many minutes passed: none piled up behind it
+ gate.set() # the reading comes in at last: drawn at the next loop's end
+ for thread in threading.enumerate():
+ if thread.name == 'TokenTV reading':
+ thread.join(5)
+ rig.clock.settle()
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.showing()[0], rig.picture())
+
+ def test_a_slow_reading_that_starts_as_a_hop_is_due_does_not_put_the_hop_off_a_loop(self):
+ # The re-grade's m-slip: readings every 63 s and an ask at 15 s put the hop's time (315 s) on a reading's
+ # tick and on a loop's end. The reading then takes long. Real time spent on the clock's path there (a wait
+ # for the reading, the 40 ms a hop takes to draw) is put on the fake clock, as it passes for the real one.
+ # (Clawd keeping still: its usual loop is 8 pictures held 420 and 630 ms, 4.2 s, so the raised hand goes on at
+ # 16.8 s; its 50 pictures take a 142 ms tick each, 7.1 s, and 42 of those loops end at 315 s.)
+ patcher = mock.patch.object(arcade, 'rest_step', lambda provider, now: (None, None))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ gate, tokentvs = threading.Event(), []
+ self.addCleanup(gate.set)
+ read = live.UsageStore.refresh
+ window = {}
+
+ def refresh(store):
+ tokentvs[:] = tokentvs or [store]
+ if store is tokentvs[0] and window.get('from', float('inf')) <= moments.CLOCK.now():
+ moments.CLOCK.held.add(threading.current_thread())
+ gate.wait(30)
+ return read(store)
+
+ def scheduling():
+ name = threading.current_thread().name
+ return '(poll)' in name and window.get('from', float('inf')) <= moments.CLOCK.now() <= window['to']
+ wait, draw = live.Wake.wait, live.render_page
+
+ def timed_wait(self, timeout=None):
+ began = time.monotonic()
+ got = wait(self, timeout)
+ if timeout is not None and scheduling():
+ moments.CLOCK.bump(min(time.monotonic() - began, timeout))
+ return got
+
+ def timed_draw(*args, **kwargs):
+ image = draw(*args, **kwargs)
+ if scheduling():
+ moments.CLOCK.bump(.04)
+ return image
+ for patcher in (mock.patch.object(live.UsageStore, 'refresh', refresh), mock.patch.object(live.Wake, 'wait', timed_wait),
+ mock.patch.object(live, 'render_page', timed_draw)):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig = Rig(self, poll_seconds=63)
+ _, first = rig.showing()
+ rig.clock.to(first + 15)
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ due = loop_end({'at': first, 'loop': physical(rig.showing()[0], rig.frame)}, asked)
+ rig.clock.to(due + .3)
+ _, start = rig.showing()
+ hop = loop_end({'at': start, 'loop': physical(rig.showing()[0], rig.frame)}, asked + 300)
+ self.assertAlmostEqual(hop - first, 5 * 63, places=6) # the hop's loop end is a reading's tick
+ window.update({'from': hop - 1, 'to': hop + 1})
+ rig.clock.to(hop + 10)
+ image, started = rig.showing()
+ self.assertEqual(image, rig.picture(('needs', 2)))
+ self.assertGreaterEqual(started, hop - 1e-6) # (16.8 and 7.1 s are no exact binary numbers)
+ self.assertLess(started, hop + .25) # on time, not a loop later
+
+ def test_a_moment_that_comes_during_a_one_off_goes_as_it_ends_in_its_quiet_loops_place(self):
+ from PIL import Image
+ from token_tv.lockbox import Box
+ stage = lambda colour: Image.new('RGB', (120, 71), colour) # noqa: E731
+ boxes = [Box('Test', 'unique', 'claude_a', tuple(stage((200, 40, 40)) for _ in range(4)), 40,
+ after=(stage((40, 40, 200)),))]
+ patcher = mock.patch.object(live.Lockbox, 'pick', side_effect=lambda snap: boxes.pop() if boxes else None)
+ rig = Rig(self)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ box = boxes[0]
+ rig.clock.advance(60) # the minute's reading opens the box: its event goes as the loop playing then ends
+ self.assertEqual(boxes, [])
+ rig.clock.to(rig.end_of_loop() + .001)
+ event, opened = rig.showing()
+ self.assertEqual(event, rig.picture(egg=box)) # and plays its loop, its quiet loop waiting for the end
+ rig.clock.advance(physical(event) / 2) # (a loop of a few pictures: as long as they take on the clock)
+ asked = rig.clock.now()
+ rig.say('claude.ask') # while the one-off plays
+ due = rig.end_of_loop()
+ rig.clock.to(due + .3)
+ self.assertAlmostEqual(due, opened + physical(event))
+ self.assertAt(rig, due, ('needs', 1), asked) # as the one-off ends, in its quiet loop's place
+ rig.clock.advance(60)
+ self.assertEqual(rig.showing()[0], rig.picture(('needs', 1)))
+ self.assertEqual(len(rig.uploads(opened + .001)), 1) # nothing else went to the clock after the event
+
+ def test_a_moment_that_comes_and_goes_during_a_one_off_leaves_its_quiet_loop_in_place(self):
+ import dataclasses
+ from PIL import Image
+ from token_tv.lockbox import Box
+ stage = lambda colour: Image.new('RGB', (120, 71), colour) # noqa: E731
+ box = Box('Test', 'unique', 'claude_a', tuple(stage((200, 40, 40)) for _ in range(4)), 40,
+ after=(stage((40, 40, 200)),))
+ boxes = [box]
+ patcher = mock.patch.object(live.Lockbox, 'pick', side_effect=lambda snap: boxes.pop() if boxes else None)
+ rig = Rig(self)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig.clock.advance(60)
+ rig.clock.to(rig.end_of_loop() + .001)
+ event, opened = rig.showing()
+ rig.clock.advance(physical(event) / 4)
+ rig.say('claude.ask')
+ rig.clock.advance(physical(event) / 4)
+ rig.say('claude.answered') # answered (the row drawn running) well before the event's end
+ rig.clock.to(opened + physical(event) + .3)
+ quiet, started = rig.showing()
+ self.assertEqual(quiet, rig.picture(egg=dataclasses.replace(box, frames=box.after, after=(), intro=False)))
+ self.assertAlmostEqual(started, opened + physical(event)) # its quiet loop, as if nothing had come
+
+ def test_a_one_off_plays_its_event_loop_whole_however_fast_its_quiet_loop_is_drawn(self):
+ import dataclasses
+ from PIL import Image
+ from token_tv.lockbox import Box
+ stage = lambda colour: Image.new('RGB', (120, 71), colour) # noqa: E731
+ box = Box('Test', 'unique', 'claude_a', tuple(stage((200, 40, 40)) for _ in range(4)), 40,
+ after=(stage((40, 40, 200)),))
+ boxes = [box]
+ patcher = mock.patch.object(live.Lockbox, 'pick', side_effect=lambda snap: boxes.pop() if boxes else None)
+ rig = Rig(self)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig.clock.advance(60) # (drawing takes no time on the fake clock: the quiet loop is ready at once)
+ rig.clock.to(rig.end_of_loop() + .001)
+ event, opened = rig.showing()
+ self.assertEqual(event, rig.picture(egg=box))
+ rig.clock.to(opened + physical(event) + .3)
+ quiet, started = rig.showing()
+ self.assertEqual(quiet, rig.picture(egg=dataclasses.replace(box, frames=box.after, after=(), intro=False)))
+ self.assertAlmostEqual(started, opened + physical(event)) # as the event's loop ended, not before
+
+ def one_off(self, seconds=40):
+ """A rig whose minute's reading, half a loop into the usual face's loop, opens a box (the event, then its
+ quiet loop for the rest of `seconds`)."""
+ from PIL import Image
+ from token_tv.lockbox import Box
+ at = float(int(time.time()))
+ learn = Rig(self, at=at)
+ loop = physical(learn.showing()[0])
+ learn.stop()
+ stage = lambda colour: Image.new('RGB', (120, 71), colour) # noqa: E731
+ box = Box('Test', 'unique', 'claude_a', tuple(stage((200, 40, 40)) for _ in range(4)), seconds,
+ after=(stage((40, 40, 200)),))
+ boxes = [box]
+ patcher = mock.patch.object(live.Lockbox, 'pick', side_effect=lambda snap: boxes.pop() if boxes else None)
+ rig = Rig(self, at=at, late=(60 - loop / 2) % loop)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ return rig, box, boxes
+
+ def test_a_one_offs_event_waits_for_the_end_of_the_loop_playing_as_it_came(self):
+ rig, box, boxes = self.one_off()
+ normal, start = rig.showing()
+ loop = physical(normal)
+ read = rig.poll_at(1)
+ due = loop_end({'at': start, 'loop': loop}, read)
+ self.assertGreater(due - read, .2) # (it comes well inside a loop)
+ rig.clock.to(due - .001)
+ self.assertEqual(boxes, []) # opened by the reading,
+ self.assertEqual(rig.switches(read), []) # and the loop that was playing not cut
+ rig.clock.to(due + .3)
+ event, opened = rig.showing()
+ self.assertEqual(event, rig.picture(egg=box))
+ self.assertGreaterEqual(opened, due - 1e-6)
+ self.assertLess(opened, due + .25)
+ self.assertEqual(len(rig.uploads(read)), 1)
+
+ def full_reading(self):
+ """A rig of one Codex account at 90 %, whose minute's reading, half a loop into the usual face's loop, says
+ 100 % (a 'full' one-off); and what each picture TokenTV draws from then on was drawn with ({bytes: egg})."""
+ at, window = float(int(time.time())), {'codex': [('5H', 90, 4 * 3600)]}
+ learn = Rig(self, providers=('codex',), wall=True, windows=window, at=at)
+ loop = physical(learn.showing()[0])
+ learn.stop()
+ rig = Rig(self, providers=('codex',), wall=True, windows=window, at=at, late=(60 - loop / 2) % loop)
+ drawn, draw = {}, live.render_page
+
+ def spy(snapshot, page=0, style='pixel', egg=None):
+ image = draw(snapshot, page, style, egg=egg)
+ drawn[image] = egg
+ return image
+ patcher = mock.patch.object(live, 'render_page', spy)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ rig.clock.to(rig.poll_at(1) - 1)
+ rig.set('codex_a', '5H', 100)
+ rig.write()
+ return rig, drawn
+
+ def test_a_reading_that_brings_a_one_off_sends_the_one_off_alone(self):
+ rig, drawn = self.full_reading()
+ normal, start = rig.showing()
+ read = rig.poll_at(1)
+ due = loop_end({'at': start, 'loop': physical(normal)}, read)
+ rig.clock.to(due - .001)
+ self.assertEqual(rig.requests(read), []) # nothing cuts the loop that was playing
+ rig.clock.to(due + .001)
+ event, opened = rig.showing()
+ self.assertEqual(drawn.get(event), 'full@codex_a') # the one-off, with no picture of the reading before it
+ self.assertEqual(len(rig.uploads(read)), 1)
+ self.assertGreaterEqual(opened, due - 1e-6)
+ rig.clock.to(opened + physical(event) + .3)
+ back, returned = rig.showing()
+ self.assertEqual(back, rig.picture(snapshot=rig.held())) # then the usual face, at 100 %, as its loop ends
+ self.assertAlmostEqual(returned, opened + physical(event))
+ self.assertEqual(len(rig.uploads(read)), 2)
+
+ def test_a_moment_that_comes_while_an_event_waits_to_go_on_goes_first_and_the_event_after_it(self):
+ rig, drawn = self.full_reading()
+ normal, start = rig.showing()
+ read = rig.poll_at(1)
+ due = loop_end({'at': start, 'loop': physical(normal)}, read)
+ rig.clock.to(read + .01)
+ rig.say('codex.end') # Codex's turn ends while the event waits for the loop's end: its bow first
+ rig.clock.to(due + .3)
+ bow, began = rig.showing()
+ self.assertEqual(bow, rig.picture(('done', 'codex'), snapshot=rig.held()))
+ self.assertGreaterEqual(began, due - 1e-6)
+ self.assertLess(began, due + .25)
+ rig.clock.to(began + physical(bow) + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(snapshot=rig.held())) # one loop of it, the usual face
+ self.assertNotIn('full@codex_a', [drawn.get(image) for _, image in rig.played])
+ nxt = rig.poll_at(2) # the next reading: no moment now, so the event's turn
+ rig.clock.to(rig.end_of_loop(nxt) + .3)
+ event, opened = rig.showing()
+ self.assertEqual(drawn.get(event), 'full@codex_a')
+ self.assertGreaterEqual(opened, nxt - 1e-6)
+ self.assertEqual([drawn.get(image) for _, image in rig.played].count('full@codex_a'), 1)
+
+ def test_a_moment_that_comes_while_a_one_off_waits_to_go_on_goes_instead(self):
+ rig, box, boxes = self.one_off()
+ normal, start = rig.showing()
+ read = rig.poll_at(1)
+ due = loop_end({'at': start, 'loop': physical(normal)}, read)
+ rig.clock.to(read + .01)
+ self.assertEqual((boxes, rig.switches(read)), ([], [])) # the box is waiting for the loop's end
+ rig.say('claude.end') # a turn's end, before it went on: the bow goes, the one-off does not start
+ rig.clock.to(due + .3)
+ self.assertAt(rig, due, ('done', 'claude'), read)
+ rig.clock.advance(120) # its loop, the usual face, two more readings: the one-off is not seen
+ self.assertEqual(rig.showing()[0], rig.picture())
+ self.assertNotIn(rig.picture(egg=box), [image for _, image in rig.played])
+
+ @unittest.skipIf(os.name == 'nt', 'no socket on Windows')
+ def test_tokentv_says_so_when_it_cannot_open_its_socket(self):
+ said = io.StringIO()
+ with mock.patch('sys.stdout', said):
+ rig = Rig(self, state_dir=Path(temp_dir(self)) / ('x' * 120) / 'state')
+ rig.say('claude.ask') # over the port still, for this test
+ self.assertIn("could not open its socket for Claude Code's and Codex's moments", said.getvalue())
+ self.assertFalse((rig.state / 'live.sock').exists())
+
+ def test_a_restart_forgets_the_moments(self):
+ rig = Rig(self)
+ rig.say('claude.ask')
+ rig.clock.advance(10)
+ self.assertEqual(rig.showing()[0], rig.picture(('needs', 1)))
+ rig.stop()
+ self.assertFalse((rig.state / 'live.url').exists())
+ self.assertFalse((rig.state / 'live.sock').exists())
+ rig.start()
+ rig.clock.advance(30)
+ self.assertEqual(rig.showing()[0], rig.picture())
+ rig.say('claude.end')
+ rig.clock.to(rig.end_of_loop() + .1)
+ self.assertEqual(rig.showing()[0], rig.picture(('done', 'claude')))
+
+ def test_moments_write_nothing_to_disk(self):
+ rig = Rig(self)
+ def files():
+ # the running TokenTV's live.lock is unreadable on Windows while held: its time is enough
+ return {p.name: (p.stat().st_mtime_ns, b'' if p.name == 'live.lock' else p.read_bytes())
+ for p in rig.state.iterdir() if p.is_file()}
+ before = files()
+ rig.say('claude.ask')
+ rig.clock.advance(20)
+ rig.say('claude.answered')
+ rig.say('claude.end')
+ rig.clock.advance(20) # all inside the minute: no reading of the usage meanwhile
+ self.assertGreaterEqual(len(rig.uploads()), 3)
+ self.assertEqual(files(), before)
+ rig.say('claude.ask')
+ rig.clock.advance(60) # now with the minute's reading, as without any moment
+ for name, (_, data) in files().items():
+ for word in (b'claude.ask', b'claude.end', b'NEEDS', b'"moment"', b'"needs"'):
+ self.assertNotIn(word, data, name)
+ self.assertEqual(files()['tokentv.gif'][1], rig.picture()) # the picture with the wait in it was not kept
+
+ def test_preview_shows_the_moment_due(self):
+ rig = Rig(self)
+ rig.say('claude.ask')
+ conn = http.client.HTTPConnection('127.0.0.1', rig.port, timeout=5)
+ conn.request('GET', '/frame/0.jpg')
+ self.assertEqual(conn.getresponse().read(), rig.picture(('needs', 1)))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_pace_tick.py b/tests/test_pace_tick.py
new file mode 100644
index 0000000..2ad6671
--- /dev/null
+++ b/tests/test_pace_tick.py
@@ -0,0 +1,200 @@
+"""v2 phase 2, x4: on every weekly window's battery a small tick where even use over the week would have left the
+charge now; the battery shows what is left, so the tick stands at the share of the week still to come, and charge
+that falls short of it is overspend, the gap to it red (the owner's style A). 5-hour windows get none. Time passing
+alone sends no picture: the tick moves with the next picture sent for anything else."""
+import io
+import sys
+import time
+import unittest
+from pathlib import Path
+
+from PIL import Image, ImageDraw
+
+sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run
+from test_moments import Rig # noqa: E402
+
+from token_tv import arcade, readout # noqa: E402
+from token_tv.sample import D, H, snapshot # noqa: E402
+
+WEEK = 7 * D
+TICK_TOLERANCE = 1 # native pixels
+NOW = int(time.mktime((2026, 11, 1, 14, 1, 0, 0, 0, -1))) # Sunday 2:01 pm wherever the tests run (the stage dims at night)
+ONE = (10, 195, 158, 20) # the one-window battery: x, y, w, h
+TWO = (24, 196 + 21, 44, 16) # the weekly one of two (under the 5-hour one)
+
+
+def track(box):
+ """The battery's usable fill track: its first column and its width."""
+ x, y, w, h = box
+ return x + 4, w - 8
+
+
+def tick_columns(image, box):
+ """The columns the tick takes, read where only it reaches: the rows above the battery's case."""
+ x, y, w, h = box
+ return [c for c in range(x - 2, x + w + 4) if image.getpixel((c, y - 1)) == readout.TICK]
+
+
+def ticked(image, box, share):
+ """Whether the tick stands for `share` of the week gone, measured along the usable track (its middle)."""
+ columns = tick_columns(image, box)
+ if not columns:
+ return False
+ ix, iw = track(box)
+ middle = (min(columns) + max(columns) + 1) / 2 # a tick two pixels wide: between them
+ return abs(middle - (ix + iw * (1 - share))) <= TICK_TOLERANCE
+
+
+def readout_image(rows, paces):
+ image = Image.new('RGB', (240, 240), readout.PANEL)
+ readout.draw_battery(image, ImageDraw.Draw(image), 'claude', 'RUNNING', rows, NOW, paces)
+ return image
+
+
+class TickPlacementTests(unittest.TestCase):
+ def test_the_tick_stands_at_the_share_of_the_week_still_to_come(self):
+ for share in (0, .25, .5, .75, .999):
+ start = NOW - 777 # a week begun at no particular hour
+ resets = start + WEEK
+ at = start + share * WEEK
+ self.assertAlmostEqual(arcade.pace_share({'resets_at': resets}, at), share)
+ one = readout_image([('WK', 30, resets, False)], [arcade.pace_share({'resets_at': resets}, at)])
+ self.assertTrue(ticked(one, ONE, share), share)
+ two = readout_image([('5H', 30, NOW + H, False), ('WK', 30, resets, False)],
+ [None, arcade.pace_share({'resets_at': resets}, at)])
+ self.assertTrue(ticked(two, TWO, share), share)
+ self.assertEqual(tick_columns(two, (24, 196, 44, 16)), []) # the 5-hour battery: none
+ ix, iw = track(ONE)
+ for c in tick_columns(one, ONE):
+ self.assertTrue(ix - 1 <= c <= ix + iw, (share, c)) # within the track, at either end too
+
+ def test_under_and_over_pace_show_at_a_glance(self):
+ resets, at = NOW + WEEK / 2, NOW # half the week gone
+ share = arcade.pace_share({'resets_at': resets}, at)
+ ix, iw = track(ONE)
+ tick = ix + iw * (1 - share)
+ for used, behind in ((25, True), (75, False)):
+ image = readout_image([('WK', used, resets, False)], [share])
+ self.assertTrue(ticked(image, ONE, share))
+ row = [image.getpixel((c, 205)) for c in range(ix, ix + iw)]
+ lit = [ix + k for k, c in enumerate(row) if c == readout.band(used)]
+ red = [ix + k for k, c in enumerate(row) if c == readout.OVERSPEND]
+ if behind: # 75% left at half the week: charge past the tick, nothing red
+ self.assertGreater(max(lit), tick)
+ self.assertEqual(red, [])
+ else: # 25% left: the charge stops short, and the gap up to the tick is red
+ self.assertLess(max(lit), tick)
+ self.assertTrue(red and min(red) > max(lit) and max(red) < tick)
+ for used in (0, 100): # full and empty: the tick still there
+ self.assertTrue(ticked(readout_image([('WK', used, resets, False)], [share]), ONE, share))
+
+ def test_over_pace_the_red_meets_the_charge_with_no_dark_column_between(self):
+ import re
+ for x, y, w, h in (ONE, TWO):
+ cells = 10 if w > 100 else 5
+ ix, iw = track((x, y, w, h))
+ cw = (iw - 2 * (cells - 1)) / cells # (a cell's width: 2 px between cells)
+ for share in (.3, .5, .7):
+ for used in range(round(100 * share) + 1, 100): # over pace: less left than the week still to come
+ image = Image.new('RGB', (240, 240), readout.PANEL)
+ readout.battery(ImageDraw.Draw(image), x, y, w, h, used, cells, pace=share)
+ for k in range(cells): # each cell, along its middle: charge, then red, then the empty track
+ x0, x1 = round(ix + k * (cw + 2)), round(ix + k * (cw + 2) + cw) - 1
+ cell = ''.join('t' if colour == readout.TRACK else 'r' if colour == readout.OVERSPEND else 'o'
+ for colour in (image.getpixel((c, y + h // 2)) for c in range(x0, x1 + 1)))
+ self.assertIsNone(re.search('t.*r', cell), (w, share, used, k, cell)) # no dark seam
+
+ def test_every_weekly_battery_gets_one_by_its_length_and_short_ones_none(self):
+ cases = [
+ ({'label': 'WEEK', 'duration_minutes': 10080}, True),
+ ({'label': 'WEEK'}, True), # no length given: by its name
+ ({'label': 'WEEK2', 'duration_minutes': 10080}, True), # a second weekly window
+ ({'label': 'WINDOW', 'duration_minutes': 10080}, True), # a week under another name
+ ({'label': '5H', 'duration_minutes': 300}, False),
+ ({'label': '5H'}, False),
+ ({'label': 'BUDGET'}, False),
+ ({'label': 'MONTH'}, False),
+ ({'label': 'WEEK', 'duration_minutes': 300}, False), # its length says otherwise
+ ]
+ for window, weekly in cases:
+ self.assertEqual(arcade.weekly(window), weekly, window)
+
+ def test_arcade_puts_each_weekly_window_its_own_tick_from_its_own_reset(self):
+ accounts = [('claude_a', 'CLAUDE A', 'claude', [('5H', 40, 2 * H), ('WEEK', 50, 2 * D)]),
+ ('codex_b', 'CODEX B', 'codex', [('WEEK', 50, 5 * D)]),
+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 50, 5 * D)])]
+ data = snapshot(NOW, accounts)
+ for row in data['accounts'].values():
+ for window in row['windows']:
+ window['duration_minutes'] = {'5H': 300, 'WEEK': 10080}.get(window['label'])
+ data['pace_at'] = NOW
+ frames = arcade.arcade_frames(data, NOW)
+ shown = arcade.shown_rows(data, NOW)
+ turn = len(frames) // len(shown)
+ for k, row in enumerate(shown):
+ frame = frames[k * turn + 1]
+ weekly = [w for w in row['windows'] if w['label'] == 'WEEK']
+ box = TWO if len(row['windows']) == 2 else ONE
+ if weekly:
+ self.assertTrue(ticked(frame, box, arcade.pace_share(weekly[0], NOW)), row['key'])
+ else:
+ self.assertEqual(tick_columns(frame, ONE), [], row['key'])
+
+ def test_a_picture_drawn_for_a_given_time_has_its_tick_there_whatever_the_time_now(self):
+ data = snapshot(NOW, [('codex_a', 'CODEX A', 'codex', [('WEEK', 50, 3 * D)])])
+ resets = data['accounts']['codex_a']['windows'][0]['resets_at']
+ for at in (NOW - 2 * D, NOW, NOW + D):
+ data['pace_at'] = at
+ frame = arcade.arcade_frames(data, NOW)[0]
+ self.assertTrue(ticked(frame, ONE, arcade.pace_share({'resets_at': resets}, at)), at)
+
+
+class TickTimingTests(unittest.TestCase):
+ """Through live.main with the wall clock moving: hours pass and the tick's place moves on, but nothing is sent
+ for it; the next picture sent for another reason has it where it is then."""
+ def test_time_alone_sends_nothing_and_the_next_real_change_brings_the_tick_along(self):
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('WEEK', 40, 3 * D)]})
+ first, began = rig.showing()
+ resets = rig.readings['codex_a']['windows'][0]['resets_at']
+ self.assertTrue(ticked(Image.open(io.BytesIO(first)).convert('RGB'), ONE,
+ arcade.pace_share({'resets_at': resets}, rig.now())))
+ k = 0
+ while rig.poll_at(k + 1) < rig.t0 + 3 * H: # three hours of the same readings: the tick's place moves on
+ k += 1
+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())
+ rig.clock.to(rig.poll_at(k) + .5)
+ self.assertEqual(rig.switches(began + .001), []) # nothing sent for it, nothing restarted
+ self.assertEqual(rig.showing()[0], first)
+ ix, iw = track(ONE)
+ moved = iw * 3 * H / WEEK
+ self.assertGreater(moved, 2) # (more than a pixel's worth of the track)
+ rig.set('codex_a', 'WEEK', 55) # a real change
+ changed = rig.poll_at(k + 1)
+ rig.write(rig.now() + changed - rig.clock.now())
+ rig.clock.to(changed + .5)
+ rig.clock.to(rig.end_of_loop(changed) + .3)
+ image, at = rig.showing()
+ self.assertEqual(len(rig.switches(began + .001)), 1) # one picture: the change and the tick together
+ drawn = rig.now() - (rig.clock.now() - changed) # it was drawn as that reading came in
+ frame = Image.open(io.BytesIO(image)).convert('RGB')
+ self.assertTrue(ticked(frame, ONE, arcade.pace_share({'resets_at': resets}, drawn)))
+ self.assertFalse(ticked(frame, ONE, arcade.pace_share({'resets_at': resets}, rig.t0 - rig.clock.now() + rig.now())))
+
+ def test_a_new_week_moves_the_tick_back_with_the_reset_picture(self):
+ rig = Rig(self, providers=('codex',), wall=True, windows={'codex': [('WEEK', 80, 60)]}) # the week nearly over
+ old, began = rig.showing()
+ frame = Image.open(io.BytesIO(old)).convert('RGB')
+ ix, iw = track(ONE)
+ self.assertLessEqual(max(tick_columns(frame, ONE)), ix + 1) # at the empty end: the week is gone
+ window = rig.readings['codex_a']['windows'][0]
+ window.update(used_percent=0, resets_at=rig.now() + 120 + WEEK) # the new week, just begun
+ rig.write(rig.now() + rig.poll_at(1) - rig.clock.now())
+ rig.clock.to(rig.poll_at(1) + 30)
+ rig.clock.advance(60)
+ image, _ = rig.showing()
+ frame = Image.open(io.BytesIO(image)).convert('RGB')
+ self.assertGreaterEqual(min(tick_columns(frame, ONE)), ix + iw - 2) # back at the full end
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_real_pace.py b/tests/test_real_pace.py
new file mode 100644
index 0000000..0c12a5a
--- /dev/null
+++ b/tests/test_real_pace.py
@@ -0,0 +1,298 @@
+"""v2 phase 2, m1: an SD_PRO shows each picture of a GIF for the delay the GIF gives it but at least one tick of about
+142 ms (`device_frame_ms` in the config), so on it every loop's end (moments, one-offs, returns) is timed by the sum of
+its pictures' times; the GIF itself is never changed for it, and other clocks keep the length the GIF declares."""
+import http.client
+import io
+import json
+import sys
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run
+from helpers import temp_dir # noqa: E402
+from test_moments import FRAME_SD, Rig, physical # noqa: E402
+
+from token_tv import gif, live, moments # noqa: E402
+from token_tv.arcade import gif_seconds # noqa: E402
+from token_tv.device import PhotoDisplay, UltraDisplay # noqa: E402
+from token_tv.moments import loop_end # noqa: E402
+from token_tv.sources import load_config # noqa: E402
+
+FRAME_ALTERNATE = 197 # ms: a pace unlike the default, for the setting
+
+
+def made(delays, colours=None):
+ """A GIF of solid pictures with these delays (ms); equal neighbours are one picture with their delays summed."""
+ colours = colours or [(k * 40 % 256, 80, 160) for k in range(len(delays))]
+ frames = [Image.new('RGB', (8, 8), c) for c in colours]
+ return gif.encode(gif.indexed(frames, 'test'), delays)
+
+
+def delays(image):
+ out, source = [], Image.open(io.BytesIO(image))
+ for n in range(source.n_frames):
+ source.seek(n)
+ out.append(source.info['duration'])
+ return out
+
+
+class LoopLengthTests(unittest.TestCase):
+ def test_an_sd_pro_shows_each_picture_for_its_delay_but_at_least_one_tick(self):
+ image = made([70, 140, 700, 70]) # the three short pictures take a tick each, the long one its delay
+ sd_pro = PhotoDisplay('http://127.0.0.1:1')
+ self.assertAlmostEqual(live.loop_seconds(image, sd_pro), (3 * live.DEVICE_FRAME_MS + 700) / 1000)
+ self.assertAlmostEqual(live.loop_seconds(image, sd_pro, FRAME_ALTERNATE), (3 * FRAME_ALTERNATE + 700) / 1000)
+ merged = made([70, 70, 70, 70], [(10, 10, 10)] * 3 + [(200, 0, 0)]) # three equal pictures: encoded once
+ self.assertEqual(delays(merged), [210, 70])
+ self.assertAlmostEqual(live.loop_seconds(merged, sd_pro), (210 + live.DEVICE_FRAME_MS) / 1000)
+ held = made([3000, 100], [(255, 0, 0), (0, 0, 255)]) # the clock showed red, not a flicker a tick apart
+ self.assertAlmostEqual(live.loop_seconds(held, sd_pro), 3.142)
+ bow = made([350, 210, 350, 140, 3150]) # the low bow's poses over a still stage, its last one held
+ self.assertAlmostEqual(live.loop_seconds(bow, sd_pro), 4.202) # the whole bow, not five ticks (0.71 s)
+
+ def test_other_clocks_keep_what_the_gif_declares(self):
+ image = made([70, 140, 700, 70])
+ self.assertAlmostEqual(live.loop_seconds(image, UltraDisplay('http://127.0.0.1:1'), FRAME_ALTERNATE), .98)
+ self.assertAlmostEqual(live.loop_seconds(image, None), gif_seconds(image))
+
+ def test_the_pace_is_one_setting_and_a_sane_one(self):
+ folder = temp_dir(self)
+ base = {'accounts': [{'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]'}]}
+ for value in (20, 142, FRAME_ALTERNATE, 2000, 141.5):
+ (folder / 'c.json').write_text(json.dumps(dict(base, device_frame_ms=value)), encoding='utf-8')
+ self.assertEqual(load_config(folder / 'c.json')['device_frame_ms'], value)
+ for value in (0, 19, 2001, True, '142', [142], float('inf')):
+ (folder / 'c.json').write_text(json.dumps(dict(base, device_frame_ms=value)), encoding='utf-8')
+ with self.assertRaises(ValueError):
+ load_config(folder / 'c.json')
+ self.assertEqual(live.DEVICE_FRAME_MS, 142)
+
+
+class RealPaceTests(unittest.TestCase):
+ """Through live.main: entry, a one-loop moment's length and its return, by the fake clock's own pace."""
+ def snack(self, rig):
+ """normal -> SNACK -> normal, the press half a loop in; ((entry due, entry), (return due, return), image)."""
+ normal, start = rig.showing()
+ rig.clock.to(start + rig.loop(normal) / 2)
+ pressed = rig.clock.now()
+ rig.say('claude.snack')
+ due = loop_end({'at': start, 'loop': rig.loop(normal)}, pressed)
+ rig.clock.to(due + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('treat', 'snack')))
+ end = began + rig.loop(image)
+ rig.clock.to(end + .3)
+ back, returned = rig.showing()
+ self.assertEqual(back, rig.picture())
+ return (due, began), (end, returned), image
+
+ def test_the_default_pace_and_another_set_in_the_config_time_every_loop_and_change_no_byte(self):
+ at = time.time()
+ pictures = []
+ for frame_ms, frame in ((None, FRAME_SD), (FRAME_ALTERNATE, FRAME_ALTERNATE / 1000)):
+ rig = Rig(self, frame_ms=frame_ms, at=at)
+ self.assertEqual(rig.frame, frame)
+ (due, began), (end, returned), image = self.snack(rig)
+ for wanted, seen in ((due, began), (end, returned)):
+ self.assertGreaterEqual(seen, wanted)
+ self.assertLess(seen, wanted + .25)
+ self.assertAlmostEqual(end - began, sum(max(ms / 1000, frame) for ms in delays(image)), places=6)
+ self.assertNotAlmostEqual(end - began, gif_seconds(image), places=1) # not what the GIF declares
+ self.assertEqual(set(delays(image)) - {70, 140, 210, 280, 350, 420}, set()) # its own delays, untouched
+ pictures.append(image)
+ self.assertEqual(pictures[0], pictures[1]) # the same bytes at either pace
+
+ def test_a_bow_that_holds_its_last_pose_is_not_cut_short(self):
+ rig = Rig(self)
+ rig.say('claude.end')
+ due = rig.end_of_loop() # the usual face's loop, its held pictures whole too
+ rig.clock.to(due + .3)
+ bow, began = rig.showing()
+ self.assertEqual(bow, rig.picture(('done', 'claude')))
+ self.assertGreaterEqual(began, due - 1e-6)
+ self.assertLess(began, due + .25)
+ self.assertGreater(max(delays(bow)), 1000) # over a still stage its poses are a few pictures, the last held
+ end = began + rig.loop(bow) # each pose for its delay: the held one whole, not a tick of it
+ rig.clock.to(end - .05)
+ self.assertEqual(rig.showing()[0], bow) # still bowing
+ rig.clock.to(end + .3)
+ back, returned = rig.showing()
+ self.assertEqual(back, rig.picture())
+ self.assertGreaterEqual(returned, end - 1e-6)
+ self.assertLess(returned, end + .25)
+
+ def test_the_next_loop_counts_from_when_the_picture_went_on_not_when_its_send_began(self):
+ rig = Rig(self, delay=.1) # each send takes 100 ms on the clock
+ normal, start = rig.showing()
+ rig.clock.to(start + rig.loop(normal) / 2)
+ rig.say('claude.snack')
+ due = rig.end_of_loop()
+ rig.clock.to(due + .3)
+ image, began = rig.showing()
+ sent = [t for t in rig.uploads() if t >= due]
+ self.assertTrue(sent and sent[0] >= due) # not begun before the loop's end
+ self.assertGreater(began, sent[0]) # on once the send was done
+ rig.clock.to(began + rig.loop(image) / 2)
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ end = began + rig.loop(image) # its own pictures from its own start, not from the send's start
+ rig.clock.to(end - .01)
+ self.assertEqual(rig.showing()[0], image)
+ rig.clock.to(end + .4)
+ waiting, at = rig.showing()
+ self.assertEqual(waiting, rig.picture(('needs', 1)))
+ self.assertGreaterEqual(at, end)
+ self.assertLess(at, end + .25)
+ rig.say('claude.answered')
+ rig.clock.to(rig.end_of_loop() + .4)
+ self.assertEqual(rig.showing()[0], rig.picture())
+ self.assertLessEqual(len(rig.uploads(asked)), 2) # the wait and the return; no stale return of the snack
+
+ def test_a_loop_counts_from_the_switchs_last_request_the_old_slot_turned_off(self):
+ rig = Rig(self, switch_off=.6) # the clock takes 0.6 s to turn the old slot off, its animation held meanwhile
+ normal, start = rig.showing()
+ rig.clock.to(start + rig.loop(normal) / 2)
+ rig.say('claude.pet')
+ due = loop_end({'at': start, 'loop': rig.loop(normal)}, rig.clock.now())
+ rig.clock.to(due + .3)
+ pet, began = rig.showing() # (when its slot went on)
+ self.assertEqual(pet, rig.picture(('treat', 'pet')))
+ self.assertGreaterEqual(began, due - 1e-6)
+ self.assertLess(began, due + .25)
+ end = began + .6 + rig.loop(pet) # its loop under way once the old slot was off
+ rig.clock.to(end - .01)
+ self.assertEqual(rig.showing()[0], pet) # not cut short by that request's hold
+ rig.clock.to(end + .3)
+ back, returned = rig.showing()
+ self.assertEqual(back, rig.picture())
+ self.assertGreaterEqual(returned, end - 1e-6)
+ self.assertLess(returned, end + .25)
+
+ def test_a_usage_redraw_goes_as_the_loop_playing_when_its_reading_came_ends_however_soon_after_its_start(self):
+ at, window = float(int(time.time())), {'codex': [('5H', 30, 4 * 3600)]}
+ learn = Rig(self, providers=('codex',), wall=True, windows=window, at=at)
+ loop = learn.loop(learn.showing()[0]) # the usual face's loop on this clock
+ learn.stop()
+ for phase in (.001, .05, loop / 2, loop - .001, 0): # how far into a loop the minute's reading comes
+ rig = Rig(self, providers=('codex',), wall=True, windows=window, at=at, late=(60 - phase) % loop)
+ normal, start = rig.showing() # (the first picture went on that much later, its loop with it)
+ rig.clock.to(rig.poll_at(1) - 1)
+ rig.set('codex_a', '5H', 45)
+ rig.write()
+ read = rig.poll_at(1)
+ due = loop_end({'at': start, 'loop': loop}, read)
+ self.assertAlmostEqual(due, read - phase + (loop if phase else 0), places=6, msg=phase)
+ rig.clock.to(due - .001)
+ self.assertEqual([t for t in rig.switches(read)], [], phase) # nothing cuts the loop that was playing
+ rig.clock.to(due + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(snapshot=rig.held()), phase) # the new reading
+ self.assertGreaterEqual(began, due - 1e-6, phase)
+ self.assertLess(began, due + .25, phase)
+ self.assertEqual(len(rig.uploads(read)), 1, phase)
+ rig.stop()
+
+ def test_an_ultra_keeps_the_length_the_gif_declares(self):
+ rig = Rig(self, model='ultra', frame_ms=FRAME_ALTERNATE) # the SD_PRO's setting is no Ultra's
+ (due, began), (end, returned), image = self.snack(rig)
+ self.assertAlmostEqual(end - began, gif_seconds(image), places=6)
+ self.assertNotAlmostEqual(end - began, physical(image, FRAME_ALTERNATE / 1000), places=1)
+ self.assertGreaterEqual(returned, end)
+ self.assertLess(returned, end + .25)
+
+
+class SlowPickTests(unittest.TestCase):
+ """The hidden one-offs are picked as a reading comes in, before it is drawn. A pick that takes PICK on the clock,
+ over the end of the loop that was playing as the reading came, puts nothing a loop later: the reading's redraw, a
+ wait asked for meanwhile and the one-off picked all go as that loop ends, here at once just after it (live.LATE)."""
+ PICK = .1
+
+ def rig(self, picked=None, asked=None, **options):
+ """A rig whose minute's reading comes 50 ms before the end of the usual face's loop, the pick then taking PICK:
+ 30 ms into it `asked` is sent (a moment, as the mod sends it), and it returns `picked`. (rig, when the reading
+ comes, that loop's end, when each pick began), the clock a second before the reading."""
+ at = float(int(time.time()))
+ learn = Rig(self, at=at, **options)
+ loop = learn.loop(learn.showing()[0])
+ learn.stop()
+ rig = Rig(self, at=at, late=(60 - (loop - .05)) % loop, **options)
+ picks = []
+
+ def pick(snapshot):
+ picks.append(moments.CLOCK.now())
+ if len(picks) > 1: # (the readings after it: at once, nothing)
+ return None
+ moments.CLOCK.bump(.03)
+ if asked: # sent from here, so it comes in while the pick goes on (rig.say would wait for TokenTV)
+ conn = http.client.HTTPConnection('127.0.0.1', rig.port, timeout=5)
+ conn.request('POST', '/moment', json.dumps({'moment': asked}), {'Content-Type': 'application/json'})
+ self.assertEqual(conn.getresponse().status, 204)
+ conn.close()
+ moments.CLOCK.bump(self.PICK - .03)
+ return picked
+ patcher = mock.patch.object(live.Lockbox, 'pick', side_effect=pick)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ normal, start = rig.showing()
+ read = rig.poll_at(1)
+ due = loop_end({'at': start, 'loop': loop}, read)
+ self.assertAlmostEqual(due - read, .05, places=6)
+ rig.clock.to(read - 1)
+ return rig, read, due, picks
+
+ def assertOn(self, rig, image, due, read, picks):
+ """`image` went on as the loop playing at `read` ended (`due`), or once the pick was done just after it, alone."""
+ self.assertEqual(picks[:1], [read]) # (picked as the reading came in)
+ shown, began = rig.showing()
+ self.assertEqual(shown, image)
+ self.assertGreaterEqual(began, due - 1e-6)
+ self.assertLess(began, due + .25) # not a loop later
+ self.assertEqual(len(rig.uploads(read)), 1)
+
+ def test_a_usage_redraw_goes_as_the_loop_its_reading_came_in_ends_however_long_the_pick_takes(self):
+ rig, read, due, picks = self.rig(providers=('codex',), wall=True, windows={'codex': [('5H', 30, 4 * 3600)]})
+ rig.set('codex_a', '5H', 45)
+ rig.write()
+ rig.clock.to(due + .3)
+ self.assertOn(rig, rig.picture(snapshot=rig.held()), due, read, picks)
+
+ def test_a_wait_asked_for_while_the_one_offs_are_picked_goes_as_the_loop_it_came_in_ends(self):
+ rig, read, due, picks = self.rig(asked='claude.ask')
+ rig.clock.to(due + .3)
+ self.assertOn(rig, rig.picture(('needs', 1)), due, read, picks)
+
+ def test_a_one_off_picked_slowly_goes_on_as_the_loop_its_reading_came_in_ends(self):
+ from token_tv.lockbox import Box
+ stage = lambda colour: Image.new('RGB', (120, 71), colour) # noqa: E731
+ box = Box('Test', 'unique', 'claude_a', tuple(stage((200, 40, 40)) for _ in range(4)), 40,
+ after=(stage((40, 40, 200)),))
+ rig, read, due, picks = self.rig(picked=box)
+ rig.clock.to(due + .3)
+ self.assertOn(rig, rig.picture(egg=box), due, read, picks)
+
+
+if __name__ == '__main__':
+ unittest.main()
+
+
+class EdgeTests(unittest.TestCase):
+ """A moment just before a loop's end, exactly at it, or just after: the first two at that end, the last at the
+ next, each counted from the picture's own start (v2p2-06)."""
+ def test_a_moment_at_a_loops_very_end(self):
+ eps = .001
+ for offset, ends in ((-eps, 3), (0, 3), (eps, 4)): # pressed around the third loop's end
+ rig = Rig(self)
+ normal, start = rig.showing()
+ loop = rig.loop(normal)
+ rig.clock.to(start + 3 * loop + offset)
+ rig.say('claude.pet')
+ due = start + ends * loop
+ rig.clock.to(due + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('treat', 'pet')), offset)
+ self.assertGreaterEqual(began, due - 1e-9, offset)
+ self.assertLess(began, due + .25, offset)
diff --git a/tests/test_treats.py b/tests/test_treats.py
new file mode 100644
index 0000000..8c736c9
--- /dev/null
+++ b/tests/test_treats.py
@@ -0,0 +1,280 @@
+"""v2 phase 2, e5: `/tokentv pet` and `/tokentv snack` in the Claude Code mod send `claude.pet` and `claude.snack`;
+Clawd shows hearts or munches for one loop at the end of the loop the clock is playing. A press while one is still to
+show or showing is dropped, and so is one while Claude waits; a wait drops one not shown yet (nothing is queued)."""
+import io
+import json
+import sys
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run
+from test_moments import FakeClock, Rig, physical, post_bytes, raw # noqa: E402
+
+from token_tv import arcade, live, moments # noqa: E402
+from token_tv.moments import Moments, loop_end, overlay # noqa: E402
+from token_tv.sample import D, snapshot # noqa: E402
+
+NOW = int(time.mktime((2026, 11, 1, 14, 1, 0, 0, 0, -1))) # Sunday 2:01 pm wherever the tests run (the stage dims at night)
+
+
+def frames(image):
+ gif = Image.open(io.BytesIO(image))
+ out = []
+ for n in range(gif.n_frames):
+ gif.seek(n)
+ out.append(gif.convert('RGB'))
+ return out
+
+
+class TreatStateTests(unittest.TestCase):
+ def setUp(self):
+ self.clock = FakeClock()
+ patcher = mock.patch.object(moments, 'CLOCK', self.clock)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.woken = []
+ self.m = Moments({'claude', 'codex'}, wake=lambda: self.woken.append(self.clock.t), active=600)
+
+ def test_the_two_names_are_moments_and_nothing_like_them_is(self):
+ self.assertIn('claude.pet', moments.MOMENTS)
+ self.assertIn('claude.snack', moments.MOMENTS)
+ for body in (b'{"moment":"claude.pet"}', b'{"moment":"claude.snack"}'):
+ self.assertEqual(live.moment_of(body), json.loads(body)['moment'])
+ for body in (b'{"moment":"Claude.Pet"}', b'{"moment":"claude.PET"}', b'{"moment":"/tokentv pet"}',
+ b'{"moment":"claude.pet","prompt":"x"}', b'{"moment":["claude.pet"]}', b'["claude.pet"]',
+ b'{"moment":"claude.pet","moment":"claude.snack"}', b'{"moment":"claude.treat"}'):
+ with self.assertRaises(ValueError):
+ live.moment_of(body)
+
+ def test_a_pet_or_a_snack_is_due_from_the_press_and_draws_on_clawds_rows(self):
+ self.assertTrue(self.m.note('claude.pet'))
+ what, since, mark = self.m.wanted()
+ self.assertEqual((what, since, mark), (('treat', 'pet'), self.clock.t, {'kind': 'pet'}))
+ self.assertEqual(self.woken, [self.clock.t])
+ drawn = overlay(snapshot(NOW, [('claude_a', 'CLAUDE A', 'claude', [('WEEK', 40, 3 * D)]),
+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 30, 3 * D)])]), what, mark)
+ self.assertEqual(drawn['accounts']['claude_a']['moment'], {'kind': 'pet'})
+ self.assertNotIn('moment', drawn['accounts']['codex_a']) # no other pet does it
+ self.m.shown(what, self.clock.t + 1)
+ self.assertEqual(self.m.wanted()[:2], (None, self.clock.t + 1)) # one loop: the usual face due after it
+
+ def test_presses_while_one_is_to_show_or_showing_are_dropped_and_change_nothing(self):
+ self.m.note('claude.snack')
+ count, woken = self.m.count, list(self.woken)
+ for name in ('claude.snack', 'claude.pet', 'claude.pet'):
+ self.assertFalse(self.m.note(name))
+ self.assertEqual((self.m.count, self.woken), (count, woken))
+ self.assertEqual(self.m.wanted()[0], ('treat', 'snack')) # neither replaced nor lengthened
+ self.m.shown(('treat', 'snack'), self.clock.t)
+ for name in ('claude.snack', 'claude.pet'): # on the clock now: dropped too
+ self.assertFalse(self.m.note(name))
+ self.assertIsNone(self.m.wanted()[0])
+ self.m.shown(None, self.clock.t + 8) # its loop over, the usual face back on
+ self.assertTrue(self.m.note('claude.pet')) # a fresh press works, no minute to wait as for a bow
+ self.assertEqual(self.m.wanted()[0], ('treat', 'pet'))
+
+ def test_a_wait_drops_a_treat_not_shown_and_a_press_while_waiting_is_dropped(self):
+ self.m.note('claude.pet')
+ self.m.note('claude.ask')
+ self.assertEqual(self.m.wanted()[0], ('needs', 1))
+ for name in ('claude.pet', 'claude.snack'):
+ self.assertFalse(self.m.note(name))
+ self.m.note('claude.answered')
+ self.assertIsNone(self.m.wanted()[0]) # nothing kept for after: no backlog drains
+
+ def test_a_wait_takes_over_from_a_treat_on_the_clock_which_does_not_come_back(self):
+ self.m.note('claude.snack')
+ self.m.shown(('treat', 'snack'), self.clock.t)
+ self.clock.t += 2
+ self.m.note('claude.ask')
+ self.assertEqual(self.m.wanted()[:2], (('needs', 1), self.clock.t)) # at the treat's loop end
+ self.m.note('claude.answered')
+ self.assertIsNone(self.m.wanted()[0])
+
+ def test_a_bow_goes_first_then_the_treat_each_its_own_loop(self):
+ self.m.note('claude.end')
+ self.m.note('claude.pet')
+ self.assertEqual(self.m.wanted()[0], ('done', 'claude'))
+ self.m.shown(('done', 'claude'), self.clock.t + 1)
+ what, since, _ = self.m.wanted()
+ self.assertEqual(what, ('treat', 'pet'))
+ self.assertEqual(loop_end({'at': self.clock.t + 1, 'loop': 2.5}, since), self.clock.t + 3.5) # at the bow's end
+ self.m.shown(what, self.clock.t + 3.5)
+ self.assertIsNone(self.m.wanted()[0])
+ self.assertTrue(self.m.cooling(self.clock.t + 3.5)) # the bow's minute is the bow's alone
+ self.m.shown(None, self.clock.t + 10) # the treat's loop over
+ self.m.note('claude.snack')
+ self.assertEqual(self.m.wanted()[0], ('treat', 'snack'))
+
+ def test_no_claude_account_no_treat_and_nothing_kept(self):
+ m = Moments({'codex'}, active=600)
+ self.assertFalse(m.note('claude.pet'))
+ self.assertEqual((m.wanted()[0], m.busy(), m.count), (None, False, 0))
+
+ def test_a_treat_with_no_clock_to_show_it_on_is_dropped(self):
+ self.m.note('claude.pet')
+ self.assertTrue(self.m.busy())
+ self.m.drop_bow()
+ self.assertEqual((self.m.wanted()[0], self.m.busy()), (None, False))
+
+
+class TreatDrawingTests(unittest.TestCase):
+ def picture(self, kind, *others):
+ accounts = [('claude_a', 'CLAUDE A', 'claude', [('WEEK', 40, 3 * D)])] + list(others)
+ data = snapshot(NOW, accounts)
+ data['accounts']['claude_a']['moment'] = {'kind': kind}
+ return arcade.render_arcade(data, NOW), data
+
+ def test_hearts_and_munching_move_through_one_loop_and_differ(self):
+ pet, snack = self.picture('pet')[0], self.picture('snack')[0]
+ self.assertNotEqual(pet, snack)
+ for image, ink in ((pet, (255, 92, 136)), (snack, (226, 172, 102))): # a heart's pink, the cookie's brown
+ shots = frames(image)
+ self.assertGreater(len(shots), 20) # moving, not a still with a label
+ stages = [shot.crop((0, 28, 240, 170)) for shot in shots]
+ self.assertGreater(len({s.tobytes() for s in stages}), 20)
+ self.assertTrue(any(ink in {c for _, c in s.getcolors(65536)} for s in stages))
+
+ def test_its_readout_says_what_clawd_does_and_no_bow_or_wait(self):
+ data = snapshot(NOW, [('claude_a', 'CLAUDE A', 'claude', [('WEEK', 40, 3 * D)])])
+ row = dict(data['accounts']['claude_a'], key='claude_a')
+ for kind, word in (('pet', 'PETTED'), ('snack', 'SNACKING')):
+ plan = arcade.scene_plan(dict(row, moment={'kind': kind}), NOW)
+ self.assertEqual(arcade.action_label(dict(row, moment={'kind': kind}), plan, None, 0, 120), word)
+
+ def test_beside_another_pet_only_clawd_does_it_and_the_other_keeps_its_place(self):
+ plain = snapshot(NOW, [('claude_a', 'CLAUDE A', 'claude', [('WEEK', 40, 3 * D)]),
+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 30, 3 * D)])])
+ petted = overlay(plain, ('treat', 'pet'), {'kind': 'pet'})
+ self.assertEqual([r['provider'] for r in arcade.shown_rows(petted, NOW)], ['claude', 'codex'])
+ usual, shots = arcade.arcade_frames(plain, NOW), arcade.arcade_frames(petted, NOW)
+ half = len(shots) // 2 # Clawd's turn, then the Codex cloud's
+ stage = lambda frame: frame.crop((0, 28, 240, 170)).tobytes() # noqa: E731
+ self.assertEqual([stage(f) for f in shots[half:]], [stage(f) for f in usual[half:]]) # the cloud as ever
+ self.assertNotEqual([stage(f) for f in shots[:half]], [stage(f) for f in usual[:half]]) # Clawd petted
+
+
+class TreatTimingTests(unittest.TestCase):
+ """On the fake SD_PRO, through live.main: each starts at the end of the loop playing, plays its own one loop of
+ pictures at the clock's pace, then the usual face; presses beside it change nothing."""
+ def test_pet_then_snack_each_one_loop_at_the_next_loop_end(self):
+ rig = Rig(self)
+ normal, start = rig.showing()
+ loop = physical(normal)
+ rig.clock.to(start + loop / 4)
+ pressed = rig.clock.now()
+ rig.say('claude.pet')
+ due = loop_end({'at': start, 'loop': loop}, pressed)
+ rig.clock.to(due - .01)
+ self.assertEqual(rig.requests(pressed), []) # nothing interrupts the loop that is playing
+ rig.clock.to(due + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('treat', 'pet')))
+ self.assertGreaterEqual(began, due)
+ self.assertLess(began, due + .25)
+ end = began + physical(image)
+ rig.clock.to(end + .3)
+ back, returned = rig.showing()
+ self.assertEqual(back, rig.picture()) # one loop, then the usual face: no bow, no wait
+ self.assertGreaterEqual(returned, end)
+ self.assertLess(returned, end + .25)
+ self.assertLessEqual(len(rig.uploads(pressed)), 2) # entry and return
+ rig.clock.to(returned + physical(back) / 2)
+ pressed = rig.clock.now()
+ rig.say('claude.snack')
+ due = rig.end_of_loop()
+ rig.clock.to(due + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('treat', 'snack')))
+ self.assertLess(began, due + .25)
+ rig.clock.to(began + physical(image) + .3)
+ self.assertEqual(rig.showing()[0], rig.picture())
+ self.assertLessEqual(len(rig.uploads(pressed)), 2)
+
+ def test_presses_while_one_is_to_show_or_showing_send_nothing_more(self):
+ rig = Rig(self)
+ normal, start = rig.showing()
+ rig.clock.to(start + physical(normal) / 4)
+ pressed = rig.clock.now()
+ rig.say('claude.snack')
+ for name in ('claude.snack', 'claude.pet', 'claude.pet', 'claude.snack'):
+ rig.say(name) # all still to show: dropped
+ rig.clock.to(rig.end_of_loop() + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('treat', 'snack')))
+ for name in ('claude.pet', 'claude.snack'):
+ rig.say(name) # showing: dropped
+ rig.clock.to(began + physical(image) + .3)
+ back, returned = rig.showing()
+ self.assertEqual(back, rig.picture())
+ rig.clock.advance(5 * physical(back)) # several quiet loops: nothing queued comes
+ self.assertLessEqual(len(rig.uploads(pressed)), 2) # (the usual face may still be on the clock: a switch)
+ self.assertEqual(len(rig.switches(pressed)), 2) # the snack on, the usual face back: no more
+ self.assertEqual(rig.showing()[0], rig.picture())
+
+ def test_a_wait_outranks_a_press_and_none_comes_back_after_it(self):
+ rig = Rig(self)
+ normal, start = rig.showing()
+ rig.clock.to(start + physical(normal) / 4)
+ rig.say('claude.pet') # still to show when the wait comes: dropped
+ asked = rig.clock.now()
+ rig.say('claude.ask')
+ rig.say('claude.snack')
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(('needs', 1)))
+ rig.say('claude.pet')
+ rig.clock.advance(30)
+ self.assertEqual(rig.showing()[0], rig.picture(('needs', 1))) # no press clears it
+ rig.say('claude.answered')
+ rig.clock.to(rig.end_of_loop() + .3)
+ back, _ = rig.showing()
+ self.assertEqual(back, rig.picture())
+ rig.clock.advance(5 * physical(back))
+ self.assertEqual(rig.showing()[0], rig.picture()) # no backlog drains
+ self.assertLessEqual(len(rig.uploads(asked)), 2)
+
+ def test_a_wait_during_a_treat_takes_over_at_its_end(self):
+ rig = Rig(self)
+ normal, start = rig.showing()
+ rig.say('claude.snack')
+ rig.clock.to(rig.end_of_loop() + .3)
+ image, began = rig.showing()
+ self.assertEqual(image, rig.picture(('treat', 'snack')))
+ rig.clock.to(began + physical(image) / 2)
+ rig.say('claude.ask')
+ end = began + physical(image)
+ rig.clock.to(end + .3)
+ waiting, at = rig.showing()
+ self.assertEqual(waiting, rig.picture(('needs', 1)))
+ self.assertGreaterEqual(at, end) # the treat's one loop whole, then the wait
+ self.assertLess(at, end + .25)
+ rig.say('claude.answered')
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.showing()[0], rig.picture()) # the treat does not play again
+
+ def test_without_claude_on_the_clock_a_press_does_nothing(self):
+ rig = Rig(self, providers=('codex',))
+ _, start = rig.showing()
+ rig.say('claude.pet')
+ rig.clock.advance(30)
+ self.assertEqual(rig.uploads(start + .001), [])
+ self.assertEqual(rig.showing()[0], rig.picture())
+
+ def test_the_endpoint_takes_the_two_names_and_refuses_what_is_near_them(self):
+ rig = Rig(self)
+ for body in (b'{"moment":"Claude.Pet"}', b'{"moment":"/tokentv pet"}', b'{"moment":"claude.pet","x":1}'):
+ status = raw(rig.port, post_bytes(rig.port, body))[0]
+ self.assertEqual(status, 400, body)
+ rig.clock.advance(10)
+ self.assertEqual(rig.uploads(rig.t0 + .001), []) # nothing changed
+ rig.say('claude.pet') # and the real one still works
+ rig.clock.to(rig.end_of_loop() + .3)
+ self.assertEqual(rig.showing()[0], rig.picture(('treat', 'pet')))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/token_tv/__init__.py b/token_tv/__init__.py
index f2e9e34..1cd5573 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.4.1"
+__version__ = "0.5.0"
diff --git a/token_tv/arcade.py b/token_tv/arcade.py
index 75b44a8..e037c7b 100644
--- a/token_tv/arcade.py
+++ b/token_tv/arcade.py
@@ -38,7 +38,7 @@ SPEED = 2 # every scene runs at twice its drawn pace; a loop plays twice in the
FRAMES = 10 * FPS
FRAME_MS = 70 # each picture's time in the GIF; a SmallTV SD_PRO shows one about every 140 ms (filmed 2026-10-31)
PLAYBACK = 2 # every other drawn frame goes to the clock (owner, 2026-10-31): on the clock, the pace drawn for
-LOOP_SECONDS = FRAMES // PLAYBACK * FRAME_MS / 1000 # the GIF's own loop, 4.2 s (the SD_PRO takes about twice that)
+LOOP_SECONDS = FRAMES // PLAYBACK * FRAME_MS / 1000 # the GIF's own loop, 4.2 s (the SD_PRO: up to about twice that)
TEXT = (226, 230, 238)
MUTED = (128, 138, 160)
WARN = (255, 96, 110)
@@ -185,6 +185,15 @@ def place_clawd(frame, name, index, scale, foot_x, foot_y, flip=False):
paste(frame, art, foot_x - (x + w / 2) * scale, foot_y - (y + h) * scale)
+def clawd_top(name, index, scale, foot_x, foot_y, left, right):
+ """The first row of the frame where Clawd, stood as place_clawd stands it, shows in columns left to right."""
+ x, y, w, h = clawd_data()[name]['a0']
+ art = clawd(name, index, scale)
+ x0, y0 = round(foot_x - (x + w / 2) * scale), round(foot_y - (y + h) * scale)
+ box = art.crop((left - x0, 0, right - x0 + 1, art.height)).getbbox()
+ return y0 + (box[1] if box else art.getbbox()[1])
+
+
@functools.lru_cache(maxsize=None)
def clawd_spun(name, index, scale, degrees):
return rotsprite(clawd(name, index, scale), degrees)
@@ -305,6 +314,99 @@ def moon_gauge(draw, cx, cy, r, left):
draw.point((cx + xx, cy + yy), fill=MOON_LIT if lit else MOON_DARK)
+# --- The agent's moments (v2): Claude Code waiting for you, a turn done -------------------------------------------
+# A moment comes from the TokenTV mod in Claude Code (or Codex's notify) as a name only; the row carries it as
+# {'kind': 'needs', 'since': t} or {'kind': 'done', 'at': t}. Waiting grows more insistent: a hand up, then hops,
+# then a sign (x2). Phase 2's (pet_moments.py): {'kind': 'pet'} or 'snack' on Clawd's rows, {'kind': 'drink'} or
+# 'stretch' on every pet's, each once through its pet's turn.
+NEEDS_LEVELS = ((15 * 60, 3), (5 * 60, 2), (0, 1)) # seconds waited -> how insistent
+MOMENT_ACTION = {'needs': 'NEEDS YOU', 'done': 'DONE', 'pet': 'PETTED', 'snack': 'SNACKING', 'drink': 'DRINKING',
+ 'stretch': 'STRETCHING'}
+ONCE_THROUGH = ('pet', 'snack', 'drink', 'stretch') # moments drawn once through the turn, a scene frame a frame
+JOINING = ('done', 'pet', 'snack') # moments that bring their pet into the loop beside the ones at work
+SIGN_INK, SIGN_BOARD, SIGN_EDGE = (34, 40, 120), (250, 244, 226), (150, 110, 70)
+
+
+def needs_level(waited):
+ return next(level for after, level in NEEDS_LEVELS if waited >= after)
+
+
+BOW_SHARE = .5 # a bow takes the first half of the loop, and its pet stands proud for the rest
+
+
+def bow_step(f, span):
+ """Where a bow is at frame `f` of its pet's turn of `span` frames (a bowing scene runs once through its turn,
+ at SPEED: arcade_frames), on the 24 steps it is drawn in: 0 to 24 over the first BOW_SHARE of the loop, or the
+ whole turn when pets share the loop (a quarter of it would make the dip a flicker), then 24 (bowed, standing) to
+ the turn's end. One bow a loop, however many pets share it."""
+ return min(24, 24 * f / (min(span, BOW_SHARE * FRAMES) * SPEED))
+
+
+def alert_mark(draw, x, y, s, f):
+ """A small speech bubble with '!' over a head at (x, y), blinking once a second."""
+ if f % FPS >= FPS * 2 // 3:
+ return
+ draw.rectangle((x, y, x + 6 * s, y + 7 * s), fill=SIGN_BOARD)
+ draw.rectangle((x + s, y + 8 * s, x + 2 * s - 1, y + 9 * s - 1), fill=SIGN_BOARD) # the bubble's tail
+ draw.rectangle((x + 3 * s, y + s, x + 4 * s - 1, y + 4 * s - 1), fill=WARN)
+ draw.rectangle((x + 3 * s, y + 5 * s, x + 4 * s - 1, y + 6 * s - 1), fill=WARN)
+
+
+def sign_sway(s, f):
+ return s if (f // 6) % 2 else 0
+
+
+def held_sign(draw, cx, top, s, f):
+ """A board on a stick, held up over the head: HEY!, swaying a pixel. The stick ends at top + 20 * s."""
+ sway = sign_sway(s, f)
+ left = cx - 15 * s + sway
+ draw.rectangle((cx - s // 2 + sway, top + 11 * s, cx + s // 2 + sway, top + 20 * s), fill=SIGN_EDGE) # the stick
+ draw.rectangle((left, top, left + 30 * s, top + 11 * s), fill=SIGN_EDGE)
+ draw.rectangle((left + s, top + s, left + 29 * s, top + 10 * s), fill=SIGN_BOARD)
+ pixel_text(draw, (left + 4 * s, top + 2 * s), 'HEY!', scale=s, color=SIGN_INK)
+
+
+def claude_moment(frame, draw, foot_x, foot_y, f, span, s, moment):
+ if moment['kind'] in ONCE_THROUGH: # petted, a snack, a drink or a stretch (pet_moments.py)
+ from token_tv import pet_moments
+ pet_moments.CLAWD_MOMENTS[moment['kind']](frame, draw, foot_x, foot_y, f, span)
+ return
+ if moment['kind'] == 'needs':
+ level = moment.get('level', 1)
+ if level == 1: # a hand up, waving at you
+ place_clawd(frame, 'Waving', 5 + (f // 2) % 12, s, foot_x, foot_y)
+ alert_mark(draw, foot_x + 9 * s, foot_y - 30 * s, s, f)
+ else: # hopping, and at the third level holding up a sign
+ index = 5 + (f // 2) % 9
+ place_clawd(frame, 'Jumping', index, s, foot_x, foot_y)
+ if level >= 3: # its stick on Clawd's head, however high the hop has it
+ stick = foot_x + sign_sway(s, f)
+ head = clawd_top('Jumping', index, s, foot_x, foot_y, stick - s // 2, stick + s // 2)
+ held_sign(draw, foot_x, head - 20 * s, s, f)
+ else:
+ alert_mark(draw, foot_x + 9 * s, foot_y - 36 * s, s, f)
+ return
+ # done: a bow, eyes shut, down low and up again once a loop, then standing proud with a smile
+ t = bow_step(f, span)
+ if bow_style(moment) == 'tilt':
+ tilt = round(28 * math.sin(math.pi * t / 14)) if t < 14 else 0
+ place_clawd_spun(frame, 'Excited', 6, s, foot_x, foot_y, -tilt)
+ elif 4 <= t < 12:
+ place_clawd(frame, 'Disappointed', 14 if 6 <= t < 10 else 12, s, foot_x, foot_y)
+ else:
+ place_clawd(frame, 'Excited', 6, s, foot_x, foot_y)
+
+
+BOW_STYLES = ('low', 'tilt') # 'low' ducks down and up; 'tilt' leans the whole body
+BOW_STYLE = None # one of BOW_STYLES for every bow; None: each bow picks one at random (the owner wants both)
+
+
+def bow_style(moment):
+ """The bow this moment plays: BOW_STYLE when one is set, else one of BOW_STYLES chosen by when the bow began,
+ so every drawing of the same bow is the same picture and the next bow may be the other one."""
+ return BOW_STYLE or random.Random(f"bow {moment.get('at')}").choice(BOW_STYLES)
+
+
def claude_scene(frame, draw, box, f, span, active, s, plan):
x, y, w, h = box
ground_y, period, pits, pit_w, shift = claude_backdrop(frame, draw, box, f, s, False) # the world stands still
@@ -313,6 +415,9 @@ def claude_scene(frame, draw, box, f, span, active, s, plan):
if s == 1:
gauge_label(draw, x + w - 12, y + 21, '5H', 'centre')
foot_x, foot_y = x + round(w * .3), ground_y
+ if isinstance(plan, dict) and plan.get('moment'):
+ claude_moment(frame, draw, foot_x, foot_y, f, span, s, plan['moment'])
+ return
if not active and isinstance(plan, dict) and plan.get('mood') == 'worried':
t = f % 40 # nearly out: pacing to and fro, looking round at each end
back = t >= 20
@@ -534,6 +639,8 @@ def flower(draw, cx, ground, g, stage, lean=0):
def codex_scene(frame, draw, box, f, span, active, s, plan, centre=.5):
x, y, w, h = box
+ bowing = isinstance(plan, dict) and (plan.get('moment') or {}).get('kind') == 'done'
+ active = active and not bowing # a turn just done: no rain while it bows
ground = garden_backdrop(draw, box, f, s)
used = plan.get('used') if isinstance(plan, dict) else None
spots = 5 # one flower per 20%, on every stage size
@@ -564,6 +671,13 @@ def codex_scene(frame, draw, box, f, span, active, s, plan, centre=.5):
mouth = 'short' if f // 4 % 2 else 'long'
mid += round(math.sin(2 * math.pi * f * 3 / FRAMES) * s)
shiver = s * (1 if flicker(f) else -1) if 1 <= phase < 1 + 2 * SPEED * PLAYBACK else 0 # two pictures: both ways
+ elif bowing: # a bow: it dips, grinning, once a loop, then floats proud
+ idle = 'bow'
+ t = bow_step(f, span)
+ dip = round(4 * math.sin(math.pi * t / 14)) if t < 14 else 0
+ eye, mouth, shiver = 'happy', 'smile', 0
+ squash = min(2, dip // 2)
+ mid += dip * s
else:
idle = idle_now(plan, f, span)
squash = 1 if 26 <= f % 60 <= 33 else 0 # breathing
@@ -1261,11 +1375,13 @@ BEAN, BEAN_SHUT, CAT_MOUTH = ('XX', 'XX', 'XX'), ('XX',), ('X.X.X', '.X.X.')
DOT_EYE, SMILE_EYE, ZED = ('XX', 'XX'), ('.X.', 'X.X'), ('XXX', '..X', '.X.', 'X..', 'XXX')
# Its poses: how tall each of the logo's ten block rows is drawn (two pixels, the legs' last row one: no feet),
# and how far the lower rows' halves move apart. A squash takes a pixel out of the legs as it lands; asleep it
-# lies low and wide like a blanket, a breath in lifting it a pixel.
+# lies low and wide like a blanket, a breath in lifting it a pixel; stretching (pet_moments) it stands up on its
+# toes, its legs a pixel longer a row.
ANTI_POSES = {'stand': ((2, 2, 2, 2, 2, 2, 2, 2, 2, 1), {}),
'squash': ((2, 2, 2, 2, 2, 2, 2, 1, 2, 1), {}),
'blanket': ((1, 1, 2, 2, 2, 1, 1, 1, 1, 1), {6: 1, 7: 1, 8: 2, 9: 2}),
- 'blanket_in': ((1, 1, 2, 2, 2, 2, 1, 1, 1, 1), {6: 1, 7: 1, 8: 2, 9: 2})}
+ 'blanket_in': ((1, 1, 2, 2, 2, 2, 1, 1, 1, 1), {6: 1, 7: 1, 8: 2, 9: 2}),
+ 'tall': ((2, 2, 2, 2, 2, 2, 3, 3, 3, 1), {})}
# The patrol: the sprite's corner round the centre wall, and the pellets, used from the top left round to the
# bottom left (what is left sits in the last corners).
ANTI_LOOP = ((3, 9), (93, 9), (93, 41), (3, 41))
@@ -1715,6 +1831,11 @@ def scene_plan(row, now, span=FRAMES / FPS):
plan['idle'] = (FLOW_MOVES[row['provider']][step], still) if step else (still, still)
if plan['mood'] == 'worried' and row['provider'] in IDLE_SETS: # nearly out: each frets its own way
plan['idle'] = ('fret', 'fret') # (Clawd paces, in its own scene)
+ moment = row.get('moment')
+ if moment and moment.get('kind') in MOMENT_ACTION:
+ plan['moment'] = dict(moment)
+ if moment['kind'] == 'needs' and moment.get('level') not in (1, 2, 3): # live.py says; a preview counts
+ plan['moment']['level'] = needs_level(stamp - (moment.get('since') or stamp))
return plan
@@ -1767,6 +1888,10 @@ def action_label(row, plan, egg, f, span):
if kind == 'full':
return FULL_ACTION.get(provider, 'ALL USED')
return 'POWER UP' if provider == 'antigravity' else 'CELEBRATING'
+ if isinstance(plan, dict) and plan.get('moment'):
+ return MOMENT_ACTION[plan['moment']['kind']]
+ if row.get('slow'): # x3: a window would run out within half an hour at its pace (state.py); the pet goes on
+ return 'SLOW'
worried = isinstance(plan, dict) and plan.get('mood') == 'worried'
if row.get('active'):
if worried:
@@ -1795,11 +1920,19 @@ def shown_rows(snapshot, now=None):
order = list(PROVIDERS)
every = [dict(row, key=key) for key, row in snapshot['accounts'].items()]
every.sort(key=lambda row: order.index(row['provider']) if row['provider'] in order else len(order))
- pool = [row for row in every if row.get('active')] or every
+ # Claude waiting for you takes the whole loop, so NEEDS YOU is on the clock all the time (the others come back
+ # once it is answered); a bow, a pet or a snack gets its turn beside the working ones, when some work. The break
+ # is every pet's: the ones that would be on the clock anyway take it, and nobody else joins them.
+ waiting = [row for row in every if (row.get('moment') or {}).get('kind') == 'needs']
+ working = [row for row in every if row.get('active')]
+ joins = lambda row: (row.get('moment') or {}).get('kind') in JOINING # noqa: E731
+ pool = waiting or ([row for row in every if row.get('active') or joins(row)] if working else every)
if len(pool) <= MAX_ROWS:
return pool
start = int((time.time() if now is None else now) // (60 * len(REST_FLOW))) * MAX_ROWS % len(pool)
- return [pool[(start + k) % len(pool)] for k in range(MAX_ROWS)]
+ turn = [pool[(start + k) % len(pool)] for k in range(len(pool))]
+ picked = ([row for row in turn if joins(row)] + [row for row in turn if not joins(row)])[:MAX_ROWS]
+ return [row for row in turn if any(row is p for p in picked)]
def egg_scene(egg, row):
@@ -1935,14 +2068,50 @@ def leave_prop(stage, row):
def scene_speed(row, eggy):
"""Scenes run at twice their pace, except Grok's jobs at work and Anti, which take the whole loop for one
- round."""
+ round, and the phase-2 moments, once through the turn a scene frame a frame."""
if eggy:
return SPEED
+ if (row.get('moment') or {}).get('kind') in ONCE_THROUGH:
+ return 1
if row['provider'] == 'antigravity':
return 1 # Anti keeps the old arcade's own pace: a round of the maze in the whole loop
return 1 if row['provider'] == 'grok' and row.get('active') else SPEED
+def moment_scene(provider, plan):
+ """The scene a pet plays in place of its own for a phase-2 moment (pet_moments.SCENE_MOMENTS: the break, for all
+ but Clawd, whose own scene draws its moments), or None."""
+ kind = (plan.get('moment') or {}).get('kind') if isinstance(plan, dict) else None
+ if kind not in ONCE_THROUGH:
+ return None
+ from token_tv import pet_moments
+ drawn = pet_moments.SCENE_MOMENTS.get(provider, {}).get(kind)
+ return drawn and (lambda frame, draw, box, f, span, active, s, plan, **_: drawn(frame, draw, box, f, span, s, plan))
+
+
+# x3 and x4 on the battery readout: a battery that would run out within half an hour (state.py) blinks red beside
+# SLOW, five pictures on and five off whatever the scene's pace; a weekly battery has a tick where even use over the
+# week would have left its charge now (the battery shows what is left: the tick sits at the share of the week still
+# to come), and charge that falls short of it is overspend, the gap to it red (the owner's style A). 5-hour windows
+# get none.
+SLOW_BLINK = 5 # pictures; about 0.7 s on an SD_PRO
+WEEK = 7 * 86400
+
+
+def weekly(value):
+ """Whether a window is a week long: by the length its service gives, else by its name."""
+ minutes = value.get('duration_minutes')
+ return minutes == 7 * 1440 if minutes else str(value.get('label', '')).rstrip('2') == 'WEEK'
+
+
+def pace_share(value, at):
+ """How much of a weekly window's week is gone at `at` (0 to 1), from its own reset time; None without one."""
+ resets_at = value.get('resets_at')
+ if not resets_at:
+ return None
+ return max(0.0, min(1.0, 1 - (resets_at - at) / WEEK))
+
+
def arcade_frames(snapshot, now, egg=None):
shown = shown_rows(snapshot, now)
# a one-off plays for its own account even when that account is not among the rows the clock cycles through
@@ -1953,6 +2122,9 @@ def arcade_frames(snapshot, now, egg=None):
starts = [k * FRAMES // len(shown) for k in range(len(shown))] + [FRAMES]
plans = [scene_plan(row, now, (starts[k + 1] - starts[k]) / FPS) for k, row in enumerate(shown)]
night = time.localtime(time.time() if now is None else now).tm_hour in NIGHT_HOURS
+ # When the pace ticks stand: the snapshot's own `pace_at` where live.py keeps the clock's (time passing alone
+ # moves no tick there), else now.
+ pace_at = snapshot.get('pace_at') or (time.time() if now is None else now)
frames, readouts = [], {}
for f in range(0, FRAMES, PLAYBACK):
index = max(k for k in range(len(shown)) if starts[k] <= f)
@@ -1961,13 +2133,15 @@ def arcade_frames(snapshot, now, egg=None):
draw = ImageDraw.Draw(frame)
used, period, old, left = info(row, now)
oneoff = egg_scene(egg, row)
- scene, tier = oneoff if oneoff else (SCENES.get(row['provider'], plain_scene), None)
+ scene, tier = oneoff if oneoff else (moment_scene(row['provider'], plans[index])
+ or SCENES.get(row['provider'], plain_scene), None)
# Every scene draws on its own half-size stage, then doubles: one 2 px grid for every sprite,
# glyph and spark, and nothing spills over the header.
stage = Image.new('RGB', (SIZE // 2, 71), PANEL)
span = starts[index + 1] - starts[index]
local = (f - starts[index]) * scene_speed(row, eggy)
- scene_f = local if eggy else local % span
+ bowing = (plans[index].get('moment') or {}).get('kind') == 'done'
+ scene_f = local if eggy or bowing else local % span # a one-off, and a bow, run once through their turn
scene(stage, ImageDraw.Draw(stage), (0, 0, SIZE // 2, 71), scene_f, span,
bool(row.get('active')), 1, plans[index])
if not oneoff and row.get('trace_prop'):
@@ -1987,14 +2161,22 @@ def arcade_frames(snapshot, now, egg=None):
label_x = 10 + (draw_badge(draw, 10, 8, tier, f) if tier in BADGES else 0) # while a one-off plays
pixel_text(draw, (label_x, 8), fit_pixel(label_of(row), 2, room - (label_x - 10)), scale=2, color=TEXT)
battery = readout_look.STYLE == 'battery'
- # the readout changes only with the account and, on the battery look, with what its pet is doing
- slot = (index, action_label(row, plans[index], egg, scene_f, span)) if battery else index
+ wins = shown_windows(row, 1)
+ # the readout changes only with the account and, on the battery look, with what its pet is doing and, beside
+ # SLOW, with its blink
+ if battery:
+ action = action_label(row, plans[index], egg, scene_f, span)
+ blink = action == 'SLOW' and f // PLAYBACK // SLOW_BLINK % 2 == 0
+ slot = (index, action, tuple(blink and value.get('label') in row['slow'] for value in wins))
+ else:
+ slot = index
if slot not in readouts:
- wins = shown_windows(row, 1)
canvas = Image.new('RGB', (SIZE, SIZE), PANEL)
if battery: # the pet and what it does, then a battery per window with its reset as a clock time
rows = [(p, u, value.get('resets_at'), o) for value in wins for u, p, o, _ in (reading(row, value),)]
- readout_look.draw_battery(canvas, ImageDraw.Draw(canvas), row['provider'], slot[1], rows, now)
+ paces = [pace_share(value, pace_at) if weekly(value) else None for value in wins]
+ readout_look.draw_battery(canvas, ImageDraw.Draw(canvas), row['provider'], slot[1], rows, now,
+ paces, slot[2])
elif len(wins) == 2: # one account at a time has room for both windows: 5H above WEEK
draw_readout(canvas, ImageDraw.Draw(canvas),
[(p, u, l, o) for u, p, o, l in (info(row, now, value) for value in wins)])
@@ -2025,13 +2207,18 @@ def encode(frames, scale=1):
def gif_seconds(image):
- """How long one loop of a GIF lasts."""
- loop = Image.open(io.BytesIO(image))
- total = 0
+ """How long one loop of a GIF lasts, as its own delays say."""
+ return sum(gif_delays(image)) / 1000
+
+
+def gif_delays(image):
+ """The delay in ms of each picture one loop of a GIF holds, as encoded (a run of equal frames is one picture, its
+ delay longer)."""
+ loop, delays = Image.open(io.BytesIO(image)), []
for n in range(getattr(loop, 'n_frames', 1)):
loop.seek(n)
- total += loop.info.get('duration', 0)
- return total / 1000
+ delays.append(loop.info.get('duration', 0))
+ return delays
def render_arcade(snapshot, now=None, scale=1, egg=None):
diff --git a/token_tv/autostart.py b/token_tv/autostart.py
index 2185fe8..52c3ee3 100644
--- a/token_tv/autostart.py
+++ b/token_tv/autostart.py
@@ -10,6 +10,7 @@ import shutil
import signal
import subprocess
import sys
+import time
from pathlib import Path
MARK = 'Written by token-tv autostart'
@@ -358,4 +359,44 @@ def remove():
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.'
+ forget_ended_run(pid_file.parent, pid)
return 'TokenTV stopped and no longer starts with this computer.'
+
+
+def forget_ended_run(state, pid):
+ """Ended outright, a TokenTV cleans up nothing: its address goes too, so no agent tells its old port. Only under
+ its live.lock (the ended copy lets go of it as it dies, within LOCK_WAIT seconds) and while live.pid still holds
+ the number just ended: a TokenTV started since holds the lock or has written its own, and keeps its files."""
+ from token_tv.private_files import open_private
+ try:
+ handle = open_private(state / 'live.lock')
+ except OSError:
+ return
+ with handle:
+ for _ in range(int(LOCK_WAIT / .05)):
+ 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)
+ break
+ except OSError:
+ time.sleep(.05)
+ else:
+ return # a TokenTV holds it: a new one, or the old one not gone yet; its files stay
+ try:
+ if int((state / 'live.pid').read_text(encoding='utf-8')) == pid:
+ for name in ('live.url', 'live.pid'):
+ (state / name).unlink(missing_ok=True)
+ except (OSError, ValueError):
+ pass
+ if os.name == 'nt': # closing lets go on POSIX; msvcrt wants its byte unlocked
+ try:
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+ except OSError:
+ pass
+
+
+LOCK_WAIT = 2.0
diff --git a/token_tv/cli.py b/token_tv/cli.py
index da7a13d..019f261 100644
--- a/token_tv/cli.py
+++ b/token_tv/cli.py
@@ -9,6 +9,7 @@
token-tv connect sign an account in with its official CLI
token-tv run start the dashboard and drive the clock
token-tv update put the newest release in the background copy's place
+ token-tv notify for Codex's notify setting: a finished turn makes Codex's pet bow on the clock
"""
import argparse
import io
@@ -723,7 +724,30 @@ def passthrough(module, args, extra):
return 0
+def notify(argv):
+ """Codex's notify program: `token-tv notify [--config PATH] '<event JSON>'`, Codex adding the JSON. A finished
+ turn (`agent-turn-complete`) tells the running TokenTV `codex.end`, the name and nothing else; nothing of the
+ event is printed, kept or passed on, and it is done within two seconds whatever happens (exit status 0)."""
+ try:
+ rest = list(argv)
+ config = os.environ.get('TOKEN_TV_CONFIG') or default_config() # as the Claude Code mod finds TokenTV
+ if rest[:1] == ['--config'] and len(rest) >= 2:
+ config, rest = rest[1], rest[2:]
+ elif rest and rest[0].startswith('--config='):
+ config, rest = rest[0][len('--config='):], rest[1:]
+ event = json.loads(rest[-1]) if rest else None
+ if isinstance(event, dict) and event.get('type') == 'agent-turn-complete':
+ from token_tv.moments import post
+ post(Path(config).expanduser().parent / 'state', 'codex.end', timeout=.8)
+ except Exception: # whatever it was, Codex goes on: there is nothing to say about it
+ pass
+ return 0
+
+
def main(argv=None):
+ argv = sys.argv[1:] if argv is None else list(argv)
+ if argv[:1] == ['notify']: # before anything that could print what Codex sent, or take time to load
+ return notify(argv[1:])
from token_tv.display import STYLES
from token_tv import __version__
parser = argparse.ArgumentParser(prog='token-tv', description=__doc__,
@@ -763,6 +787,7 @@ def main(argv=None):
add_help=False)
commands.add_parser('run', parents=[config], help='start the dashboard and drive the clock',
add_help=False)
+ commands.add_parser('notify', help="for Codex's notify setting: tell TokenTV a turn ended (docs/claude-code-mod.md)")
args, extra = parser.parse_known_args(argv)
global CONFIG
diff --git a/token_tv/device.py b/token_tv/device.py
index 823767c..2c34186 100644
--- a/token_tv/device.py
+++ b/token_tv/device.py
@@ -163,13 +163,18 @@ class PhotoDisplay:
self.held[slot] = (digest, len(image))
return slot, receipts
- def select(self, original, name):
+ def select(self, original, name, on=None):
"""Make `name` the one picture the clock shows: between slots two toggles, else the full activation. If
- anything fails, what the clock has enabled is unknown: the next change lists it and activates in full."""
+ anything fails, what the clock has enabled is unknown: the next change lists it and activates in full.
+ `on()`, when given, is called as the picture goes on: as its slot is turned on, the old one still to go off
+ (so a caller knows it was on the clock even if that fails). The switch is done, and the picture's loop under
+ way, only once this returns: the clock's animation holds for every request, the last one too."""
try:
if self.active in self.SLOTS and name in self.SLOTS and self.active != name:
self.toggle("photo", "name", name, True) # the new one on before the old one off: never empty
self.enabled.add(name)
+ if on:
+ on()
self.toggle("photo", "name", self.active, False)
self.enabled.discard(self.active)
elif self.active != name:
diff --git a/token_tv/live.py b/token_tv/live.py
index bdfa8cd..68b6dc1 100644
--- a/token_tv/live.py
+++ b/token_tv/live.py
@@ -4,9 +4,13 @@ import atexit
import dataclasses
import hashlib
import io
+import ipaddress
import json
import os
+import re
+import signal
import socket
+import socketserver
import sys
import tempfile
import threading
@@ -20,9 +24,10 @@ from urllib.parse import parse_qs, urlparse
from token_tv.device import FILES, BackupMismatch, open_display
from token_tv.catalog import payload as theme_payload
from token_tv.display import STYLES, overview_rows, render_page, watch_payload
-from token_tv.arcade import LOOP_SECONDS, gif_seconds
+from token_tv.arcade import LOOP_SECONDS, gif_delays, gif_seconds
from token_tv.events import EGG_SECONDS
from token_tv.lockbox import Lockbox
+from token_tv import moments
# After a unique one has played its prop stays in the scene for an hour; a legend's, till midnight.
TRACE = {'unique': lambda now: now + 3600,
@@ -31,16 +36,45 @@ from token_tv.private_files import open_private, private_dir, write_private
from token_tv.update import UpdateNotice
from token_tv.web_assets import HTML, ASSETS, asset
from token_tv.sources import load_config
-from token_tv.state import MIN_FETCH_SECONDS, UsageStore
+from token_tv.state import ACTIVE_SECONDS, MIN_FETCH_SECONDS, UsageStore
+
+# How long an SD_PRO shows each picture of a GIF (m1): the delay the GIF gives it, but never less than one tick of
+# about 142 ms, max(delay, tick). On the author's unit, with every picture asking 70 ms, it put up a new one every
+# ~142 ms (two 120 fps films); a GIF of red for 3000 ms then blue for 100 ms showed red, not a flicker a tick apart;
+# and an older film showed pictures held 1.1-1.7 s. Long delays are not yet timed frame by frame. A loop there is the
+# sum of its pictures' times (the marked line in loop_seconds: another rule per picture is a change to that line
+# alone), and every loop's end on it is timed so. `device_frame_ms` in the config sets the tick; other clocks play
+# as long as the GIF says until one is measured. The GIF itself is never changed for it.
+DEVICE_FRAME_MS = 142
+
+
+def loop_seconds(image, device, frame_ms=DEVICE_FRAME_MS):
+ """How long one loop of the GIF `image` lasts on the clock `device`."""
+ if getattr(device, 'MODEL', None) == 'sdpro':
+ return sum(max(delay, frame_ms) for delay in gif_delays(image)) / 1000 # each picture: max(delay, tick)
+ return gif_seconds(image)
def until_loop_end(shown, now):
- """Seconds until the clock's GIF finishes a loop (it started at 'at' and loops every 'loop' seconds); 0 when
- nothing loops yet."""
- if shown.get('at') is None or not shown.get('loop'):
- return 0
- wait = shown['loop'] - (now - shown['at']) % shown['loop']
- return 0 if wait > shown['loop'] - .1 else wait # right on time is no reason to wait a whole loop
+ """Seconds until the loop the clock's GIF plays at `now` ends (it started at 'at' and loops every 'loop' seconds,
+ moments.loop_end): 0 right at a loop's end or when nothing loops yet. A picture that has only just gone on plays
+ its first loop whole (a one-off's event, before what follows it)."""
+ end = moments.loop_end(shown, now)
+ return 0 if end is None else max(0.0, end - now)
+
+
+LATE = .2 # seconds past a loop's end that a change due at it still goes (it was drawn as the loop ended)
+
+
+def switch_at(shown, came, now):
+ """When a picture of a change that came in at `came` goes on the clock (moments.CLOCK): as the loop the clock was
+ playing then ends, or, once that end is more than LATE gone by `now` (the clock was being sent to, or the drawing
+ took that long), as the next one ends; None when nothing loops yet (at once). Every switch is timed so: the
+ agents' moments, usage redraws, a one-off, what follows it and the return."""
+ due = moments.loop_end(shown, came)
+ if due is not None and due + LATE < now:
+ due = moments.loop_end(shown, now)
+ return due
LOST_POLLS = 3 # polls in a row the clock does not answer before TokenTV looks for it on the network again
@@ -257,6 +291,39 @@ def mismatch_message(error, backup_path):
"restore it, or move that file away so TokenTV saves a new backup.")
+class Wake:
+ """A threading.Event (set, clear, is_set, wait) that also keeps why it was set: 'moment' when an agent's
+ moment set it, 'other' for anything else (a new face, a replay, a clock found again)."""
+ def __init__(self):
+ self.cond = threading.Condition()
+ self.why = set()
+
+ def set(self, why='other'):
+ with self.cond:
+ self.why.add(why)
+ self.cond.notify_all()
+
+ def clear(self):
+ with self.cond:
+ self.why.clear()
+
+ def is_set(self):
+ with self.cond:
+ return bool(self.why)
+
+ def wait(self, timeout=None):
+ with self.cond:
+ if not self.why:
+ self.cond.wait(timeout)
+ return bool(self.why)
+
+ def take(self):
+ """Why it was set since the last take, and clear it."""
+ with self.cond:
+ why, self.why = self.why, set()
+ return why
+
+
class DisplayPreferences:
def __init__(self, config_path, config):
self.path = Path(config_path)
@@ -265,7 +332,7 @@ class DisplayPreferences:
self.applied_style = None
self.status = 'queued' if config.get('device_url') else 'preview_only'
self.lock = threading.Lock()
- self.changed = threading.Event()
+ self.changed = Wake()
self.trouble = None # why pictures do not reach the clock now, for the dashboard
def snapshot(self):
@@ -345,6 +412,84 @@ def keepsake(image):
LOCAL_NAMES = ('127.0.0.1', 'localhost', '::1')
+HOST_FORM = re.compile(r'(\[::1\]|[A-Za-z0-9._-]+)(:[0-9]{1,5})?') # a Host header: a name or address, a port
+READ_SECONDS = 2 # the most a moment's request may take to arrive, line, headers and body: a slow sender is let go
+PAGE_SECONDS = 10 # the same for the dashboard's other requests: a phone on poor Wi-Fi is still answered
+
+
+def host_name(header):
+ """The name a Host header asks by, in lower case without its port or a final dot; None when it is not one
+ plain name or address. In brackets only IPv6's loopback, [::1]: anything else bracketed is no address of ours."""
+ found = HOST_FORM.fullmatch((header or '').strip())
+ return found.group(1).strip('[]').lower().rstrip('.') if found else None
+
+
+def same_origin(origin, host):
+ """Whether a browser's Origin is the page this server gave it: http(s), the very Host it asks by, no path. One
+ that does not even parse (a bracket left open) is not."""
+ try:
+ parsed = urlparse(origin)
+ except ValueError:
+ return False
+ return parsed.scheme in ('http', 'https') and parsed.netloc == host and parsed.path in ('', '/')
+
+
+class Late(Exception):
+ """A request that did not arrive in its time (Deadline): its handler answers 408. Not an OSError, so nothing on
+ its way takes it for a failure of TokenTV's own (a display choice that could not be saved)."""
+
+
+class Deadline(io.RawIOBase):
+ """A request's socket as its handler reads it: one deadline for the whole request (the handler's `deadline`),
+ not a timeout per read, so a sender that drips a byte now and then is let go as surely as one that stops. It
+ counts what arrived (`received`): a request cut off part-way is answered, a connection that sent nothing not."""
+ def __init__(self, sock, handler):
+ self.sock, self.handler = sock, handler
+
+ def readable(self):
+ return True
+
+ def readinto(self, buffer):
+ left = self.handler.deadline - time.monotonic()
+ if left <= 0:
+ raise Late('The request took too long to arrive')
+ before = self.sock.gettimeout()
+ self.sock.settimeout(left if before is None else min(before, left))
+ try:
+ got = self.sock.recv_into(buffer)
+ except TimeoutError:
+ raise Late('The request took too long to arrive') from None
+ finally:
+ self.sock.settimeout(before) # what it writes back keeps its own time
+ self.handler.received += got
+ return got
+
+
+def unique_keys(pairs):
+ """json.loads' object_pairs_hook: a key given twice is no request of ours."""
+ keys = [key for key, _ in pairs]
+ if len(set(keys)) != len(keys):
+ raise ValueError('A key given twice')
+ return dict(pairs)
+
+
+def moment_of(body):
+ """The moment a request body names: exactly {"moment": <one of moments.MOMENTS>}, as strict UTF-8 JSON; else
+ ValueError (UnicodeError is one)."""
+ data = json.loads(body.decode('utf-8'), object_pairs_hook=unique_keys)
+ if not isinstance(data, dict) or set(data) != {'moment'} or data['moment'] not in moments.MOMENTS:
+ raise ValueError('Not a moment')
+ return data['moment']
+
+
+class MomentSocket(socketserver.ThreadingUnixStreamServer if hasattr(socketserver, 'ThreadingUnixStreamServer')
+ else object):
+ """The moment endpoint again on a socket in TokenTV's own state folder (live.sock), for the Claude Code mod: a
+ request over it meets no proxy and cannot be redirected anywhere else. Linux and macOS."""
+ daemon_threads = True
+
+ def handle_error(self, request, client_address):
+ return
def lan_names(bound=None):
@@ -364,29 +509,85 @@ def lan_names(bound=None):
return {name.lower().rstrip('.') for name in names if name} | set(LOCAL_NAMES)
-def handler(store, preferences=None, locks=None, replays=None, wake=None, local_only=True, names=None, notice=None):
+def handler(store, preferences=None, locks=None, replays=None, wake=None, local_only=True, names=None, notice=None,
+ agents=None, moments_only=False, pace=None):
# Answered by: this computer's own names; on the network (LAN mode) also its names and addresses there.
hosts = set(LOCAL_NAMES) if local_only else {n.lower().rstrip('.') for n in (lan_names() if names is None else names)} | set(LOCAL_NAMES)
class Handler(BaseHTTPRequestHandler):
+ timeout = 2 if moments_only else None # the moments' own socket: a sender that stalls anywhere is let go
+
+ def setup(self):
+ super().setup()
+ self.rfile.close() # read instead with one deadline per request, here and on the port
+ self.rfile = io.BufferedReader(Deadline(self.connection, self))
+
+ def handle_one_request(self):
+ # One deadline for the whole request: a moment's READ_SECONDS (all the socket takes), the dashboard's
+ # PAGE_SECONDS until its first line says it is a moment (parse_request). One that runs out is answered
+ # 408, if anything of it came at all, and never as TokenTV's own failure.
+ self.began, self.received = time.monotonic(), 0
+ self.deadline = self.began + (READ_SECONDS if moments_only else PAGE_SECONDS)
+ try:
+ super().handle_one_request()
+ except Late:
+ self.close_connection = True
+ if self.received:
+ self.late()
+
+ def parse_request(self):
+ words = self.raw_requestline.split()
+ try:
+ moment = len(words) > 1 and urlparse(words[1].decode('latin-1')).path == '/moment'
+ except ValueError:
+ moment = False
+ if moment: # its line, headers and body in READ_SECONDS from its start
+ self.deadline = min(self.deadline, self.began + READ_SECONDS)
+ return super().parse_request()
+
+ def late(self):
+ for name, value in (('requestline', ''), ('request_version', 'HTTP/1.0'), ('command', '')):
+ if not hasattr(self, name): # cut off in its very first line
+ setattr(self, name, value)
+ try:
+ self.send_error(408)
+ self.wfile.flush()
+ except OSError:
+ pass
+
def log_message(self, *args):
return
+ def send_error(self, code, message=None, explain=None):
+ # The base class names what it could not take ("Unsupported method ('X')", a broken request line):
+ # those get the bare reason, so nothing sent comes back. An unknown method is no 501 but a 405.
+ if code == 501:
+ code, message = 405, None
+ super().send_error(code, message if getattr(self, 'answering', False) else None)
+
+ def do_OPTIONS(self): # a browser's preflight: no page elsewhere is let in
+ self.answering = True
+ if moments_only or not self.foreign_host():
+ self.send_error(405)
+
def foreign_host(self):
"""True, having answered 403, when the dashboard is asked by a name not this computer's: a web page
- that renamed its own address to this computer (DNS rebinding) must not read or change anything."""
- try:
- host = (urlparse('//' + (self.headers.get('Host') or '')).hostname or '').rstrip('.')
- except ValueError:
- host = ''
- if host in hosts:
+ that renamed its own address to this computer (DNS rebinding) must not read or change anything. The Host
+ is read as the moments read it (host_name)."""
+ if host_name(self.headers.get('Host')) in hosts:
return False
self.send_error(403, 'This dashboard answers only as 127.0.0.1 or localhost' if local_only else
"This dashboard answers only by this computer's names and addresses")
return True
def do_GET(self):
- if self.foreign_host():
+ self.answering = True
+ if urlparse(self.path).path == '/moment':
+ self.moment_check()
+ return
+ if moments_only or self.foreign_host():
+ if moments_only:
+ self.send_error(404)
return
url = urlparse(self.path)
path = url.path
@@ -411,6 +612,10 @@ def handler(store, preferences=None, locks=None, replays=None, wake=None, local_
if style not in STYLES:
self.send_error(400, 'Unknown display style')
return
+ if agents is not None and style == 'arcade': # the agents' moment, as the clock will show it
+ snapshot = moments.overlay(snapshot, *agents.wanted()[::2])
+ if pace and pace.get('at') is not None: # the pace ticks where the clock's picture has them
+ snapshot['pace_at'] = pace['at']
body = render_page(snapshot, int(path[7]), style)
content_type = "image/gif" if body[:4] == b"GIF8" else "image/jpeg"
elif path == '/themes':
@@ -450,6 +655,13 @@ def handler(store, preferences=None, locks=None, replays=None, wake=None, local_
self.wfile.write(body)
def do_POST(self):
+ self.answering = True
+ if self.path == '/moment' or urlparse(self.path).path == '/moment':
+ self.moment_request()
+ return
+ if moments_only:
+ self.send_error(404)
+ return
if self.foreign_host():
return
if urlparse(self.path).path == '/collection/replay':
@@ -462,29 +674,130 @@ def handler(store, preferences=None, locks=None, replays=None, wake=None, local_
self.send_error(409, 'Display settings unavailable')
return
origin = self.headers.get('Origin')
- if origin and (urlparse(origin).scheme not in ('http', 'https') or urlparse(origin).netloc != self.headers.get('Host')):
+ if origin and not same_origin(origin, self.headers.get('Host')):
self.send_error(403, 'Origin mismatch')
return
- try:
+ try: # (a body that comes too late is a 408: Late, in handle_one_request)
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= 1024 or self.headers.get('Content-Type', '').split(';')[0] != 'application/json':
raise ValueError('Invalid JSON request')
data = json.loads(self.rfile.read(length))
if not isinstance(data, dict) or set(data) != {'style'} or data['style'] not in STYLES:
raise ValueError('Unknown display style')
- preferences.set_style(data['style'])
except (ValueError, UnicodeError):
self.send_error(400, 'Choose a supported display style')
return
- except OSError:
+ try:
+ preferences.set_style(data['style'])
+ except (OSError, ValueError): # the config could not be written, or read back (edited by hand, say)
self.send_error(500, 'Could not save display choice')
return
self.reply(200, json.dumps(preferences.snapshot()).encode())
+ def moment_refusal(self, body=True):
+ """Why a moment request is refused, as (status, words), or None. Only this computer may tell TokenTV a
+ moment, by its own name, and never a web page; the body is read only once it can be small JSON. With
+ `body` False, the same for GET /moment, which carries none."""
+ if isinstance(self.client_address, tuple): # over TCP (on the socket, the peer is this computer)
+ try:
+ if not ipaddress.ip_address(self.client_address[0].split('%')[0]).is_loopback:
+ return 403, 'Moments come only from this computer'
+ except ValueError:
+ return 403, 'Moments come only from this computer'
+ given = self.headers.get_all('Host') or []
+ host = host_name(given[0]) if len(given) == 1 else None
+ if host is None:
+ return 400, 'One plain Host header is needed'
+ if host not in hosts:
+ return 403, 'This dashboard answers only by this computer\'s names'
+ if urlparse(self.path).query or self.path != '/moment':
+ return 400, 'A moment carries nothing in its address'
+ origins = self.headers.get_all('Origin') or []
+ if len(origins) > 1 or (origins and not same_origin(origins[0], given[0].strip())):
+ return 403, 'Origin mismatch'
+ if not body:
+ return (404, 'Not Found') if agents is None else None
+ if self.headers.get_all('Transfer-Encoding'):
+ return 400, 'A moment is sent with its length'
+ types = self.headers.get_all('Content-Type') or []
+ if len(types) != 1 or types[0].split(';')[0].strip().lower() != 'application/json':
+ return 415, 'A moment is JSON'
+ lengths = self.headers.get_all('Content-Length') or []
+ if len(lengths) != 1 or not lengths[0].strip().isdigit() or not lengths[0].strip().isascii():
+ return 400, 'A moment is sent with its length'
+ if int(lengths[0]) > moments.BODY_LIMIT:
+ return 413, 'A moment is a short name'
+ if int(lengths[0]) == 0:
+ return 400, 'A moment is a short name'
+ if agents is None:
+ return 404, 'Not Found'
+ return None
+
+ def moment_request(self):
+ """POST /moment {"moment": "claude.ask"}: one of moments.MOMENTS, from the Claude Code mod or Codex's
+ notify program. Answered 204 at once; nothing of it is logged or kept, a refusal echoes nothing. One that
+ came whole but past its READ_SECONDS is a 408 and changes nothing: its sender has given up on it."""
+ refusal = self.moment_refusal()
+ if refusal:
+ self.refuse(*refusal)
+ return
+ try:
+ self.connection.settimeout(1) # a sender that stops part-way is let go
+ body = self.rfile.read(int(self.headers['Content-Length']))
+ if len(body) != int(self.headers['Content-Length']):
+ raise ValueError('Cut short')
+ name = moment_of(body)
+ except (ValueError, OSError): # UnicodeError and JSON errors are ValueErrors (one that stops: Late, 408)
+ self.refuse(400, 'Choose a moment TokenTV knows')
+ return
+ # The deadline is looked at only when a read waits for more: a request whose rest came in one go while
+ # its first line still had the dashboard's PAGE_SECONDS (its first byte at once, the rest 8 s later) is
+ # read whole from the buffer. Past its READ_SECONDS, it counts for nothing all the same.
+ if time.monotonic() >= self.deadline:
+ raise Late('The request took too long to arrive')
+ agents.note(name)
+ waited = agents.waited() if name == 'claude.ask' else None
+ self.send_response(204)
+ self.send_header('Cache-Control', 'no-store')
+ if waited is not None: # how long the wait this ask joined has lasted: when TokenTV lets it go
+ self.send_header('TokenTV-Wait-Age', f'{waited:.1f}')
+ self.end_headers()
+
+ def moment_check(self):
+ """GET /moment is no moment: 405, POST only. Refused as a moment is; nothing changes."""
+ refusal = self.moment_refusal(body=False)
+ if refusal:
+ self.refuse(*refusal)
+ return
+ self.send_response(405)
+ self.send_header('Allow', 'POST')
+ self.send_header('Cache-Control', 'no-store')
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+
+ def refuse(self, status, words):
+ """Answer a refusal and close; a sender still sending (a body far too long, say) gets to finish into
+ nothing, at most 1 MiB for half a second, so it reads the refusal and not a reset. Nothing it sent is
+ kept or looked at."""
+ self.close_connection = True
+ try:
+ self.send_error(status, words)
+ self.wfile.flush()
+ self.connection.shutdown(socket.SHUT_WR)
+ self.connection.settimeout(.25)
+ left, end = 1 << 20, time.monotonic() + .5
+ while left > 0 and time.monotonic() < end: # half a second in all, however slowly it comes
+ chunk = self.connection.recv(min(65536, left))
+ if not chunk:
+ break
+ left -= len(chunk)
+ except OSError:
+ pass
+
def replay_request(self):
"""POST {"check": ...}: play a found one-off on the clock again."""
origin = self.headers.get('Origin')
- if origin and (urlparse(origin).scheme not in ('http', 'https') or urlparse(origin).netloc != self.headers.get('Host')):
+ if origin and not same_origin(origin, self.headers.get('Host')):
self.send_error(403, 'Origin mismatch')
return
try:
@@ -503,7 +816,10 @@ def handler(store, preferences=None, locks=None, replays=None, wake=None, local_
refusal = ('No clock connected' if shown.get('status') == 'preview_only' else
'The clock is not answering' if shown.get('status') == 'error' else
'Waiting for the clock' if preferences is not None and shown.get('applied_style') is None else
- 'Switch the clock to Arcade first' if preferences is not None and shown.get('style') != 'arcade' else '')
+ 'Switch the clock to Arcade first' if preferences is not None and shown.get('style') != 'arcade' else
+ 'Claude Code is waiting for you' if agents is not None and agents.busy() and agents.waits else
+ 'A bow is on its way' if agents is not None and agents.busy() and agents.bow else
+ 'A moment is on its way' if agents is not None and agents.busy() else '')
if refusal: # short: the dashboard puts it on the button as it is
self.reply(409, json.dumps({'error': refusal}).encode())
return
@@ -514,7 +830,9 @@ def handler(store, preferences=None, locks=None, replays=None, wake=None, local_
return Handler
-def main():
+def main(argv=None, ready=None):
+ """Run TokenTV: the dashboard, the clock and the agents' moments. `ready(server)` is told once it listens
+ (tests and graders stop it with server.shutdown())."""
parser = argparse.ArgumentParser(description="TokenTV live account display")
parser.add_argument("--config", help="Credential-free account metadata (default: the one `token-tv start` uses)")
parser.add_argument("--host", default="127.0.0.1")
@@ -523,7 +841,7 @@ def main():
parser.add_argument("--output", help="Write a normalized snapshot rather than stdout")
parser.add_argument("--state-dir", default=".runtime")
parser.add_argument("--restore-display", action="store_true")
- args = parser.parse_args()
+ args = parser.parse_args(argv)
if args.config is None:
from token_tv.cli import default_config
args.config = default_config()
@@ -597,18 +915,39 @@ def main():
traces = {} # account key -> (tier, until, prop): what a unique or legend leaves after it has played
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
+ shown = {'at': None, 'loop': None} # when the clock's GIF started (moments.CLOCK), and its loop on that clock
+ frame_ms = config.get('device_frame_ms') or DEVICE_FRAME_MS # an SD_PRO's pace (m1)
+ pace = {'at': None} # when the pace ticks in the clock's picture stand (x4): time alone sends no new picture
+ readings = {'count': 0} # usage readings taken in: a picture waiting for its loop's end is drawn again with one
lost = {'polls': 0, 'scanned': None} # polls in a row the clock did not answer, and when it was last looked for
refused = {'url': None} # a clock another TokenTV drives, said once
+ # The agents' moments (Claude Code waiting for you, a turn done, a pet or a snack, the pets' break): in memory
+ # only, gone with a restart.
+ unsure = ('unsure',) # what the clock shows is not known (a send failed): never what is wanted
+ displayed = {'what': None} # the moment in the picture on the clock: None or one of Moments.due()'s
+ # Sends in a row of a picture with the break that the clock did not take, and when the break goes once more after
+ # the first of them: as the loop the clock plays then ends (moments.CLOCK), or None.
+ failed = {'break': 0, 'again': None}
+ kick = threading.Event() # set when the moments change, and to stop: a wait for a loop's end looks again
+ agents = moments.Moments({account.get('provider') for account in config['accounts']},
+ wake=lambda: (kick.set(), preferences.changed.set('moment')), active=ACTIVE_SECONDS)
+
+ def version():
+ """What a picture waiting for its loop's end was drawn from: the moments due and the readings in."""
+ return agents.count, readings['count']
+
def follow_clock():
"""The clock to drive: the address in the config, read again each minute (`start` finding the clock, or
- `start --device-url`, while this runs). With none there, no clock: one on this network may be someone else's."""
- nonlocal device, last_upload
+ `start --device-url`, while this runs), and its pace (`device_frame_ms`). With no address there, no clock: one
+ on this network may be someone else's."""
+ nonlocal device, last_upload, frame_ms
try:
- wanted = plain(load_config(args.config).get("device_url"))
+ read = load_config(args.config)
except (OSError, ValueError):
return
+ wanted = plain(read.get("device_url"))
+ frame_ms = read.get('device_frame_ms') or DEVICE_FRAME_MS # (the next picture's loop is timed by it)
if refused['url'] and wanted != refused['url']: # what was refused is no longer asked for
refused['url'] = None
preferences.problem(None)
@@ -647,16 +986,8 @@ def main():
preferences.trouble = None
print(f"TokenTV drives the clock at {wanted} now." if wanted else "TokenTV runs without a clock now.", flush=True)
- 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, device
- delivered = False
- if refresh and not args.once:
- follow_clock()
- if refresh:
- store.refresh()
+ def base():
+ """The reading to draw: the store's, with what the one-offs leave (a run of full periods, a prop)."""
snapshot = store.snapshot()
for key, count in streaks.items():
if key in snapshot['accounts']:
@@ -666,45 +997,133 @@ def main():
snapshot['accounts'][key].update(trace=tier, trace_prop=prop)
else:
traces.pop(key, None)
+ return snapshot
+
+ def hold(until, seen, what, follows=True):
+ """Wait until `until` (moments.CLOCK) to send a picture drawn with the moment `what`; False as soon as the
+ moments or the readings change from `seen` (version()) or, when the picture follows them, what is due
+ changes with time (a hop, a sign, a wait let go, the hour of work done), or TokenTV stops. The kick is cleared
+ before each look, so a change between the look and the wait still ends it."""
+ while not stopping.is_set():
+ kick.clear()
+ if version() != seen or (follows and agents.wanted()[0] != what):
+ return False
+ now = moments.CLOCK.now()
+ if until <= now:
+ return True
+ turn = agents.next_change(now) # (a one-off's quiet loop, which follows no moment, looks again too)
+ moments.CLOCK.wait(kick, min(until, until if turn is None else turn) - now)
+ return False
+
+ def show(image, name, digest, what, receipts, where, paced=None):
+ """Send `image` and make it the one the clock shows, its loop starting as the switch is done; `what` is the
+ agent's moment in it, `paced` when its pace ticks stand. A bow, a treat or the break is then over: it plays
+ that one loop, and what follows is due as it ends."""
+ nonlocal last_upload
+ begun, on = moments.CLOCK.now(), {}
+ try:
+ slot, sent = device.put(name, image, digest)
+ receipts.extend(sent)
+ where['phase'] = "activate"
+ device.select(original, slot, on=lambda: on.update(at=moments.CLOCK.now(), wall=time.time()))
+ except Exception:
+ if shown['at'] is not None: # the old loop held while the clock tried: it ends that much later
+ shown['at'] += moments.CLOCK.now() - begun
+ last_upload = None # what the clock shows is unknown: the next picture goes in full, even this one
+ displayed['what'] = unsure
+ if on: # its slot went on before the old one failed to go off: its moment has been on the clock
+ agents.shown(what, on['at'], on['wall'])
+ elif what and what[0] == 'break': # still due: once more as the next loop ends (sync_moments), not before
+ failed['break'] += 1
+ failed['again'] = moments.loop_end(shown, moments.CLOCK.now() + .001) if failed['break'] == 1 else None
+ agents.shown(unsure, None)
+ raise
+ failed.update({'break': 0, 'again': None})
+ # Its loop starts once the switch is done: every request holds the clock's animation, the one turning the
+ # old slot off after the new one went on too (and every one of a full activation).
+ shown['at'], wall = moments.CLOCK.now(), time.time()
+ shown['loop'] = loop_seconds(image, device, frame_ms) if name == FILES[1] else None
+ last_upload = (name, digest)
+ pace['at'] = paced
+ displayed['what'] = what
+ agents.shown(what, shown['at'], wall)
+
+ def picture(snapshot, style, egg=None):
+ """(image, its file name, digest, when its pace ticks stand) for `snapshot` on `style`. Time passing alone
+ moves no pace tick on the clock (x4): a picture that differs from the clock's in its ticks alone is the
+ clock's own, its ticks where they stood; any other change draws them as they stand now."""
+ if style == 'arcade' and pace['at'] is not None and last_upload:
+ image = render_page(dict(snapshot, pace_at=pace['at']), 0, style, egg=egg)
+ name, digest = FILES[1] if image[:4] == b"GIF8" else FILES[0], hashlib.sha256(image).hexdigest()
+ if (name, digest) == last_upload:
+ return image, name, digest, pace['at']
+ at = time.time()
+ image = render_page(dict(snapshot, pace_at=at), 0, style, egg=egg)
+ return image, FILES[1] if image[:4] == b"GIF8" else FILES[0], hashlib.sha256(image).hexdigest(), at
+
+ def cycle(refresh=True, egg=None, came=None):
+ """Read (if `refresh`: `--once`; a running TokenTV reads in read_usage), 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 too. On Arcade the picture carries the
+ agents' moment due now, and one that changes while the loop plays out is drawn in before it goes; one due as
+ a one-off's quiet loop would follow it goes in that loop's place, and one due before a one-off's first
+ picture went on goes instead of the one-off (None: nothing sent). `came`: when the change it draws came in
+ (moments.CLOCK; now if not given), so the time a reading's one-offs take to pick puts it no later; a moment
+ the clock does not show yet goes no later than as the loop playing when it became due ends."""
+ nonlocal original, device
+ delivered = False
+ if refresh:
+ store.refresh()
+ snapshot = base()
style = preferences.snapshot()['style']
if not args.once and device:
receipts = []
- phase = "backup"
+ where = {'phase': "backup"}
+ what = None
try:
if original is None:
original = load_original(device, backup_path)
- phase = "upload"
- image = render_page(snapshot, 0, style, egg=egg)
- name = FILES[1] if image[:4] == b"GIF8" else FILES[0]
- digest = hashlib.sha256(image).hexdigest()
- if (name, digest) != last_upload: # identical frames are not rewritten to flash
- write_private(state_dir / name, image)
+ where['phase'] = "upload"
+ quiet_loop = egg if egg is not None and not getattr(egg, 'intro', True) else None
+ entry = egg is not None and quiet_loop is None # a one-off's own first picture: an event, a box's cut-in
+ came = moments.CLOCK.now() if came is None else came
+ for _ in range(25): # a storm of moments still ends in a picture
+ seen = version() # what it is drawn from (and `came`, when the first change of it came in)
+ snapshot = base() # (a reading that came in while the last one waited for its loop's end)
+ if quiet_loop is not None: # an agent's moment due as the one-off ends goes in its quiet loop's place
+ egg = None if style == 'arcade' and agents.wanted()[0] else quiet_loop
+ elif entry and style == 'arcade' and agents.wanted()[0]: # one came while it waited: it goes first
+ return None
+ follows = style == 'arcade' and egg is None # a one-off takes the whole loop: no moment in it
+ what, since, mark = agents.wanted() if follows else (None, None, None)
+ image, name, digest, paced = picture(moments.overlay(snapshot, what, mark), style, egg)
+ if (name, digest) == last_upload: # identical frames are not rewritten to flash
+ displayed['what'] = what
+ agents.shown(what, shown['at'])
+ break
+ if what is None: # a picture with an agent's moment in it is never kept
+ write_private(state_dir / name, image)
# The clock plays and answers on one core: while it takes a picture the animation holds. So
# the send and the switch go together as the loop ends: the loop plays out whole, holds a
- # moment, and the new one starts. An event or a box goes at once.
- if not (egg is not None and getattr(egg, 'intro', True)):
- stopping.wait(until_loop_end(shown, time.monotonic()))
- started = time.monotonic()
- try:
- slot, sent = device.put(name, image, digest)
- receipts.extend(sent)
- phase = "activate"
- device.select(original, slot)
- except Exception:
- if shown['at'] is not None: # the old loop held while the clock tried: it ends that much later
- shown['at'] += time.monotonic() - started
- last_upload = None # what the clock shows is unknown: the next picture goes in full, even this one
- raise
- shown['at'] = time.monotonic()
- shown['loop'] = gif_seconds(image) if name == FILES[1] else None
- last_upload = (name, digest)
- write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "uploads": receipts})
+ # moment, and the new one starts. A one-off's event or a box's cut-in waits for it too.
+ due = switch_at(shown, came, moments.CLOCK.now())
+ if follows and due is not None and what != displayed['what']: # as sync_moments would show it
+ due = min(due, switch_at(shown, since, moments.CLOCK.now()))
+ if due is not None and not hold(due, seen, what, follows):
+ if stopping.is_set():
+ return delivered
+ continue # a moment or a reading changed while the loop played out: draw it in
+ show(image, name, digest, what, receipts, where, paced)
+ break
+ if what is None: # receipts say nothing of the agents' moments
+ write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "uploads": receipts})
preferences.delivered(style, True)
# Pictures arrive; a clock asked for that another TokenTV drives is still worth saying.
preferences.problem('other_tokentv' if refused['url'] else None, refused['url'])
delivered = True
lost['polls'] = 0
except (OSError, ValueError, KeyError, HTTPException) as error:
+ phase = where['phase']
silent = swapped = False
if isinstance(error, BackupMismatch):
again = open_display(device.base_url) # guessed while the clock was off? ask it again
@@ -744,8 +1163,9 @@ def main():
lost['polls'] = 0
preferences.changed.set() # send to it now, not at the next poll
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,
- "reason": reason, "uploads": receipts, "http_status": getattr(error, "code", None)})
+ if what is None:
+ write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "status": "error",
+ "phase": phase, "reason": reason, "uploads": receipts, "http_status": getattr(error, "code", None)})
preferences.delivered(style, False)
snapshot['display'] = preferences.snapshot()
write_json(state_dir / "snapshot.json", snapshot)
@@ -759,25 +1179,111 @@ def main():
print(json.dumps(store.snapshot(), ensure_ascii=False, separators=(",", ":")))
return
- def play(egg, mark=True):
- """One one-off on the clock: the event, then for a unique or legend its quiet aftermath, then the usual face."""
+ def sync_moments():
+ """Bring the agents' moments to the clock (Claude Code waiting for you, a turn done) as the loop it is
+ playing ends: one upload per change of what it shows, none for the same again, never mid-loop. A change
+ asked for while the loop plays out is drawn in, not queued; a bow with no clock to bow on is dropped. The
+ break stays due: one the clock fails to take goes once more as the loop it then plays ends, and after that
+ with the clock's next picture. Nothing of it is written anywhere."""
+ for _ in range(25): # a storm of moments still ends in a picture
+ if stopping.is_set():
+ return
+ seen = version()
+ what, since, mark = agents.wanted()
+ if what == displayed['what']:
+ return
+ state = preferences.snapshot()
+ again = what is not None and what[0] == 'break' and failed['again'] is not None # its send failed once
+ if not device or state['style'] != 'arcade' or (state['status'] == 'error' and not again):
+ agents.drop_bow() # no picture of ours to follow: the next one carries the moment
+ return
+ if again: # the break once more as the loop after the failed send ends: the clock gets that loop
+ if moments.CLOCK.now() < failed['again']:
+ if not hold(failed['again'], seen, what) and stopping.is_set():
+ return
+ continue
+ failed['again'] = None
+ if last_upload is None: # nothing of this run's on the clock yet (its first reading not in), or what it
+ cycle(False) # shows is not known (a send failed): one in full, drawn from what TokenTV has, with the
+ continue # moment, at once or as the loop it holds ends
+ image, name, digest, paced = picture(moments.overlay(base(), what, mark), 'arcade')
+ due = switch_at(shown, since, moments.CLOCK.now()) # the end of the loop that was playing when it became due
+ if due is not None and not hold(due, seen, what):
+ if stopping.is_set():
+ return
+ continue # changed again while the loop played out: draw the newest instead
+ if (name, digest) == last_upload:
+ displayed['what'] = what
+ agents.shown(what, shown['at'])
+ continue
+ try:
+ show(image, name, digest, what, [], {}, paced)
+ except (OSError, ValueError, KeyError, HTTPException) as error:
+ agents.drop_bow() # (a break stays due)
+ reason = problem_of(error)
+ preferences.problem(reason, device.base_url, str(error) if reason in ('clock_full', 'error') else '')
+ preferences.delivered('arcade', False)
+ if failed['again'] is not None: # the break, not on the clock: once more as the next loop ends
+ continue
+ return
+ preferences.delivered('arcade', True)
+
+ def quiet_wait(seconds):
+ """Wait out a one-off's quiet loop; True when TokenTV stops or an agent's moment wants the clock first, the
+ break included, which comes due with time alone."""
+ end = moments.CLOCK.now() + seconds
+ while not stopping.is_set() and moments.CLOCK.now() < end:
+ kick.clear()
+ if agents.wanted()[0] != displayed['what']:
+ return True
+ turn = agents.next_change()
+ moments.CLOCK.wait(kick, min(end, end if turn is None else turn) - moments.CLOCK.now())
+ return stopping.is_set() or agents.wanted()[0] != displayed['what']
+
+ def play(egg, mark=True, came=None):
+ """One one-off on the clock: the event, then for a unique or legend its quiet aftermath, then the usual face.
+ True once its event went on; None when an agent's moment came while it waited for the loop's end and went
+ first (its turn comes again: put it back), False when it did not reach the clock. `came`: when the reading
+ that brought it came in (cycle)."""
+ went = False
try:
- if not cycle(False, egg):
+ went = cycle(False, egg, came)
+ if not went:
if mark and not isinstance(egg, str):
locks.forget() # never shown, so not seen: it may come again
- return
+ return went
if mark and getattr(egg, 'tier', None) in TRACE and getattr(egg, 'prop', ''): # in case it was missed
traces[egg.key] = (egg.tier, TRACE[egg.tier](time.time()), egg.prop)
# One loop of the event: the next picture is timed by cycle() to land as it ends, so its start never
# plays again. A unique or legend then keeps its quiet loop for the rest of its time.
seconds = getattr(egg, 'seconds', EGG_SECONDS)
+ event = shown['loop'] or LOOP_SECONDS # how long the event's one loop lasts on this clock
if getattr(egg, 'after', ()):
cycle(False, dataclasses.replace(egg, frames=egg.after, after=(), intro=False))
- if stopping.wait(max(0, seconds - LOOP_SECONDS - (shown['loop'] or 0))): # its last loop lands it
- return
+ if displayed['what'] not in (None, unsure): # an agent's moment went in the quiet loop's place
+ return True
+ if quiet_wait(max(0, seconds - event - (shown['loop'] or 0))): # its last loop lands it
+ return True
cycle(False)
except Exception:
print("TokenTV easter egg skipped.", flush=True)
+ return bool(went)
+
+ def read_usage():
+ """Read every account (a provider may take its time) apart from the clock's work, so that no agent's moment
+ waits for it: the moments keep their loop ends with the last reading. The clock is told once it is in."""
+ try:
+ store.refresh()
+ except Exception:
+ # Never serialize exception text, which may include auth material.
+ print("TokenTV poll failed; retained previous snapshot.", flush=True)
+ try:
+ agents.observe(store.snapshot()) # who is at work, for the pets' break
+ except Exception:
+ print("TokenTV moment skipped.", flush=True)
+ readings['count'] += 1
+ kick.set() # a picture waiting for its loop's end is drawn again with this reading
+ preferences.changed.set('reading')
def poll():
nonlocal device
@@ -785,75 +1291,142 @@ def main():
device = open_display(config["device_url"]) if config.get("device_url") else None
except ValueError:
pass # an address edited into the config by hand: follow_clock says what is wrong with it
- next_refresh = 0
+ next_refresh, reading = 0, None
while not stopping.is_set():
- preferences.changed.clear()
- refresh = time.monotonic() >= next_refresh
- try:
- cycle(refresh)
- except Exception:
- # Never serialize exception text, which may include auth material.
- print("TokenTV poll failed; retained previous snapshot.", flush=True)
+ if moments.CLOCK.now() >= next_refresh and not (reading and reading.is_alive()):
+ next_refresh = moments.CLOCK.now() + interval
+ # One reading at a time, never waited for: it wakes this loop once it is in, and is drawn then. Till
+ # then everything goes on with what TokenTV has, the first picture of a run included if a moment
+ # needs the clock before the first reading (sync_moments).
+ reading = threading.Thread(target=read_usage, name='TokenTV reading', daemon=True)
+ reading.start()
+ why, came = preferences.changed.take(), moments.CLOCK.now() # what changed, and when it came in
+ new_reading = 'reading' in why
+ if new_reading:
+ try:
+ follow_clock() # the clock's address in the config, looked at again with each reading
+ except Exception:
+ # Never serialize exception text, which may include auth material.
+ print("TokenTV poll failed; retained previous snapshot.", flush=True)
arcade_on = preferences.snapshot()['style'] == 'arcade'
if not arcade_on:
pending.clear() # another face now (even for a moment): what was waiting is not played later
- if refresh:
- next_refresh = time.monotonic() + interval
- if device:
- # A one-off: a window that just reset or ran out, else a hidden box whose moment has
- # come. It plays once on the clock, then the usual face comes back. Events are noted
- # under any face, but played only on Arcade, never saved up for later.
- snap = store.snapshot()
- rows = [dict(row, key=key) for key, row in snap['accounts'].items()]
- fresh = sorted((row['event_at'], row['key'], row['event']) for row in rows
- if row.get('event') and row.get('event_at', 0) > seen_events.get(row['key'], started))
- for at, key, kind in fresh:
- seen_events[key] = at
- if not arcade_on:
- continue
- if kind == 'full': # how many periods in a row now, for the scenes that count them
- try:
- locks.history.observe(snap, time.time())
- streaks[key] = max(locks.history.full_streak(key, time.time()),
- locks.history.five_hour_run(key))
- except (OSError, ValueError):
- streaks[key] = 1 # history out of reach: the event still plays
- pending.append(f"{kind}@{key}")
- try:
- egg = (pending.pop(0) if pending else locks.pick(snap)) if arcade_on else None
- except (OSError, ValueError):
- egg = None
- print("TokenTV hidden one-offs skipped.", flush=True)
- if egg:
- play(egg)
- while device and replays: # asked for from the collection book: play it again now
- egg = locks.replay(replays.pop(0))
- if egg:
- play(egg, mark=False)
- preferences.changed.wait(max(0, next_refresh - time.monotonic()))
+ egg = None
+ if new_reading and device:
+ # A one-off: a window that just reset or ran out, else a hidden box whose moment has
+ # come. It plays once on the clock, then the usual face comes back. Events are noted
+ # under any face, but played only on Arcade, never saved up for later.
+ snap = store.snapshot()
+ rows = [dict(row, key=key) for key, row in snap['accounts'].items()]
+ fresh = sorted((row['event_at'], row['key'], row['event']) for row in rows
+ if row.get('event') and row.get('event_at', 0) > seen_events.get(row['key'], started))
+ for at, key, kind in fresh:
+ seen_events[key] = at
+ if not arcade_on:
+ continue
+ if kind == 'full': # how many periods in a row now, for the scenes that count them
+ try:
+ locks.history.observe(snap, time.time())
+ streaks[key] = max(locks.history.full_streak(key, time.time()),
+ locks.history.five_hour_run(key))
+ except (OSError, ValueError):
+ streaks[key] = 1 # history out of reach: the event still plays
+ pending.append(f"{kind}@{key}")
+ # An agent's moment comes first: no one-off starts while one is due or on the clock.
+ busy = agents.busy() or displayed['what'] not in (None, unsure)
+ try:
+ egg = (pending.pop(0) if pending else locks.pick(snap)) if arcade_on and not busy else None
+ except (OSError, ValueError):
+ egg = None
+ print("TokenTV hidden one-offs skipped.", flush=True)
+ # A one-off the reading brings goes on in place of its picture: the one-off's own pictures and the usual
+ # face after them show the reading, so the clock takes one picture for it, never two at once. Either goes
+ # as the loop playing when the reading came in ends, however long the pick took.
+ went = play(egg, came=came) if egg else False
+ if went is None and isinstance(egg, str):
+ pending.insert(0, egg) # an agent's moment came first: the event waits its turn again
+ if not went and (new_reading or why - {'moment'}): # a moment alone is sync_moments' to show
+ try:
+ cycle(False, came=came)
+ except Exception:
+ # Never serialize exception text, which may include auth material.
+ print("TokenTV poll failed; retained previous snapshot.", flush=True)
+ # Asked for from the collection book: played now, or once an agent's moment is off the clock.
+ while device and replays and not (agents.busy() or displayed['what'] not in (None, unsure)):
+ check = replays.pop(0)
+ egg = locks.replay(check)
+ if egg and play(egg, mark=False) is None:
+ replays.insert(0, check) # (one came first: once it is over)
+ try:
+ sync_moments()
+ except Exception:
+ print("TokenTV moment skipped.", flush=True)
+ if device and replays and not (agents.busy() or displayed['what'] not in (None, unsure)):
+ continue # a replay waited for a moment that is over now
+ due = agents.next_change() # a wait grows more insistent, or is let go, on time without a poll
+ # and for the next reading, unless one is still under way (that one says when it is in)
+ times = [t for t in (due, None if reading.is_alive() else next_refresh) if t is not None]
+ until = min(times) if times else moments.CLOCK.now() + interval
+ moments.CLOCK.wait(preferences.changed, until - moments.CLOCK.now())
try: # the dashboard's port first: if another program has it, stop before touching the clock
local = args.host in LOCAL_NAMES # bound to this computer only: answer only by its own names
names = None if local else lan_names(args.host) # on the network: by its names and addresses there
notice = UpdateNotice(state_dir, enabled=config.get('update_check', True))
server = QuietServer((args.host, args.port), handler(store, preferences, locks, replays, preferences.changed, local, names,
- notice))
+ notice, agents, pace=pace))
except OSError as error:
raise SystemExit(f"Port {args.port} is in use on this computer ({error.strerror or error}). "
f"Pass another with --port, or use {start_command()}, which picks a free one.")
+ # The moments again on a socket of its own in the state folder, for the Claude Code mod (Linux and macOS):
+ # what goes over it meets no proxy and is never redirected to another program or computer.
+ sock_path, sock_server = state_dir / "live.sock", None
+ if hasattr(socketserver, 'ThreadingUnixStreamServer') and not moments.WINDOWS:
+ try:
+ sock_path.unlink(missing_ok=True) # one left by a run that ended without its cleanup
+ sock_server = MomentSocket(str(sock_path), handler(store, preferences, agents=agents, moments_only=True))
+ os.chmod(sock_path, 0o600)
+ atexit.register(sock_path.unlink, missing_ok=True)
+ except OSError as error: # a path too long for a socket, say
+ if sock_server:
+ sock_server.server_close()
+ sock_server = None
+ # The Claude Code mod and Codex's notify send here alone on Linux and macOS: say so, once.
+ print(f"TokenTV could not open its socket for Claude Code's and Codex's moments in {state_dir} "
+ f"({error.strerror or error}); the clock will not show them.", flush=True)
thread = threading.Thread(target=poll, daemon=True)
thread.start()
threading.Thread(target=notice.watch, args=(stopping,), daemon=True).start()
+ if sock_server:
+ threading.Thread(target=sock_server.serve_forever, daemon=True).start()
+ # Asked to stop (as systemd and launchd stop it, or `kill`): it ends as Ctrl+C ends it, its address and socket
+ # gone with it, so no agent goes on telling a port another program may hold next. (Windows ends it outright.)
+ told = None
+ if os.name != 'nt' and threading.current_thread() is threading.main_thread():
+ def asked_to_stop(signum, frame):
+ signal.signal(signal.SIGTERM, signal.SIG_IGN) # asked once: a second one does not cut the cleanup short
+ raise KeyboardInterrupt
+ told = signal.signal(signal.SIGTERM, asked_to_stop)
try:
with server:
print(f"TokenTV live listening at http://{args.host}:{args.port}", flush=True)
+ if ready:
+ ready(server)
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
stopping.set()
+ kick.set()
preferences.changed.set()
thread.join(timeout=2)
+ if sock_server:
+ sock_server.shutdown()
+ sock_server.server_close()
+ sock_path.unlink(missing_ok=True)
+ (state_dir / "live.url").unlink(missing_ok=True) # stopped: the agents find no TokenTV to tell
+ if told is not None:
+ signal.signal(signal.SIGTERM, told)
if __name__ == "__main__":
diff --git a/token_tv/lockbox.py b/token_tv/lockbox.py
index aab7e94..b43524c 100644
--- a/token_tv/lockbox.py
+++ b/token_tv/lockbox.py
@@ -14,7 +14,8 @@ each time its situation comes about (not every minute it lasts). The odds are se
whole: each rare or unique tier aims at one opening every `PACE` days, shared by the boxes of that tier
whose situations come about on this clock, so a box whose situation comes daily gets small odds and one
that comes weekly gets large ones, and a box that comes less often than its share opens every time (doubled
-until first seen; sure once a box is twice its share overdue).
+until first seen; once a box is a share overdue its odds climb, sure at twice its share, like a game's bad-luck
+protection without a cliff).
A win waits a random moment while the situation holds; a cooldown keeps one scene from repeating soon,
two of a tier keep `SPACING` apart, and two hidden one-offs keep `GAP` apart unless the second is a legend.
"""
@@ -83,6 +84,12 @@ def odds(count, days, share, first):
return min(1.0, (2 if first else 1) / max(share * per_day(count, days), 1e-9))
+def overdue(chance, late):
+ """A box's chance when `late` shares have passed since it last opened (or was first met): as it was up to one,
+ then climbing in a straight line to sure at two."""
+ return 1.0 if late >= 2 else chance + (1 - chance) * max(0.0, late - 1)
+
+
def daypart(hour):
"""midnight 0–1, night 2–4, dawn 5, morning 6–11, afternoon 12–17, evening 18–21, late 22–23."""
for end, name in ((2, 'midnight'), (5, 'night'), (6, 'dawn'), (12, 'morning'), (18, 'afternoon'),
@@ -408,7 +415,8 @@ class Lockbox:
def odds_now(self, record, check, tier, now):
"""This occurrence's chance: sure for a box sealed sure and for the tiers without a pace, else the box's
- share of its tier's pace, sure once twice its share has passed since it last opened (or was first met)."""
+ share of its tier's pace, climbing once a share has passed since it last opened (or was first met), sure at
+ two."""
if record.get('chance', 1) >= 1 or tier not in PACE:
return 1.0
data = self.history.data
@@ -416,9 +424,10 @@ class Lockbox:
rates = [per_day(m['count'], (now - m['first']) / 86400) for c, m in met.items()
if m.get('tier') == tier and now - held.get(c, 0) < MET_DAYS * 86400]
share, seen = shares(rates, PACE[tier]), met[check]
- if now - fired.get(check, seen['first']) >= 2 * share * 86400:
- return 1.0
- return odds(seen['count'], (now - seen['first']) / 86400, share, check not in fired)
+ chance = odds(seen['count'], (now - seen['first']) / 86400, share, check not in fired)
+ if share <= 0: # every box of the tier comes about less often than the pace: each opens every time
+ return chance
+ return overdue(chance, (now - fired.get(check, seen['first'])) / (share * 86400))
def forget(self):
"""The last pick never reached the screen: take it back, so it is neither seen nor resting."""
diff --git a/token_tv/moments.py b/token_tv/moments.py
new file mode 100644
index 0000000..0757293
--- /dev/null
+++ b/token_tv/moments.py
@@ -0,0 +1,532 @@
+"""What the agents are doing right now (v2): Claude Code waiting for you, a turn done, Clawd petted or given a snack,
+and the pets' break once an hour of work.
+
+A moment arrives as its name and nothing else (MOMENTS): from the TokenTV mod in Claude Code (claude-plugin/) and
+from Codex's notify program (`token-tv notify`). TokenTV keeps what they mean in memory only, never on disk and never
+in a log, so a restart forgets them. The break comes from the usage readings alone (Work). Time here is CLOCK's,
+which a test or a grader can replace to run a half-hour wait at once; the readings' times are the wall clock's
+(`time.time()`), which moves with it.
+"""
+import bisect
+import json
+import math
+import os
+import random
+import socket
+import sys
+import threading
+import time
+from http.client import HTTPConnection, HTTPException
+from pathlib import Path
+
+MOMENTS = ('claude.ask', 'claude.answered', 'claude.end', 'codex.end', 'claude.pet', 'claude.snack')
+HOP, SIGN = 5 * 60, 15 * 60 # seconds waited before Clawd hops, and before it holds up a sign (arcade.NEEDS_LEVELS)
+EXPIRE = 30 * 60 # the waits are let go this long after the continuous wait began, answered or not
+COOLDOWN = 60 # at most one bow in any 60 s, Claude's and Codex's together; one asked for inside it is dropped
+TREATS = {'claude.pet': 'pet', 'claude.snack': 'snack'} # /tokentv pet and /tokentv snack: one loop of Clawd's
+WORK = 60 * 60 # an hour of work, any account's, since the last break (or the last reminder) brings one...
+BREAK = 10 * 60 # ...where a break is this long with no account at work (its own length, not state.ACTIVE_SECONDS)
+BREAKS = ('drink', 'stretch') # the reminder: a glass of water or a stretch for the pets on the clock
+RANDOM = random.Random() # picks each reminder's break, once (a test or a grader seeds it, or puts its own here)
+BODY_LIMIT = 256 # bytes: the most a moment's request may carry
+WINDOWS = os.name == 'nt' # no TokenTV socket there: its port on this computer instead
+
+
+# Elapsed time that keeps counting while the computer sleeps, as the clock on the desk and the mods' own clocks do:
+# a wait that spans a laptop's sleep is as old as it looks. (time.monotonic() stops then on Linux and macOS.)
+if sys.platform.startswith('linux') and hasattr(time, 'CLOCK_BOOTTIME'):
+ def elapsed():
+ return time.clock_gettime(time.CLOCK_BOOTTIME)
+elif sys.platform == 'darwin' and hasattr(time, 'CLOCK_MONOTONIC'):
+ def elapsed():
+ return time.clock_gettime(time.CLOCK_MONOTONIC) # macOS's counts sleep; time.monotonic()'s does not
+else:
+ elapsed = time.monotonic
+
+
+class Clock:
+ """Elapsed seconds and waits that end early when an event is set. The moments and the clock's loop run on it;
+ a test or a grader puts a fake one in `CLOCK` to run thirty minutes in a moment."""
+ def now(self):
+ return elapsed()
+
+ def wait(self, event, seconds):
+ """Wait until `event` is set or `seconds` have passed; True when the event was set. Looked at again every
+ few seconds: a wait's own timer stops while the computer sleeps, the time here does not."""
+ end = elapsed() + max(0, seconds)
+ while True:
+ left = end - elapsed()
+ if left <= 0:
+ return event.is_set()
+ if event.wait(min(left, 5)):
+ return True
+
+
+CLOCK = Clock()
+
+
+def number(value):
+ """A time or an amount as a reading gives one: a finite int or float (not a bool)."""
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
+
+
+class Work:
+ """How long the accounts have worked toward the pets' next break (e6), on the wall clock, as the readings tell
+ it: working is any account at work (its usage rose within `active` seconds, state.ACTIVE_SECONDS, as Arcade's
+ `active`), their times together, never added up, whatever order the readings come in: a rise read late counts
+ for when it was measured. An hour of it makes the reminder due, once; BREAK in a row with none at work starts the
+ hour over (a reminder not yet shown goes with it), and so does a reminder going on the clock. None pile up.
+
+ A break is settled by the rise that ends it, at the readings' own times: one at exactly BREAK after the last
+ account stopped counting as at work starts the hour over; one a moment sooner does not, nor one that a rise read
+ later falls in. Till then, a reminder due through BREAK with none at work is not shown (rested).
+
+ An account at work as its readings began to fail (rate limited, an outage: its last rise within `active` of its
+ last good reading) is neither at work nor resting from that good reading until one comes in again, for at most
+ WORK: that time counts toward neither the hour nor a break. Failing longer (a computer asleep, an account let
+ go), the rest of it counts as rest.
+
+ The rises are kept and the hour counted from them again as they change; those older than KEEP before the latest
+ reading are summed up (`base`), as is all before a reminder that went on."""
+ KEEP = 2 * 60 * 60 # seconds: no reading comes in that late (a snapshot file goes OLD in a quarter of an hour)
+ READ = ('ok', 'quota_unavailable') # a reading that came in, with numbers or without; any other status failed
+
+ def __init__(self, active=None):
+ if active is None:
+ from token_tv.state import ACTIVE_SECONDS as active # here: `token-tv notify` loads no more than it needs
+ self.active = active
+ self.seen = {} # account key -> its rose_at as last read: another is a rise
+ self.failing = {} # account key -> while its readings fail: since when it is held (at work then), or None
+ self.held = [] # [(from, to)]: an account at work whose readings failed, till one came in again
+ self.rises = [] # the rises counted from `base` on, oldest first
+ # The hour as summed up: (from when the rises count, when the hour began, the work in it by then, when the
+ # reminder fell due, when the work before ended); nothing yet, at first.
+ self.base = (None, None, 0.0, None, None)
+ self.last = None # the latest rise of any account
+ self.mark = None # how far the readings tell (the latest reading's time)
+ self.kind = None # the break picked for the reminder due now: once, as it falls due
+ self.counted = None # count() of the rises as they stand, till they change
+ self.start, self.credit, self.due = None, 0.0, None # up to `mark`: the hour's start, its work, the reminder
+
+ def observe(self, rows, now):
+ """The rises in a reading (`rows`: a snapshot's accounts), and whose readings fail, as of the wall clock's
+ `now`."""
+ for key, row in rows.items():
+ if not isinstance(row, dict):
+ continue
+ at = row.get('rose_at')
+ if number(at) and at != self.seen.get(key):
+ self.seen[key] = at
+ self.rise(min(at, now))
+ self.reading(key, row)
+ self.advance(now)
+ self.trim()
+
+ def reading(self, key, row):
+ """Whether `key`'s reading came in: one at work as its readings began to fail is held till one does."""
+ status = row.get('status')
+ if status in self.READ:
+ began = self.failing.pop(key, None)
+ if began is not None: # in again: neither at work nor resting from its last good reading to this one
+ good = row.get('last_success_at')
+ self.held.append((began, good if number(good) and good > began else began))
+ self.counted = None
+ elif isinstance(status, str) and status != 'loading' and key not in self.failing:
+ good, rose = row.get('last_success_at'), row.get('rose_at')
+ self.failing[key] = good if number(good) and number(rose) and good - rose < self.active else None
+ if self.failing[key] is not None:
+ self.counted = None
+
+ def holding(self, start, end):
+ """Seconds of [start, end) when an account at work could not be read (each for at most WORK)."""
+ spans = sorted([(a, min(b, a + WORK)) for a, b in self.held] +
+ [(a, a + WORK) for a in self.failing.values() if a is not None])
+ total, reach = 0.0, start
+ for a, b in spans:
+ a, b = max(a, reach), min(b, end)
+ if b > a:
+ total, reach = total + b - a, b
+ return total
+
+ def rise(self, at):
+ """An account's usage rose at `at`, read in whatever order: it counts for when it was measured."""
+ since, start, credit, due, ended = self.base
+ if since is not None and at + self.active <= since: # its work ended before what is summed up: only its edge
+ self.base = (since, start, credit, due, at + self.active if ended is None else max(ended, at + self.active))
+ else:
+ bisect.insort(self.rises, at)
+ self.last = at if self.last is None else max(self.last, at)
+ self.counted = None
+
+ def spans(self):
+ """When someone was at work by the rises kept: [[from, to]], oldest first, none touching another."""
+ out = []
+ for at in self.rises:
+ if out and at <= out[-1][1]:
+ out[-1][1] = max(out[-1][1], at + self.active)
+ else:
+ out.append([at, at + self.active])
+ return out
+
+ def count(self, upto=None):
+ """(when the hour began, the work in it, when the reminder fell due or would, when the work known ends): the
+ rises from `base` on, counted to the end of the work they tell (or up to `upto`)."""
+ since, start, credit, due, ended = self.base
+ for begin, end in self.spans():
+ if upto is not None and begin >= upto:
+ break
+ if (ended is not None and (since is None or begin > since)
+ and begin - ended - self.holding(ended, begin) >= BREAK):
+ start, credit, due = begin, 0.0, None # a break before it: the hour starts over at it
+ if start is None:
+ start = begin
+ low = max(begin, start) if since is None else max(begin, start, since)
+ high = end if upto is None else min(end, upto)
+ if high > low:
+ if due is None and credit + (high - low) >= WORK - 1e-6:
+ due = low + max(0.0, WORK - credit)
+ credit += high - low
+ ended = end if ended is None else max(ended, end)
+ return start, credit, due, ended
+
+ def advance(self, now):
+ """Count the hour's work up to `now`: the reminder falls due as the hour completes."""
+ self.mark = now if self.mark is None else max(self.mark, now)
+ if self.counted is None:
+ self.counted = self.count()
+ start, credit, due, ended = self.counted
+ self.start = start
+ self.credit = credit if ended is None else max(0.0, credit - max(0.0, ended - self.mark))
+ if due is not None and due <= self.mark + 1e-6:
+ if self.kind is None:
+ self.kind = RANDOM.choice(BREAKS) # its break, picked once as it falls due
+ self.due = (due, self.kind)
+ else:
+ self.due = self.kind = None
+
+ def trim(self):
+ """Sum up the rises older than KEEP before the latest reading, so that a long run keeps a short list."""
+ if self.mark is None or not self.rises or self.rises[0] + self.active > self.mark - self.KEEP:
+ return
+ upto = self.mark - self.KEEP
+ self.base = (upto, *self.count(upto))
+ self.rises = [at for at in self.rises if at + self.active > upto]
+ self.prune()
+
+ def prune(self):
+ """Let go of the holds over before the work summed up ended: no break after it can take from them."""
+ ended = self.base[4]
+ if ended is not None:
+ self.held = [(a, b) for a, b in self.held if min(b, a + WORK) > ended]
+ self.counted = None
+
+ def rested(self, now):
+ """Whether nobody has been at work for BREAK by `now`, the time an account at work could not be read left out
+ (the rise that ends it settles the break)."""
+ if self.last is None:
+ return False
+ if self.counted is None:
+ self.counted = self.count()
+ ended = self.counted[3]
+ return now - ended - self.holding(ended, now) >= BREAK
+
+ def next_due(self, now):
+ """When the reminder falls due if the work goes on as it is (no new rise needed), or None."""
+ self.advance(now)
+ due = self.counted[2]
+ return due if self.due is None and due is not None else None
+
+ def shown(self, at):
+ """The reminder went on the clock at `at`: the next hour counts from there."""
+ self.advance(at)
+ ended = self.base[4]
+ for rise in self.rises:
+ if rise + self.active <= at: # (its work over by then: only where it ended counts, for a break after)
+ ended = rise + self.active if ended is None else max(ended, rise + self.active)
+ self.rises = [rise for rise in self.rises if rise + self.active > at]
+ self.base = (at, at, 0.0, None, ended)
+ self.kind = None
+ self.prune()
+ self.advance(at)
+
+
+class Moments:
+ """The moments, as what the clock should show now: Claude waiting (outstanding waits counted across sessions,
+ as old as the first continuous wait, more insistent at HOP and SIGN), one bow when a turn ends, Clawd petted or
+ given a snack (/tokentv pet, /tokentv snack), the pets' break after an hour of work (Work), or the usual face. A
+ wait outranks the rest; a bow is dropped, never queued, inside COOLDOWN.
+
+ The waits come as names only: each ask counts one more, each answer one fewer. The wait ends when the count is
+ back to none, or EXPIRE after the continuous wait began, whichever comes first; then everything counted is let
+ go (an answer with none counted closes nothing), and the next ask starts a new wait at the hand.
+
+ A pet or a snack plays one loop of Clawd's. One asked for while another is still to show or showing is dropped,
+ and so is one asked for while Claude waits; a wait drops one not shown yet. Nothing is queued: what is not shown
+ is gone. A break due while Claude waits plays after it, if the work did not stop for a break meanwhile, and one
+ the clock could not take stays due till it can. Each of these takes its own loop, a bow first, then a treat,
+ then the break.
+
+ wanted() says what is due and since when, for the publisher to show at the end of the loop the clock is playing
+ then; shown() is told when a picture went on the clock (a bow, a treat or the break plays that one loop, and what
+ follows is due after it)."""
+
+ def __init__(self, services, wake=None, active=None):
+ self.services = set(services) # the services this TokenTV shows: a moment of any other is ignored
+ self.wake = wake # called when what the clock should show changes
+ self.lock = threading.Lock()
+ self.waits = 0 # Claude waits outstanding, every session's
+ self.since = None # when the continuous wait on the clock began
+ self.started = None # the same, on the wall clock (the drawing's `since`)
+ self.bow = None # (service, when it was asked for, the same on the wall clock): a bow due at the loop's end
+ self.bowed = None # when the last bow went on the clock: the cooldown runs from there
+ self.treat = None # ('pet' or 'snack', when it was asked for): one loop of Clawd's at the loop's end
+ self.on = None # what the clock last started showing: a press while a treat is on it is dropped
+ self.work = Work(active) # the hour of work toward the pets' break
+ self.calm = 0.0 # when the usual face last became due
+ self.count = 0 # goes up with every change of what is due, so a waiting publisher knows to look again
+
+ def note(self, name):
+ """Take one moment by name; True when it changed what the clock should show. Unknown names: ValueError."""
+ if name not in MOMENTS:
+ raise ValueError('Unknown moment')
+ service = name.partition('.')[0]
+ if service not in self.services: # nothing of it is shown, nor kept for a service added later
+ return False
+ with self.lock:
+ now = CLOCK.now()
+ self.expire(now)
+ before = self.due(now)[0]
+ if name == 'claude.ask':
+ if not self.waits:
+ self.since, self.started = now, time.time()
+ self.waits += 1
+ self.bow = self.treat = None # a wait outranks them; one put off is dropped, not kept for later
+ elif name == 'claude.answered':
+ if self.waits: # (an answer with none counted, from a wait already let go, closes nothing)
+ self.waits -= 1
+ if not self.waits:
+ self.since = self.started = None
+ self.calm = now
+ elif name in TREATS:
+ if not (self.waits or self.treat or (self.on is not None and self.on[0] == 'treat')):
+ self.treat = (TREATS[name], now)
+ elif not (self.waits or self.bow or self.cooling(now)):
+ self.bow = (service, now, time.time())
+ changed = self.due(now)[0] != before
+ if changed:
+ self.count += 1
+ if changed and self.wake:
+ self.wake()
+ return changed
+
+ def observe(self, snapshot):
+ """Take a reading of the usage (the store's snapshot) for the pets' break: an account whose usage rose is at
+ work. True when that changed what the clock should show."""
+ with self.lock:
+ now = CLOCK.now()
+ before = self.due(now)[0] # as the publisher last saw it: the hour may be done since
+ self.expire(now)
+ self.work.observe(snapshot.get('accounts') or {}, self.walls(now))
+ changed = self.due(now)[0] != before
+ if changed:
+ self.count += 1
+ if changed and self.wake:
+ self.wake()
+ return changed
+
+ def walls(self, now):
+ """The wall clock's time at CLOCK's `now`: the readings' times are its."""
+ return time.time() - (CLOCK.now() - now)
+
+ def expire(self, now, wall=None):
+ if self.waits and self.since + EXPIRE <= now: # waited EXPIRE in all: every wait counted is let go
+ self.calm = self.since + EXPIRE # due from the deadline itself, however late it is looked at
+ self.waits, self.since, self.started = 0, None, None
+ self.count += 1
+ due = self.work.due
+ self.work.advance(self.walls(now) if wall is None else wall)
+ if self.work.due != due: # the hour of work is done
+ self.count += 1
+
+ def cooling(self, now):
+ return self.bowed is not None and now - self.bowed < COOLDOWN
+
+ def resting(self, now):
+ """The break the pets are due, as (when it fell due on CLOCK, which break), or None."""
+ wall = self.walls(now)
+ if self.work.due is None or self.work.rested(wall):
+ return None
+ at, kind = self.work.due
+ return now - (wall - at), kind
+
+ def due(self, now):
+ """(what, since when): ('needs', level), ('done', service), ('treat', 'pet' or 'snack'), ('break', 'drink' or
+ 'stretch'), or None for the usual face."""
+ if self.waits:
+ waited = now - self.since
+ level = 3 if waited >= SIGN else 2 if waited >= HOP else 1
+ return ('needs', level), self.since + (0, 0, HOP, SIGN)[level]
+ if self.bow:
+ return ('done', self.bow[0]), self.bow[1]
+ if self.treat:
+ return ('treat', self.treat[0]), self.treat[1]
+ rest = self.resting(now)
+ if rest: # due since the hour was done, or since what kept it off the clock ended
+ return ('break', rest[1]), max(rest[0], self.calm)
+ return None, self.calm
+
+ def wanted(self, now=None):
+ """(what, since when, the row's `moment` for the drawing or None) for the clock now."""
+ with self.lock:
+ now = CLOCK.now() if now is None else now
+ self.expire(now)
+ what, since = self.due(now)
+ if what is None:
+ mark = None
+ elif what[0] == 'needs':
+ mark = {'kind': 'needs', 'since': self.started, 'level': what[1]}
+ elif what[0] == 'done':
+ mark = {'kind': 'done', 'at': self.bow[2]}
+ else:
+ mark = {'kind': what[1]}
+ return what, since, mark
+
+ def waited(self):
+ """Seconds the continuous Claude wait has lasted, or None with no wait open: TokenTV's answer to an ask says
+ it, so the mod that asked knows when TokenTV lets that wait go, and sends no answer after (it would close
+ another, newer wait)."""
+ with self.lock:
+ now = CLOCK.now()
+ self.expire(now)
+ return now - self.since if self.waits else None
+
+ def next_change(self, now=None):
+ """When what is due changes by itself (a wait grows more insistent or is let go, the hour of work is done);
+ None when nothing will."""
+ with self.lock:
+ now = CLOCK.now() if now is None else now
+ wall = self.walls(now)
+ self.expire(now, wall)
+ times = [t for t in (self.since + HOP, self.since + SIGN, self.since + EXPIRE) if t > now] if self.waits else []
+ done = self.work.next_due(wall) # (counted to `wall` already: nothing changes here)
+ if done is not None:
+ times.append(now + max(1e-6, done - wall))
+ return min(times) if times else None
+
+ def busy(self):
+ """Whether a wait, a bow, a treat or the break is due: the hidden one-offs keep out of their way."""
+ with self.lock:
+ now = CLOCK.now()
+ self.expire(now)
+ return bool(self.waits or self.bow or self.treat or self.resting(now))
+
+ def shown(self, what, at, wall=None):
+ """The clock started showing `what` at `at` (CLOCK; `wall`, the wall clock then): a bow, a treat or the break
+ plays that one loop, and what follows is due after it."""
+ with self.lock:
+ self.on = what
+ if not what:
+ return
+ if what[0] == 'done' and self.bow and self.bow[0] == what[1]:
+ self.bow, self.bowed, self.calm = None, at, at
+ self.count += 1
+ elif what[0] == 'treat' and self.treat and self.treat[0] == what[1]:
+ self.treat, self.calm = None, at
+ self.count += 1
+ elif what[0] == 'break' and self.work.due and self.work.due[1] == what[1]:
+ self.work.shown(self.walls(at) if wall is None else wall)
+ self.calm = at
+ self.count += 1
+
+ def drop_bow(self):
+ """No clock to bow on now (none set, another face, or it does not answer): the bow is dropped, and does not
+ hold the next one back; so is a pet or a snack. The break stays due: it goes when the clock takes a picture
+ of ours again, and its hour counts again only once it is on the clock (shown)."""
+ with self.lock:
+ if self.bow or self.treat:
+ self.bow = self.treat = None
+ self.count += 1
+
+
+def overlay(snapshot, what, mark):
+ """`snapshot` with the moment on the rows of its service (Claude's wait or treat, or the service that bows), or
+ on every row for the break: a copy, for drawing only. Nothing is added: a service without an account has no row
+ to mark."""
+ if what is None:
+ return snapshot
+ service = None if what[0] == 'break' else 'claude' if what[0] in ('needs', 'treat') else what[1]
+ accounts = {key: dict(row, moment=dict(mark)) if service in (None, row.get('provider')) else row
+ for key, row in snapshot.get('accounts', {}).items()}
+ return dict(snapshot, accounts=accounts)
+
+
+def loop_end(shown, at):
+ """When the loop the clock is playing at `at` ends: the first end of a loop at or after `at`, counted from the
+ picture's start ('at') and its loop ('loop'); None when nothing loops there (send at once)."""
+ if shown.get('at') is None or not shown.get('loop'):
+ return None
+ loops = max(1, math.ceil((at - shown['at']) / shown['loop'] - 1e-9))
+ return shown['at'] + loops * shown['loop']
+
+
+# --- Sending one (Codex's notify) --------------------------------------------------------------------------------
+
+LOOPBACK = {'127.0.0.1': '127.0.0.1', 'localhost': '127.0.0.1', '[::1]': '::1'}
+
+
+def address(text):
+ """(host, port) of a running TokenTV from its live.url, only when that is this computer's loopback (127.0.0.1,
+ localhost or [::1]) with a port and nothing else; else None. Nothing is looked up: a name that is not one of
+ these, or anything with a path, a user or a query, is not ours to send to."""
+ text = (text or '').strip()
+ if not text.startswith('http://'):
+ return None
+ host, sep, port = text[7:].rpartition(':')
+ if not sep or host not in LOOPBACK or not port.isdigit() or len(port) > 5 or not 0 < int(port) < 65536:
+ return None
+ return LOOPBACK[host], int(port)
+
+
+class UnixConnection(HTTPConnection):
+ """HTTP over TokenTV's own socket in its state folder: no proxy, no other program, nothing to redirect to."""
+ def __init__(self, path, host, timeout):
+ super().__init__(host, timeout=timeout)
+ self.path = path
+
+ def connect(self):
+ self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ self.sock.settimeout(self.timeout)
+ self.sock.connect(self.path)
+
+
+def post(state_dir, name, timeout=1.0):
+ """Tell the TokenTV whose state folder is `state_dir` the moment `name`; True once it took it. Quiet whatever
+ happens: no TokenTV running, no answer. Nothing is retried or kept. On Linux and macOS it goes only over
+ TokenTV's socket (live.sock): a live.url without it may be left from a TokenTV that stopped, its port another
+ program's now. On Windows, to TokenTV's port on this computer."""
+ if name not in MOMENTS:
+ raise ValueError('Unknown moment')
+ state_dir = Path(state_dir)
+ try:
+ place = address((state_dir / 'live.url').read_text(encoding='utf-8'))
+ except (OSError, UnicodeError):
+ return False
+ if place is None:
+ return False
+ host, port = place
+ netloc = f'[{host}]:{port}' if ':' in host else f'{host}:{port}'
+ sock = state_dir / 'live.sock'
+ if WINDOWS:
+ conn = HTTPConnection(host, port, timeout=timeout)
+ elif sock.is_socket():
+ conn = UnixConnection(str(sock), host, timeout)
+ else:
+ return False
+ try:
+ conn.request('POST', '/moment', json.dumps({'moment': name}),
+ {'Host': netloc, 'Content-Type': 'application/json'})
+ return conn.getresponse().status == 204
+ except (OSError, HTTPException, ValueError):
+ return False
+ finally:
+ conn.close()
diff --git a/token_tv/pet_moments.py b/token_tv/pet_moments.py
new file mode 100644
index 0000000..90aa35e
--- /dev/null
+++ b/token_tv/pet_moments.py
@@ -0,0 +1,662 @@
+"""The pets' phase-2 moments on the Arcade stage, as the owner approved them (drafts w1-w12, 2026-11-01): the break
+after an hour of work (e6: drinking water or stretching) for all five pets, and Clawd petted or given a snack (e5:
+/tokentv pet, /tokentv snack).
+
+Each plays once through its pet's turn, one scene frame a frame (a lone pet's loop: 60 pictures, about 8.5 s on an
+SD_PRO), and the next loop is the pet's usual one. Everything is drawn on the scene's 120 x 71 stage, which Arcade
+doubles. The props look the same for every pet (one glass of water, one sparkle); each pet drinks and stretches its own
+way: Clawd tips the glass with its hand, the Codex cloud draws the water up like rain falling backwards, Grok and
+Copilot sip through a straw, and Anti floats over its glass with the straw up through its arch. A stretch is the same
+steps for all five (up tall with eyes shut, a lean each way, a squash, a sparkle); the leans are shears, which keep the
+pixel art crisp where a turn blurred it. Clawd's poses are its own frames from Clawd's Quest; only the props, a few
+shut-eye pixels and the leans are new.
+
+arcade.py draws them: claude_moment for Clawd (CLAWD_MOMENTS), and in place of the other pets' scenes while the break
+plays (SCENE_MOMENTS).
+"""
+import functools
+import math
+
+from PIL import Image
+
+from token_tv import arcade
+from token_tv.arcade import paste
+
+
+# --- helpers ----------------------------------------------------------------------------------------------------------
+
+def sprite(rows, ink):
+ """A small sprite from rows of keys; each key in `ink` is a colour, any other key is clear."""
+ art = Image.new('RGBA', (max(map(len, rows)), len(rows)))
+ for y, line in enumerate(rows):
+ for x, key in enumerate(line):
+ if key in ink:
+ art.putpixel((x, y), tuple(ink[key]) + (255,))
+ return art
+
+
+def step_of(p, marks):
+ """The step of a moment at progress `p` (0..1) and how far through it (0..1); `marks` are (name, end)."""
+ start = 0.0
+ for name, end in marks:
+ if p < end:
+ return name, (p - start) / (end - start)
+ start = end
+ return marks[-1][0], 1.0
+
+
+def ease(q):
+ return q * q * (3 - 2 * q)
+
+
[email protected]_cache(maxsize=None)
+def leaning(build, args, pivot, dx):
+ """build(*args) leaning `dx` pixels at its top: its feet (the pivot's row) stay and each row above moves in
+ proportion to its height, a shear that keeps pixel art crisp where a turn would blur it. Returns the art and
+ where the pivot is in it."""
+ art = build(*args)
+ if not dx:
+ return art, pivot
+ top, bottom = art.getbbox()[1], pivot[1]
+ out = Image.new('RGBA', (art.width + abs(dx), art.height))
+ for y in range(art.height):
+ k = max(0.0, min(1.0, (bottom - 1 - y) / max(1, bottom - 1 - top)))
+ row = art.crop((0, y, art.width, y + 1))
+ out.paste(row, (round(dx * k) + (abs(dx) if dx < 0 else 0), y), row)
+ return out, (pivot[0] + (abs(dx) if dx < 0 else 0), pivot[1])
+
+
+def put_leaning(frame, build, args, pivot, dx, x, y):
+ """Paste build(*args), leaning `dx` at its top, with its pivot at (x, y)."""
+ art, (px, py) = leaning(build, args, pivot, dx)
+ paste(frame, art, x - px, y - py)
+
+
[email protected]_cache(maxsize=None)
+def taller(build, args, rows):
+ """build(*args) drawn `rows` pixels taller (rows repeated evenly, the width kept, so eyes keep their shape);
+ fewer rows and a column more each side for rows < 0: a squash."""
+ art = build(*args)
+ if rows > 0:
+ return art.resize((art.width, art.height + rows), Image.Resampling.NEAREST)
+ if rows < 0:
+ return art.resize((art.width - rows, art.height + rows), Image.Resampling.NEAREST)
+ return art
+
+
+def sway(step, q):
+ """How far the top leans in a stretch's lean steps: two pixels, then three, then two, each way."""
+ if step not in ('left', 'right'):
+ return 0
+ return (2 if q < .2 or q >= .8 else 3) * (-1 if step == 'left' else 1)
+
+
+STRETCH_MARK = (236, 240, 255)
+
+
+def stretch_marks(draw, cx, top, half, q):
+ """Two short strokes either side of a stretching pet's top, flickering: the effort of a good stretch."""
+ if int(q * 6) % 2:
+ return
+ for side in (-1, 1):
+ x = cx + side * (half + 2)
+ draw.line((x, top + 1, x + side, top - 1), fill=STRETCH_MARK)
+
+
+# --- the props, the same for every pet --------------------------------------------------------------------------------
+
+GLASS_EDGE, GLASS_SHINE, GLASS_AIR = (196, 214, 238), (255, 255, 255), (66, 84, 110)
+WATER, WATER_TOP = (52, 140, 255), (150, 204, 255)
+GLASS = ('E.....E', 'ES....E', 'ES....E', 'E.....E', 'E.....E', 'E.....E', 'E.....E', '.EEEEE.') # 7 x 8 tumbler
+GLASS_LEVELS = 5 # water fills rows 2-6
+LAST_SIP = 1 # a row of water is left at the end: an empty glass read as a letter U
+
+
[email protected]_cache(maxsize=None)
+def glass_art(level):
+ """The glass upright with `level` rows of water (0 to 5), the top row lighter (the surface), a glint down its
+ side, and the air above the water a faint glass tint."""
+ rows = [list(r) for r in GLASS]
+ for v in range(7):
+ for u in range(1, 6):
+ if rows[v][u] == '.':
+ k = 6 - v # rows of water from the bottom
+ rows[v][u] = 'T' if k == level - 1 else 'W' if k < level else 'A'
+ return sprite([''.join(r) for r in rows], {'E': GLASS_EDGE, 'S': GLASS_SHINE, 'W': WATER, 'T': WATER_TOP,
+ 'A': GLASS_AIR})
+
+
[email protected]_cache(maxsize=None)
+def glass_tipped(degrees, water):
+ """The glass turned `degrees` anticlockwise (RotSprite for its outline), with `water` (0..1) of a full glass lying
+ level at its lowest side, as water does: past 90 degrees it sits against the rim. Returns the art and where the
+ middle of its rim is in it."""
+ edge = sprite(GLASS, {'E': GLASS_EDGE})
+ art = arcade.rotsprite(edge, -degrees)
+ w, h = art.size
+ a = math.radians(degrees)
+ inside = [] # the turned interior: pixels whose middle maps back inside the glass (u 1-5, v 0-6)
+ for y in range(h):
+ for x in range(w):
+ dx, dy = x + .5 - w / 2, y + .5 - h / 2
+ u = dx * math.cos(a) - dy * math.sin(a) + 3.5 # undo an anticlockwise turn on screen (y down)
+ v = dx * math.sin(a) + dy * math.cos(a) + 4
+ if 1 <= u < 6 and 0 <= v < 7 and not art.getpixel((x, y))[3]:
+ inside.append((x, y))
+ wet = round(water * 25 * len(inside) / 35) # a full glass holds 5 of its 7 rows
+ inside.sort(key=lambda p: -p[1])
+ surface = inside[wet - 1][1] if wet else None
+ for n, (x, y) in enumerate(inside):
+ art.putpixel((x, y), (WATER_TOP if y == surface else WATER) + (255,) if n < wet else GLASS_AIR + (255,))
+ rim = (3.5 - 3.5, -4.0) # the rim's middle from the glass's middle, turned
+ rx = rim[0] * math.cos(a) + rim[1] * math.sin(a)
+ ry = -rim[0] * math.sin(a) + rim[1] * math.cos(a)
+ return art, (round(w / 2 + rx), round(h / 2 + ry))
+
+
+def glass(frame, x, bottom, level):
+ """The glass standing with its left edge at x and its base on the row above `bottom`."""
+ paste(frame, glass_art(level), x, bottom - len(GLASS))
+
+
+def sip_level(q):
+ """The water left at `q` (0..1) through sipping with a straw: full, then a row less at a time, down to the last."""
+ return max(LAST_SIP, GLASS_LEVELS - int(q * (GLASS_LEVELS - LAST_SIP + 1)))
+
+
+STRAW, STRAW_STRIPE = (250, 250, 252), (240, 84, 100)
+
+
+def straw(draw, points):
+ """A bendy straw along `points`, white with red stripes, one pixel wide."""
+ n = 0
+ for (x0, y0), (x1, y1) in zip(points, points[1:]):
+ length = max(abs(x1 - x0), abs(y1 - y0), 1)
+ for k in range(length + (1 if (x1, y1) == points[-1] else 0)):
+ px_, py_ = round(x0 + (x1 - x0) * k / length), round(y0 + (y1 - y0) * k / length)
+ draw.point((px_, py_), fill=STRAW_STRIPE if (n // 2) % 2 else STRAW)
+ n += 1
+
+
+SPARK, SPARK_CORE = (255, 232, 140), (255, 255, 255)
+
+
+def sparkle(draw, cx, cy, size):
+ """A twinkle: a small plus (size 1) or a long one (size 2) with a white heart."""
+ if size <= 0:
+ return
+ for k in range(1, size + 1):
+ for dx, dy in ((k, 0), (-k, 0), (0, k), (0, -k)):
+ draw.point((cx + dx, cy + dy), fill=SPARK)
+ draw.point((cx, cy), fill=SPARK_CORE)
+
+
+def twinkle(q):
+ """Two twinkles over the last step: 1, 2, 2, 1, gone, 1, 2, 1, gone."""
+ return (1, 2, 2, 1, 0, 1, 2, 1, 0)[min(8, int(q * 9))]
+
+
+HEART_INK, HEART_SHINE = (255, 92, 136), (255, 200, 214)
+HEART_BIG = sprite(('.H.H.', 'HSHHH', 'HHHHH', '.HHH.', '..H..'), {'H': HEART_INK, 'S': HEART_SHINE})
+HEART_SMALL = sprite(('H.H', 'HHH', '.H.'), {'H': HEART_INK})
+
+COOKIE_INK = {'C': (226, 172, 102), 'K': (112, 66, 40)}
+COOKIE = ('..CCC..', '.CCKCC.', 'CKCCCCC', 'CCCCKCC', 'CCKCCCC', '.CCCCK.', '..CCC..') # 7 x 7, chips in it
+BITES = (((-1.5, 2.0), 2.6), ((-1.0, 5.0), 2.6), ((2.0, 3.0), 3.3)) # each bite's middle and size, from its left
+
+
[email protected]_cache(maxsize=None)
+def cookie_art(bites):
+ """The cookie after `bites` bites taken from its left, the side its eater is on (0: whole; 4: gone)."""
+ rows = [list(r) for r in COOKIE]
+ for (bx, by), r in BITES[:bites]:
+ for y, row in enumerate(rows):
+ for x in range(len(row)):
+ if (x + .5 - bx) ** 2 + (y + .5 - by) ** 2 < r * r:
+ row[x] = '.'
+ if bites >= 4:
+ rows = [['.'] * 7 for _ in rows]
+ return sprite([''.join(r) for r in rows], COOKIE_INK)
+
+
+# --- Clawd ------------------------------------------------------------------------------------------------------------
+
+BODY, DARK, THOUGHT = '#d97757', '#141413', '#699acb'
+
+
[email protected]_cache(maxsize=None)
+def clawd_art(name, index, eyes=None):
+ """One of Clawd's own frames at one pixel a pixel, without Thinking's thought bubble; eyes='shut' closes each
+ open eye the game's way (a line three pixels long on the eye's lowest row, reaching a pixel toward the middle).
+ Those eye pixels are the only ones redrawn."""
+ sheet = arcade.clawd_data()[name]
+ w, h = sheet['w'], sheet['h']
+ keys = [c.lower() for c in sheet['palette']]
+ palette = [tuple(int(c[i:i + 2], 16) for i in (1, 3, 5)) for c in keys]
+ values = [255 if v != 255 and keys[v] == THOUGHT else v for v in arcade.clawd_frames(name)[index]]
+ if eyes == 'shut' and DARK in keys and BODY in keys:
+ dark, body = keys.index(DARK), keys.index(BODY)
+ spots = [(i % w, i // w) for i, v in enumerate(values) if v == dark]
+ for left_eye in (True, False):
+ eye = [(x, y) for x, y in spots if (x < w / 2) == left_eye]
+ if not eye:
+ continue
+ for x, y in eye:
+ values[y * w + x] = body
+ low, xs = max(y for _, y in eye), [x for x, _ in eye]
+ for x in range(min(xs) - (not left_eye), max(xs) + 1 + left_eye):
+ values[low * w + x] = dark
+ art = Image.new('RGBA', (w, h))
+ art.putdata([(0, 0, 0, 0) if v == 255 else palette[v] + (255,) for v in values])
+ return art
+
+
+def clawd_pivot(name, index, eyes=None, grounded=False):
+ """Where Clawd's frame stands: the bottom middle of its body box, as place_clawd stands it; `grounded` stands
+ the frame's lowest pixel on the ground instead (a frame from mid-jump, set down)."""
+ x, y, w, h = arcade.clawd_data()[name]['a0']
+ bottom = clawd_art(name, index, eyes).getbbox()[3] if grounded else y + h
+ return round(x + w / 2), bottom
+
+
+def put_clawd(frame, name, index, foot_x, foot_y, eyes=None, grounded=False, lean=0, lift=0):
+ pivot = clawd_pivot(name, index, eyes, grounded)
+ put_leaning(frame, clawd_art, (name, index, eyes), pivot, lean, foot_x, foot_y - lift)
+
+
+DRINK = (('stand', .07), ('lift', .15), ('sip', .66), ('lower', .73), ('ahh', 1.0))
+STRETCH = (('stand', .07), ('rise', .13), ('up', .24), ('left', .40), ('right', .56), ('back', .63), ('settle', .73),
+ ('ahh', 1.0))
+HAND = (10, -14) # Thinking's hand by its face, from where Clawd stands (the frames themselves are Clawd's own)
+
+
+def clawd_ahh(frame, draw, foot_x, foot_y, q):
+ """Refreshed: the bow's proud pose (eyes ^ ^), a squash first, and a sparkle twinkling twice by its head."""
+ put_clawd(frame, 'Excited', 3 if q < .08 else 6, foot_x, foot_y)
+ sparkle(draw, foot_x + 12, foot_y - 19, twinkle(q))
+
+
+def clawd_drink(frame, draw, foot_x, foot_y, f, span):
+ """The glass on the ground by Clawd, then held up by its face (Thinking's hand, its own frame); it drinks with its
+ eyes shut, tipping the glass further as it empties, as one does; it sets the glass down and is refreshed."""
+ step, q = step_of(f / span, DRINK)
+ hx, hy = foot_x + HAND[0], foot_y + HAND[1]
+ if step == 'stand':
+ glass(frame, foot_x + 15, foot_y, GLASS_LEVELS)
+ put_clawd(frame, 'LookingAround', 0, foot_x, foot_y)
+ elif step in ('lift', 'lower'): # held up by its face: full on the way up, nearly empty on the way down
+ glass(frame, hx - 1, hy + 3, GLASS_LEVELS if step == 'lift' else LAST_SIP)
+ put_clawd(frame, 'Thinking', 4, foot_x, foot_y)
+ elif step == 'sip': # the rim at its face, the glass's bottom rising as the water goes
+ put_clawd(frame, 'Thinking', 4, foot_x, foot_y)
+ art, (rx, ry) = glass_tipped(round(60 + 60 * q, -1), round(1 - .8 * q, 1))
+ paste(frame, art, hx - 1 - rx, hy - 1 - ry)
+ else:
+ glass(frame, foot_x + 15, foot_y, LAST_SIP) # set down
+ clawd_ahh(frame, draw, foot_x, foot_y, q)
+
+
+def clawd_stretch(frame, draw, foot_x, foot_y, f, span):
+ """Arms up (the game's own jump frames, set down on the ground), eyes shut, a lean each way, then the landing
+ squash and a sparkle. Distinct from the rest flow's sway, which Clawd does every few minutes anyway."""
+ step, q = step_of(f / span, STRETCH)
+ if step == 'stand':
+ put_clawd(frame, 'LookingAround', 0, foot_x, foot_y)
+ elif step == 'rise':
+ put_clawd(frame, 'Jumping', 5, foot_x, foot_y, grounded=True)
+ elif step in ('up', 'back'):
+ put_clawd(frame, 'Jumping', 7, foot_x, foot_y, 'shut', grounded=True, lift=1 if step == 'up' and q > .4 else 0)
+ elif step in ('left', 'right'):
+ put_clawd(frame, 'Jumping', 7, foot_x, foot_y, 'shut', grounded=True, lean=sway(step, q))
+ elif step == 'settle':
+ put_clawd(frame, 'Jumping', 13 if q < .3 else 14 if q < .6 else 15, foot_x, foot_y, grounded=True)
+ else:
+ clawd_ahh(frame, draw, foot_x, foot_y, q)
+
+
+PET = (('stand', .06), ('squash', .12), ('happy', .92), ('back', 1.0))
+HEARTS = ((.12, -3), (.30, 4), (.48, -1), (.62, 5)) # when each heart sets off (progress), and its drift
+
+
+def hearts(frame, foot_x, foot_y, p, life=.32, rise=18):
+ """Hearts floating up from Clawd's head, each big at first, small near the top, then gone."""
+ for start, drift in HEARTS:
+ a = (p - start) / life
+ if 0 <= a < 1:
+ art = HEART_BIG if a < .6 else HEART_SMALL
+ x = foot_x + 2 + drift + round(math.sin(a * math.pi * 2) * 1.5)
+ y = foot_y - 22 - round(rise * a)
+ paste(frame, art, x - art.width // 2, y - art.height)
+
+
+def clawd_pet(frame, draw, foot_x, foot_y, f, span):
+ """Petted: a squash (the game's Excited), eyes ^ ^ and a happy wiggle, hearts floating up."""
+ p = f / span
+ step, q = step_of(p, PET)
+ if step == 'stand':
+ put_clawd(frame, 'LookingAround', 0, foot_x, foot_y)
+ elif step == 'squash':
+ put_clawd(frame, 'Excited', 3 if q < .5 else 4, foot_x, foot_y)
+ elif step == 'happy':
+ put_clawd(frame, 'Excited', 5 + int(q * 32) % 16, foot_x, foot_y)
+ else:
+ put_clawd(frame, 'Excited', 21 if q < .5 else 22, foot_x, foot_y)
+ hearts(frame, foot_x, foot_y, p)
+
+
+SNACK = (('drop', .12), ('catch', .2), ('munch', .74), ('ahh', 1.0))
+CRUMB = (190, 140, 84)
+
+
+def clawd_snack(frame, draw, foot_x, foot_y, f, span):
+ """A cookie drops in from above (the treat from /tokentv snack), Clawd catches it by its face (Thinking's hand,
+ its own frame), takes it in four bites with a chew each and crumbs falling, then ^ ^."""
+ step, q = step_of(f / span, SNACK)
+ hx, hy = foot_x + HAND[0], foot_y + HAND[1]
+ cookie_at = (hx - 1, hy - 5) # its top left, held by the face
+ if step == 'drop':
+ put_clawd(frame, 'LookingAround', 0, foot_x, foot_y)
+ paste(frame, cookie_art(0), cookie_at[0], round(-8 + (cookie_at[1] + 8) * q * q))
+ elif step == 'catch':
+ put_clawd(frame, 'Thinking', 4, foot_x, foot_y)
+ paste(frame, cookie_art(0), *cookie_at)
+ elif step == 'munch':
+ bites = min(4, int(q * 4.4))
+ chew = (q * 4.4) % 1 # within a bite: to the face, a bite, back with a chew
+ near = 1 if chew < .3 else 0
+ put_clawd(frame, 'Thinking', 4, foot_x, foot_y, lift=1 if .4 <= chew < .6 else 0)
+ paste(frame, cookie_art(bites), cookie_at[0] - near, cookie_at[1])
+ if bites and chew >= .3: # crumbs from the bite, falling to the ground
+ fall = (chew - .3) / .7
+ for k, dx in enumerate((0, 2, -1)):
+ cy = hy + round((foot_y - hy) * min(1, fall * (1 + .35 * k)))
+ if cy < foot_y:
+ draw.point((hx + dx, cy), fill=CRUMB)
+ else:
+ clawd_ahh(frame, draw, foot_x, foot_y, q)
+
+
+CLAWD_MOMENTS = {'drink': clawd_drink, 'stretch': clawd_stretch, 'pet': clawd_pet, 'snack': clawd_snack}
+
+
+# --- Codex ------------------------------------------------------------------------------------------------------------
+
+def codex_garden(frame, draw, box, f, s, plan):
+ """The garden as codex_scene draws it at rest: the flowers are its gauge, so they stay."""
+ x, y, w, h = box
+ ground = arcade.garden_backdrop(draw, box, f, s)
+ used = plan.get('used') if isinstance(plan, dict) else None
+ xs = [x + round(w * (i + .5) / 5) for i in range(5)]
+ bloomed = 0 if used is None else min(5, int(used * 5 // 100))
+ if s == 1 and isinstance(plan, dict) and plan.get('label'):
+ arcade.gauge_label(draw, x + 1, y + 1, plan['label'])
+ if used is not None:
+ for i, fx in enumerate(xs):
+ if i < bloomed:
+ arcade.flower(draw, fx, ground, s, 1, s * (1 if (f // 30 + i) % 2 else 0))
+ else:
+ draw.rectangle((fx - 2 * s, ground - s, fx + s - 1, ground - 1), fill=arcade.PLOT)
+ if bloomed < 5:
+ arcade.flower(draw, xs[bloomed], ground, s, .15 + .66 * (used % 20) / 20)
+ return ground
+
+
+def codex_drink(frame, draw, box, f, span, s, plan):
+ """The cloud drifts over its glass and draws the water up like rain falling backwards, eyes shut, plumping up a
+ little as it fills; then it floats home grinning."""
+ x, y, w, h = box
+ ground = codex_garden(frame, draw, box, f, s, plan)
+ step, q = step_of(f / span, DRINK)
+ cw, ch = arcade.codex_art(s).size
+ home = (x + round(w * .5), y + max(2, round(h * .05)) + ch // 2)
+ gx = x + 72 # between the third and fourth flowers
+ over = (gx, home[1] + 13)
+ level, eye, mouth, squash = GLASS_LEVELS, 'open', 'long', 0
+ if step == 'stand':
+ cx, mid = home
+ elif step == 'lift':
+ cx, mid = (round(a + (b - a) * ease(q)) for a, b in zip(home, over))
+ elif step == 'sip':
+ cx, mid = over
+ level, eye, mouth = sip_level(q), 'closed', 'short' if (f // 8) % 2 else 'long'
+ squash = 1 if q > .55 else 0
+ elif step == 'lower':
+ cx, mid = (round(b + (a - b) * ease(q)) for a, b in zip(home, over))
+ level, squash = LAST_SIP, 1
+ else:
+ cx, mid = home
+ level, eye, mouth = LAST_SIP, 'happy', 'smile'
+ glass(frame, gx - 3, ground, level)
+ cloud = arcade.codex_art(s, eye, mouth, squash)
+ if step == 'sip': # drops rising from the glass into the cloud's underside
+ top, bottom = mid + cloud.height // 2 - 3, ground - len(GLASS) + 3
+ for k, dx in enumerate((-2, 1, -1, 2)):
+ t = ((f / 2 + k * 2.6) % 10) / 10
+ dy = bottom - round((bottom - top) * t)
+ if top < dy <= bottom:
+ draw.rectangle((gx + dx, dy - 1, gx + dx, dy), fill=WATER_TOP if k % 2 else WATER)
+ paste(frame, cloud, cx - cloud.width / 2, mid - cloud.height / 2)
+ if step == 'ahh':
+ sparkle(draw, cx + cw // 2 + 2, mid - ch // 2 + 1, twinkle(q))
+
+
+def codex_stretch(frame, draw, box, f, span, s, plan):
+ """Drawn up tall with a yawn, a lean each way, a wide wobble back, and a grin."""
+ x, y, w, h = box
+ codex_garden(frame, draw, box, f, s, plan)
+ step, q = step_of(f / span, STRETCH)
+ cw, ch = arcade.codex_art(s).size
+ cx, mid = x + round(w * .5), y + max(2, round(h * .05)) + ch // 2
+ face, rows = (s, 'open', 'long', 0), 0
+ if step == 'rise':
+ face, rows = (s, 'closed', 'open', 0), 2
+ elif step in ('up', 'back', 'left', 'right'):
+ face, rows = (s, 'closed', 'open', 0), 4
+ elif step == 'settle':
+ face = (s, 'open', 'long', (2, 2, 1, 0, 0, 0)[min(5, int(q * 6))])
+ elif step == 'ahh':
+ face = (s, 'happy', 'smile', 0)
+ art = taller(arcade.codex_art, face, rows)
+ bottom = mid + ch // 2 + rows // 2 # it grows up and down about its middle, as a cloud would
+ put_leaning(frame, taller, (arcade.codex_art, face, rows), (art.width // 2, art.height), sway(step, q), cx, bottom)
+ if step in ('up', 'back'):
+ stretch_marks(draw, cx, bottom - art.height, art.width // 2, q)
+ if step == 'ahh':
+ sparkle(draw, cx + cw // 2 + 2, mid - ch // 2 + 1, twinkle(q))
+
+
+# --- Grok -------------------------------------------------------------------------------------------------------------
+
+def grok_pad(frame, draw, box, f, s, plan):
+ """Grok's Moon at rest: the fuel tank (its gauge), the Falcon on its pad, the pad's lamp off."""
+ x, y, w, h = box
+ u, ground, deck, hr, rx, rest_art, gsize, gx0, sep = arcade.grok_backdrop(draw, box, f, s)
+ used = plan.get('used') if isinstance(plan, dict) else None
+ if used is not None:
+ arcade.fuel_tank(draw, x + 2 * s, ground, s, 1 - used / 100, plan.get('label', ''))
+ arcade.draw_stage(frame, draw, rx, deck, hr, u, ('left', 'centre', 'right'), 0, 0, 'empty', 0, 0, 1.0, 0, f)
+ lamp = rx - rest_art.width // 2 - round(4 * u)
+ draw.rectangle((lamp, deck - 1, lamp + max(1, round(u)), deck - 1), fill=arcade.DECK_EDGE)
+ return ground, gsize, gx0
+
+
+def grok_drink(frame, draw, box, f, span, s, plan):
+ """A glass at Grok's side and a straw to its face; eyes shut as it sips, a hop and a sparkle after."""
+ ground, gsize, gx = grok_pad(frame, draw, box, f, s, plan)
+ step, q = step_of(f / span, DRINK)
+ level, eyes, lift, squash = GLASS_LEVELS, 'open', 0, 0
+ if step == 'lift':
+ squash = 1 if q < .5 else 0 # a little bob as it bends to the straw
+ elif step == 'sip':
+ level, eyes = sip_level(q), 'shut'
+ elif step == 'lower':
+ level = LAST_SIP
+ elif step == 'ahh':
+ level, eyes = LAST_SIP, 'shut'
+ lift = (0, 2, 3, 2, 0, 0, 0, 0, 0)[min(8, int(q * 9))]
+ art = arcade.grok_pose(gsize, eyes, squash)
+ left = round(gx - art.width / 2)
+ gl = left + art.width + 2
+ glass(frame, gl, ground, level)
+ if step in ('lift', 'sip', 'lower'):
+ straw(draw, [(gl + 4, ground - 3), (gl + 4, ground - len(GLASS) - 3), (left + art.width - 2, ground - 7)])
+ paste(frame, art, left, ground - art.height - lift)
+ if step == 'ahh':
+ sparkle(draw, left + art.width + 1, ground - art.height - 2, twinkle(q))
+
+
+def grok_stretch(frame, draw, box, f, span, s, plan):
+ """Drawn up tall, eyes shut, a lean each way, a squash on settling, a sparkle."""
+ ground, gsize, gx = grok_pad(frame, draw, box, f, s, plan)
+ step, q = step_of(f / span, STRETCH)
+ pose, rows = (gsize, 'open', 0), 0
+ if step == 'rise':
+ pose, rows = (gsize, 'shut', 0), 2
+ elif step in ('up', 'back', 'left', 'right'):
+ pose, rows = (gsize, 'shut', 0), 5
+ elif step == 'settle':
+ pose = (gsize, 'open', (2, 2, 1, 0, 0, 0)[min(5, int(q * 6))])
+ elif step == 'ahh':
+ pose = (gsize, 'shut', 0)
+ art = taller(arcade.grok_pose, pose, rows)
+ put_leaning(frame, taller, (arcade.grok_pose, pose, rows), (art.width // 2, art.height), sway(step, q), gx, ground)
+ if step in ('up', 'back'):
+ stretch_marks(draw, gx, ground - art.height, art.width // 2, q)
+ if step == 'ahh':
+ sparkle(draw, gx + art.width // 2 + 2, ground - art.height - 1, twinkle(q))
+
+
+# --- Copilot ----------------------------------------------------------------------------------------------------------
+
+def copilot_sky(frame, draw, box, f, s, plan, centre=.5):
+ """Copilot's sky at rest: the clouds that count its use, and its own cloud; returns where the head stands."""
+ x, y, w, h = box
+ u = s / 2
+ arcade.copilot_backdrop(draw, box, f, s, clouds=False)
+ used = plan.get('used') if isinstance(plan, dict) else None
+ if used is not None:
+ arcade.cloud_count(draw, box, s, used, plan.get('label', ''))
+ base_y = y + round(h * .78)
+ arcade.cloud(draw, x + round(w * centre), base_y, max(5, round(14 * u)))
+ return x + round(w * centre), base_y - round(4 * u)
+
+
+def copilot_drink(frame, draw, box, f, span, s, plan):
+ """The glass on a small cloud of its own beside Copilot, a straw up to the bottom of its visor; eyes shut as it
+ sips, a hop and a sparkle after."""
+ cx, stand = copilot_sky(frame, draw, box, f, s, plan) # where it always sits, so the loop meets the next one
+ step, q = step_of(f / span, DRINK)
+ level, eyes, lift = GLASS_LEVELS, 'open', 0
+ if step == 'sip':
+ level, eyes = sip_level(q), 'shut'
+ elif step == 'lower':
+ level = LAST_SIP
+ elif step == 'ahh':
+ level = LAST_SIP
+ lift = (0, 2, 3, 2, 0, 0, 0, 0, 0)[min(8, int(q * 9))]
+ head = arcade.copilot_pose(arcade.COPILOT_HEAD * s, eyes)
+ hx, hy = cx - head.width // 2, stand - head.height - lift
+ side = (hx + head.width + 8, stand + 1) # the little cloud the glass stands on
+ arcade.cloud(draw, side[0], side[1], 4)
+ glass(frame, side[0] - 3, side[1] - 2, level)
+ if step in ('lift', 'sip', 'lower'):
+ top = side[1] - 2 - len(GLASS)
+ straw(draw, [(side[0], top + 4), (side[0], top - 3), (hx + 19, hy + 16)])
+ paste(frame, head, hx, hy)
+ if step == 'ahh':
+ sparkle(draw, hx + head.width, hy - 1, twinkle(q))
+
+
+def copilot_stretch(frame, draw, box, f, span, s, plan):
+ """Up off its cloud and drawn up tall, eyes shut, a lean each way, a squash back onto the cloud, a sparkle."""
+ cx, stand = copilot_sky(frame, draw, box, f, s, plan)
+ step, q = step_of(f / span, STRETCH)
+ size = arcade.COPILOT_HEAD * s
+ pose, rows, lift = (size, 'open'), 0, 0
+ if step == 'rise':
+ pose, rows, lift = (size, 'shut'), 2, 1
+ elif step in ('up', 'back', 'left', 'right'):
+ pose, rows, lift = (size, 'shut'), 3, 2
+ elif step == 'settle':
+ rows = (-2, -2, -1, 0, 0, 0)[min(5, int(q * 6))]
+ elif step == 'ahh':
+ pose = (size, 'shut')
+ art = taller(arcade.copilot_pose, pose, rows)
+ put_leaning(frame, taller, (arcade.copilot_pose, pose, rows), (art.width // 2, art.height), sway(step, q), cx,
+ stand - lift)
+ if step in ('up', 'back'):
+ stretch_marks(draw, cx, stand - lift - art.height, art.width // 2, q)
+ if step == 'ahh':
+ sparkle(draw, cx + art.width // 2 + 1, stand - art.height - 1, twinkle(q))
+
+
+# --- Anti -------------------------------------------------------------------------------------------------------------
+
+ANTI_HOVER = 7 # how high Anti floats over its glass (its float rest goes as high as 6)
+
+
+def anti_drink(frame, draw, box, f, span, s, plan):
+ """Anti floats up and over its glass, the antigravity way, and sips through a straw that comes up through its
+ arch to its cat's mouth, eyes shut; it settles back down beside the glass, ^ ^."""
+ x, y = box[:2]
+ step, q = step_of(f / span, DRINK)
+ gx = x + arcade.ANTI_MID + 16 # the glass, on the floor to Anti's right
+ level, face, lift, sx = GLASS_LEVELS, 'normal', 0, 0
+ if step == 'lift':
+ k = ease(q)
+ lift, sx = round(ANTI_HOVER * k), round(16 * k)
+ elif step == 'sip':
+ level, face = sip_level(q), 'blink'
+ lift, sx = ANTI_HOVER + (1 if (f // 6) % 2 else 0), 16
+ elif step == 'lower':
+ k = 1 - ease(q)
+ level, lift, sx = LAST_SIP, round(ANTI_HOVER * k), round(16 * k)
+ elif step == 'ahh':
+ level, face = LAST_SIP, 'happy'
+ glass(frame, gx - 3, y + arcade.ANTI_FLOOR + 1, level)
+ left, top = arcade.anti_stand(frame, box, arcade.anti_art(face, dy=1 if face == 'normal' else 0), lift, sx)
+ if step == 'sip':
+ straw(draw, [(gx, y + arcade.ANTI_FLOOR - 2), (gx, top + 10)])
+ if step == 'ahh':
+ sparkle(draw, left + 21, top + 1, twinkle(q))
+
+
+def anti_stretch(frame, draw, box, f, span, s, plan):
+ """Up on its toes (its legs a pixel longer a row), eyes shut, a lean each way, the landing squash, ^ ^."""
+ x, y = box[:2]
+ step, q = step_of(f / span, STRETCH)
+ face, pose = 'normal', 'stand'
+ if step in ('rise', 'up', 'back', 'left', 'right'):
+ face, pose = 'blink', 'tall' if step != 'rise' or q >= .5 else 'stand'
+ elif step == 'settle':
+ pose = 'squash' if q < .5 else 'stand'
+ elif step == 'ahh':
+ face = 'happy'
+ args = (face, 'logo', 0, 0, False, 1, pose)
+ art = arcade.anti_art(*args)
+ cx, floor = x + arcade.ANTI_MID, y + arcade.ANTI_FLOOR + 1
+ put_leaning(frame, arcade.anti_art, args, (art.width // 2, art.height), sway(step, q), cx, floor)
+ if step in ('up', 'back'):
+ stretch_marks(draw, cx, floor - art.height, 4, q)
+ if step == 'ahh':
+ sparkle(draw, cx + 11, floor - art.height - 1, twinkle(q))
+
+
+def anti_moment_scene(moment_draw):
+ def scene(frame, draw, box, f, span, s, plan):
+ left = arcade.anti_left(plan)
+ label = plan.get('anti_label', '') if isinstance(plan, dict) and s == 1 else ''
+ arcade.anti_maze(draw, box, f, s, left, 'floor', pellets=False)
+ moment_draw(frame, draw, box, f, span, s, plan)
+ if left is not None:
+ arcade.anti_pellets(draw, box, left, label)
+ return scene
+
+
+SCENE_MOMENTS = {
+ 'codex': {'drink': codex_drink, 'stretch': codex_stretch},
+ 'grok': {'drink': grok_drink, 'stretch': grok_stretch},
+ 'copilot': {'drink': copilot_drink, 'stretch': copilot_stretch},
+ 'antigravity': {'drink': anti_moment_scene(anti_drink), 'stretch': anti_moment_scene(anti_stretch)},
+}
+
diff --git a/token_tv/readout.py b/token_tv/readout.py
index 17bbc6a..53293b4 100644
--- a/token_tv/readout.py
+++ b/token_tv/readout.py
@@ -381,6 +381,9 @@ LCD_BARS.update({'capsule': bar_capsule_plain, 'capsule_along': bar_capsule_alon
# --- 'battery': the pet, what it does, and a battery of what is left ------------------------------------------------
PETS = {'claude': ('CLAWD', (217, 132, 94)), 'codex': ('CODEX', (150, 160, 255)), 'grok': ('GROK', (238, 240, 245)),
'copilot': ('COPILOT', (120, 190, 255)), 'antigravity': ('ANTI', (90, 170, 255))}
+WARN = (255, 96, 110) # arcade.WARN: SLOW, and the battery that blinks beside it (x3)
+OVERSPEND = shade(WARN, .55) # over pace on a weekly battery: the track from the charge to the pace tick (x4)
+TICK = (255, 255, 255) # the pace tick
def text_width(text, scale):
@@ -396,54 +399,77 @@ def reset_clock(resets_at, now=None):
return at.strftime('%H:%M') if resets_at - now < 86400 else at.strftime('%a %H:%M').upper()
-def battery(draw, x, y, w, h, used, cells, old=False):
+def battery(draw, x, y, w, h, used, cells, old=False, alarm=False, pace=None):
"""A pixel battery of what is left: a 2 px case and nub, `cells` equal cells (the last one filled in part), a lit
- top edge. Muted when the reading is old; empty when there is none."""
+ top edge. Muted when the reading is old; empty when there is none. `alarm` draws its case red (a blink's 'on'
+ picture beside SLOW); `pace` (a weekly window's share of the week gone) puts a tick where even use would have
+ left the charge now, and over pace the gap from the charge to it in red."""
draw.rounded_rectangle((x, y, x + w - 1, y + h - 1), radius=3, outline=MUTED, width=2, fill=PANEL)
draw.rectangle((x + w, y + h // 2 - 3, x + w + 2, y + h // 2 + 2), fill=MUTED)
ix, iy, iw, ih, gap = x + 4, y + 4, w - 8, h - 8, 2
cw = (iw - gap * (cells - 1)) / cells
left = None if used is None else max(0, 100 - round(used))
colour = MUTED if old or used is None else band(used)
+ filled = [] # each cell's last charged column (x0 - 1 when empty)
for k in range(cells):
x0 = round(ix + k * (cw + gap))
x1 = round(ix + k * (cw + gap) + cw) - 1
draw.rectangle((x0, iy, x1, iy + ih - 1), fill=TRACK)
part = 0 if left is None else max(0.0, min(1.0, left / 100 * cells - k))
+ fx = x0 - 1
if part > 0:
fx = x0 + max(1, round((x1 - x0 + 1) * part)) - 1
draw.rectangle((x0, iy, fx, iy + ih - 1), fill=colour)
draw.rectangle((x0, iy, fx, iy), fill=shade(colour, 1.25))
if ih > 6:
draw.rectangle((x0, iy + ih - 1, fx, iy + ih - 1), fill=shade(colour, 0.7))
-
-
-def draw_battery(frame, draw, provider, action, rows, now=None):
- """The battery readout for one account: `rows` are [(window label, used %, resets_at, old?)], one or two."""
+ filled.append(fx)
+ if alarm:
+ draw.rounded_rectangle((x, y, x + w - 1, y + h - 1), radius=3, outline=WARN, width=2)
+ draw.rectangle((x + w, y + h // 2 - 3, x + w + 2, y + h // 2 + 2), fill=WARN)
+ if pace is None or used is None:
+ return
+ even = round(ix + iw * (1 - pace)) # where the charge would stand at an even pace
+ charge = round(ix + iw * max(0, 100 - used) / 100)
+ for k in range(cells if charge < even else 0): # over pace: the empty track from the charge to the tick, dim red
+ x0, x1 = round(ix + k * (cw + gap)), round(ix + k * (cw + gap) + cw) - 1
+ a, b = max(x0, min(charge, filled[k] + 1)), min(x1, even - 1) # (from the cell's charge on: no dark seam)
+ if a <= b:
+ draw.rectangle((a, iy, b, iy + ih - 1), fill=OVERSPEND)
+ draw.rectangle((even - 1, y - 2, even, y + h + 1), fill=TICK)
+
+
+def draw_battery(frame, draw, provider, action, rows, now=None, paces=(), alarms=()):
+ """The battery readout for one account: `rows` are [(window label, used %, resets_at, old?)], one or two;
+ `paces` the share of the week gone for each weekly one (None for the rest: no tick) and `alarms` whether each
+ blinks red in this picture, beside SLOW (x3, x4)."""
+ paces, alarms = list(paces) + [None, None], list(alarms) + [False, False] # (for the rows they do not cover)
pet, colour = PETS.get(provider, (provider.upper()[:8], TEXT))
pixel_text(draw, (10, 176), pet, scale=2, color=colour)
if action:
x = 10 + text_width(pet, 2) + 12
+ ink = WARN if action == 'SLOW' else MUTED
if x + text_width(action, 2) <= 230:
- pixel_text(draw, (x, 176), action, scale=2, color=MUTED)
+ pixel_text(draw, (x, 176), action, scale=2, color=ink)
else: # a long name beside a long one: smaller, still on the line
- pixel_text(draw, (x, 180), action, scale=1, color=MUTED)
+ pixel_text(draw, (x, 180), action, scale=1, color=ink)
if len(rows) >= 2:
for i, (label, used, resets_at, old) in enumerate(rows[:2]):
y = 196 + i * 21
pixel_text(draw, (10, y + 4), label, color=MUTED)
- battery(draw, 24, y, 44, 16, used, 5, old)
+ battery(draw, 24, y, 44, 16, used, 5, old, alarms[i], paces[i])
left = '--' if used is None else f'{max(0, 100 - round(used))}%'
- pixel_text(draw, (78, y + 1), left, scale=2, color=MUTED if old else TEXT) # an old one: grey (OLD on top)
+ # an old one grey (OLD on top); one blinking, red with its battery
+ pixel_text(draw, (78, y + 1), left, scale=2, color=WARN if alarms[i] else MUTED if old else TEXT)
day, _, clock = reset_clock(resets_at, now).rpartition(' ')
pixel_text(draw, (230, y + 1), clock, scale=2, color=TEXT, align='right')
if day: # a day or more off: the weekday small beside the time, so even 100% keeps its room
pixel_text(draw, (230 - text_width(clock, 2) - 4, y + 4), day, color=MUTED, align='right')
return
label, used, resets_at, old = rows[0] if rows else ('', None, None, False)
- battery(draw, 10, 195, 158, 20, used, 10, old)
+ battery(draw, 10, 195, 158, 20, used, 10, old, alarms[0], paces[0])
left = '--' if used is None else f'{max(0, 100 - round(used))}%'
- pixel_text(draw, (230, 198), left, scale=2, color=MUTED if old else TEXT, align='right')
+ pixel_text(draw, (230, 198), left, scale=2, color=WARN if alarms[0] else MUTED if old else TEXT, align='right')
pixel_text(draw, (10, 226), f'{label} OLD' if old else f'{label} LEFT', color=MUTED)
at = reset_clock(resets_at, now)
pixel_text(draw, (230, 222), at, scale=2, color=TEXT, align='right')
diff --git a/token_tv/sources.py b/token_tv/sources.py
index b13d975..eb7e9ca 100644
--- a/token_tv/sources.py
+++ b/token_tv/sources.py
@@ -120,10 +120,13 @@ class RPC:
def load_config(path):
data = json.loads(Path(path).read_text(encoding="utf-8"))
- if set(data) - {"accounts", "device_url", "poll_seconds", "font", "display_style", "update_check"}:
+ if set(data) - {"accounts", "device_url", "poll_seconds", "font", "display_style", "update_check", "device_frame_ms"}:
raise ValueError("Unsupported configuration field")
if not isinstance(data.get("update_check", True), bool):
raise ValueError("update_check is true or false")
+ pace = data.get("device_frame_ms") # an SD_PRO's shortest picture, its tick (live.DEVICE_FRAME_MS when unset)
+ if pace is not None and (isinstance(pace, bool) or not isinstance(pace, (int, float)) or not 20 <= pace <= 2000):
+ raise ValueError("device_frame_ms is the clock's shortest picture in milliseconds, from 20 to 2000")
if data.get('display_style', 'pixel') not in STYLES:
raise ValueError('Unknown display style')
seen = set()
diff --git a/token_tv/state.py b/token_tv/state.py
index b791c2b..d4dae3e 100644
--- a/token_tv/state.py
+++ b/token_tv/state.py
@@ -3,6 +3,7 @@ import copy
import threading
import time
from concurrent.futures import ThreadPoolExecutor
+from fractions import Fraction
from token_tv.sources import STALE_SECONDS, fetch_account
@@ -74,6 +75,60 @@ NEWS_SECONDS = 600 # what a reading brought (a jump, a crossing, a spent reset)
RATE_SECONDS = 600 # a jump is the rise in used % over ten minutes
+# x3: a window running out. Its pace is its rise over the last RATE_WINDOW, from its readings there (one at or
+# before the window's start, and every one since); at that pace, a window still under 100% that would reach it in
+# under HORIZON is SLOW. A window's readings are its own: a new reset time (beyond SAME_WINDOW, as a reset time
+# wobbles by seconds) or a drop in its use starts them over, so a reset is never taken for use.
+RATE_WINDOW = 15 * 60
+HORIZON = 30 * 60
+SAME_WINDOW = 600
+
+
+def same_window(a, b):
+ """Whether two reset times are one window's."""
+ return (a is None) == (b is None) and (a is None or abs(a - b) <= SAME_WINDOW)
+
+
+def exact(value):
+ """A reading's number as the decimal it was read as: 55.3 is 553/10, not the binary float nearest it."""
+ return Fraction(str(value))
+
+
+def running_out(readings):
+ """Whether a window's readings [(measured at, used %, resets at)], oldest first, the first at or before
+ RATE_WINDOW before the last, say it runs out within HORIZON at its pace: its rise over the last RATE_WINDOW (the
+ use at that window's start read between the two readings either side of it). Exact, in fractions of the numbers
+ as read (exact()): an ETA of just HORIZON is not under it. A history shorter than RATE_WINDOW says nothing."""
+ if len(readings) < 2:
+ return False
+ (t0, u0, _), (t1, u1, _), (at, used, _) = readings[0], readings[1], readings[-1]
+ t0, u0, t1, u1, at, used = (exact(value) for value in (t0, u0, t1, u1, at, used))
+ start = at - RATE_WINDOW
+ if t0 > start:
+ return False
+ begun = u0 + (u1 - u0) * (start - t0) / (t1 - t0)
+ rise, left = used - begun, 100 - used
+ return rise > 0 and left > 0 and left * RATE_WINDOW < rise * HORIZON
+
+
+def lasting(row, slow, now, good):
+ """The SLOW labels `slow` that a row whose reading did not come in (failed, or grew old) keeps at `now`, each its
+ own window's: while the good reading it was found at (`good`: label -> (measured at, used %, resets at), the last
+ one taken into that window's pace) is under HORIZON old, and while the row shows that window still, no lower. A
+ reading or two failing do not make the warning drop and come back; one that brings a new window (another reset
+ time, same_window) or a lower use lets it go, and so do readings failing past the warning's own horizon, however
+ new the old copies among them."""
+ windows = {w.get("label"): w for w in row.get("windows", [])}
+ kept = []
+ for label in slow:
+ reading, shown = good.get(label), windows.get(label)
+ if reading is None or shown is None or now - reading[0] >= HORIZON:
+ continue
+ used = shown.get("used_percent")
+ if same_window(reading[2], shown.get("resets_at")) and not (used is not None and used < reading[1]):
+ kept.append(label)
+ return kept
+
def trail_of(row):
"""The good readings behind `row` for rates, oldest first: [(measured at, {label: used %})], the ones in the
@@ -127,6 +182,7 @@ class UsageStore:
self.waits = {} # account key -> (monotonic, wall, asked): not read again before; asked = the service said so
self.lock = threading.Lock()
self.updated_at = 0
+ self.paces = {} # (account key, window label) -> its readings for running_out, in memory only
self.rows = {a["key"]: {"key": a["key"], "alias": a["alias"], "provider": a["provider"],
"status": "loading", "windows": [], "fetched_at": 0,
"identity_verified": False, "source": "mini"}
@@ -208,9 +264,40 @@ class UsageStore:
row["reset_credits"] = previous["reset_credits"]
row["last_success_at"] = previous["last_success_at"]
row["identity_verified"] = previous.get("identity_verified", False)
+ # x3: the windows running out, for the battery to blink (a reading not in keeps the last good one's)
+ row["slow"] = (self.slow(row) if row["status"] == "ok" else
+ lasting(row, previous.get("slow") or [], wall, self.good(row["key"])))
self.rows[row["key"]] = row
self.updated_at = int(time.time())
+ def slow(self, row):
+ """The labels of `row`'s windows running out (running_out), its reading (one that came in) taken into their
+ histories."""
+ at, found, kept = row.get("last_success_at") or row["fetched_at"], [], set()
+ for w in row["windows"]:
+ used = w.get("used_percent")
+ if used is None:
+ continue
+ key = (row["key"], w["label"])
+ kept.add(key)
+ readings = self.paces.setdefault(key, [])
+ if not readings or at > readings[-1][0]: # (a reading already taken, or an older one, adds nothing)
+ if readings and (used < readings[-1][1] or not same_window(readings[-1][2], w.get("resets_at"))):
+ readings.clear() # a new window, or a correction: its pace starts over
+ readings.append((at, used, w.get("resets_at")))
+ while len(readings) > 1 and readings[1][0] <= readings[-1][0] - RATE_WINDOW:
+ readings.pop(0) # one at or before the window's start is enough
+ if running_out(readings):
+ found.append(w["label"])
+ for key in [key for key in self.paces if key[0] == row["key"] and key not in kept]:
+ del self.paces[key] # a window no longer reported
+ return found
+
+ def good(self, key):
+ """The last good reading of each of account `key`'s windows, as taken into its pace: {label: (measured at,
+ used %, resets at)}. Only a reading that came in goes there, never an old copy (lasting)."""
+ return {label: readings[-1] for (owner, label), readings in self.paces.items() if owner == key and readings}
+
def schedule(self, row, started, wall):
"""When a failing account is read next: when its service said (Retry-After, at most RETRY_CAP), else after a
backoff that grows with each failure in a row; a reading that works starts it over. Other accounts are
@@ -235,11 +322,14 @@ class UsageStore:
with self.lock:
rows = copy.deepcopy(self.rows)
updated = self.updated_at
+ good = {key: self.good(key) for key in rows}
now = time.time()
- for row in rows.values():
+ for key, row in rows.items():
if row["status"] == "ok" and now - row.get("last_success_at", row["fetched_at"]) > STALE_SECONDS:
row["status"] = "stale"
row.setdefault("error_code", "snapshot_old")
+ if row["status"] != "ok": # OLD: the last good reading's SLOW, only while it is under HORIZON old
+ row["slow"] = lasting(row, row.get("slow") or [], now, good[key])
row["active"] = bool(row.get("rose_at")) and now - row["rose_at"] < ACTIVE_SECONDS
by_label = {w["label"]: w for w in row["windows"]}
for prefix, label in (("session", "5H"), ("weekly", "WEEK")):