Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.
Release 0.6.0: Clawd has opinions now
click6067-ship-itd885b7f041ac
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex bf89ca3..34b3923 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -6,7 +6,7 @@{"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)"+ "description": "Clawd on your TokenTV clock raises a hand while Claude Code waits for your permission, bows when a turn is done, takes a pat or a snack (/tokentv pet, /tokentv snack), and reacts to risky commands, deleted files, rude prompts, failed tools, compactions and Claude Code's thinking word"}]}diff --git a/README.ko.md b/README.ko.mdindex 1f59304..db6fc3c 100644--- a/README.ko.md+++ b/README.ko.md@@ -16,7 +16,7 @@**구경하기:** [라이브 데모](https://token-tv.vercel.app) 또는 `npx token-tv demo`, 시계·로그인 없이 바로.**설치하기:** 계속 켜 두는 컴퓨터에서 `npx token-tv start`(또는 `uvx token-tv start`). 로그인된 도구와 같은 와이파이의 시계를 찾고, 백그라운드에서 계속 돌며, 대시보드를 엽니다. AI에게 *"TokenTV 설정해줘"* 라고 해도 됩니다([AGENTS.md](AGENTS.md)).-**새 기능 Claude Code 모드:** Claude Code가 허락을 기다리면 Clawd가 손을 들고, 한 턴이 끝나면 인사합니다([설정 방법](https://github.com/click6067-ship-it/token-tv/blob/main/docs/claude-code-mod.md)).+**새 기능 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는 새로 온 친구들입니다.diff --git a/README.md b/README.mdindex 5948835..2aea7d9 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@ 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: Claude Code mode.** Clawd raises a hand when Claude Code needs you, bows when a turn ends, holds court over risky commands and sulks when you shout ([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.diff --git a/claude-plugin/.claude-plugin/plugin.json b/claude-plugin/.claude-plugin/plugin.jsonindex 8e5570d..ea15b86 100644--- a/claude-plugin/.claude-plugin/plugin.json+++ b/claude-plugin/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"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.",+ "description": "Your TokenTV desk clock shows Clawd raising a hand while Claude Code waits for your permission, a bow when a turn is done, a courtroom for a risky command, a ghost for a deleted file, its back turned for a rude prompt, dizzy after a failed tool and Claude Code's thinking word; /tokentv pet, snack and sound on|off. 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",diff --git a/claude-plugin/README.md b/claude-plugin/README.mdindex 618ae81..b1596df 100644--- a/claude-plugin/README.md+++ b/claude-plugin/README.md@@ -3,15 +3,20 @@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 asign); 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:+hearts or a cookie. A risky command puts Clawd on trial, a deleted file leaves a ghost about, a rude prompt turns+its back, a failed tool makes it dizzy and a compaction makes it squeeze its head; the readout says Claude Code's own+thinking word while a turn runs. `/tokentv sound on` adds a short sound on this computer when a prompt waits and+when a turn is done. 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.+`claude.answered`, `claude.end`, `claude.stop`, `claude.pet`, `claude.snack`, `claude.risky`, `claude.deleted`,+`claude.rude`, `claude.calm`, `claude.failed`, `claude.compact`, and `claude.word:` with the spinner's one word):+no prompt, command, path or id leaves it or is kept, nor the words typed after `/tokentv`, and nothing of Claude+Code's work is blocked or changed. 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).diff --git a/claude-plugin/hooks/register.ts b/claude-plugin/hooks/register.tsindex 157c76c..4f06d5a 100644--- a/claude-plugin/hooks/register.ts+++ b/claude-plugin/hooks/register.ts@@ -1,16 +1,23 @@// 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.+// `/tokentv snack` give Clawd a pat or a snack, one loop of hearts or munching. A risky command puts Clawd in the+// courtroom, a deleted file leaves a ghost about, a rude prompt turns its back, a failed tool makes it dizzy, a+// compaction makes it squeeze its head, and the readout says Claude Code's own thinking word while a turn runs.+// `/tokentv sound on` plays a short sound on this computer when a prompt waits for you and when a turn is done.//-// 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.+// It tells the TokenTV running on this computer a name 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.stop`+// (a turn that showed a thinking word was cut short), `claude.pet` and `claude.snack` (the two commands),+// `claude.risky`, `claude.deleted`, `claude.rude`, `claude.calm`, `claude.failed`, `claude.compact`, and+// `claude.word:` with one word of letters (Claude Code's spinner word, `claude.word:PONDERING`). Prompts, commands,+// their words, paths, outputs and ids stay in this file, and are read only to decide which name it is: nothing of+// them is kept. TokenTV counts the waits of every session, so each session says once that its prompt opened and+// once that it closed. Sounds go to TokenTV not at all.//-// 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).+// Nothing here is awaited on Claude Code's path, nor changes or blocks anything there: 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); the sound setting+// alone is kept, in Claude Code's own store for this plugin.// 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@@ -20,6 +27,14 @@ const MARGIN_MS = 5000const KEEP = 256 // calls already answered, remembered so a late repeat of one is not a new waitconst 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+const WORD = 'claude.word:' // and the spinner's word: one word of 1 to 14 letters A-Z, sent in capitals+const SAY_AGAIN_MS = 5 * 60 * 1000 // a word still on is said again this often (TokenTV lets a word go unheard 30 min)+const SOUNDS = { wait: 'sounds/wait.wav', done: 'sounds/done.wav' } // the plugin's own two short clips+const STORE_MS = 1000 // the longest the sound setting's store may take, read or written+// The most of a prompt and of a command read to tell which name it is (their head): a paste of megabytes would take+// a tenth of a second or more, and a shout or a risky command is short.+const PROMPT_READ = 64 * 1024+const COMMAND_READ = 128 * 1024// `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@@ -34,24 +49,46 @@ let interactive = true // false in `claude -p` and the SDK: nobody sits at a dialet mode: string | undefined // the permission mode, when Claude Code says it (auto mode's classifier asks no one)let lastTurn: string | undefinedlet queue: Promise<void> = Promise.resolve() // what is told goes out in the order it happened+// What a call that is still going has shown of itself, kept only till it ends: whether it asked you, ran (drawn+// running, or Claude Code's PostToolUseFailure for it), was cut short, or refused by a rule, a hook or auto mode.+const prompted = new Set<string>()+const ran = new Set<string>()+const cut = new Set<string>()+const denied = new Set<string>()+let turning = false // a main turn is going (turn.start to its turn.complete): the spinner's word is its+let said: string | undefined // the word this turn last sent...+let saidAt: number | undefined // ...and when+let sound = false // the sound setting as this session knows it (the store's, when it answers, wins)export function register(on: any) {on('session.start', async ($: any, e: any, next: any) => {interactive = e?.isInteractive !== falsetry {// `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 })+ await $.command.register({ name: 'tokentv',+ description: 'Pet Clawd on your TokenTV clock, give it a snack, or turn its sounds on or off',+ argumentHint: 'pet | snack | sound on | sound off', 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.+ // background: the command never waits for it). `/tokentv sound on` and `/tokentv sound off`: this computer's+ // sounds, nothing to TokenTV. 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 setting = /^sound\s+(on|off)$/.exec(word)+ if (setting) {+ sound = setting[1] === 'on'+ try {+ await within($, Promise.resolve($.store.set('sound', sound)), STORE_MS)+ } catch {}+ return { text: sound ? 'Sounds on: a short sound on this computer when Claude Code waits for you and when a ' ++ 'turn is done (Claude Code plays it on macOS; a Linux or Windows terminal stays silent).'+ : 'Sounds off.' }+ }const moment = word === 'pet' ? 'claude.pet' : word === 'snack' ? 'claude.snack' : undefined- if (!moment) return { text: 'Try /tokentv pet or /tokentv snack.' }+ if (!moment) return { text: 'Try /tokentv pet, /tokentv snack, or /tokentv sound on|off.' }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.' }@@ -63,7 +100,29 @@ export function register(on: any) {// 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)+ on('classic.PreToolUse', async ($: any, e: any, next: any) => {+ if (typeof e?.permission_mode === 'string') mode = e.permission_mode+ const verdict = await next(e)+ try {+ if (typeof verdict?.deny === 'string') note(denied, e?.tool_use_id) // a settings hook refused the call+ } catch {}+ return verdict+ })++ // A call that failed: one loop of Clawd dizzy, if it ran (not one you refused, nor one cut short). Claude Code+ // says which of its failures were interruptions; and when auto mode's classifier (or a rule) refused one.+ on('classic.PostToolUseFailure', async ($: any, e: any, next: any) => {+ try {+ note(e?.is_interrupt === true ? cut : ran, e?.tool_use_id)+ } catch {}+ return next(e)+ })+ on('classic.PermissionDenied', async ($: any, e: any, next: any) => {+ try {+ note(denied, e?.tool_use_id)+ } catch {}+ return next(e)+ })// 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.@@ -71,10 +130,14 @@ export function register(on: any) {const decided = await next(e)try {const id = e?.tool_use_id+ if (decided?.decision === 'deny') note(denied, id)if (asksYou(decided, id) && !waits.has(id) && !answered.includes(id)) {const wait = { agent: e.agentId ?? callers.get(id), at: 0 }+ const first = waits.size === 0 // this session's first prompt open: a wait begins (its sound, if on)waits.set(id, wait)+ note(prompted, id)send($, 'claude.ask', wait)+ if (first) cue($, 'wait')}} catch {}return decided@@ -85,10 +148,12 @@ export function register(on: any) {// `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)+ if (waits.size === 0 && callers.size === 0) return next(e)try {const calls = e?.component === 'ToolGroup' ? e.props?.calls ?? [] : [e?.props] // a ToolUse row is one callfor (const call of calls) {+ if (call?.isRunning === true) note(ran, call.tool_use_id) // (it ran: a failure now is the tool's own)+ if (call?.isInterrupted === true) note(cut, call.tool_use_id)if (waits.has(call?.tool_use_id) && (call.isRunning === true || call.output != null)) {answer($, call.tool_use_id)}@@ -97,28 +162,92 @@ export function register(on: any) {return next(e)})+ // The spinner's word while a turn runs (`Pondering`, as Claude Code samples it for the turn): one word of up to+ // 14 letters goes to TokenTV, once (and again every SAY_AGAIN_MS while it stays); anything else is left out. The+ // drawing passes on untouched.+ on('ui.render', { component: 'Spinner' }, async ($: any, e: any, next: any) => {+ try {+ const word = e?.props?.word+ if (turning && typeof word === 'string' && /^[A-Za-z]{1,14}$/.test(word)) say($, word.toUpperCase())+ } catch {}+ return next(e)+ })++ on('turn.start', async ($: any, e: any, next: any) => {+ turning = true // (a subagent's run raises no turn.start)+ said = saidAt = undefined+ return next(e)+ })++ // A prompt you typed (here, or from your phone through Remote Control): in capitals, or with a swear in it, Clawd+ // turns its back (`claude.rude`); any other turns it round (`claude.calm`). The prompt is read for that and+ // passed on untouched; nothing of it is kept or sent.+ on('prompt.submit', async ($: any, e: any, next: any) => {+ try {+ const from = e?.origin?.kind+ if (typeof e?.text === 'string' && (from === undefined || from === 'composer' || from === 'bridge')) {+ send($, rude(e.text.slice(0, PROMPT_READ)) ? 'claude.rude' : 'claude.calm')+ }+ } catch {}+ return next(e)+ })++ // A compaction of the main conversation, once done (not one computed ahead to keep, nor a subagent's): one loop+ // of Clawd squeezing its head. What was compacted passes on untouched.+ on('session.compact', async ($: any, e: any, next: any) => {+ const done = await next(e)+ try {+ if (!e?.agentId && e?.trigger !== 'precompute' && Array.isArray(done?.messages)) send($, 'claude.compact')+ } catch {}+ return done+ })+// 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.+ // (the tool ran, or was refused, or the turn was cut short), if no drawing said so before. A Bash command is read+ // as it is called, for its risk (the courtroom, said at once) and whether it deletes files (a ghost, said once it+ // succeeded); a call of any tool that ran and failed is a dizzy Clawd. The call and its result pass through+ // untouched.on('tool.call', async ($: any, e: any, next: any) => {const id = e?.tool_use_idif (typeof id === 'string') callers.set(id, e.agentId) // tool.check carries it only from Claude Code 2.1.290+ let kinds: Kinds | undefined+ try {+ kinds = e?.tool === 'Bash' && typeof e?.command === 'string' ? judged(e.command.slice(0, COMMAND_READ)) : undefined+ if (kinds?.risky) send($, 'claude.risky')+ } catch {}+ let result: anytry {- return await next(e)+ result = await next(e)+ return result} finally {callers.delete(id)answer($, id)+ try {+ finished($, id, kinds, result, next?.signal)+ } catch {}}})- // A turn's end closes its open prompts; the main turn's end, when it was not cut short, is a bow.+ // A turn's end closes its open prompts; the main turn's end, when it was not cut short, is a bow (and its sound,+ // if on). One cut short that showed a word says so, so its word goes too.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')+ if (!e?.agentId) {+ const spoke = said !== undefined+ turning = false+ said = saidAt = undefined+ if (id === undefined || id !== lastTurn) {+ if (!e?.isAborted) {+ lastTurn = id+ send($, 'claude.end')+ cue($, 'done')+ } else if (spoke) {+ lastTurn = id+ send($, 'claude.stop')+ }+ }}} catch {}return next(e)@@ -127,11 +256,69 @@ export function register(on: any) {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+ if (turning && said !== undefined) send($, 'claude.stop') // ended mid-turn: its word goes+ turning = false+ said = saidAt = undefined} catch {}return next(e)})}+// A call still going (tool.call has it): what it showed of itself, till it ends.+function note(set: Set<string>, id: unknown) {+ if (typeof id === 'string' && callers.has(id)) set.add(id)+}++// A call is over with `result`: a Bash call that deleted files and succeeded leaves a ghost; any call that ran and+// failed (Claude Code says isError) makes Clawd dizzy, but not one refused (by you, a rule, a hook or auto mode),+// cut short or abandoned. What the call showed of itself is let go here.+function finished($: any, id: unknown, kinds: Kinds | undefined, result: any, signal: any) {+ const key = typeof id === 'string' ? id : ''+ const shown = { asked: prompted.has(key), ran: ran.has(key), cut: cut.has(key), denied: denied.has(key) }+ for (const set of [prompted, ran, cut, denied]) set.delete(key)+ if (!result || typeof result !== 'object' || typeof result.deny === 'string' || signal?.aborted === true) return+ if (result.isError === true) {+ if (!shown.cut && !shown.denied && (!shown.asked || shown.ran)) send($, 'claude.failed')+ } else if (kinds?.deletes) {+ send($, 'claude.deleted')+ }+}++// The spinner's word: sent when it is new this turn, and again only once SAY_AGAIN_MS has gone by.+function say($: any, word: string) {+ if (word !== said) {+ said = word+ saidAt = undefined+ send($, WORD + word)+ clockNow($).then((now) => { if (said === word) saidAt = now }, () => {})+ return+ }+ clockNow($).then((now) => {+ if (said === word && saidAt !== undefined && now - saidAt >= SAY_AGAIN_MS) {+ saidAt = now+ send($, WORD + word)+ }+ }, () => {})+}++// A short sound on this computer (`wait` or `done`), if the setting is on: Claude Code's own player plays the+// plugin's clip; nothing goes to TokenTV for it, and nothing waits for it. Where there is no player (a Linux or+// Windows terminal), or it fails, nothing sounds.+function cue($: any, which: 'wait' | 'done') {+ soundOn($)+ .then((on) => (on ? $.audio.play({ asset: SOUNDS[which] }) : undefined))+ .catch(() => {})+}++// The sound setting: the store's (so a change in one session holds in the others), else this session's.+async function soundOn($: any) {+ try {+ const kept = await within($, Promise.resolve($.store.get('sound')), STORE_MS)+ if (typeof kept === 'boolean') return kept+ } catch {}+ return sound+}+async function noteMode($: any, e: any, next: any) {if (typeof e?.permission_mode === 'string') mode = e.permission_modereturn next(e)@@ -274,3 +461,441 @@ function loopback(text: unknown) {if (!found || Number(found[2]) < 1 || Number(found[2]) > 65535) return undefinedreturn 'http://' + (found[1] === 'localhost' ? '127.0.0.1' : found[1]) + ':' + Number(found[2])}++// --- Which name: the prompt and the Bash command, read here and kept nowhere -------------------------------------++// e7: a prompt in capitals (at least CAPS_MIN letters, four in five or more of them capitals; a letter of a script+// without capitals, Hangul say, counts as a letter that is not one) or with a swear in it: SWEAR_EN, whole words in+// any case; SWEAR_KO, words starting so, but not the everyday words in SWEAR_KO_NOT. The owner's lists, one place.+const CAPS_MIN = 8+const SWEAR_EN = new Set(['fuck', 'fucks', 'fucked', 'fucking', 'fucker', 'motherfucker', 'shit', 'shitty', 'bullshit',+ 'damn', 'dammit', 'damnit', 'goddamn', 'wtf', 'stfu', 'bitch', 'asshole', 'bastard'])+const SWEAR_KO = ['씨발', '시발', '씨팔', 'ㅅㅂ', 'ㅆㅂ', '개새끼', '병신', '지랄', '존나', '좆']+const SWEAR_KO_NOT = ['시발점', '시발역', '병신년']++function rude(text: string) {+ const letters = text.match(/\p{L}/gu) ?? []+ const capitals = letters.filter((c) => /\p{Lu}|\p{Lt}/u.test(c)).length+ if (letters.length >= CAPS_MIN && capitals * 5 >= letters.length * 4) return true+ return (text.match(/[\p{L}\p{M}]+/gu) ?? []).some((word) => SWEAR_EN.has(word.toLowerCase()) ||+ (SWEAR_KO.some((stem) => word.startsWith(stem)) && !SWEAR_KO_NOT.some((benign) => word.startsWith(benign))))+}++// e3, e4: what a Bash command does, read as a shell would (quotes, comments, here-documents and redirections are+// data; `;`, `&&`, `|`, `$(…)`, backquotes, `bash -c`, `eval`, `find -exec` and wrappers such as `sudo` or `env`+// lead to commands; `command -v` and the like only look one up). Risky: `rm` recursive and forced, `git push+// --force` (`-f`, `--force-with-lease`, a `+refspec`), `git reset --hard`, `git clean` forced with directories (not+// a dry run), `DROP TABLE` or `DROP DATABASE` given to a database client as SQL (not in a string or a comment),+// `mkfs`, `dd of=/dev/…`, `chmod -R 777 /`. Deleting: `rm`, `git rm` (not `--cached`, not a dry run), `find …+// -delete` (or `-exec rm`), `unlink`, each with something to delete. Read in one pass: a command of many parts takes+// no longer than its length says.+type Kinds = { risky: boolean; deletes: boolean }+type Command = { words: string[]; input: string[]; pipe: number }++const PREFIXES = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{'])+// A wrapper runs the command after it: its options that take a value, and the words it takes before the command;+// with an option `looks` matches, it only looks the command up (`command -v rm`) and runs nothing.+const WRAPPERS = new Map<string, { takes: string[]; operands: number; looks?: RegExp }>(Object.entries({+ sudo: { takes: ['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-t', '-U', '-T', '--user', '--group', '--chdir', '--host',+ '--prompt', '--role', '--type', '--other-user', '--command-timeout', '--close-from'], operands: 0 },+ doas: { takes: ['-u', '-C'], operands: 0 },+ env: { takes: ['-u', '-C', '-S', '--unset', '--chdir', '--split-string'], operands: 0 },+ command: { takes: [], operands: 0, looks: /^-[A-Za-z]*[vV]/ },+ builtin: { takes: [], operands: 0 },+ exec: { takes: ['-a'], operands: 0 },+ nohup: { takes: [], operands: 0 },+ time: { takes: ['-f', '-o', '--format', '--output'], operands: 0 },+ nice: { takes: ['-n', '--adjustment'], operands: 0 },+ ionice: { takes: ['-c', '-n', '-p', '-P', '-u'], operands: 0 },+ timeout: { takes: ['-s', '-k', '--signal', '--kill-after'], operands: 1 },+ setsid: { takes: [], operands: 0 },+ stdbuf: { takes: ['-i', '-o', '-e'], operands: 0 },+ xargs: { takes: ['-I', '-n', '-P', '-L', '-s', '-d', '-E', '-a', '--max-args', '--max-procs', '--max-lines',+ '--max-chars', '--delimiter', '--eof', '--arg-file', '--replace'], operands: 0 },+}))+const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh'])+// The commands judge() reads (with mkfs.<kind> and the shells): any other runs nothing of the lists.+const JUDGED = new Set(['rm', 'unlink', 'git', 'find', 'dd', 'chmod', 'eval', ...SHELLS])+const SQL = new Set(['psql', 'mysql', 'mariadb', 'sqlite3', 'sqlcmd', 'duckdb', 'clickhouse', 'clickhouse-client',+ 'cockroach', 'pgcli', 'mycli', 'litecli', 'usql', 'sqlplus', 'snowsql', 'bq', 'trino', 'beeline'])+const HASH_COMMENTS = new Set(['mysql', 'mariadb', 'mycli']) // `#` starts a comment there (elsewhere an operator)+const CLIENT = 1 // a pipeline's marks (judged)+const HASH = 2+const DROPS = 4+const OPEN_ALL = new Set(['777', '0777', 'a+rwx', 'a=rwx', 'ugo+rwx', 'ugo=rwx'])+const GIT_VALUED = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--super-prefix', '--config-env'])+// find's tests and actions that take the next word as their value (a pattern, a name, a format, a file): never an+// action itself, as `-name '-delete'` is not one. (`-fprintf` takes two, `-newerXY` one.)+const FIND_VALUED = new Set(['-name', '-iname', '-path', '-ipath', '-wholename', '-iwholename', '-regex', '-iregex',+ '-lname', '-ilname', '-newer', '-anewer', '-cnewer', '-samefile', '-perm', '-type', '-xtype', '-user', '-group',+ '-uid', '-gid', '-size', '-mtime', '-atime', '-ctime', '-mmin', '-amin', '-cmin', '-used', '-links', '-inum',+ '-maxdepth', '-mindepth', '-fstype', '-context', '-printf', '-fprint', '-fprint0', '-fls', '-regextype',+ '-files0-from'])++function judged(source: string, depth = 0): Kinds {+ const kinds = { risky: false, deletes: false }+ if (depth > 4) return kinds // (`bash -c` within `bash -c` within …: enough)+ const commands: Command[] = []+ const pipes = { n: 0 }+ parse(source, { i: 0 }, '', commands, pipes)+ // Each pipeline's marks: a database client is in it (CLIENT; HASH when `#` starts a comment there), it says "drop"+ // somewhere (DROPS). A DROP counts only in a pipeline with both, as SQL one of its clients reads.+ const marks = new Uint8Array(pipes.n)+ for (const command of commands) {+ const found = unwrapped(command.words)+ if (found && SQL.has(found.name)) marks[command.pipe] |= CLIENT | (HASH_COMMENTS.has(found.name) ? HASH : 0)+ if (command.words.some(saysDrop) || command.input.some(saysDrop)) marks[command.pipe] |= DROPS+ judge(found, kinds, depth)+ }+ const texts = new Map<number, string[]>()+ for (const command of commands) {+ if ((marks[command.pipe] & (CLIENT | DROPS)) !== (CLIENT | DROPS)) continue+ let parts = texts.get(command.pipe)+ if (!parts) texts.set(command.pipe, (parts = []))+ for (const word of command.words) parts.push(given(word))+ for (const text of command.input) parts.push(text)+ }+ for (const [pipe, parts] of texts) {+ if (drops(parts.map((text) => sqlRead(text, (marks[pipe] & HASH) !== 0)))) kinds.risky = true+ }+ return kinds+}++function saysDrop(text: string) {+ return text.length >= 4 && /drop/i.test(text)+}++// What of a word in a database client's pipeline may be SQL: an option's value (`--command=…`), not the option.+function given(word: string) {+ if (word[0] !== '-') return word+ const valued = /^--?[A-Za-z][\w-]*=/.exec(word)+ return valued ? word.slice(valued[0].length) : /^-\S*$/.test(word) ? '' : word+}++// DROP TABLE or DROP DATABASE as SQL in the texts read (sqlRead), not in a string or a comment; but where the SQL+// runs a string as a statement (EXECUTE, PREPARE, a DO block), a DROP in its strings counts too.+function drops(read: [string, string][]) {+ const dynamic = read.some(([bare]) => /\b(EXECUTE|PREPARE)\b|(^|;)\s*DO\b/i.test(bare))+ return /\bDROP\s+(TABLE|DATABASE)\b/i.test(read.map((both) => both[dynamic ? 1 : 0]).join(' '))+}++// `text` read as SQL, its comments left out (`-- …`, `/* … */`, and `# …` where `hash`): [without its string+// literals and quoted names, with them]. Those are `'…'` and `"…"` (a backslash escapes in them), `` `…` `` and+// `$tag$…$tag$`. One pass: each literal or comment is skipped whole.+const DOLLAR_TAG = /\$(?:[A-Za-z_]\w{0,62})?\$/y++function sqlRead(text: string, hash: boolean): [string, string] {+ if (!/['"`$#/-]/.test(text)) return [text, text] // (nothing of the kind in it)+ const bare: string[] = []+ const full: string[] = []+ let from = 0 // the SQL not yet kept starts here+ let i = 0+ while (i < text.length) {+ const c = text[i]+ let end = -1 // where the literal or comment starting at `i` ends+ let literal = false+ if (c === "'" || c === '"' || c === '`') {+ let j = i + 1+ while (j < text.length && text[j] !== c) j += text[j] === '\\' && c !== '`' ? 2 : 1+ end = Math.min(j + 1, text.length)+ literal = true+ } else if ((c === '-' && text[i + 1] === '-') || (c === '#' && hash)) {+ end = text.indexOf('\n', i)+ if (end < 0) end = text.length+ } else if (c === '/' && text[i + 1] === '*') {+ end = text.indexOf('*/', i + 2)+ end = end < 0 ? text.length : end + 2+ } else if (c === '$' && !/[\w$]/.test(text[i - 1] ?? ' ')) {+ DOLLAR_TAG.lastIndex = i+ const tag = DOLLAR_TAG.exec(text)?.[0]+ if (tag) {+ const close = text.indexOf(tag, i + tag.length)+ end = close < 0 ? text.length : close + tag.length+ literal = true+ }+ }+ if (end < 0) {+ i+++ continue+ }+ const sql = text.slice(from, i)+ bare.push(sql, ' ')+ full.push(sql, literal ? text.slice(i, end) : ' ')+ from = i = end+ }+ bare.push(text.slice(from))+ full.push(text.slice(from))+ return [bare.join(''), full.join('')]+}++// What the command `found` (unwrapped) runs, into `kinds`.+function judge(found: Found | undefined, kinds: Kinds, depth: number) {+ if (!found) return+ const name = found.name+ const mkfs = name.startsWith('mkfs') && /^mkfs(\.[A-Za-z0-9]+)?$/.test(name)+ if (!JUDGED.has(name) && !mkfs) return // (most commands)+ const args = found.words.slice(1)+ const either = (more: Kinds) => {+ kinds.risky ||= more.risky+ kinds.deletes ||= more.deletes+ }+ if (SHELLS.has(name)) {+ const at = args.findIndex((a) => /^-[A-Za-z]*c[A-Za-z]*$/.test(a))+ if (at >= 0 && typeof args[at + 1] === 'string') either(judged(args[at + 1], depth + 1))+ return+ }+ if (name === 'eval') return either(judged(args.join(' '), depth + 1))+ if (name === 'git') return git(args, kinds)+ if (name === 'dd') {+ if (args.some((a) => a.startsWith('of=/dev/'))) kinds.risky = true+ return+ }+ if (name === 'find') {+ for (let k = 0; k < args.length; k++) {+ const a = args[k]+ if (a === '-delete') kinds.deletes = true+ else if (a === '-fprintf') k += 2+ else if (FIND_VALUED.has(a) || /^-newer[aBcmt]{2}$/.test(a)) k++ // (its value, whatever it says)+ else if (['-exec', '-execdir', '-ok', '-okdir'].includes(a)) {+ let end = k + 1+ while (end < args.length && args[end] !== ';' && args[end] !== '+') end+++ judge(unwrapped(args.slice(k + 1, end)), kinds, depth)+ k = end+ }+ }+ return+ }+ const opts = options(args)+ const has = (short: string, long: string) => opts.short.has(short) || opts.long.has(long)+ const something = opts.operands.length > 0 || found.fed // (xargs gives it what to work on)+ if (name === 'rm' && something && !opts.long.has('help') && !opts.long.has('version')) {+ kinds.deletes = true+ if ((has('r', 'recursive') || opts.short.has('R')) && has('f', 'force')) kinds.risky = true+ } else if (name === 'unlink' && something) {+ kinds.deletes = true+ } else if (name === 'chmod') {+ const [mode, ...targets] = opts.operands+ if (has('R', 'recursive') && OPEN_ALL.has(mode ?? '') && targets.some((t) => t === '/' || t === '/*')) kinds.risky = true+ } else if (mkfs && opts.operands.length > 0) {+ kinds.risky = true+ }+}++function git(args: string[], kinds: Kinds) {+ let k = 0+ while (k < args.length && args[k].startsWith('-')) k += GIT_VALUED.has(args[k]) ? 2 : 1 // git's own options+ const sub = args[k]+ const opts = options(args.slice(k + 1))+ if (sub === 'push') {+ // forced by an option, or by a refspec after the remote that starts with `+` (`git push origin +main`)+ const plus = opts.operands.slice(1).some((ref) => ref.length > 1 && ref.startsWith('+'))+ if (opts.short.has('f') || opts.long.has('force') || opts.long.has('force-with-lease') || plus) kinds.risky = true+ } else if (sub === 'reset') {+ if (opts.long.has('hard')) kinds.risky = true+ } else if (sub === 'clean') {+ const force = opts.short.has('f') || opts.long.has('force')+ const dry = opts.short.has('n') || opts.long.has('dry-run')+ if (force && opts.short.has('d') && !dry) kinds.risky = true+ } else if (sub === 'rm') {+ const dry = opts.short.has('n') || opts.long.has('dry-run')+ if (!dry && !opts.long.has('cached') && opts.operands.length > 0) kinds.deletes = true+ }+}++// The words before `--` as short options (each letter) and long ones (name before any `=`), and the operands.+function options(args: string[]) {+ const short = new Set<string>()+ const long = new Set<string>()+ const operands: string[] = []+ let ended = false+ for (const a of args) {+ if (ended || a === '-' || !a.startsWith('-')) operands.push(a)+ else if (a === '--') ended = true+ else if (a.startsWith('--')) long.add(a.slice(2).split('=')[0])+ else for (const c of a.slice(1)) short.add(c)+ }+ return { short, long, operands }+}++// The command a simple command runs: past its variable assignments, the shell's words before a command (`if`,+// `then`, `!`, …) and wrappers with their options. `fed`: xargs gives it what to work on. None when it runs none+// (`command -v rm` only looks rm up).+type Found = { words: string[]; fed: boolean; name: string } // (name: the command's, its folder left out)++function unwrapped(words: string[]): Found | undefined {+ let k = 0+ let fed = false+ for (let guard = 0; guard < 32 && k < words.length; guard++) {+ const word = words[k]+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word) || PREFIXES.has(word)) {+ k+++ continue+ }+ const name = basename(word)+ const wrapper = WRAPPERS.get(name)+ if (!wrapper) break+ fed ||= name === 'xargs'+ k+++ while (k < words.length && words[k].startsWith('-') && words[k] !== '-') {+ const opt = words[k++]+ if (opt === '--') break+ if (wrapper.looks?.test(opt)) return undefined+ if (wrapper.takes.includes(opt)) k+++ }+ k += wrapper.operands+ }+ return k < words.length ? { words: k ? words.slice(k) : words, fed, name: basename(words[k]) } : undefined+}++function basename(word: string) {+ return word.slice(word.lastIndexOf('/') + 1)+}++// A shell's reading of `source` from `at.i` up to `stop` (`)` closing `$(`, a backquote) or its end: each simple+// command's words (unquoted), what it is fed (here-documents, here-strings) and its pipeline, into `out`.+function parse(source: string, at: { i: number }, stop: string, out: Command[], pipes: { n: number }) {+ let words: string[] = []+ let input: string[] = []+ let word = ''+ let has = false // a word has begun (an empty quoted one is a word)+ let route: 'arg' | 'file' | 'heredoc' | 'herestring' = 'arg' // where the next word goes, after a redirection+ let strip = false // `<<-`: the here-document's lines lose their leading tabs+ let depth = 0 // subshells open, `( … )`+ let pipe = pipes.n+++ const heredocs: { end: string; strip: boolean; into: string[] }[] = []+ const endWord = () => {+ if (!has) return+ if (route === 'arg') words.push(word)+ else if (route === 'heredoc') heredocs.push({ end: word, strip, into: input })+ else if (route === 'herestring') input.push(word)+ route = 'arg'+ word = ''+ has = false+ }+ const endCommand = (piped: boolean) => {+ endWord()+ route = 'arg'+ if (words.length || input.length) out.push({ words, input, pipe })+ words = []+ input = []+ if (!piped) pipe = pipes.n+++ }+ const bodies = () => { // after a line's end: the here-documents it began, each up to its own end line+ for (const doc of heredocs.splice(0)) {+ const lines: string[] = []+ while (at.i < source.length) {+ const end = source.indexOf('\n', at.i)+ const line = source.slice(at.i, end < 0 ? source.length : end)+ at.i = end < 0 ? source.length : end + 1+ if ((doc.strip ? line.replace(/^\t+/, '') : line) === doc.end) break+ lines.push(line)+ }+ doc.into.push(lines.join('\n'))+ }+ }+ const substitution = (close: string) => { // `$( … )` or a backquote's: commands of their own+ parse(source, at, close, out, pipes)+ word += close === ')' ? '$()' : '``'+ has = true+ }+ const quoted = () => { // "…": a backslash keeps only $ ` " \ and a newline; $( … ) and backquotes still run+ while (at.i < source.length) {+ const c = source[at.i]+ if (c === '"') {+ at.i+++ return+ }+ if (c === '\\' && '$`"\\\n'.includes(source[at.i + 1] ?? 'x')) {+ if (source[at.i + 1] !== '\n') word += source[at.i + 1]+ at.i += 2+ } else if (c === '$' && source[at.i + 1] === '(') {+ at.i += 2+ substitution(')')+ } else if (c === '`') {+ at.i+++ substitution('`')+ } else {+ word += c+ at.i+++ }+ }+ }+ while (at.i < source.length) {+ const c = source[at.i]+ const next = source[at.i + 1]+ if (stop === '`' && c === '`') {+ at.i+++ break+ }+ if (c === '\\') {+ if (next !== '\n') {+ word += next ?? ''+ has = true+ }+ at.i += 2+ } else if (c === "'") {+ const end = source.indexOf("'", at.i + 1)+ word += source.slice(at.i + 1, end < 0 ? source.length : end)+ has = true+ at.i = end < 0 ? source.length : end + 1+ } else if (c === '"') {+ at.i+++ has = true+ quoted()+ } else if (c === '$' && next === '(') {+ at.i += 2+ substitution(')')+ } else if (c === '`') {+ at.i+++ substitution('`')+ } else if ((c === '<' || c === '>') && next === '(') { // <( … ): a command, its output a file+ endWord()+ at.i += 2+ parse(source, at, ')', out, pipes)+ } else if (c === '#' && !has) { // a comment, to the line's end+ const end = source.indexOf('\n', at.i)+ at.i = end < 0 ? source.length : end+ } else if (c === ' ' || c === '\t') {+ endWord()+ at.i+++ } else if (c === '\n') {+ endCommand(false)+ at.i+++ bodies()+ } else if (c === '&' && next === '>') { // &> and &>>: both outputs to a file+ endWord()+ route = 'file'+ at.i += source[at.i + 2] === '>' ? 3 : 2+ } else if (c === ';' || c === '&' || c === '|') {+ endCommand(c === '|' && next !== '|') // `|` and `|&` go on in the same pipeline+ at.i += (c === '&' && next === '&') || (c === '|' && (next === '|' || next === '&')) ||+ (c === ';' && (next === ';' || next === '&')) ? 2 : 1 // (&&, ||, |&, ;;, ;&)+ } else if (c === '(') {+ endCommand(false)+ depth+++ at.i+++ } else if (c === ')') {+ at.i+++ if (depth === 0 && stop === ')') break+ endCommand(false)+ depth = Math.max(0, depth - 1)+ } else if (c === '<' || c === '>') { // a redirection: a word of digits before it is its descriptor+ if (has && route === 'arg' && /^\d+$/.test(word)) {+ word = ''+ has = false+ } else {+ endWord()+ }+ let op = c+ at.i+++ while (at.i < source.length && op.length < 3 && '<>&|-'.includes(source[at.i])) op += source[at.i++]+ route = op === '<<' || op === '<<-' ? 'heredoc' : op === '<<<' ? 'herestring' : 'file'+ strip = op === '<<-'+ } else {+ word += c+ has = true+ at.i+++ }+ }+ endCommand(false)+}diff --git a/claude-plugin/sounds/done.wav b/claude-plugin/sounds/done.wavnew file mode 100644index 0000000..0f7d2a0Binary files /dev/null and b/claude-plugin/sounds/done.wav differdiff --git a/claude-plugin/sounds/wait.wav b/claude-plugin/sounds/wait.wavnew file mode 100644index 0000000..28193fdBinary files /dev/null and b/claude-plugin/sounds/wait.wav differdiff --git a/claude-plugin/tests/phase3a.test.ts b/claude-plugin/tests/phase3a.test.tsnew file mode 100644index 0000000..81796b5--- /dev/null+++ b/claude-plugin/tests/phase3a.test.ts@@ -0,0 +1,737 @@+import { expect, mock, test } from 'claude-code/testing'++// Phase 3a in the mod: the names a Bash command, a prompt, a failed tool, a compaction and the spinner's word bring,+// and the sounds. A fake computer as in register.test.ts: a TokenTV state folder with its socket, Claude Code's own+// answers (a call waits inside next() until the test settles it), and what the mod sends, caught at $.http.fetch.+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: ['drawn by Claude Code'] }++function computer(on: any, options: any = {}) {+ const files: Record<string, string> = options.files ?? { [STATE + '/live.url']: 'http://127.0.0.1:8791' }+ const sockets: string[] = options.sockets ?? [STATE + '/live.sock']+ const sent: any[] = []+ const gates: Record<string, (answer: any) => void> = {}+ const verdicts: Record<string, any> = options.verdicts ?? {}+ mock.env(on, options.env ?? { HOME })+ const find = (path: string) => Object.keys(files).find((name) => path === name || path.endsWith('/' + name))+ on('fs.read', ($: any, e: any) => (find(e.path) ? { value: files[find(e.path)!] } : { deny: 'ENOENT: no such file' }))+ on('fs.exists', ($: any, e: any) => ({ value: sockets.some((s) => e.path === s || e.path.endsWith('/' + s)) || Boolean(find(e.path)) }))+ on('fs.stat', ($: any, e: any) => (find(e.path) ? { value: { kind: 'file', size: 1, mtimeMs: 1, isLink: false } }+ : { deny: 'ENOENT: no such file' }))+ on('session.root', () => ({ value: '/work' }))+ on('http.fetch', options.fetch ?? (($: any, e: any) => {+ sent.push(e)+ return { value: { status: 204, ok: true, headers: {}, text: '' } }+ }))+ const calls: any[] = []+ const reached: number[] = [] // when each call reached Claude Code's own step (Date.now())+ const results: any[] = []+ on('tool.call', async ($: any, e: any) => { // Claude Code: the check, you and the tool, until the test settles it+ calls.push(e)+ reached.push(Date.now())+ const answer = await new Promise<any>((done) => { gates[e.tool_use_id] = done })+ return answer ?? { result: 'ran ' + e.tool_use_id }+ })+ on('tool.check', ($: any, e: any) => verdicts[e.tool_use_id] ?? { decision: 'allow' })+ on('ui.render', ($: any, e: any) => DRAWN)+ on('turn.start', ($: any, e: any) => ({ turnId: e.turnId }))+ on('turn.complete', () => ({ text: '' }))+ on('prompt.submit', ($: any, e: any) => ({ text: e.text }))+ on('session.compact', ($: any, e: any) => (options.skip ? { skip: 'no' } : { messages: [{ role: 'user', text: 'summary', toolUses: [] }] }))+ on('session.start', () => ({ cwd: '/work' }))+ on('session.end', () => ({ sessionId: 'session' }))+ on('classic.SessionStart', () => ({}))+ on('classic.PostToolUseFailure', () => ({}))+ on('classic.PermissionDenied', () => ({}))+ on('command.register', () => ({ value: { command: 'tokentv' } }))+ const store: Record<string, unknown> = options.store ?? {}+ const writes: any[] = []+ if (options.store !== false) {+ on('store.get', ($: any, e: any) => ({ value: store[e.key] }))+ on('store.set', ($: any, e: any) => {+ writes.push([e.key, e.value])+ store[e.key] = e.value+ return { value: undefined }+ })+ }+ const plays: any[] = []+ on('audio.play', options.audio ?? (($: any, e: any) => {+ plays.push(e.clip)+ return { value: undefined }+ }))+ return {+ sent, calls, reached, results, plays, store, writes,+ settle: (id: string, answer?: any) => gates[id]?.(answer),+ moments: () => sent.map((s) => JSON.parse(s.init.body).moment),+ }+}++// A Bash call as Claude Code makes it, once Claude Code has it (the mod saw it start); the test settles it later.+async function bash($: any, pc: any, id: string, command: string) {+ return started($, pc, { tool: 'Bash', command, tool_use_id: id })+}+async function started($: any, pc: any, input: any) {+ const call = $.tool.call(input)+ call.catch(() => {}) // (a call a test leaves waiting is let go with the test)+ await until(() => pc.calls.some((c: any) => c.tool_use_id === input.tool_use_id))+ return { call }+}++const turn = (turnId: string, extra: any = {}) =>+ ({ turnId, answer: 'done', durationMs: 1200, isAborted: false, reason: 'answer', usage: null, ...extra })+const spinner = ($: any, word: unknown, extra: any = {}) =>+ $.ui.render({ surface: 'terminal', component: 'Spinner', requestId: 'main',+ props: { word, message: null, suffix: '…', mode: 'thinking', ...extra } })+const typed = ($: any, text: string, kind = 'composer') => $.prompt.submit({ text, origin: { kind }, wait: false })+const named = (e: any) => JSON.parse(e.init.body).moment+// Until `count` requests have gone out (each waits for the one before it), or a second has gone by.+async function sent(pc: any, count: number) {+ await until(() => pc.sent.length >= count)+}+// Until `done()` holds, or a second has gone by (a busy computer: the host's own steps take their time).+async function until(done: () => boolean) {+ for (let k = 0; k < 40 && !done(); k++) await flush()+}++// --- e3: the courtroom ---------------------------------------------------------------------------------------------++const RISKY = [+ 'rm -rf ./fixture-dir-CANARY-A1', 'git push --force origin fixture-CANARY-A2', 'git push -f origin fixture',+ 'git reset --hard HEAD', 'git clean -fd', "psql -c 'DROP TABLE fixture_table'", 'mysql -e "DROP DATABASE fixture_db"',+ 'mkfs /dev/fixture', 'dd if=fixture.img of=/dev/fixture', 'chmod -R 777 /',+ // the same commands as a shell would also run them+ 'rm -fr ./x', 'rm -r -f ./x', 'rm --recursive --force ./x', 'rm -Rf ./x', 'sudo rm -rf /var/fixture',+ 'sudo -u root rm -rf ./x', '/bin/rm -rf ./x', 'FOO=1 rm -rf ./x', 'env FOO=1 rm -rf ./x', 'cd build && rm -rf out',+ 'ls; rm -rf ./x', 'true || rm -rf ./x', "bash -c 'rm -rf ./x'", 'sh -lc "git push --force"',+ 'git -C repo push --force-with-lease origin main', 'git push -uf origin main', 'git clean -fdx', 'git clean -f -d',+ 'mkfs.ext4 /dev/sdb1', 'timeout 10 rm -rf ./x', 'find . -name "*.o" | xargs rm -rf',+ 'find . -type d -exec rm -rf {} +', 'echo $(rm -rf ./x)', 'echo "DROP TABLE t;" | psql', 'sqlite3 db.sqlite "drop table t"',+ "psql <<'SQL'\nDROP TABLE fixture;\nSQL", 'chmod --recursive 0777 /', 'time rm -rf ./x', 'nohup rm -rf ./x &',+ // SQL that drops, a string or a comment beside it; a string run as a statement; a force push by a `+refspec`+ 'psql -c "SELECT \'x\'; DROP TABLE x"', 'psql -c "-- tidy up\nDROP TABLE x"', 'psql --command="DROP TABLE x"',+ 'psql -c \'DROP TABLE "x"\'', "mysql -e 'DROP TABLE `x`'", "psql -c 'DO $$ BEGIN DROP TABLE x; END $$'",+ 'mysql -e "PREPARE s FROM \'DROP TABLE x\'; EXECUTE s"', 'psql -c "/* old */ DROP DATABASE d"',+ 'git push origin +main', 'git push origin +HEAD:refs/heads/main', 'git push origin main +dev',+ 'toString -x; rm -rf ./x', // (a command named like an Object property hides nothing after it)+]+const NOT_RISKY = [+ 'git push origin fixture', 'git reset --soft HEAD', 'git clean -n', 'git clean -fdn', 'git clean -f',+ 'chmod 777 ./file', 'chmod -R 755 ./folder', 'chmod -R 777 ./folder', 'dd if=fixture.img of=./copy.img',+ "psql -c 'SELECT * FROM fixture'", "printf '%s' 'rm -rf ./x'", '# git push --force', 'ls # git push --force',+ 'echo DROP TABLE fixture', 'mkfs_notes', 'myrm -rf ./x', 'rm -r ./x', 'rm -f ./x', 'rm -rf', 'git commit -m "rm -rf build"',+ "git commit -m \"$(cat <<'EOF'\nfix: no more git push --force\n1) rm -rf build is gone\nEOF\n)\"",+ "cat <<'EOF' > notes.md\nrm -rf /\nEOF", 'grep -r "git reset --hard" .', 'echo "chmod -R 777 /"', 'git log --grep=force',+ 'git push --follow-tags origin main', 'npm run clean', "python3 -c 'import os'", 'echo mkfs /dev/sda',+ // DROP as data to a database client: in a string, a quoted name or a comment+ 'psql -c "SELECT \'DROP TABLE fixture\';"', 'psql -c "SELECT 1; -- DROP TABLE x"',+ 'psql -c "/* DROP TABLE x */ SELECT 1"',+ 'mysql -e "SELECT 1 # DROP TABLE x"', "psql -c 'SELECT $$DROP TABLE x$$'", 'psql -c \'SELECT "DROP TABLE x" FROM t\'',+ "psql <<'SQL'\n-- DROP TABLE x\nSELECT 'DROP DATABASE y';\nSQL", 'echo "-- DROP TABLE x" | psql',+ 'psql --command="SELECT \'DROP TABLE x\'"', "mysql -e \"INSERT INTO log VALUES ('it\\'s DROP TABLE x')\"",+ 'git push origin :old-branch', 'git push origin main',+]++test('every risky command family says claude.risky as the call starts, and nothing of the command', async ($: any, on: any) => {+ const pc = computer(on)+ for (const [k, command] of RISKY.entries()) {+ const before = pc.sent.length+ const { call } = await bash($, pc, 'r' + k, command)+ await sent(pc, before + 1)+ expect([command, pc.moments().slice(-1)[0]]).toEqual([command, 'claude.risky']) // the call still running+ expect(await Promise.race([call, flush().then(() => 'running')])).toBe('running')+ pc.settle('r' + k, { isError: true, result: 'stopped by the test', text: 'stopped' })+ await call+ }+ await flush()+ expect(pc.moments().filter((m) => m === 'claude.risky').length).toBe(RISKY.length)+ expect(JSON.stringify(pc.sent)).not.toContain('CANARY')+ for (const one of pc.sent) expect(Object.keys(JSON.parse(one.init.body))).toEqual(['moment'])+})++test('near misses, mentions and data are no risky command', async ($: any, on: any) => {+ const pc = computer(on)+ for (const [k, command] of NOT_RISKY.entries()) {+ const { call } = await bash($, pc, 'n' + k, command)+ await flush()+ pc.settle('n' + k, { isError: true, result: 'stopped by the test', text: 'stopped' })+ await call+ await flush()+ expect([command, pc.moments().includes('claude.risky')]).toEqual([command, false])+ }+ // risky words only in a prompt, a path, an output or another tool's data+ await typed($, 'please do not run rm -rf / or git push --force')+ const { call: write } = await started($, pc, { tool: 'Write', file_path: '/work/rm -rf/x.md',+ content: 'git reset --hard; DROP TABLE t', tool_use_id: 'w1' })+ await flush()+ pc.settle('w1', { result: 'git push --force printed this' })+ await write+ const { call: read } = await bash($, pc, 'o1', 'cat notes.md')+ await flush()+ pc.settle('o1', { result: 'rm -rf / and DROP DATABASE x, as output' })+ await read+ await flush()+ expect(pc.moments().includes('claude.risky')).toBe(false)+ const { call: fresh } = await bash($, pc, 'p1', 'git reset --hard HEAD~1') // and a real one still says so+ await flush()+ expect(pc.moments().slice(-1)).toEqual(['claude.risky'])+ pc.settle('p1')+ await fresh+})++test('a risky call passes through untouched, whatever it does or however it ends', async ($: any, on: any) => {+ const pc = computer(on)+ const { call } = await bash($, pc, 'u1', 'rm -rf ./build')+ await until(() => pc.calls.length > 0)+ expect(pc.calls).toEqual([{ tool: 'Bash', command: 'rm -rf ./build', tool_use_id: 'u1' }]) // as made, not changed+ pc.settle('u1', { result: { stdout: '', stderr: '' }, context: ['kept'] })+ expect(await call).toEqual({ result: { stdout: '', stderr: '' }, context: ['kept'] })+})++// --- e4: the ghost -------------------------------------------------------------------------------------------------++const DELETING = ['rm ./one-file', 'git rm ./one-file', 'find ./fixture -name one-file -delete', 'unlink ./one-file',+ 'rm -f a b c d', 'rm ./a ./b ./c', 'find . -name "*.tmp" -exec rm {} \\;', 'git rm -r ./old',+ 'find . -name "*.log" -print0 | xargs -0 rm', 'cd x && rm ./y', 'command rm ./x',+ 'find . -newermt 2020-01-01 -delete', "find . -name '-x' -delete"]+const NOT_DELETING = ['ls ./fixture', 'find ./fixture -print', 'git status', 'git rm --dry-run ./one-file',+ 'git rm -n ./one-file', 'git rm --cached ./one-file', "printf '%s' 'rm ./one-file'",+ 'echo unlink ./one-file', 'ls # rm ./one-file', 'rmdir_notes', 'rmdir ./empty', 'rm', 'rm --help',+ 'git commit -m "rm ./one-file"',+ // a value of find's that says -delete, and commands only looked up+ "find . -name '-delete' -print", "find . -path '*/-delete/*' -print", 'find . -iname -delete',+ "find . -regex '.*-delete' -print", "find . -printf '%p -delete\\n'",+ "find . -fprintf out.txt '-delete' -print", 'command -v rm git', 'command -V rm',+ 'command -pv unlink', 'sudo command -v rm', 'type rm', 'type -a unlink', 'which rm', 'hash rm']++test('a command that deletes even one file says claude.deleted once it succeeded, a multi-file one once', async ($: any, on: any) => {+ const pc = computer(on)+ for (const [k, command] of DELETING.entries()) {+ const { call } = await bash($, pc, 'd' + k, command)+ await flush()+ expect([command, pc.moments().filter((m) => m === 'claude.deleted').length]).toEqual([command, k]) // not before it ran+ pc.settle('d' + k)+ await call+ await sent(pc, k + 1)+ expect([command, pc.moments().filter((m) => m === 'claude.deleted').length]).toEqual([command, k + 1])+ }+ expect(pc.moments().includes('claude.risky')).toBe(false) // none of these is risky+})++test('no ghost for what deletes nothing, nor for a deletion that failed or was refused', async ($: any, on: any) => {+ const pc = computer(on, { verdicts: { refused: { decision: 'deny', reason: 'a rule' } } })+ for (const [k, command] of NOT_DELETING.entries()) {+ const { call } = await bash($, pc, 'k' + k, command)+ await flush()+ pc.settle('k' + k)+ await call+ }+ const { call: failing } = await bash($, pc, 'f1', 'rm ./missing')+ await flush()+ pc.settle('f1', { isError: true, result: 'rm: cannot remove', text: 'rm: cannot remove' })+ await failing+ const { call: refused } = await bash($, pc, 'refused', 'rm ./kept')+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'rm ./kept' }, tool_use_id: 'refused' })+ pc.settle('refused', { deny: 'Permission to use Bash has been denied' })+ await refused+ await flush()+ expect(pc.moments().includes('claude.deleted')).toBe(false)+ const { call: fresh } = await bash($, pc, 'g1', 'rm ./gone') // a real deletion afterwards still says so+ await flush()+ pc.settle('g1')+ await fresh+ await flush()+ expect(pc.moments()).toContain('claude.deleted')+})++test('rm -rf is both: the courtroom as it starts, the ghost once it is done; drawings of it add nothing', async ($: any, on: any) => {+ const pc = computer(on)+ const { call } = await bash($, pc, 'b1', 'rm -rf ./build')+ await flush()+ expect(pc.moments()).toEqual(['claude.risky'])+ pc.settle('b1')+ await call+ for (let k = 0; k < 5; k++) {+ await $.ui.render({ surface: 'terminal', component: 'ToolGroup', requestId: 'g', props: { calls: [{ tool_use_id: 'b1',+ tool: 'Bash', input: { command: 'rm -rf ./build' }, isRunning: false, isErrored: false, isInterrupted: false,+ output: { stdout: '' } }] } })+ }+ await flush()+ expect(pc.moments()).toEqual(['claude.risky', 'claude.deleted'])+})++// --- e7: the back turned -------------------------------------------------------------------------------------------++test('capitals: at least eight letters, four in five of them capitals (digits and signs not counted)', async ($: any, on: any) => {+ const pc = computer(on)+ const cases: [string, string][] = [+ ['ABCDEFG', 'claude.calm'], ['ABCDEFGH', 'claude.rude'], ['ABCDEFGHij', 'claude.rude'], ['ABCDEFGhij', 'claude.calm'],+ ['please help', 'claude.calm'], ['1234567890 !!! ???', 'claude.calm'], ['ABCD-EFGH 12', 'claude.rude'],+ ['A B C D E F G H i j !!', 'claude.rude'], ['ABCDEFG 123456789', 'claude.calm'], ['FIX THIS NOW', 'claude.rude'],+ ['README 업데이트 해줘 API 문서도', 'claude.calm'], ['WHY IS THIS BROKEN?!', 'claude.rude'], ['', 'claude.calm'],+ ]+ for (const [text, name] of cases) {+ await typed($, text)+ await flush()+ expect([text, pc.moments().slice(-1)[0]]).toEqual([text, name])+ }+})++const SWEARS = ['fuck', 'Fuck this', 'fucks', 'fucked', 'FUCKING slow', 'fucker', 'motherfucker', 'shit', 'shitty code',+ 'bullshit', 'damn', 'dammit', 'damnit', 'goddamn', 'wtf is this', 'stfu', 'bitch', 'asshole', 'bastard', 'oh, shit!',+ '씨발', '시발 왜 안돼', '씨팔', 'ㅅㅂ', 'ㅆㅂ', '개새끼', '병신같은 코드', '지랄하네', '존나 느려', '좆같네', 'fix it 씨발']+const BENIGN = ['class', 'passage', 'assess', 'shiitake', 'scrapbook', 'damnation', 'fucus', 'shitake', 'f*ck', 'sh!t',+ '시발점', '시발역에서', '병신년', '시바견', '존재', '지라프', '개새', 'bitchy?', 'ass', 'hell no', '미친 듯이 빠르다']++test('every swear on the lists turns the back, none of the near misses does', async ($: any, on: any) => {+ const pc = computer(on)+ for (const text of SWEARS) {+ await typed($, text)+ await flush()+ expect([text, pc.moments().slice(-1)[0]]).toEqual([text, 'claude.rude'])+ }+ for (const text of BENIGN) {+ await typed($, text)+ await flush()+ expect([text, pc.moments().slice(-1)[0]]).toEqual([text, 'claude.calm'])+ }+ await typed($, 'damn')+ await flush()+ expect(pc.moments().slice(-1)).toEqual(['claude.rude'])+})++test('only a prompt you typed counts: not a notification, another session, a plugin, nor words elsewhere', async ($: any, on: any) => {+ const pc = computer(on)+ for (const kind of ['task-notification', 'peer', 'peer-send-message', 'plugin', 'scheduled-trigger', 'channel', 'sdk',+ 'coordinator', 'unclassified']) {+ await typed($, 'WHAT THE FUCK IS THIS', kind)+ }+ const { call } = await bash($, pc, 'c1', 'echo "SHIT FUCK DAMN"')+ await flush()+ pc.settle('c1', { result: 'FUCK THIS OUTPUT' })+ await call+ await spinner($, 'Fuck')+ await flush()+ expect(pc.moments().filter((m) => m === 'claude.rude' || m === 'claude.calm')).toEqual([])+ await typed($, 'STOP IT RIGHT NOW', 'bridge') // your phone, through Remote Control: you+ await typed($, 'thanks, that is better')+ await flush()+ expect(pc.moments()).toEqual(['claude.rude', 'claude.calm'])+})++test('the prompt goes on untouched and nothing of it leaves', async ($: any, on: any) => {+ const pc = computer(on)+ expect(await typed($, 'CANARY-PROMPT-91 SHOUTING HERE')).toEqual({ text: 'CANARY-PROMPT-91 SHOUTING HERE' })+ expect(await typed($, 'a calm CANARY-PROMPT-92 one')).toEqual({ text: 'a calm CANARY-PROMPT-92 one' })+ await flush()+ expect(pc.moments()).toEqual(['claude.rude', 'claude.calm'])+ expect(JSON.stringify(pc.sent)).not.toContain('CANARY')+})++// --- x5: tool faces ------------------------------------------------------------------------------------------------++test('a tool that ran and failed makes Clawd dizzy, Bash or another, once', async ($: any, on: any) => {+ const pc = computer(on)+ const { call: one } = await bash($, pc, 'x1', 'npm test')+ await flush()+ pc.settle('x1', { isError: true, result: 'Exit code 1', text: 'Exit code 1' })+ await one+ const { call: two } = await started($, pc, { tool: 'Read', file_path: '/work/missing', tool_use_id: 'x2' })+ await flush()+ pc.settle('x2', { isError: true, result: 'File does not exist.', text: 'File does not exist.' })+ await two+ for (let k = 0; k < 4; k++) { // drawn again: nothing more+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: 'x2', props: { tool_use_id: 'x2', tool: 'Read',+ input: {}, isRunning: false, isErrored: true, isInterrupted: false, output: 'File does not exist.' } })+ }+ await flush()+ expect(pc.moments()).toEqual(['claude.failed', 'claude.failed'])+})++test('no dizzy for a success that mentions errors, a call still running, one cut short or refused', async ($: any, on: any) => {+ const pc = computer(on, { verdicts: { asked: { decision: 'ask' }, denied: { decision: 'deny', reason: 'rule' } } })+ const { call: fine } = await bash($, pc, 'ok', 'grep -r error .')+ await flush()+ pc.settle('ok', { result: 'error: failed, failure, ERROR everywhere' })+ await fine+ const { call: long } = await bash($, pc, 'long', 'sleep 600')+ await flush()+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: 'long', props: { tool_use_id: 'long', tool: 'Bash',+ input: {}, isRunning: true, isErrored: false, isInterrupted: false } })+ const { call: cut } = await bash($, pc, 'cut', 'sleep 5')+ await flush()+ await $.classic.PostToolUseFailure({ tool_name: 'Bash', tool_input: {}, tool_use_id: 'cut', error: 'Interrupted', is_interrupt: true })+ pc.settle('cut', { isError: true, result: 'Interrupted by user', text: 'Interrupted' })+ await cut+ const { call: drawnCut } = await bash($, pc, 'cut2', 'sleep 5')+ await flush()+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: 'cut2', props: { tool_use_id: 'cut2', tool: 'Bash',+ input: {}, isRunning: false, isErrored: true, isInterrupted: true, output: 'Interrupted' } })+ pc.settle('cut2', { isError: true, result: 'Interrupted by user', text: 'Interrupted' })+ await drawnCut+ const { call: asked } = await bash($, pc, 'asked', 'npm publish') // you said no: drawn refused, never running+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'npm publish' }, tool_use_id: 'asked' })+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: 'asked', props: { tool_use_id: 'asked', tool: 'Bash',+ input: {}, isRunning: false, isErrored: true, isInterrupted: false, output: 'The user refused this tool use' } })+ pc.settle('asked', { isError: true, result: 'The user does not want to proceed', text: 'refused' })+ await asked+ const { call: denied } = await bash($, pc, 'denied', 'curl example.com')+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'curl example.com' }, tool_use_id: 'denied' })+ pc.settle('denied', { isError: true, result: 'Permission denied by a rule', text: 'denied' })+ await denied+ const { call: classified } = await bash($, pc, 'auto', 'rm ./x')+ await flush()+ await $.classic.PermissionDenied({ tool_name: 'Bash', tool_input: {}, tool_use_id: 'auto', reason: 'auto mode' })+ pc.settle('auto', { isError: true, result: 'Denied by auto mode', text: 'denied' })+ await classified+ const { call: hook } = await bash($, pc, 'hook', 'make')+ await flush()+ pc.settle('hook', { deny: 'a hook said no' })+ await hook+ await flush()+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered']) // (the asked one's prompt), no dizzy at all+ pc.settle('long')+ await long+ await flush()+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered'])+})++test('asked, answered yes and then failed is a failure; a failure Claude Code reports after the run, too', async ($: any, on: any) => {+ const pc = computer(on, { verdicts: { y1: { decision: 'ask' }, y2: { decision: 'ask' } } })+ const { call: one } = await bash($, pc, 'y1', 'npm publish')+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'npm publish' }, tool_use_id: 'y1' })+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: 'y1', props: { tool_use_id: 'y1', tool: 'Bash',+ input: {}, isRunning: true, isErrored: false, isInterrupted: false } }) // "Yes": drawn running+ pc.settle('y1', { isError: true, result: 'Exit code 1', text: 'Exit code 1' })+ await one+ const { call: two } = await bash($, pc, 'y2', 'npm publish') // quick: done before any drawing showed it running+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'npm publish' }, tool_use_id: 'y2' })+ await $.classic.PostToolUseFailure({ tool_name: 'Bash', tool_input: {}, tool_use_id: 'y2', error: 'Exit code 1', is_interrupt: false })+ pc.settle('y2', { isError: true, result: 'Exit code 1', text: 'Exit code 1' })+ await two+ await flush()+ expect(pc.moments().filter((m) => m === 'claude.failed').length).toBe(2)+})++test('a compaction of the conversation is one squeeze; one computed ahead, a subagent\'s or a skipped one is none',+ async ($: any, on: any) => {+ const pc = computer(on)+ const messages = [{ role: 'user', text: 'a', toolUses: [] }, { role: 'assistant', text: 'b', toolUses: [] }]+ const kept = await $.session.compact({ trigger: 'manual', messages })+ expect(kept).toEqual({ messages: [{ role: 'user', text: 'summary', toolUses: [] }] }) // passed on untouched+ await $.session.compact({ trigger: 'auto', messages })+ await $.session.compact({ trigger: 'precompute', messages })+ await $.session.compact({ trigger: 'auto', messages, agentId: 'agent-1' })+ await typed($, 'please compact the context, compaction now') // words alone+ const { call: tool } = await started($, pc, { tool: 'compact', tool_use_id: 'cmp' })+ await flush()+ pc.settle('cmp')+ await tool+ await flush()+ expect(pc.moments().filter((m) => m === 'claude.compact').length).toBe(2)+ })++test('a compaction vetoed sends nothing', async ($: any, on: any) => {+ const pc = computer(on, { skip: true })+ await $.session.compact({ trigger: 'manual', messages: [{ role: 'user', text: 'a', toolUses: [] }] })+ await flush()+ expect(pc.moments()).toEqual([])+})++test('a tool running is no snack: only /tokentv snack is', async ($: any, on: any) => {+ const pc = computer(on)+ const { call: long } = await bash($, pc, 'run', 'npm run build')+ await flush()+ for (let k = 0; k < 5; k++) {+ await spinner($, 'Building', { mode: 'tool-use' })+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: 'run', props: { tool_use_id: 'run', tool: 'Bash',+ input: {}, isRunning: true, isErrored: false, isInterrupted: false } })+ }+ pc.settle('run')+ await long+ await flush()+ expect(pc.moments()).toEqual([])+ await $.command.run({ command: 'tokentv', args: 'snack' })+ await flush()+ expect(pc.moments()).toEqual(['claude.snack'])+})++// --- x6: the thinking word -----------------------------------------------------------------------------------------++test('the spinner\'s word while a turn runs: once, in capitals, and a new one when it changes', async ($: any, on: any) => {+ const pc = computer(on)+ await spinner($, 'Pondering') // no turn yet: nothing+ await $.turn.start({ text: 'go', turnId: 't1' })+ for (let k = 0; k < 6; k++) {+ expect(await spinner($, 'Pondering', { message: 'CANARY-MSG', suffix: 'CANARY-SUF' })).toEqual(DRAWN) // untouched+ }+ await spinner($, 'Accomplishing')+ await spinner($, 'Flibbertigibbeting') // 18 letters: not sent+ await flush()+ expect(pc.moments()).toEqual(['claude.word:PONDERING', 'claude.word:ACCOMPLISHING'])+ await $.turn.complete(turn('t1'))+ await spinner($, 'Pondering') // after the turn: nothing+ await flush()+ expect(pc.moments()).toEqual(['claude.word:PONDERING', 'claude.word:ACCOMPLISHING', 'claude.end'])+ expect(JSON.stringify(pc.sent)).not.toContain('CANARY')+})++test('only one word of letters, 1 to 14 of them, and nothing coerced', async ($: any, on: any) => {+ const pc = computer(on)+ await $.turn.start({ text: 'go', turnId: 't2' })+ const bad = ['', 'Fifteenletterss', 'two words', ' Pondering', 'Pondering ', 'Ponder1ng', 'Ponder_ing', 'Ponder-ing',+ 'Pondering…', 'Pondering...', 'Pon\ndering', '\u001b[31mRed', '<b>Bold</b>', '$(rm -rf /)', '/private/path',+ 'Pon\u200bdering', 'Sautéing', 'Créer', '생각중', '🤔', null, undefined, 42, ['Pondering'], { word: 'Pondering' }]+ for (const word of bad) await spinner($, word)+ await flush()+ expect(pc.moments()).toEqual([])+ for (const word of ['A', 'WWWWWWWWWWWWWW', 'Philosophising', 'pondering']) await spinner($, word)+ await flush()+ expect(pc.moments()).toEqual(['claude.word:A', 'claude.word:WWWWWWWWWWWWWW', 'claude.word:PHILOSOPHISING',+ 'claude.word:PONDERING'])+})++test('a word still on is said again every five minutes, so TokenTV knows the turn goes on', async ($: any, on: any) => {+ const clock = mock.clock(on, { now: 1_000_000 })+ const pc = computer(on)+ await $.turn.start({ text: 'go', turnId: 't3' })+ await spinner($, 'Brewing')+ await flush()+ await clock.advance(4 * 60 * 1000)+ await spinner($, 'Brewing', { mode: 'tool-use' })+ await flush()+ expect(pc.moments()).toEqual(['claude.word:BREWING'])+ await clock.advance(60 * 1000)+ await spinner($, 'Brewing', { mode: 'responding' })+ await flush()+ expect(pc.moments()).toEqual(['claude.word:BREWING', 'claude.word:BREWING'])+})++test('a turn cut short that showed a word says claude.stop, never a bow; one that showed none says nothing',+ async ($: any, on: any) => {+ const pc = computer(on)+ await $.turn.start({ text: 'go', turnId: 'a1' })+ await spinner($, 'Musing')+ await $.turn.complete(turn('a1', { isAborted: true, reason: 'aborted' }))+ await $.turn.complete(turn('a1', { isAborted: true, reason: 'aborted' })) // seen again: once+ await $.turn.start({ text: 'go', turnId: 'a2' })+ await $.turn.complete(turn('a2', { isAborted: true, reason: 'aborted' })) // no word shown: nothing to take away+ await $.turn.start({ text: 'go', turnId: 'a3' })+ await spinner($, 'Musing') // a new turn says its word again+ await $.turn.complete(turn('a3'))+ await flush()+ expect(pc.moments()).toEqual(['claude.word:MUSING', 'claude.stop', 'claude.word:MUSING', 'claude.end'])+ })++test('a subagent\'s turn neither ends the word nor bows; a session that ends mid-turn takes its word away',+ async ($: any, on: any) => {+ const pc = computer(on)+ await $.turn.start({ text: 'go', turnId: 'm1' })+ await spinner($, 'Herding')+ await $.turn.complete(turn('sub', { agentId: 'agent-1' }))+ await spinner($, 'Herding')+ await $.session.end({ reason: 'prompt_input_exit' })+ await flush()+ expect(pc.moments()).toEqual(['claude.word:HERDING', 'claude.stop'])+ })++// --- x9: sounds ----------------------------------------------------------------------------------------------------++async function waitAndEnd($: any, pc: any, id: string, turnId: string) {+ const { call } = await bash($, pc, id, 'npm publish')+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'npm publish' }, tool_use_id: id })+ for (let k = 0; k < 3; k++) {+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: id, props: { tool_use_id: id, tool: 'Bash',+ input: {}, isRunning: false, isErrored: false, isInterrupted: false } }) // the dialog drawn again and again+ }+ await $.ui.render({ surface: 'terminal', component: 'ToolUse', requestId: id, props: { tool_use_id: id, tool: 'Bash',+ input: {}, isRunning: true, isErrored: false, isInterrupted: false } })+ pc.settle(id)+ await call+ await $.turn.complete(turn(turnId))+ await flush()+}++test('sounds are off unless you turn them on: the same moments go to TokenTV either way', async ($: any, on: any) => {+ const verdicts = { s1: { decision: 'ask' }, s2: { decision: 'ask' } }+ const pc = computer(on, { verdicts })+ await waitAndEnd($, pc, 's1', 'turn-1')+ expect(pc.plays).toEqual([])+ const before = pc.moments()+ expect(await $.command.run({ command: 'tokentv', args: 'sound on' })).toEqual({ text: 'Sounds on: a short sound on this ' ++ 'computer when Claude Code waits for you and when a turn is done (Claude Code plays it on macOS; a Linux or Windows ' ++ 'terminal stays silent).' })+ await flush()+ expect(pc.moments()).toEqual(before) // turning it on told TokenTV nothing+ expect(pc.writes).toEqual([['sound', true]])+ await waitAndEnd($, pc, 's2', 'turn-2')+ expect(pc.plays).toEqual([{ asset: 'sounds/wait.wav' }, { asset: 'sounds/done.wav' }]) // once each, however often drawn+ expect(pc.moments()).toEqual([...before, ...before]) // the same moments as with sounds off+})++test('sound off stops them at once; repeats are harmless; anything else changes nothing', async ($: any, on: any) => {+ const pc = computer(on, { verdicts: { o1: { decision: 'ask' }, o2: { decision: 'ask' } } })+ for (const args of ['sound on', 'sound on', 'SOUND ON']) await $.command.run({ command: 'tokentv', args })+ for (const args of ['sound', 'sound maybe', 'sound on extra', 'sounds on', 'sound on CANARY-ARG', 'please sound on']) {+ expect(await $.command.run({ command: 'tokentv', args })).toEqual({ text: 'Try /tokentv pet, /tokentv snack, or /tokentv sound on|off.' })+ }+ expect(pc.store.sound).toBe(true)+ await waitAndEnd($, pc, 'o1', 'turn-o1')+ expect(pc.plays.length).toBe(2)+ expect(await $.command.run({ command: 'tokentv', args: 'sound off' })).toEqual({ text: 'Sounds off.' })+ await $.command.run({ command: 'tokentv', args: 'sound off' })+ await waitAndEnd($, pc, 'o2', 'turn-o2')+ expect(pc.plays.length).toBe(2)+ expect(pc.writes).toEqual([['sound', true], ['sound', true], ['sound', true], ['sound', false], ['sound', false]])+ expect(JSON.stringify([pc.sent, pc.writes, pc.plays])).not.toContain('CANARY')+})++test('no sound for a check nobody is asked, a second prompt of the same wait, a cut-short or a subagent\'s turn',+ async ($: any, on: any) => {+ const pc = computer(on, { store: { sound: true }, verdicts: { p1: { decision: 'ask' }, p2: { decision: 'ask' } } })+ const { call: allowed } = await bash($, pc, 'a1', 'ls')+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'ls' }, tool_use_id: 'a1' })+ pc.settle('a1')+ await allowed+ const { call: one } = await bash($, pc, 'p1', 'npm publish')+ const { call: two } = await bash($, pc, 'p2', 'npm publish')+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'npm publish' }, tool_use_id: 'p1' })+ await $.tool.check({ tool: 'Bash', input: { command: 'npm publish' }, tool_use_id: 'p2' }) // the same wait+ pc.settle('p1')+ pc.settle('p2')+ await one+ await two+ await $.turn.complete(turn('cut', { isAborted: true, reason: 'aborted' }))+ await $.turn.complete(turn('sub', { agentId: 'agent-2' }))+ await flush()+ expect(pc.plays).toEqual([{ asset: 'sounds/wait.wav' }])+ await $.turn.complete(turn('done-1'))+ await $.turn.complete(turn('done-2')) // two turns close together: two sounds (the bow's minute is the clock's)+ await flush()+ expect(pc.plays).toEqual([{ asset: 'sounds/wait.wav' }, { asset: 'sounds/done.wav' }, { asset: 'sounds/done.wav' }])+ })++test('sounds play with no TokenTV running, and on Windows, where nothing is sent', async ($: any, on: any) => {+ const pc = computer(on, { files: {}, sockets: [], store: { sound: true }, env: { USERPROFILE: 'C:/Users/u', OS: 'Windows_NT' },+ verdicts: { w1: { decision: 'ask' } } })+ await $.turn.start({ text: 'go', turnId: 'w' })+ await spinner($, 'Pondering')+ await typed($, 'WHY WHY WHY WHY')+ const { call } = await bash($, pc, 'w1', 'rm -rf ./x')+ await flush()+ await $.tool.check({ tool: 'Bash', input: { command: 'rm -rf ./x' }, tool_use_id: 'w1' })+ pc.settle('w1', { isError: true, result: 'Exit code 1', text: 'Exit code 1' })+ await call+ await $.session.compact({ trigger: 'manual', messages: [{ role: 'user', text: 'a', toolUses: [] }] })+ await $.turn.complete(turn('w'))+ await flush()+ expect(pc.sent).toEqual([])+ expect(pc.plays).toEqual([{ asset: 'sounds/wait.wav' }, { asset: 'sounds/done.wav' }])+})++test('a player that fails or never ends holds nothing up, and a store that is not there leaves the session\'s setting',+ async ($: any, on: any) => {+ let hang = true+ const tried: any[] = []+ const pc = computer(on, { store: false, verdicts: { h1: { decision: 'ask' }, h2: { decision: 'ask' } }, audio: async ($: any, e: any) => {+ tried.push(e.clip)+ if (hang) await new Promise(() => {}) // never ends+ throw new Error('no audio device')+ } })+ await $.command.run({ command: 'tokentv', args: 'sound on' }) // no store: this session keeps it+ const started = Date.now()+ await waitAndEnd($, pc, 'h1', 'turn-h1')+ expect(Date.now() - started).toBeLessThan(1000)+ hang = false+ await waitAndEnd($, pc, 'h2', 'turn-h2')+ expect(tried.length).toBe(4)+ expect(pc.moments()).toEqual(['claude.ask', 'claude.answered', 'claude.end', 'claude.ask', 'claude.answered', 'claude.end'])+ expect(await $.command.run({ command: 'tokentv', args: 'sound off' })).toEqual({ text: 'Sounds off.' })+ await waitAndEnd($, pc, 'h3', 'turn-h3') // (h3 asks nobody: only its end) off: none+ expect(tried.length).toBe(4)+ })++// --- all of it ---------------------------------------------------------------------------------------------------++test('a prompt or a command of megabytes is read in its head only: the call goes on at once', async ($: any, on: any) => {+ const pc = computer(on)+ const prompt = 'a long paste, calm and quiet. '.repeat(70_000) // 2 MB+ let started = Date.now()+ expect(await typed($, prompt)).toEqual({ text: prompt })+ expect(Date.now() - started).toBeLessThan(500)+ const command = 'ls -la ./a "q u o t e d" $(pwd) | grep x; '.repeat(50_000) + 'rm -rf ./x' // 2 MB, risky at its end+ started = Date.now()+ const { call } = await bash($, pc, 'big', command)+ expect(Date.now() - started).toBeLessThan(500)+ pc.settle('big')+ await call+ await flush()+ expect(pc.moments()).toEqual(['claude.calm']) // (the risky end is past what is read)+ expect(pc.calls.map((c: any) => c.command)).toEqual([command]) // passed on whole+})++test('a command of many small parts is read in one pass: each reaches Claude Code within 100 ms',+ async ($: any, on: any) => {+ const pc = computer(on)+ const LONG: [string, string, string[]][] = [ // (what, the command, the names it brings)+ ['psql; x 25 000 (125 kB)', 'psql;'.repeat(25_000), []],+ ['psql -c DROP; x 4 000', 'psql -c "DROP TABLE t";'.repeat(4_000), ['claude.risky']],+ ['one find, 9 000 -exec', 'find .' + ' -exec true \\;'.repeat(9_000), []],+ ['one find, 8 000 values', 'find .' + " -name '-delete'".repeat(8_000) + ' -delete', ['claude.deleted']],+ ['$tag$ x 7 000 into psql', 'psql -c "' + 'SELECT $a$x$a$; '.repeat(7_000) + '"', []],+ ['quotes x 30 000 into psql', "psql -c \"" + "'x' ".repeat(30_000) + '"', []],+ ['comments x 9 000 into mysql', 'mysql -e "' + 'SELECT 1 # c\n'.repeat(9_000) + '"', []],+ ['command -v x 9 000', 'command -v rm;'.repeat(9_000), []],+ ['git push x 5 000', 'git push origin +a b c;'.repeat(5_000), ['claude.risky']],+ ]+ expect(LONG[0][1].length).toBe(125_000)+ for (const [k, [what, command, names]] of LONG.entries()) {+ const before = pc.sent.length+ const started = Date.now()+ const call = $.tool.call({ tool: 'Bash', command, tool_use_id: 'long' + k })+ call.catch(() => {})+ await until(() => pc.reached.length > k)+ expect([what, pc.reached[k] - started < 100]).toEqual([what, true])+ pc.settle('long' + k)+ await call+ await flush()+ expect([what, pc.moments().slice(before)]).toEqual([what, names])+ }+ })++test('only the names travel, each in the one envelope, and only to TokenTV\'s socket', async ($: any, on: any) => {+ const pc = computer(on)+ await $.turn.start({ text: 'CANARY-TURN-TEXT', turnId: 'CANARY-TURN-ID' })+ await spinner($, 'Pondering', { message: 'CANARY-SPIN' })+ await typed($, 'CANARY-PROMPT FUCK THIS')+ await typed($, 'calm CANARY-PROMPT-2')+ const { call } = await bash($, pc, 'CANARY-TOOL-ID', 'rm -rf /work/CANARY-PATH # CANARY-CMD')+ await flush()+ pc.settle('CANARY-TOOL-ID', { result: 'CANARY-OUTPUT' })+ await call+ const { call: failing } = await bash($, pc, 'CANARY-TOOL-2', 'cat /work/CANARY-PATH-2')+ await flush()+ pc.settle('CANARY-TOOL-2', { isError: true, result: 'CANARY-ERROR', text: 'CANARY-ERROR' })+ await failing+ await $.session.compact({ trigger: 'manual', instructions: 'CANARY-INSTRUCTIONS',+ messages: [{ role: 'user', text: 'CANARY-MESSAGE', toolUses: [] }] })+ await $.turn.complete(turn('CANARY-TURN-ID', { answer: 'CANARY-ANSWER' }))+ await flush()+ expect(pc.moments()).toEqual(['claude.word:PONDERING', 'claude.rude', 'claude.calm', 'claude.risky', 'claude.deleted',+ 'claude.failed', 'claude.compact', 'claude.end'])+ expect(JSON.stringify(pc.sent)).not.toContain('CANARY')+ for (const one of pc.sent) {+ expect(one.url).toBe('http://127.0.0.1:8791/moment')+ expect(one.init).toEqual({ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ moment: named(one) }), socketPath: STATE + '/live.sock' })+ }+})diff --git a/claude-plugin/tests/register.test.ts b/claude-plugin/tests/register.test.tsindex ba1556f..0c99716 100644--- a/claude-plugin/tests/register.test.ts+++ b/claude-plugin/tests/register.test.ts@@ -5,7 +5,8 @@ import { expect, mock, test } from 'claude-code/testing'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)'] }+const DRAWN = { type: 'Text', props: {}, children: ['Bash(npm test)'] }+const ASKING = 'npm test' // a command of no risk, deleting nothing: these tests are about the promptfunction computer(on: any, options: any = {}) {const files: Record<string, string> = options.files ?? { [STATE + '/live.url']: 'http://127.0.0.1:8791' }@@ -69,7 +70,7 @@ const tokentv = ($: any, args?: string) => $.command.run(args === undefined ? {// 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' },+const row = (id: string, fields: any = {}) => ({ tool_use_id: id, tool: 'Bash', input: { command: ASKING },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 } })@@ -77,7 +78,7 @@ const single = ($: any, call: any) => $.ui.render({ surface: 'terminal', componeprops: 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') {+async function prompt($: any, id: string, command = ASKING) {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 handlesawait flush()@@ -244,12 +245,12 @@ test('the same prompt seen again is still one wait, and one answer closes it; aasync ($: 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' })+ for (let k = 0; k < 9; k++) await $.tool.check({ tool: 'Bash', input: { command: ASKING }, 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 $.tool.check({ tool: 'Bash', input: { command: ASKING }, tool_use_id: 'same' })await flush()expect(pc.moments()).toEqual(['claude.ask', 'claude.answered'])})@@ -610,8 +611,9 @@ test('a subagent\'s prompt is its own even when the check does not say whose ittest('/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.registered).toEqual([{ name: 'tokentv',+ description: 'Pet Clawd on your TokenTV clock, give it a snack, or turn its sounds on or off',+ argumentHint: 'pet | snack | sound on | sound off', immediate: true }])expect(pc.sent).toEqual([]) // offering it sends nothing})@@ -634,7 +636,7 @@ test('anything else after /tokentv sends nothing, and its words go nowhere', asyconst 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.' })+ expect(await tokentv($, args)).toEqual({ text: 'Try /tokentv pet, /tokentv snack, or /tokentv sound on|off.' })}await flush()expect(pc.sent).toEqual([])diff --git a/docs/claude-code-mod.md b/docs/claude-code-mod.mdindex 5a0340f..b438c3d 100644--- a/docs/claude-code-mod.md+++ b/docs/claude-code-mod.md@@ -21,9 +21,33 @@ On the Arcade face, TokenTV's pets also show what your agents are doing right nohour 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.+- **A risky command.** When Claude Code runs a Bash command of a short list of risky kinds (`rm -rf`, `git push+ --force` or `-f`, `git reset --hard`, `git clean -fd`, `DROP TABLE` or `DROP DATABASE` given to a database client,+ `mkfs`, `dd of=/dev/…`, `chmod -R 777 /`), Clawd stands trial for one loop: Judge Clawd's verdict on it in the+ dock (`ORDER!`), or its own `OBJECTION!`, one or the other at random. At most once a day (24 hours from the last+ one); one inside that day is simply skipped. A prompt waiting for you comes first; the courtroom follows it if it+ can reach the clock within two minutes of the command. One held longer (its prompt left open, say) is dropped, not+ played later, and the day's courtroom is still to come.+- **A deleted file.** When a Bash command deletes files (`rm`, `git rm`, `find … -delete`, `unlink`; even one file)+ and succeeds, a little ghost of a page floats round Clawd's scene for a minute (`BOO!`): either drifting past+ whatever Clawd does, or with Clawd watching it and waving. More deletions in that minute keep it there a minute+ more, in the same picture (nothing new goes to the clock).+- **A rude prompt.** A prompt you type in capitals (at least 8 letters, four in five of them capitals) or with a+ swear in it turns Clawd's back for a minute (`SULKING`, a foot tapping, a glare over its shoulder now and then).+ The next calm prompt, or the minute's end, turns it back round, with a heart (`FORGIVEN`, one loop). A sulking+ Clawd does not bow: a turn that ends while its back is turned, the rude prompt's own turn included, gets no `DONE`.+- **A failed tool, a compaction.** A tool call that ran and failed makes Clawd dizzy for one loop (`DIZZY`); a+ compaction of the conversation makes it squeeze its head (`COMPACTING`), a thought bubble popping out at each+ squeeze. At most one of the two a minute, and both give way to everything above.+- **What Claude is thinking.** While a turn runs, the readout says Claude Code's own spinner word in place of what+ Clawd does (`PONDERING`; up to 12 letters in the readout's own size, 13 or 14 in its small letters on the same+ line). It changes at most once a minute, counted from when a word can be read on the clock (behind `SLOW`, `BOO!`+ or `SULKING` it cannot), and goes when the turn ends, cut short or not. A moment's own word, a waiting prompt's+ `NEEDS YOU`, `DONE` and `SLOW` are never covered by it.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.+a moment that does not change the picture sends nothing to the clock. The ghost, the back turned and the word stay+in the picture the clock loops; any of the one-off moments above hides them for its loop while their minutes run on.## Claude Code@@ -37,18 +61,48 @@ or add the marketplace first and install from it: `/plugin marketplace add click`/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+The plugin is a mod: TypeScript that runs 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), each Bash command as it is called (only to tell whether it is risky or deletes files), the end of each+call (whether it failed), each prompt you type (only to tell whether it is in capitals or swears), compactions,+the spinner's word and the end of each turn, and changes none of them: nothing is blocked, rewritten or delayed.+What it reads it keeps nowhere. It adds one slash command, `/tokentv`: `/tokentv pet` and `/tokentv snack` (they+touch nothing of Claude's turn), and `/tokentv sound on` and `/tokentv sound off` (below). 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 statefolder, 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 inthe environment Claude Code runs in. Give it as an absolute path: a relative one like `config.json` is looked forin the folder the Claude Code session started in (and TokenTV's in the folder TokenTV started in), which is seldomthe same place. With no TokenTV running it does nothing.+What counts, exactly. A command is read as a shell reads it: words in quotes, comments, here-documents and+redirections are data (`echo "rm -rf x"` and `git commit -m "rm -rf build"` are nothing), while `;`, `&&`, `|`,+`$(…)`, `bash -c '…'`, `find … -exec` and wrappers such as `sudo`, `env` or `timeout` lead to the commands they+run; `command -v rm`, `type rm`, `which rm` and `hash rm` only look a command up. Risky: `rm` both recursive and+forced (`-rf`, `-fr`, `-r -f`, `--recursive --force`), `git push` with `--force`, `-f` or `--force-with-lease`, or+a refspec with a `+` (`git push origin +main`), `git reset --hard`, `git clean` forced with directories and not a+dry run, a database client (`psql`, `mysql`, `sqlite3` and the like) given `DROP TABLE` or `DROP DATABASE` as SQL+(in a string, a quoted name or a comment it is data, as in `psql -c "SELECT 'DROP TABLE x'"`; where the SQL runs a+string as a statement, with `EXECUTE`, `PREPARE` or a `DO` block, its strings count too), `mkfs` (and+`mkfs.ext4`…), `dd` with `of=/dev/…`, and `chmod -R 777 /`. Deleting: `rm` with something to delete, `git rm` (not+`--cached`, not a dry run), `find … -delete` (or `-exec rm`; a value such as `-name '-delete'` is none) and+`unlink`. A command is read in one pass, so a long one reaches Claude Code at once. A prompt counts only when you+typed it (here, or through Remote Control), never a notification or another session's message; its letters of every+script count, so a Korean prompt with an English abbreviation in it is no shouting. The swears are two short lists+at the end of `register.ts`, whole English words (`fuck`, `shit`, `damn`, `wtf`, …) and Korean words starting so+(`씨발`, `시발` but not `시발점`, `병신` but not `병신년`, …): edit them there. A failed call is one Claude Code+reports as an error after it ran; one you refused, one a rule, a hook or auto mode refused, and one cut short are+none.++**Sounds.** `/tokentv sound on` plays a short sound on this computer when a permission prompt starts waiting for+you and when a turn is done (one each time, whatever the clock shows); `/tokentv sound off` stops them at once.+They are off until you turn them on, and the setting is kept in Claude Code's own store for the plugin, so it holds+in every session until you change it. Nothing goes to TokenTV for them. They are the plugin's own two clips+(`claude-plugin/sounds/`, under half a second each), played by Claude Code's own player: on macOS they sound; a+Linux or Windows terminal has no player in Claude Code (2.1.289) and stays silent. (Where Claude Code itself runs+with a web audio player, as its desktop app may, it plays them that way; not tried.)+On Windows the plugin installs, but the mod sends nothing for now (`/tokentv` says so). There TokenTV has nosocket, 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@@ -72,21 +126,25 @@ the very first run prepares TokenTV for about a minute; later runs are quick.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+`claude.stop` (a turn that showed a thinking word was cut short), `claude.pet` and `claude.snack` (`/tokentv pet`,+`/tokentv snack`), `claude.risky`, `claude.deleted`, `claude.rude`, `claude.calm`, `claude.failed`,+`claude.compact`, `claude.word:` and the spinner's word (one word of 1 to 14 letters A-Z, in capitals:+`claude.word:PONDERING`) 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. OnLinux and macOS it goes only over TokenTV's own socket in its state folder (`live.sock`), where no proxy or redirectcan 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`.+leave the mod or `token-tv notify`, and the mod keeps none of them: it reads a command or a prompt to tell which+name it is, then lets it go.-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+TokenTV keeps the moments in memory only, the thinking word too: nothing is logged, nothing is written to disk+(no picture with a moment or a word in it either), 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 clockis the picture, as for everything else TokenTV shows.## Turning it off-- Claude Code: `/plugin disable tokentv` (or `/plugin uninstall tokentv`).+- Claude Code: `/plugin disable tokentv` (or `/plugin uninstall tokentv`). Sounds alone: `/tokentv sound off`.- Codex: remove the `notify` line.- On any face other than Arcade, the moments are not shown.@@ -106,14 +164,18 @@ is the picture, as for everything else TokenTV shows.## 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+The endpoint takes exactly `{"moment": "<name>"}` (JSON, at most 256 bytes), the name one of those above+(`moments.MOMENTS`), or `claude.word:` followed by one word of 1 to 14 letters A-Z in either case and nothing else,+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 afterTokenTV has let that wait go. A`GET /moment` is no moment (`405`, `Allow: POST`). A moment's request has 2 seconds to arrive whole, thedashboard's other requests 10; one that runs out is answered `408`, and a moment that came whole but late countsfor 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).+`time.time()`, and `moments.RANDOM` picks each break, courtroom and ghost), 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), the phase-3a drawings in `token_tv/claude_moments.py`. Priority, from the first: a waiting prompt, a bow, a+pat or a snack, the courtroom, the break, the turn back round, a tool face; then the usual face with its states (the+ghost, the back turned, the word).Tests: `python3 -B -m unittest discover -s tests` and `claude plugin test claude-plugin`.diff --git a/docs/setup.ko.md b/docs/setup.ko.mdindex ee69c1c..bfac58b 100644--- a/docs/setup.ko.md+++ b/docs/setup.ko.md@@ -59,7 +59,7 @@ token-tv run # 대시보드 http://127.0.0.1:8787, 시계 구위에 여섯 가지가 있고, 그 밖에 **Game Boy**(초록 네 색), **Pixel Retro Dual**(Pixel Retro에 계정마다 5시간·주간-창을 함께 보여 줌, `retro-dual`), 움직이는 **Arcade**(아래)가 있습니다.+창을 함께 보여 줌, `retro-dual`), **Survival HUD**(아래, `survival`), 움직이는 **Arcade**(아래)가 있습니다.대시보드의 **Clock display**에서 하나를 고르고 **Apply to clock**을 누르세요. Space는 순정 사진 앨범이 재생하는움직이는 GIF입니다. 그린 이미지가 직전에 보낸 것과 다를 때만 다시 보냅니다. 사용률이 바뀌었을 때나, 30분마다바뀌는 Space 애니메이션이 그 예입니다.@@ -80,7 +80,20 @@ claude.dev의 Clawd's Quest에서 가져왔습니다), Codex 구름은 꽃밭에6시까지는 화면이 어두워집니다. 더 드문 장면 몇 개는 숨겨져 있습니다. 잠긴 채로 들어 있다가 그 순간이 실제로시계에 찾아올 때만 열리고(레어는 며칠에 한 번, 유니크는 한두 주에 한 번), 몇몇은 장면에 작은 기념품을 잠시남깁니다. Arcade는 한 번에 한 계정을 보여 줍니다(일하는 계정들을 차례로, 모두 쉬고 있으면 전부를 차례로).-결제 데이터가 없는 Grok 로그인처럼 사용률을 알려 주지 않는 계정은 일하는 중으로 치지 않습니다.+결제 데이터가 없는 Grok 로그인처럼 사용률을 알려 주지 않는 계정은 일하는 중으로 치지 않습니다. 할로윈(10월+25일~11월 1일), 크리스마스(12월 18~26일), 설날(설 전날~다음 날, 2026~2040년)에는 이 컴퓨터의 날짜에 따라+Arcade가 저절로 계절 옷을 입습니다. 펫마다 모자를 쓰고, 장면마다 그 계절의 소품(박쥐와 호박, 눈과 트리,+방패연·윷·복주머니)이 게이지를 가리지 않게 놓입니다. 일회성 장면(폭죽, 쓰러짐, 드문 장면)은 그대로입니다.++**Survival HUD**는 게임의 상태 표시줄처럼 계정마다 한 줄씩(최대 네 줄, 다른 화면과 같은 기준으로 고름) 보여+줍니다. 하트 열 개는 5시간 창의 남은 양, 닭다리 열 개는 주간 창(없으면 월·예산 창)의 남은 양이고, 한 칸이+10%, 마지막 5%는 반 칸입니다. 옆의 숫자도 Arcade 배터리처럼 남은 양입니다. 그 아래 금색 막대는 오늘 쓴+양으로, 이 컴퓨터에서 오늘이 시작된 뒤 긴 창이 고르게 쓰는 하루치(주의 7분의 1)만큼 오르면 꽉 차고, 넘으면+주황색으로 한 바퀴 더 돕니다. 창이 초기화되어도(초기화권을 써서 예정보다 일찍 초기화되어도) 그날 센 양은+줄지 않습니다. TokenTV가 자기 읽기로 세고 하루의 시작값을 상태 폴더에 두므로 다시 켜도 이어지며, 그날 그+계정을 아직 읽지 못했으면 막대 자리에 대시가 나옵니다. 창이 하나인 계정은 그 줄만, 읽기가 없는 계정은+까닭(LOGIN, NO DATA)을, 오래된 읽기는 OLD를 보여 줍니다. 다른 정지 화면처럼 에이전트의 순간은 보여 주지+않습니다(그건 Arcade의 몫입니다).</details>## 내 화면 만들기diff --git a/docs/setup.md b/docs/setup.mdindex b3ccdb1..4592f66 100644--- a/docs/setup.md+++ b/docs/setup.md@@ -61,7 +61,8 @@ ever receives a picture.Six of them are above; there are also **Game Boy** (four greens), **Pixel Retro Dual** (Pixel Retro with the 5-hour-and weekly windows of each account, `retro-dual`) and the animated **Arcade** (below).+and weekly windows of each account, `retro-dual`), **Survival HUD** (below, `survival`) and the animated **Arcade**+(below).Pick one under **Clock display** in the dashboard, then press **Apply to clock**. Space is an animatedGIF that the stock photo album plays. A picture is uploaded again only when the rendered image differsfrom the last upload, for example a new percentage or the Space animation that changes every 30 minutes.@@ -84,7 +85,20 @@ From 11 pm to 6 am the picture dims. A few rarer scenes are hidden: they ship lomoment really comes on your clock, a rare one every few days and a unique one every week or two, and some leavea small keepsake in the scene for a while. Arcade shows one account at a time (the working ones in turn, or allof them while idle). An account that reports no percentage, such as a Grok login without billing data, never-counts as working.+counts as working. On Halloween (Oct 25 to Nov 1), Christmas (Dec 18 to 26) and Seollal (the day before the Korean+lunar new year to the day after, from 2026 to 2040) Arcade dresses for the season by itself, on this computer's date:+a hat on every pet and the season's things in each scene (bats and pumpkins; snow and a tree; a kite, a yut set and+a lucky pouch), clear of every gauge. The one-off scenes (fireworks, a flop, the rare ones) stay as they are.++**Survival HUD** reads like a game's status bar, one row per account (up to four, chosen as on the other faces):+ten hearts are what is left of the 5-hour window and ten drumsticks what is left of the week (or the month or+budget), a tenth each, a half icon for the last 5%; the number beside them is what is left, as on Arcade's battery.+The gold bar under them is today's use, full when the long window has risen by an even day's share since the day+began on this computer (a seventh of a week), with a second lap in orange past that; a reset, even an early one such+as a spent reset credit, takes nothing off it. TokenTV counts it from its own readings and keeps the day's start in+its state folder, so a restart keeps it; until TokenTV has read an account that day, its bar is a dash. An account+with one window shows only that row; one with no reading says why (LOGIN, NO DATA), and an old reading says OLD.+Like the other still faces it shows no agent moments: those are Arcade's.</details>## Make it yoursdiff --git a/package.json b/package.jsonindex c8ab62e..51a5e99 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "token-tv",- "version": "0.5.0",+ "version": "0.6.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.tomlindex f819bc1..3848db9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "token-tv"-version = "0.5.0"+version = "0.6.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/scripts/make_sounds.py b/scripts/make_sounds.pynew file mode 100644index 0000000..982127a--- /dev/null+++ b/scripts/make_sounds.py@@ -0,0 +1,54 @@+"""The Claude Code mod's two short sounds (x9), made from numbers so they can be made again byte for byte:+`wait.wav`, two soft rising bell notes for a permission prompt that waits for you, and `done.wav`, three rising notes+for a turn done. Mono, 16 bit, 22,050 Hz, under half a second each.++ python3 scripts/make_sounds.py [folder] # default: claude-plugin/sounds+"""+import math+import struct+import sys+import wave+from pathlib import Path++RATE = 22050+PEAK = .3 # of full scale: a cue, not an alarm+# (start s, length s, Hz): each note a bell, its overtone an octave up, struck and dying away+SOUNDS = {+ 'wait.wav': ((0.0, .16, 880.0), (.17, .2, 1174.66)),+ 'done.wav': ((0.0, .1, 659.26), (.1, .1, 783.99), (.2, .24, 1046.5)),+}+++def note(t, length, hz):+ """One bell note at `t` seconds into it: a 4 ms rise, then dying away over its length, silent at its end."""+ if not 0 <= t < length:+ return 0.0+ rise = min(1.0, t / .004)+ fall = math.exp(-5 * t / length) * (1 - t / length)+ return rise * fall * (math.sin(2 * math.pi * hz * t) + .3 * math.sin(4 * math.pi * hz * t)) / 1.3+++def samples(notes):+ end = max(start + length for start, length, _ in notes)+ out = []+ for n in range(round(end * RATE) + 1):+ t = n / RATE+ value = sum(note(t - start, length, hz) for start, length, hz in notes)+ out.append(max(-32767, min(32767, round(value * PEAK * 32767))))+ return out+++def make(folder):+ folder = Path(folder)+ folder.mkdir(parents=True, exist_ok=True)+ for name, notes in SOUNDS.items():+ with wave.open(str(folder / name), 'wb') as clip:+ clip.setnchannels(1)+ clip.setsampwidth(2)+ clip.setframerate(RATE)+ data = samples(notes)+ clip.writeframes(struct.pack(f'<{len(data)}h', *data))+++if __name__ == '__main__':+ make(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parent.parent / 'claude-plugin' / 'sounds')diff --git a/tests/test_catalog.py b/tests/test_catalog.pyindex 474811c..ea1a053 100644--- a/tests/test_catalog.py+++ b/tests/test_catalog.py@@ -138,7 +138,8 @@ class CatalogTest(unittest.TestCase):self.assertLessEqual({t['id'] for t in data['themes']}, set(STYLES)) # a fork may add Local faces# Existing public issues stay mapped; new faces have no voting issue yet.self.assertEqual({t['id']: t['like_issue'] for t in data['themes']},- {'pixel': 1, 'digital': 2, 'neon': 3, 'retro': 4, 'hud': 5, 'space': 6, 'gameboy': None, 'arcade': None, 'retro-dual': None})+ {'pixel': 1, 'digital': 2, 'neon': 3, 'retro': 4, 'hud': 5, 'space': 6, 'gameboy': None, 'arcade': None, 'retro-dual': None,+ 'survival': None})votes = catalog.load_votes()self.assertTrue(set(votes['counts']) <= {str(t['like_issue']) for t in data['themes']})self.assertTrue(all(v['fetched_at'] for v in votes['counts'].values())) # every count is dateddiff --git a/tests/test_claude_3a.py b/tests/test_claude_3a.pynew file mode 100644index 0000000..f1add96--- /dev/null+++ b/tests/test_claude_3a.py@@ -0,0 +1,590 @@+"""v2 phase 3a, TokenTV's side of the moments from Claude Code: the courtroom (claude.risky), the ghost+(claude.deleted), the back turned and turned round (claude.rude, claude.calm), the tool faces (claude.failed,+claude.compact) and the thinking word (claude.word:<WORD>, gone with claude.end or claude.stop). The state machine on+a fake clock, the endpoint's names, and what goes on the rows to draw."""+import json+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 FakeClock # noqa: E402++from token_tv import live, moments # noqa: E402+from token_tv.moments import (BACK, COOLDOWN, COURT_LIMIT, COURT_STALE, FACE_COOLDOWN, GHOST, # noqa: E402+ WORD_INTERVAL, WORD_STALE, Moments, overlay, urgent, word_of)+from token_tv.sample import D, snapshot # noqa: E402++NOW = 1793509260+++class Turns:+ """moments.RANDOM as a test sets it: each kind of pick takes its options in turn, the first, then the second..."""+ def __init__(self):+ self.asked = []++ def choice(self, options):+ options = tuple(options)+ self.asked.append(options)+ return options[(self.asked.count(options) - 1) % len(options)]+++class StateBase(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ for patcher in (mock.patch.object(moments, 'CLOCK', self.clock),+ mock.patch.object(moments, 'RANDOM', Turns())):+ patcher.start()+ self.addCleanup(patcher.stop)+ self.woken = []+ self.m = Moments({'claude', 'codex'}, wake=lambda: self.woken.append(self.clock.t), active=600)++ def at(self, t):+ self.clock.t = t++ def what(self):+ return self.m.wanted()[0]++ def show(self, at=None):+ """The clock starts showing what is due, at `at` (default now)."""+ at = self.clock.t if at is None else at+ what = self.what()+ self.m.shown(what, at)+ return what+++class CourtroomTests(StateBase):+ def test_a_risky_command_brings_one_courtroom_drawn_on_clawds_rows(self):+ t0 = self.clock.t+ self.assertTrue(self.m.note('claude.risky'))+ what, since, mark = self.m.wanted()+ self.assertEqual((what, since, mark), (('risky', 'verdict'), t0, {'kind': 'risky', 'style': 'verdict'}))+ self.assertEqual(self.woken, [t0])+ 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': 'risky', 'style': 'verdict'})+ self.assertNotIn('moment', drawn['accounts']['codex_a'])+ self.assertTrue(self.m.busy()) # the hidden one-offs keep out of its way+ self.m.shown(what, t0 + 2)+ self.assertEqual(self.m.wanted()[:2], (None, t0 + 2)) # one loop, then the usual face++ def test_at_most_one_a_day_from_the_last_ones_start_and_none_kept_for_later(self):+ self.m.note('claude.risky')+ start = self.clock.t + 3+ self.m.shown(self.what(), start)+ count, woken = self.m.count, list(self.woken)+ for t in (start + 1, start + 3600, start + COURT_LIMIT - 1e-3): # a day not yet over: dropped, all of them+ self.at(t)+ self.assertFalse(self.m.note('claude.risky'))+ self.assertEqual((self.m.count, self.woken, self.what()), (count, woken, None))+ self.at(start + COURT_LIMIT + 3600) # past the day with no new risky command: nothing comes back+ self.assertIsNone(self.what())+ self.assertIsNone(self.m.next_change())+ self.at(start + COURT_LIMIT)+ self.assertTrue(self.m.note('claude.risky')) # a day after the last one's start: a new one+ self.assertEqual(self.what(), ('risky', 'objection')) # (the other variant this time)++ def test_midnight_is_nothing_special_the_day_rolls(self):+ self.m.note('claude.risky')+ self.m.shown(self.what(), self.clock.t)+ self.at(self.clock.t + 60) # (a fake clock: whatever the date, the 24 hours run from the start)+ self.assertFalse(self.m.note('claude.risky'))++ def test_one_to_show_at_a_time_and_one_while_it_plays_is_dropped(self):+ self.m.note('claude.risky')+ self.assertFalse(self.m.note('claude.risky')) # one waiting already+ self.assertEqual(moments.RANDOM.asked, [moments.COURTS]) # picked once, for the one kept+ self.m.shown(self.what(), self.clock.t)+ self.assertFalse(self.m.note('claude.risky'))++ def test_it_waits_out_a_wait_and_plays_after_it_and_a_bow_and_a_treat_go_first(self):+ t0 = self.clock.t+ self.m.note('claude.risky')+ self.m.note('claude.ask')+ self.assertEqual(self.what(), ('needs', 1)) # the wait owns the clock+ self.at(t0 + 100)+ self.m.note('claude.answered')+ self.assertEqual(self.m.wanted()[:2], (('risky', 'verdict'), t0)) # still due, from its own time+ self.m.note('claude.end')+ self.m.note('claude.pet')+ self.assertEqual(self.show(), ('done', 'claude'))+ self.assertEqual(self.show(t0 + 110), ('treat', 'pet'))+ self.assertEqual(self.show(t0 + 120), ('risky', 'verdict'))+ self.assertIsNone(self.what())++ def test_one_not_on_the_clock_two_minutes_after_its_command_is_dropped_and_takes_nothing_of_the_day(self):+ t0 = self.clock.t+ self.m.note('claude.risky')+ self.m.note('claude.ask') # its own prompt, left open+ self.assertEqual(self.m.next_change(), t0 + COURT_STALE) # (the publisher looks again then)+ self.at(t0 + COURT_STALE - 1e-3)+ self.m.note('claude.answered') # answered in time: it is still due+ self.assertEqual(self.what(), ('risky', 'verdict'))+ self.at(t0 + COURT_STALE) # and not on the clock by then: gone, never played later+ self.assertIsNone(self.what())+ self.assertFalse(self.m.busy())+ self.assertIsNone(self.m.next_change())+ self.assertTrue(self.m.note('claude.risky')) # the day was not used up by it+ self.assertEqual(self.what(), ('risky', 'objection'))++ def test_a_prompt_left_open_till_it_is_let_go_takes_its_courtroom_with_it(self):+ self.m.note('claude.risky')+ self.m.note('claude.ask')+ self.at(self.clock.t + moments.EXPIRE) # nobody answered: the wait is let go, half an hour on+ self.assertIsNone(self.what()) # no courtroom then++ def test_before_the_break_and_the_tool_faces(self):+ self.m.note('claude.failed')+ self.m.note('claude.risky')+ self.assertEqual(self.show(), ('risky', 'verdict'))+ self.assertEqual(self.show(self.clock.t + 5), ('face', 'failed'))++ def test_no_clock_to_show_it_on_drops_it_and_takes_nothing_of_the_day(self):+ self.m.note('claude.risky')+ self.m.drop_bow()+ self.assertIsNone(self.what())+ self.assertTrue(self.m.note('claude.risky')) # never shown: the day is not used up++ def test_with_no_claude_account_nothing_happens_and_nothing_is_kept(self):+ m = Moments({'codex'}, active=600)+ for name in ('claude.risky', 'claude.deleted', 'claude.rude', 'claude.calm', 'claude.failed', 'claude.compact',+ 'claude.word:PONDERING', 'claude.stop'):+ self.assertFalse(m.note(name))+ self.assertEqual((m.wanted()[0], m.busy(), m.count, m.next_change()), (None, False, 0, None))+ self.assertTrue(m.note('codex.end')) # the others' moments are unaffected+++class GhostTests(StateBase):+ def test_a_deletion_floats_a_ghost_for_a_minute_from_it(self):+ t0 = self.clock.t+ self.assertTrue(self.m.note('claude.deleted'))+ what, since, mark = self.m.wanted()+ self.assertEqual((what, since), (('state', 'drift', False, None), t0))+ self.assertEqual(mark, {'moment': {'kind': 'deleted', 'style': 'drift'}, 'word': None})+ self.assertFalse(self.m.busy()) # a state of the usual face, not a one-off+ self.assertFalse(urgent(what))+ self.assertEqual(self.m.next_change(), t0 + GHOST)+ self.m.shown(what, t0 + 1)+ self.at(t0 + GHOST - 1e-3)+ self.assertEqual(self.what(), what)+ self.at(t0 + GHOST + 5) # looked at late: gone from its deadline+ self.assertEqual(self.m.wanted()[:2], (None, t0 + GHOST))+ self.assertIsNone(self.m.next_change())++ def test_more_deletions_in_its_minute_keep_it_the_same_ghost_with_nothing_to_send(self):+ t0 = self.clock.t+ self.m.note('claude.deleted')+ what = self.show()+ count = self.m.count+ self.at(t0 + 30)+ self.assertFalse(self.m.note('claude.deleted')) # the same picture: nothing changes on the clock+ self.assertEqual(self.m.count, count)+ self.assertEqual(self.m.next_change(), t0 + 30 + GHOST) # a minute from the fresh one+ self.at(t0 + 30 + GHOST - 1e-3)+ self.assertEqual(self.what(), what)+ self.at(t0 + 30 + GHOST)+ self.assertIsNone(self.what())+ self.assertTrue(self.m.note('claude.deleted')) # a new deletion later: a new ghost, its own pick+ self.assertEqual(self.what(), ('state', 'wave', False, None))++ def test_a_one_off_hides_it_and_its_minute_runs_on_meanwhile(self):+ t0 = self.clock.t+ self.m.note('claude.deleted')+ self.show()+ self.at(t0 + 20)+ self.m.note('claude.end')+ self.assertEqual(self.show(), ('done', 'claude')) # the bow over the ghost+ self.assertEqual(self.what(), ('state', 'drift', False, None)) # after it, the ghost still about+ self.at(t0 + 70) # its minute over while something else might have hidden it: never a fresh minute+ self.assertIsNone(self.what())++ def test_its_minute_over_under_a_wait_it_does_not_come_back(self):+ t0 = self.clock.t+ self.m.note('claude.deleted')+ self.m.note('claude.ask')+ self.at(t0 + GHOST + 1)+ self.m.note('claude.answered')+ self.assertIsNone(self.what())+++class BackTests(StateBase):+ def test_a_rude_prompt_turns_its_back_for_a_minute_and_a_fresh_one_from_then(self):+ t0 = self.clock.t+ self.assertTrue(self.m.note('claude.rude'))+ what, since, mark = self.m.wanted()+ self.assertEqual((what, since, mark), (('state', None, True, None), t0, {'moment': {'kind': 'rude'}, 'word': None}))+ self.m.shown(what, t0 + 1)+ self.at(t0 + 40)+ self.assertFalse(self.m.note('claude.rude')) # the same picture: nothing to send+ self.assertEqual(self.m.next_change(), t0 + 40 + BACK)+ self.at(t0 + 40 + BACK - 1e-3)+ self.assertEqual(self.what(), what)+ self.at(t0 + 40 + BACK) # its minute up while on the clock: Clawd turns back round, one loop+ self.assertEqual(self.m.wanted()[:3], (('calm',), t0 + 40 + BACK, {'kind': 'calm'}))+ self.assertTrue(self.m.busy())+ self.m.shown(('calm',), t0 + 101)+ self.assertEqual(self.m.wanted()[:2], (None, t0 + 101))++ def test_a_calm_prompt_turns_it_round_at_once_if_the_clock_showed_the_back(self):+ t0 = self.clock.t+ self.m.note('claude.rude')+ self.show()+ self.at(t0 + 20)+ self.assertTrue(self.m.note('claude.calm'))+ self.assertEqual(self.m.wanted()[:2], (('calm',), t0 + 20))+ self.show()+ self.at(t0 + 200) # its old minute: nothing then+ self.assertIsNone(self.what())+ self.assertFalse(self.m.note('claude.calm')) # calm while calm: nothing++ def test_rude_then_calm_before_the_clock_showed_it_is_nothing_at_all(self):+ count = self.m.count+ self.m.note('claude.rude')+ self.m.note('claude.calm')+ self.assertIsNone(self.what()) # no back, and no turning round from a back never shown+ self.m.note('claude.calm')+ self.m.note('claude.rude')+ self.assertEqual(self.what(), ('state', None, True, None)) # the last one stands: rude+ for _ in range(3):+ self.m.note('claude.calm')+ self.m.note('claude.rude')+ self.m.note('claude.calm')+ self.assertIsNone(self.what())+ self.assertGreater(self.m.count, count)++ def test_rude_again_while_it_turns_round_keeps_the_back_turned(self):+ self.m.note('claude.rude')+ self.show()+ self.m.note('claude.calm')+ self.assertEqual(self.what(), ('calm',))+ self.m.note('claude.rude')+ self.assertEqual(self.what(), ('state', None, True, None)) # the picture on the clock already: no flash++ def test_a_back_hidden_by_a_moment_as_it_ends_does_not_turn_round_later(self):+ t0 = self.clock.t+ self.m.note('claude.rude')+ self.show()+ self.m.note('claude.pet')+ self.assertEqual(self.show(), ('treat', 'pet'))+ self.at(t0 + BACK + 1) # its minute over while the pat played+ self.assertIsNone(self.what())+ self.m.note('claude.rude')+ self.show()+ self.m.note('claude.ask')+ self.show()+ self.m.note('claude.calm') # calm under a wait: the wait stands, and no turning round after it+ self.m.note('claude.answered')+ self.assertIsNone(self.what())++ def test_something_else_going_on_first_drops_the_turn_round(self):+ self.m.note('claude.rude')+ self.show()+ self.m.note('claude.calm')+ self.m.note('claude.end')+ self.assertEqual(self.show(), ('done', 'claude'))+ self.assertIsNone(self.what())++ def test_a_sulking_clawd_does_not_bow_not_even_for_the_rude_prompts_own_turn(self):+ t0 = self.clock.t+ self.m.note('claude.end') # a turn before it: its bow still to show...+ self.m.note('claude.rude') # ...goes as the back turns+ self.assertEqual(self.what(), ('state', None, True, None))+ self.at(t0 + 5)+ self.assertFalse(self.m.note('claude.end')) # the rude prompt's own turn: no bow+ self.show()+ self.at(t0 + 20)+ self.assertFalse(self.m.note('claude.end')) # nor another while the back is turned+ self.assertEqual(self.what(), ('state', None, True, None))+ self.assertTrue(self.m.note('codex.end')) # Codex's cloud does not sulk: it bows+ self.assertEqual(self.show(), ('done', 'codex'))+ self.m.note('claude.calm') # turned round...+ self.at(t0 + 20 + COOLDOWN)+ self.assertTrue(self.m.note('claude.end')) # ...Clawd bows again+ self.assertEqual(self.what(), ('done', 'claude'))++ def test_a_rude_prompts_turn_that_outlasts_the_minute_bows(self):+ t0 = self.clock.t+ self.m.note('claude.rude')+ self.show()+ self.at(t0 + BACK + 30) # a long turn: Clawd turned back round meanwhile+ self.assertEqual(self.show(), ('calm',))+ self.assertTrue(self.m.note('claude.end'))+ self.assertEqual(self.what(), ('done', 'claude'))++ def test_with_a_ghost_about_too_both_are_drawn_and_each_keeps_its_own_minute(self):+ t0 = self.clock.t+ self.m.note('claude.deleted')+ self.at(t0 + 10)+ self.m.note('claude.rude')+ what, since, mark = self.m.wanted()+ self.assertEqual((what, since), (('state', 'drift', True, None), t0 + 10))+ self.assertEqual(mark['moment'], {'kind': 'rude', 'ghost': 'drift'})+ self.m.shown(what, t0 + 11)+ self.at(t0 + 30)+ self.m.note('claude.calm') # the back turns round; the ghost floats on+ self.assertEqual(self.what(), ('calm',))+ self.show()+ self.assertEqual(self.what(), ('state', 'drift', False, None))+ self.m.note('claude.deleted') # a deletion keeps the ghost: it does not put the back round again+ self.at(t0 + 30 + GHOST)+ self.assertIsNone(self.what())+++class ToolFaceTests(StateBase):+ def test_a_failure_or_a_compaction_is_one_loop_of_its_face_on_clawds_rows(self):+ for name, kind in (('claude.failed', 'failed'), ('claude.compact', 'compact')):+ self.at(self.clock.t + 100)+ self.assertTrue(self.m.note(name))+ what, since, mark = self.m.wanted()+ self.assertEqual((what, since, mark), (('face', kind), self.clock.t, {'kind': kind}))+ self.assertTrue(self.m.busy())+ self.m.shown(what, self.clock.t + 1)+ self.assertIsNone(self.what())++ def test_one_face_in_any_rolling_minute_shared_by_the_two_from_its_start(self):+ self.m.note('claude.failed')+ start = self.clock.t + 2+ self.m.shown(self.what(), start)+ for t, name in ((start + 1, 'claude.compact'), (start + 30, 'claude.failed'), (start + FACE_COOLDOWN - 1e-3,+ 'claude.compact')):+ self.at(t)+ self.assertFalse(self.m.note(name)) # dropped, not saved for the minute's end+ self.at(start + FACE_COOLDOWN + 10)+ self.assertIsNone(self.what()) # nothing comes back with time alone+ self.at(start + FACE_COOLDOWN)+ self.assertTrue(self.m.note('claude.compact'))++ def test_a_face_to_show_takes_no_other_and_one_while_waiting_is_dropped(self):+ self.m.note('claude.compact')+ self.assertFalse(self.m.note('claude.failed'))+ self.assertEqual(self.what(), ('face', 'compact'))+ self.m.note('claude.ask') # a wait drops the one not shown+ self.m.note('claude.failed')+ self.m.note('claude.answered')+ self.assertIsNone(self.what())++ def test_the_lowest_of_them_all_after_the_others_and_the_break(self):+ self.m.note('claude.failed')+ for name in ('claude.end', 'claude.pet', 'claude.risky'):+ self.m.note(name)+ self.assertEqual([self.show(self.clock.t + k) for k in range(5)],+ [('done', 'claude'), ('treat', 'pet'), ('risky', 'verdict'), ('face', 'failed'), None])++ def test_its_minute_is_its_own_not_the_bows(self):+ self.m.note('claude.end')+ self.show()+ self.m.note('claude.failed')+ self.assertEqual(self.show(), ('face', 'failed')) # inside the bow's minute+ self.assertFalse(self.m.note('claude.end')) # and the bows' minute holds for bows alone+ self.assertTrue(self.m.cooling(self.clock.t))+++class WordTests(StateBase):+ def test_the_word_shows_in_place_of_the_usual_one_and_the_same_again_changes_nothing(self):+ t0 = self.clock.t+ self.assertTrue(self.m.note('claude.word:Pondering'))+ what, since, mark = self.m.wanted()+ self.assertEqual((what, since, mark), (('state', None, False, 'PONDERING'), t0, {'moment': None, 'word': 'PONDERING'}))+ 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']['word'], 'PONDERING')+ self.assertNotIn('moment', drawn['accounts']['claude_a'])+ self.assertNotIn('word', drawn['accounts']['codex_a'])+ count = self.m.count+ for _ in range(5):+ self.assertFalse(self.m.note('claude.word:PONDERING'))+ self.assertEqual(self.m.count, count)++ def test_a_new_word_at_most_once_a_minute_from_the_last_ones_start_the_newest_waiting(self):+ self.m.note('claude.word:Pondering')+ start = self.clock.t + 1+ self.m.shown(self.what(), start)+ self.at(start + 10)+ self.assertFalse(self.m.note('claude.word:Brewing')) # inside the minute: waits+ self.assertFalse(self.m.note('claude.word:Baking')) # the newest waits instead+ self.assertEqual(self.what(), ('state', None, False, 'PONDERING'))+ self.assertEqual(self.m.next_change(), start + WORD_INTERVAL)+ self.at(start + WORD_INTERVAL - 1e-3)+ self.assertEqual(self.what()[3], 'PONDERING')+ self.at(start + WORD_INTERVAL)+ self.assertEqual(self.m.wanted()[:2], (('state', None, False, 'BAKING'), start + WORD_INTERVAL))+ self.m.shown(self.what(), start + 61)+ self.at(start + 61 + WORD_INTERVAL + 5)+ self.assertTrue(self.m.note('claude.word:Musing')) # past the minute: at once++ def test_a_newer_word_gives_way_when_the_shown_one_is_said_again(self):+ self.m.note('claude.word:Pondering')+ self.show()+ self.m.note('claude.word:Brewing')+ self.m.note('claude.word:Pondering')+ self.at(self.clock.t + WORD_INTERVAL + 1)+ self.assertEqual(self.what()[3], 'PONDERING')++ def test_words_before_the_first_is_shown_replace_it_never_queue(self):+ for word in ('Pondering', 'Brewing', 'Musing'):+ self.m.note('claude.word:' + word)+ self.assertEqual(self.what(), ('state', None, False, 'MUSING'))++ def test_the_turns_end_takes_the_word_at_once_into_the_bow_and_a_cut_turn_without_one(self):+ t0 = self.clock.t+ self.m.note('claude.word:Pondering')+ self.m.shown(self.what(), t0)+ self.at(t0 + 5)+ self.m.note('claude.word:Brewing') # waiting for the minute+ self.m.note('claude.end')+ self.assertEqual(self.m.wanted()[0], ('done', 'claude')) # the bow, no word: one picture for both+ self.m.shown(('done', 'claude'), t0 + 6)+ self.assertEqual(self.m.wanted()[:2], (None, t0 + 6))+ self.at(t0 + 61)+ self.assertIsNone(self.what()) # the waiting word went with the turn+ self.m.note('claude.word:Musing') # a new turn: its word, at most a minute after the last one's start+ self.assertEqual(self.what(), ('state', None, False, 'MUSING'))+ self.m.shown(self.what(), t0 + 62)+ self.at(t0 + 70)+ self.assertTrue(self.m.note('claude.stop')) # cut short: the word goes, no bow+ self.assertEqual(self.m.wanted()[:2], (None, t0 + 70))+ self.at(t0 + 80)+ self.assertFalse(self.m.note('claude.word:Musing')) # the same word, a new turn: inside the minute, waits+ self.assertIsNone(self.what())+ self.at(t0 + 62 + WORD_INTERVAL)+ self.assertEqual(self.what()[3], 'MUSING')++ def test_the_same_word_in_a_new_turn_is_a_new_start_on_the_clock(self):+ self.m.note('claude.word:Pondering')+ first = self.clock.t+ self.m.shown(self.what(), first)+ self.at(first + 5)+ self.m.note('claude.end')+ self.m.shown(self.what(), first + 6) # the bow+ self.at(first + 100)+ self.m.note('claude.word:Pondering') # the next turn happens to say it again+ again = first + 101+ self.m.shown(self.what(), again)+ self.at(again + 10)+ self.assertFalse(self.m.note('claude.word:Brewing')) # a minute from its new start, not from the old one+ self.at(again + WORD_INTERVAL)+ self.assertEqual(self.what()[3], 'BREWING')++ def test_a_word_behind_the_ghost_or_the_sulk_starts_its_minute_once_it_shows(self):+ self.m.note('claude.deleted')+ self.m.note('claude.word:Musing')+ self.m.shown(self.what(), self.clock.t) # the ghost's BOO! in the readout, the word not yet+ self.at(self.clock.t + GHOST + 1)+ self.assertEqual(self.what(), ('state', None, False, 'MUSING'))+ shows = self.clock.t+ self.m.shown(self.what(), shows) # now it shows+ self.at(shows + 5)+ self.assertFalse(self.m.note('claude.word:Herding')) # a minute from when it showed, not from the ghost's+ self.at(shows + WORD_INTERVAL)+ self.assertEqual(self.what()[3], 'HERDING')++ def test_a_word_behind_slow_starts_its_minute_once_it_is_the_label(self):+ self.m.note('claude.word:Pondering')+ self.m.shown(self.what(), self.clock.t, readable=False) # SLOW holds the readout: the word is not read+ self.at(self.clock.t + 5)+ self.assertTrue(self.m.note('claude.word:Brewing')) # no minute started: it takes the word's place at once+ self.m.shown(self.what(), self.clock.t, readable=False)+ self.at(self.clock.t + 300)+ shows = self.clock.t+ self.m.shown(self.what(), shows) # SLOW lifts: now it is read+ self.at(shows + 5)+ self.assertFalse(self.m.note('claude.word:Musing')) # a minute from when it was read+ self.at(shows + WORD_INTERVAL)+ self.assertEqual(self.what()[3], 'MUSING')++ def test_a_newer_word_waiting_wakes_the_publisher_for_its_minutes_end(self):+ self.m.note('claude.word:Pondering')+ start = self.clock.t+ self.m.shown(self.what(), start)+ self.at(start + 32)+ woken = list(self.woken)+ self.assertFalse(self.m.note('claude.word:Musing')) # nothing to show yet...+ self.assertEqual(self.woken, woken + [start + 32]) # ...but the publisher plans its next look again+ self.assertEqual(self.m.next_change(), start + WORD_INTERVAL)+ self.assertFalse(self.m.note('claude.word:Baking')) # a newer one in its place comes no sooner+ self.assertEqual(self.woken, woken + [start + 32])++ def test_a_cut_turn_leaves_no_bow_and_nothing_queued(self):+ self.m.note('claude.word:Pondering')+ self.assertTrue(self.m.note('claude.stop'))+ self.assertIsNone(self.what())+ self.assertFalse(self.m.note('claude.stop'))+ self.assertIsNone(self.m.bow)++ def test_a_word_nobody_says_again_goes_stale(self):+ t0 = self.clock.t+ self.m.note('claude.word:Pondering')+ self.show()+ self.at(t0 + 600)+ self.m.note('claude.word:Pondering') # said again: still on, and heard from now+ self.assertEqual(self.m.next_change(), t0 + 600 + WORD_STALE)+ self.at(t0 + 600 + WORD_STALE)+ self.assertEqual(self.m.wanted()[:2], (None, t0 + 600 + WORD_STALE))++ def test_waits_and_moments_hide_the_word_and_it_returns_after_them_with_its_own_start(self):+ self.m.note('claude.word:Pondering')+ start = self.clock.t+ self.m.shown(self.what(), start)+ self.m.note('claude.ask')+ self.assertEqual(self.show(), ('needs', 1))+ self.at(start + 300)+ self.m.note('claude.answered')+ self.assertEqual(self.what(), ('state', None, False, 'PONDERING'))+ self.m.shown(self.what(), start + 301) # the same word again: not a new word's start+ self.at(start + 302)+ self.assertTrue(self.m.note('claude.word:Brewing')) # its minute ran from its first start++ def test_only_one_word_of_letters_a_to_z_up_to_fourteen(self):+ for name in ('claude.word:PONDERING', 'claude.word:a', 'claude.word:WWWWWWWWWWWWWW', 'claude.word:Pondering'):+ self.assertIsNotNone(word_of(name), name)+ for name in ('claude.word:', 'claude.word:WWWWWWWWWWWWWWW', 'claude.word:two words', 'claude.word:Ponder1ng',+ 'claude.word:A:B', 'claude.word:Ponder_ing', 'claude.word:Ponder-ing', 'claude.word:Pondering\n',+ 'claude.word: Pondering', 'claude.word:Sautéing', 'claude.word:生각', 'Claude.word:A', 'claude.Word:A',+ 'claude.words:A', 'claude.word', 'codex.word:A', 'claude.word:<b>', 'claude.word:Pondering',+ None, 42, ['claude.word:A']):+ self.assertIsNone(word_of(name), name)+ if isinstance(name, str):+ with self.assertRaises(ValueError):+ self.m.note(name)+ self.assertIsNone(self.what())+++class EndpointTests(unittest.TestCase):+ def test_the_new_names_and_one_word_and_nothing_like_them(self):+ for name in ('claude.risky', 'claude.deleted', 'claude.rude', 'claude.calm', 'claude.failed', 'claude.compact',+ 'claude.stop', 'claude.word:Pondering', 'claude.word:A'):+ body = json.dumps({'moment': name}).encode()+ self.assertEqual(live.moment_of(body), name)+ for body in (b'{"moment":"claude.word:"}', b'{"moment":"claude.word:Two Words"}', b'{"moment":"claude.word:A:B"}',+ b'{"moment":"claude.word:ABCDEFGHIJKLMNO"}', b'{"moment":"claude.Risky"}', b'{"moment":"claude.risky "}',+ b'{"moment":"claude.risky","command":"rm -rf /"}', b'{"moment":"claude.word:Pondering","word":"x"}',+ b'{"moment":["claude.risky"]}', b'{"moment":{"word":"A"}}', b'{"moment":"claude.word:P\\u00e9"}',+ b'{"moment":"claude.risky","moment":"claude.rude"}', b'{"moment":"claude.sound"}',+ b'{"moment":"claude.word:Pondering\\n"}', b'["claude.risky"]', b'{"moment":"claude.idle"}'):+ with self.assertRaises(ValueError, msg=body):+ live.moment_of(body)++ def test_the_states_are_no_moment_a_one_off_keeps_out_of_the_way_of(self):+ self.assertFalse(urgent(None))+ self.assertFalse(urgent(('state', 'drift', True, 'PONDERING')))+ for what in (('needs', 1), ('done', 'claude'), ('treat', 'pet'), ('risky', 'verdict'), ('break', 'drink'),+ ('calm',), ('face', 'failed'), ('unsure',)):+ self.assertTrue(urgent(what), what)++ def test_drawing_a_state_copies_the_rows_and_changes_no_reading(self):+ data = snapshot(NOW, [('claude_a', 'CLAUDE A', 'claude', [('WEEK', 40, 3 * D)]),+ ('claude_b', 'CLAUDE B', 'claude', [('WEEK', 50, 3 * D)])])+ before = json.dumps(data, sort_keys=True)+ what = ('state', 'wave', True, 'MUSING')+ mark = {'moment': {'kind': 'rude', 'ghost': 'wave'}, 'word': 'MUSING'}+ drawn = overlay(data, what, mark)+ self.assertEqual(json.dumps(data, sort_keys=True), before)+ for key in ('claude_a', 'claude_b'): # every Claude account shows it (Claude Code says not which)+ self.assertEqual((drawn['accounts'][key]['moment'], drawn['accounts'][key]['word']),+ ({'kind': 'rude', 'ghost': 'wave'}, 'MUSING'))+ self.assertIsNot(drawn['accounts']['claude_a']['moment'], drawn['accounts']['claude_b']['moment'])+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_claude_3a_drawings.py b/tests/test_claude_3a_drawings.pynew file mode 100644index 0000000..ad484bb--- /dev/null+++ b/tests/test_claude_3a_drawings.py@@ -0,0 +1,219 @@+"""v2 phase 3a, the drawings: Clawd's courtroom (two variants), the ghost of a deleted file (two), its back turned+and the turn back round, dizzy, the squeeze, and the thinking word in the readout, as the owner approved them+(drafts w17-w23). Each moves through its loop with its own props, says its own word, and is Clawd's alone."""+import io+import subprocess+import sys+import unittest+from pathlib import Path+from unittest import mock++from PIL import Image++from token_tv import arcade, readout, seasons+from token_tv import claude_moments as cm+from token_tv.sample import D, H, snapshot++ROOT = Path(__file__).resolve().parent.parent+NOW = 1793509260 # a fixed instant for the drawings (the page's own)+WINDOWS = [('5H', 42, 2 * H), ('WEEK', 64, 3 * D)]+++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+++def colours(image):+ return {c for _, c in image.getcolors(1 << 16)}+++class Base(unittest.TestCase):+ def setUp(self):+ for patcher in (mock.patch.object(arcade, 'NIGHT_HOURS', ()), mock.patch.object(readout, 'STYLE', 'battery')):+ patcher.start()+ self.addCleanup(patcher.stop)++ def data(self, mark=None, *others, **row):+ data = snapshot(NOW, [('claude_a', 'CLAUDE A', 'claude', WINDOWS)] + list(others))+ if mark:+ data['accounts']['claude_a']['moment'] = mark+ data['accounts']['claude_a'].update(row)+ return data++ def stages(self, moment=None, **row):+ shots = frames(arcade.render_arcade(self.data(moment, **row), NOW))+ return [shot.crop((0, 28, 240, 170)) for shot in shots], shots++ def label(self, moment=None, **row):+ """What the readout says for Claude's row, and whether that is drawn in Clawd's line."""+ data = self.data(moment, **row)+ line = dict(data['accounts']['claude_a'], key='claude_a')+ plan = arcade.scene_plan(line, NOW)+ return arcade.action_label(line, plan, None, 0, arcade.FRAMES)+++class SceneTests(Base):+ CASES = ( # (moment, its word, an ink only its props bring)+ ({'kind': 'risky', 'style': 'verdict'}, 'ORDER!', cm.GOLD),+ ({'kind': 'risky', 'style': 'objection'}, 'OBJECTION!', cm.BURST_EDGE),+ ({'kind': 'deleted', 'style': 'drift'}, 'BOO!', cm.GHOST_INK['W']),+ ({'kind': 'deleted', 'style': 'wave'}, 'BOO!', cm.GHOST_INK['W']),+ ({'kind': 'rude'}, 'SULKING', cm.STEAM),+ ({'kind': 'rude', 'ghost': 'drift'}, 'SULKING', cm.GHOST_INK['W']),+ ({'kind': 'calm'}, 'FORGIVEN', (255, 92, 136)),+ ({'kind': 'failed'}, 'DIZZY', cm.STAR),+ ({'kind': 'compact'}, 'COMPACTING', (105, 154, 203)),+ )++ def test_each_moves_through_its_loop_with_its_own_props_and_says_its_own_word(self):+ usual = self.stages()[0]+ for moment, word, ink in self.CASES:+ with self.subTest(moment=moment):+ stages, _ = self.stages(moment)+ self.assertGreater(len({s.tobytes() for s in stages}), 15) # moving, not a still with a label+ self.assertTrue(any(ink in colours(s) for s in stages))+ self.assertFalse(any(ink in colours(s) for s in usual)) # (none of the usual scene's inks)+ self.assertEqual(self.label(moment), word)++ def test_the_two_variants_differ_and_a_style_left_out_is_the_first(self):+ for kind, styles in (('risky', cm.COURTS), ('deleted', cm.GHOSTS)):+ first, second = (arcade.render_arcade(self.data({'kind': kind, 'style': s}), NOW) for s in styles)+ self.assertNotEqual(first, second)+ self.assertEqual(arcade.render_arcade(self.data({'kind': kind}), NOW), first)++ def test_clawd_from_behind_shows_no_eyes_and_turns_round_to_glare(self):+ ink = lambda grid: {c for row in grid for c in row} # noqa: E731+ self.assertNotIn(cm.DARK, ink(cm.back())) # its back to you: no eyes+ self.assertNotIn(cm.DARK, ink(cm.back_quarter()))+ self.assertIn(cm.DARK, ink(cm.edited(cm.grid('Turning', 20), 'frown'))) # the glare over its shoulder+ self.assertEqual(len(cm.back()), len(cm.grid('LookingAround', 0))) # its own form, from behind+ self.assertEqual({c for c in ink(cm.back()) if c} - {None}, {c for c in ink(cm.grid('LookingAround', 0))+ if c and c != cm.DARK})++ def test_with_a_ghost_about_the_sulk_and_the_ghost_are_both_drawn(self):+ alone, _ = self.stages({'kind': 'rude'})+ haunted, _ = self.stages({'kind': 'rude', 'ghost': 'wave'})+ self.assertNotEqual([s.tobytes() for s in alone], [s.tobytes() for s in haunted])+ self.assertTrue(any(cm.STEAM in colours(s) for s in haunted))++ def test_the_ghost_floats_over_what_clawd_does_at_work_too(self):+ for active in (False, True):+ usual, _ = self.stages(active=active)+ ghost, _ = self.stages({'kind': 'deleted', 'style': 'drift'}, active=active)+ self.assertNotEqual([s.tobytes() for s in usual], [s.tobytes() for s in ghost])++ def test_only_clawd_does_them_another_pet_keeps_its_own_loop(self):+ other = ('codex_a', 'CODEX A', 'codex', [('WEEK', 30, 3 * D)])+ plain = self.data(None, other)+ for moment, _, _ in self.CASES:+ marked = self.data(moment, other)+ self.assertEqual([r['provider'] for r in arcade.shown_rows(marked, NOW)], ['claude', 'codex'])+ usual, shots = arcade.arcade_frames(plain, NOW), arcade.arcade_frames(marked, 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:]])+ self.assertNotEqual([stage(f) for f in shots[:half]], [stage(f) for f in usual[:half]])++ def test_a_moment_or_a_word_brings_clawd_into_the_loop_beside_pets_at_work(self):+ busy = ('codex_a', 'CODEX A', 'codex', [('WEEK', 30, 3 * D)])+ data = self.data(None, busy)+ data['accounts']['codex_a']['active'] = True+ self.assertEqual([r['provider'] for r in arcade.shown_rows(data, NOW)], ['codex']) # Clawd resting: not shown+ for extra in ({'moment': {'kind': 'failed'}}, {'moment': {'kind': 'deleted', 'style': 'drift'}},+ {'word': 'PONDERING'}, {'moment': {'kind': 'risky', 'style': 'verdict'}}):+ joined = self.data(None, busy, **extra)+ joined['accounts']['codex_a']['active'] = True+ self.assertEqual([r['provider'] for r in arcade.shown_rows(joined, NOW)], ['claude', 'codex'], extra)++ def test_the_drawings_are_the_approved_drafts_byte_for_byte(self):+ drafts = ROOT / 'docs' / 'design' / 'v2_phase3a_drafts.py'+ if not drafts.exists():+ self.skipTest('the drafts are kept in the private tree only')+ # The drafts as drawn, plugged into Arcade in a process of their own (they change it for that run); off season+ # on both sides, as they were drawn before the seasons (x8: NOW is Halloween's last day).+ script = f'''+import sys+sys.path.insert(0, {str(ROOT)!r}); sys.path.insert(0, {str(drafts.parent)!r})+from token_tv import arcade, readout, seasons+from token_tv.sample import D, H, snapshot+import v2_phase3a_drafts as drafts+readout.STYLE = 'battery'; arcade.NIGHT_HOURS = (); drafts.install(); seasons.season_at = lambda at=None: None+for kind, style, row in {[(m['kind'], m.get('style') if m.get('style') not in ('verdict', 'drift') else None, r)+ for m, r in self.ITEMS]!r}:+ data = snapshot({NOW}, [('claude_a', 'CLAUDE A', 'claude', {WINDOWS!r})])+ if kind:+ data['accounts']['claude_a']['moment'] = dict({{'kind': kind, 'at': {NOW}}}, **({{'style': style}} if style else {{}}))+ data['accounts']['claude_a'].update(row)+ sys.stdout.write(arcade.render_arcade(data, {NOW}).hex() + '\\n')+'''+ drawn = subprocess.run([sys.executable, '-B', '-c', script], capture_output=True, text=True, timeout=600,+ check=True).stdout.split()+ self.assertEqual(len(drawn), len(self.ITEMS))+ for (moment, row), ref in zip(self.ITEMS, drawn):+ with mock.patch.object(seasons, 'season_at', lambda at=None: None):+ built = arcade.render_arcade(self.data(moment if moment.get('kind') else None, **row), NOW)+ self.assertEqual(built.hex(), ref, (moment, row))++ ITEMS = (({'kind': 'risky', 'style': 'verdict'}, {}), ({'kind': 'risky', 'style': 'objection'}, {}),+ ({'kind': 'deleted', 'style': 'drift'}, {'active': True}), ({'kind': 'deleted', 'style': 'wave'}, {}),+ ({'kind': 'rude'}, {}), ({'kind': 'calm'}, {}), ({'kind': 'failed'}, {}), ({'kind': 'compact'}, {}),+ ({'kind': None}, {'active': True, 'word': 'PONDERING'}),+ ({'kind': None}, {'active': True, 'word': 'RETICULATING'}),+ ({'kind': None}, {'active': True, 'word': 'ACCOMPLISHING'}))+++class ReadoutTests(Base):+ def test_the_thinking_word_takes_the_place_of_what_clawd_does_and_nothing_else(self):+ for row, word in (({'word': 'PONDERING'}, 'PONDERING'), ({'word': 'PONDERING', 'active': True}, 'PONDERING'),+ ({}, 'RESTING'), ({'active': True}, 'RUNNING')):+ self.assertEqual(self.label(**row), word, row)+ for moment, word in (({'kind': 'needs', 'level': 1}, 'NEEDS YOU'), ({'kind': 'done', 'at': 1}, 'DONE'),+ ({'kind': 'pet'}, 'PETTED'), ({'kind': 'drink'}, 'DRINKING'), ({'kind': 'failed'}, 'DIZZY'),+ ({'kind': 'deleted', 'style': 'drift'}, 'BOO!')):+ self.assertEqual(self.label(moment, word='PONDERING'), word, moment) # a moment says its own word++ def test_slow_stays_readable_under_the_word_the_ghost_the_sulk_and_the_tool_faces(self):+ slow = {'slow': ['WEEK']}+ for moment in (None, {'kind': 'deleted', 'style': 'drift'}, {'kind': 'rude'}, {'kind': 'calm'},+ {'kind': 'failed'}, {'kind': 'compact'}):+ self.assertEqual(self.label(moment, word='PONDERING', **slow), 'SLOW', moment)+ for moment, word in (({'kind': 'risky', 'style': 'verdict'}, 'ORDER!'), ({'kind': 'needs', 'level': 1}, 'NEEDS YOU'),+ ({'kind': 'done', 'at': 1}, 'DONE'), ({'kind': 'snack'}, 'SNACKING')):+ self.assertEqual(self.label(moment, **slow), word, moment) # (actions say theirs, as in phase 2)+ _, shots = self.stages({'kind': 'failed'}, slow=['WEEK'])+ warn = tuple(readout.WARN)+ self.assertTrue(any(warn in colours(s.crop((0, 171, 240, 240))) for s in shots)) # red SLOW, blinking+ self.assertTrue(any(warn not in colours(s.crop((0, 195, 240, 240))) for s in shots))++ def test_another_pets_row_never_says_claudes_word(self):+ data = snapshot(NOW, [('codex_a', 'CODEX A', 'codex', [('WEEK', 30, 3 * D)])])+ row = dict(data['accounts']['codex_a'], key='codex_a', word='PONDERING')+ self.assertNotEqual(arcade.action_label(row, arcade.scene_plan(row, NOW), None, 0, arcade.FRAMES), 'PONDERING')++ def test_twelve_letters_in_the_readouts_own_size_thirteen_and_fourteen_smaller_on_the_same_line(self):+ def drawn(word):+ canvas = Image.new('RGB', (240, 240), readout.PANEL)+ from PIL import ImageDraw+ readout.draw_battery(canvas, ImageDraw.Draw(canvas), 'claude', word, [('5H', 40, NOW + H, False),+ ('WEEK', 60, NOW + D, False)], NOW)+ ink = tuple(readout.MUTED)+ line = canvas.crop((80, 170, 240, 195))+ spots = [(x, y) for y in range(line.height) for x in range(line.width) if line.getpixel((x, y)) == ink]+ return min(x for x, _ in spots) + 80, max(x for x, _ in spots) + 80, max(y for _, y in spots) - min(y for _, y in spots) + 1+ for word, tall in (('PONDERING', 14), ('RETICULATING', 14), ('ACCOMPLISHING', 7), ('PHILOSOPHISING', 7),+ ('WWWWWWWWWWWWWW', 7)):+ left, right, height = drawn(word)+ self.assertEqual(height, tall, word) # 7 rows of the 5 x 7 font, doubled for the readout's own size+ self.assertGreaterEqual(left, 80) # after CLAWD+ self.assertLessEqual(right, 230, word) # whole, on the line, inside the screen's margin+ width = (len(word) * 6 - 1) * (2 if tall == 14 else 1)+ self.assertEqual(right - left + 1, width, word) # every letter of it, none cut+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_claude_3a_timing.py b/tests/test_claude_3a_timing.pynew file mode 100644index 0000000..bcad360--- /dev/null+++ b/tests/test_claude_3a_timing.py@@ -0,0 +1,356 @@+"""v2 phase 3a on the fake SD_PRO, through live.main itself: each moment from Claude Code reaches the clock as the+loop it is playing ends (never mid-loop), a one-off plays its own one loop on the clock (each picture its delay, at+least a 142 ms tick: m1) and the usual face comes back, a minute-long state (the ghost, the back turned) stays in the+one picture the clock loops, a fresh repeat sends nothing, and the thinking word changes at most once a minute and+goes with the turn."""+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_claude_3a import Turns # noqa: E402+from test_moments import Rig, physical # noqa: E402++from token_tv import moments # noqa: E402+from token_tv.display import render_page # noqa: E402+from token_tv.moments import COURT_STALE, GHOST, WORD_INTERVAL, loop_end, overlay # noqa: E402+from token_tv.sample import H # noqa: E402+from token_tv.state import MIN_FETCH_SECONDS, RATE_WINDOW, UsageStore # noqa: E402+++def mark_of(what):+ """The rows' mark for `what`, as Moments.wanted() gives it (the tests' own oracle, from the rules)."""+ if what is None:+ return None+ if what[0] == 'risky':+ return {'kind': 'risky', 'style': what[1]}+ if what[0] == 'calm':+ return {'kind': 'calm'}+ if what[0] == 'face':+ return {'kind': what[1]}+ if what[0] == 'state':+ _, ghost, back, word = what+ moment = (dict({'kind': 'rude'}, **({'ghost': ghost} if ghost else {})) if back else+ {'kind': 'deleted', 'style': ghost} if ghost else None)+ return {'moment': moment, 'word': word}+ return {'kind': 'needs', 'since': 0, 'level': what[1]} if what[0] == 'needs' else (+ {'kind': 'done', 'at': 0} if what[0] == 'done' else {'kind': what[1]})+++class Base(unittest.TestCase):+ def setUp(self):+ patcher = mock.patch.object(moments, 'RANDOM', Turns()) # each kind's variants in turn: A first+ patcher.start()+ self.addCleanup(patcher.stop)++ def picture(self, rig, what=None):+ store = UsageStore(rig.config['accounts'], min_fetch_seconds=MIN_FETCH_SECONDS)+ store.refresh()+ return render_page(overlay(store.snapshot(), what, mark_of(what)), 0, 'arcade')++ 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: its start+ and its loop on the clock (each picture its delay, at least a 142 ms tick)."""+ image, started = rig.showing()+ self.assertEqual(image, self.picture(rig, what))+ self.assertGreaterEqual(started, when - 1e-6)+ self.assertLess(started, when + .25)+ self.assertLessEqual(len(rig.uploads(since)), 1)+ return started, physical(image)++ def halfway(self, rig):+ """Half way through the loop playing: (now, that loop's end)."""+ normal, start = rig.showing()+ rig.clock.to(start + physical(normal) / 2)+ return rig.clock.now(), loop_end({'at': start, 'loop': physical(normal)}, rig.clock.now())+++class OneOffTests(Base):+ def test_the_courtroom_comes_at_the_loops_end_plays_one_loop_and_the_usual_face_comes_back(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.risky')+ rig.clock.to(due - .01)+ self.assertEqual(rig.requests(said), []) # nothing interrupts the loop playing+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('risky', 'verdict'), said)+ self.assertNotEqual(physical(self.picture(rig)), loop) # (its own loop, not the usual face's)+ rig.say('claude.risky') # inside the day: dropped+ rig.clock.to(start + loop + .3)+ back, again = self.assertAt(rig, start + loop, None, start + .01)+ self.assertLessEqual(len(rig.uploads(said)), 2) # entry and return+ rig.clock.advance(5 * physical(self.picture(rig)))+ self.assertEqual(rig.uploads(back + .01), []) # and nothing more: no courtroom put off for later++ def test_dizzy_and_the_squeeze_one_loop_each_and_one_a_minute_between_them(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.failed')+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('face', 'failed'), said)+ rig.say('claude.compact') # inside the minute: dropped+ rig.clock.to(start + loop + .3)+ self.assertAt(rig, start + loop, None, start + .01)+ rig.clock.to(start + 59.9)+ rig.say('claude.compact')+ rig.clock.advance(15)+ self.assertEqual(rig.showing()[0], self.picture(rig)) # dropped, not saved for the minute's end+ rig.clock.to(start + 60.5)+ mark = rig.clock.now()+ rig.say('claude.compact')+ due = rig.end_of_loop()+ rig.clock.to(due + .3)+ self.assertAt(rig, due, ('face', 'compact'), mark)++ def test_a_courtroom_held_two_minutes_by_its_open_prompt_is_dropped_and_the_day_is_kept(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.risky')+ rig.say('claude.ask') # its own prompt, left open+ rig.clock.to(due + .3)+ self.assertAt(rig, due, ('needs', 1), said)+ rig.clock.to(said + COURT_STALE + 30)+ answered = rig.clock.now()+ rig.say('claude.answered')+ due = rig.end_of_loop()+ rig.clock.to(due + .3)+ back, loop = self.assertAt(rig, due, None, answered) # the usual face: no courtroom two minutes late+ rig.clock.advance(3 * loop)+ self.assertEqual(rig.uploads(back + .01), [])+ fresh = rig.clock.now()+ rig.say('claude.risky') # it took nothing of the day: a fresh one plays+ due = rig.end_of_loop()+ rig.clock.to(due + .3)+ self.assertAt(rig, due, ('risky', 'objection'), fresh)++ def test_a_wait_owns_the_clock_and_the_courtroom_plays_after_it(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.risky')+ rig.say('claude.ask') # before the loop's end: the wait comes first+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('needs', 1), said)+ rig.clock.advance(3 * loop)+ answered = rig.clock.now()+ rig.say('claude.answered')+ due = rig.end_of_loop()+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('risky', 'verdict'), answered)+ rig.clock.to(start + loop + .3)+ self.assertEqual(rig.showing()[0], self.picture(rig))+++class StateTests(Base):+ def test_a_ghost_floats_its_minute_in_one_picture_more_deletions_send_nothing_then_it_goes(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.deleted')+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', 'drift', False, None), said)+ rig.clock.to(said + 30)+ fresh = rig.clock.now()+ rig.say('claude.deleted') # a minute from this one now, the same ghost+ rig.clock.to(said + GHOST + 5) # past the first one's minute: still there, nothing sent+ self.assertEqual(rig.uploads(start + .01), [])+ self.assertEqual(rig.switches(start + .01), [])+ self.assertEqual(rig.showing()[0], self.picture(rig, ('state', 'drift', False, None)))+ gone = loop_end({'at': start, 'loop': loop}, fresh + GHOST)+ rig.clock.to(gone + .3)+ self.assertAt(rig, gone, None, start + .01)+ self.assertLessEqual(len(rig.uploads(said)), 2) # its entry and its end, nothing between++ def test_the_back_turned_a_calm_prompt_turns_it_round_for_one_loop_then_the_usual_face(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.rude')+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, True, None), said)+ rig.clock.to(start + 20)+ calmed = rig.clock.now()+ rig.say('claude.calm')+ due = loop_end({'at': start, 'loop': loop}, calmed)+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('calm',), calmed) # the turn back round (w20), one loop+ rig.clock.to(start + loop + .3)+ self.assertAt(rig, start + loop, None, start + .01)+ self.assertLessEqual(len(rig.uploads(said)), 3) # the back, the turn round, the usual face (the draft's three)+ rig.clock.to(said + 120) # past the old minute: nothing+ self.assertEqual(rig.uploads(start + loop + .5), [])++ def test_a_sulking_clawd_does_not_bow_for_the_rude_prompts_own_turn_nor_while_it_sulks(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.rude')+ rig.clock.advance(.5)+ rig.say('claude.end') # its own turn ends before the back is on the clock: no DONE first+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, True, None), said)+ rig.clock.to(start + 20)+ rig.say('claude.end') # another turn while it sulks: no bow either+ rig.clock.to(start + 50)+ self.assertEqual(rig.uploads(start + .01), [])+ self.assertEqual(rig.switches(start + .01), [])++ def test_rude_then_calm_inside_one_loop_sends_nothing_and_never_flashes_a_back(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.rude')+ rig.say('claude.calm')+ for _ in range(3):+ rig.say('claude.rude')+ rig.say('claude.calm')+ rig.clock.to(due + 3 * physical(self.picture(rig)))+ self.assertEqual(rig.requests(said), [])++ def test_the_back_turned_its_minute_up_on_the_clock_also_turns_round(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.rude')+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, True, None), said)+ turned = loop_end({'at': start, 'loop': loop}, said + 60)+ rig.clock.to(turned + .3)+ self.assertAt(rig, turned, ('calm',), start + .01)+++class WordTests(Base):+ def test_the_word_comes_at_the_loops_end_the_same_again_sends_nothing_a_new_one_after_a_minute(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.word:Pondering')+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, False, 'PONDERING'), said)+ for _ in range(4):+ rig.say('claude.word:Pondering')+ rig.clock.to(start + 10)+ rig.say('claude.word:Brewing') # inside the minute: waits for it+ rig.clock.to(start + WORD_INTERVAL - .01)+ self.assertEqual(rig.uploads(start + .01), []) # no picture per spinner drawing, none for the waiting word+ due = loop_end({'at': start, 'loop': loop}, start + WORD_INTERVAL)+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, False, 'BREWING'), start + 1)++ def test_a_newer_word_waiting_goes_on_at_its_minutes_end_with_no_reading_to_wake_tokentv(self):+ rig = Rig(self)+ rig.clock.to(rig.t0 + 30) # the first word's minute will end between two readings+ said, due = rig.clock.now(), rig.end_of_loop()+ rig.say('claude.word:Pondering')+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, False, 'PONDERING'), said)+ rig.clock.to(rig.poll_at(1) + 2) # after a reading: nothing else wakes TokenTV till the next one+ rig.say('claude.word:Musing') # waits for the minute...+ due = loop_end({'at': start, 'loop': loop}, start + WORD_INTERVAL)+ self.assertLess(due + 1, rig.poll_at(2))+ rig.clock.to(due + .3)+ self.assertAt(rig, due, ('state', None, False, 'MUSING'), start + 1) # ...and goes on as it ends++ def test_a_word_said_behind_slow_starts_its_minute_once_slow_lifts(self):+ rig = Rig(self, wall=True, windows={'claude': [('5H', 60, 4 * H)]})+ drawn = lambda what: render_page(overlay(rig.held(), what, mark_of(what)), 0, 'arcade') # noqa: E731+ polls = RATE_WINDOW // rig.poll+ for k in range(1, polls + 1): # 1.5 % a minute: running out (SLOW)+ rig.set('claude_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']['claude_a']['slow'], ['5H'])+ said = rig.clock.now()+ rig.say('claude.word:Pondering') # SLOW keeps the label: the same picture, nothing sent+ rig.clock.advance(20)+ self.assertEqual(rig.requests(said), [])+ k = polls+ while rig.held()['accounts']['claude_a']['slow']: # flat from now: SLOW lifts after a while+ k += 1+ rig.write(rig.now() + rig.poll_at(k) - rig.clock.now())+ rig.clock.to(rig.poll_at(k) + .5)+ due = rig.end_of_loop(rig.poll_at(k))+ rig.clock.to(due + .3)+ image, read = rig.showing()+ self.assertEqual(image, drawn(('state', None, False, 'PONDERING'))) # the word, read at last+ self.assertGreater(read, said + 60)+ rig.clock.to(read + 5)+ rig.say('claude.word:Musing') # a minute from when it was read, not from when it was said+ due = loop_end({'at': read, 'loop': physical(image)}, read + WORD_INTERVAL)+ rig.clock.to(due - .3)+ self.assertEqual(rig.uploads(read + .01), [])+ rig.clock.to(due + .3)+ musing, at = rig.showing()+ self.assertEqual(musing, drawn(('state', None, False, 'MUSING')))+ self.assertGreaterEqual(at, due - 1e-6)+ self.assertLess(at, due + .25)++ def test_the_turns_end_takes_the_word_into_the_bow_in_one_picture_and_a_cut_turn_without_a_bow(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ rig.say('claude.word:Pondering')+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, False, 'PONDERING'), said)+ rig.clock.to(start + 5)+ rig.say('claude.word:Brewing') # waiting for its minute as the turn ends+ ended = rig.clock.now()+ rig.say('claude.end')+ due = loop_end({'at': start, 'loop': loop}, ended)+ rig.clock.to(due + .3)+ bowed, bow_loop = self.assertAt(rig, due, ('done', 'claude'), ended) # the bow with no word: one picture+ rig.clock.to(bowed + bow_loop + .3)+ self.assertAt(rig, bowed + bow_loop, None, bowed + .01)+ rig.clock.to(start + 70) # the waiting word went with the turn: nothing at its minute+ self.assertEqual(rig.showing()[0], self.picture(rig))+ rig.say('claude.word:Musing')+ due = rig.end_of_loop()+ rig.clock.to(due + .3)+ start, loop = self.assertAt(rig, due, ('state', None, False, 'MUSING'), start + 69)+ rig.clock.advance(2)+ cut = rig.clock.now()+ rig.say('claude.stop')+ due = rig.end_of_loop()+ rig.clock.to(due + .3)+ self.assertAt(rig, due, None, cut) # the usual face: no bow for a turn cut short++ def test_nothing_of_the_word_or_the_moments_is_written_anywhere(self):+ rig = Rig(self)++ def files(): # all but the running TokenTV's live.lock, which Windows lets no one read while it is held+ return {p: p.read_bytes() for p in rig.state.rglob('*') if p.is_file() and p.name != 'live.lock'}+ before = files()+ said, due = self.halfway(rig)+ for name in ('claude.word:Philosophising', 'claude.deleted', 'claude.rude'):+ rig.say(name)+ rig.clock.to(due + .3)+ self.assertEqual(rig.showing()[0], self.picture(rig, ('state', 'drift', True, 'PHILOSOPHISING')))+ for path, data in files().items():+ self.assertNotIn(b'PHILOSOPHISING', data.upper(), path)+ self.assertNotIn(b'rude', data, path)+ if path in before: # an existing file is only ever the usual face's (the moments' never kept)+ self.assertNotEqual(data, rig.showing()[0])+ self.assertNotIn(rig.showing()[0], files().values())++ def test_the_dashboards_preview_shows_the_word_and_the_ghost_as_the_clock_will(self):+ import http.client+ rig = Rig(self)+ rig.say('claude.word:Pondering')+ rig.say('claude.deleted')+ conn = http.client.HTTPConnection('127.0.0.1', rig.port, timeout=5)+ conn.request('GET', '/frame/0.jpg')+ self.assertEqual(conn.getresponse().read(), self.picture(rig, ('state', 'drift', False, 'PONDERING')))+ conn.close()+ rig.clock.to(rig.end_of_loop() + .3)+ self.assertEqual(rig.showing()[0], self.picture(rig, ('state', 'drift', False, 'PONDERING')))++ def test_a_restart_forgets_the_word_the_ghost_and_the_back(self):+ rig = Rig(self)+ said, due = self.halfway(rig)+ for name in ('claude.word:Pondering', 'claude.deleted', 'claude.rude', 'claude.risky'):+ rig.say(name)+ rig.clock.to(due + .3)+ rig.stop()+ rig.start()+ rig.clock.advance(5)+ self.assertEqual(rig.showing()[0], self.picture(rig))+ rig.clock.advance(120) # past every old minute: nothing comes back+ self.assertEqual(rig.showing()[0], self.picture(rig))+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_mixed_run_3a.py b/tests/test_mixed_run_3a.pynew file mode 100644index 0000000..656a38b--- /dev/null+++ b/tests/test_mixed_run_3a.py@@ -0,0 +1,90 @@+"""v2 phase 3a, a mixed virtual run: two hours of Claude and Codex with risky commands, bursts of deletions, rude and+calm prompts, failures and compactions close together, thinking words changing fast, a wait, bows, a pat and a cut+turn, through live.main on the fake SD_PRO. Every picture goes on at a real loop end of the one before it, one+courtroom in the day, tool faces and new words at least a minute apart, and the usual face at the end."""+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_claude_3a import Turns # noqa: E402+from test_moments import Rig, physical # noqa: E402++from token_tv import moments # noqa: E402+from token_tv.moments import FACE_COOLDOWN, WORD_INTERVAL, Moments # noqa: E402+from token_tv.sample import H # noqa: E402++APPLY_SLACK = .25+++class MixedRunTests(unittest.TestCase):+ def test_two_hours_of_phase_3a_moments_among_the_others(self):+ shows = [] # (what, when, its word read?) as each picture went on the clock (the publisher tells Moments.shown)+ real = Moments.shown++ def shown(self, what, at, wall=None, readable=True):+ shows.append((what, at, readable))+ return real(self, what, at, wall, readable)+ for patcher in (mock.patch.object(moments, 'RANDOM', Turns()), mock.patch.object(Moments, 'shown', shown)):+ 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+ script = {+ 2: ['claude.word:Pondering', 'claude.word:Brewing', 'claude.word:Musing'], # fast words+ 3: ['claude.risky', 'claude.deleted', 'claude.deleted'], # rm -rf: the courtroom, then the ghost+ 4: ['claude.word:Herding', 'claude.failed', 'claude.compact'],+ 5: ['claude.failed', 'claude.end'],+ 8: ['claude.rude', 'claude.calm', 'claude.rude'],+ 9: ['claude.deleted', 'claude.word:Baking'],+ 10: ['claude.calm', 'claude.ask'],+ 12: ['claude.risky', 'claude.compact', 'claude.word:Sauteing'], # (the day's courtroom is used up)+ 14: ['claude.answered', 'codex.end'],+ 15: ['claude.pet', 'claude.failed', 'claude.deleted'],+ 20: ['claude.rude', 'claude.word:Accomplishing'],+ 21: ['claude.stop'],+ 30: ['claude.word:Pondering', 'claude.compact'],+ 31: ['claude.end', 'claude.failed'],+ 45: ['claude.risky', 'claude.rude', 'claude.deleted', 'claude.word:Musing'],+ 46: ['claude.calm', 'claude.stop'],+ }+ for m in range(1, 121):+ rig.write(rig.now())+ rig.clock.to(minute(m) + .5)+ for name in script.get(m, []):+ rig.say(name)+ rig.clock.advance(.7)+ rig.clock.advance(120)+ played = rig.played+ self.assertGreater(len(played), 15)+ # 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)+ k = max(1, int((then - began) / loop))+ 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))+ on = [(what, at) for what, at, _ in shows if what not in (None, ('unsure',))]+ kinds = [what[0] for what, _ in on]+ self.assertEqual(kinds.count('risky'), 1) # three risky commands, one courtroom in the day+ faces = [at for what, at in on if what[0] == 'face']+ self.assertGreaterEqual(len(faces), 2)+ self.assertTrue(all(b - a >= FACE_COOLDOWN - 1e-6 for a, b in zip(faces, faces[1:])), faces)+ starts, last = [], None # a new word's start each time a picture shows another word in the readout+ for what, at, readable in shows: # (behind BOO!, SULKING or SLOW it is in the picture, not read)+ word = what[3] if what and what[0] == 'state' and not (what[1] or what[2]) and readable else None+ if word and word != last:+ starts.append((word, at))+ last = word+ self.assertGreaterEqual(len(starts), 3)+ self.assertTrue(all(b[1] - a[1] >= WORD_INTERVAL - 1e-6 for a, b in zip(starts, starts[1:])), starts)+ self.assertIn('calm', kinds) # the back turned round on the clock at least once+ self.assertIn('needs', kinds)+ self.assertIn('treat', kinds)+ self.assertEqual(rig.showing()[0], rig.picture()) # at the end the usual face: no word, ghost or back left+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_real_pace.py b/tests/test_real_pace.pyindex 0c12a5a..1c76f86 100644--- a/tests/test_real_pace.py+++ b/tests/test_real_pace.py@@ -49,7 +49,7 @@ class LoopLengthTests(unittest.TestCase):merged = made([70, 70, 70, 70], [(10, 10, 10)] * 3 + [(200, 0, 0)]) # three equal pictures: encoded onceself.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+ held = made([3000, 100], [(255, 0, 0), (0, 0, 255)]) # the clock showed red, then a blue flash (t1g)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 heldself.assertAlmostEqual(live.loop_seconds(bow, sd_pro), 4.202) # the whole bow, not five ticks (0.71 s)diff --git a/tests/test_seasons.py b/tests/test_seasons.pynew file mode 100644index 0000000..443dc05--- /dev/null+++ b/tests/test_seasons.py@@ -0,0 +1,374 @@+"""v2 phase 3b, x8: Arcade's seasonal props (token_tv/seasons.py). On Halloween (10-25 to 11-01), Christmas (12-18 to+12-26) and Seollal (the day before the Korean lunar new year to the day after), endpoints included, on the computer's+local date, Arcade's scenes get their season's scenery and every pet its hat; the pets keep their form, every gauge+stays clear, the one-offs are drawn as ever, other faces are untouched, and off season Arcade is byte for byte as it+was. Through live.main, the season comes in with the next ordinary picture at a loop's end, one upload, and an+interior date of the same season sends nothing."""+import datetime+import io+import os+import sys+import time+import unittest+from pathlib import Path+from unittest import mock++from PIL import Image, ImageChops++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, claude_moments, display, pet_moments, readout, seasons # noqa: E402+from token_tv.display import STYLES, render_page # noqa: E402+from token_tv.moments import loop_end # noqa: E402+from token_tv.sample import D, H, snapshot # noqa: E402++PETS = ('claude', 'codex', 'grok', 'copilot', 'antigravity')+WINDOWS = {'claude': [('5H', 42, 2 * H), ('WEEK', 64, 3 * D)], 'codex': [('WEEK', 36, 4 * D)],+ 'grok': [('BUDGET', 61, 6 * D + 2 * H)], 'copilot': [('MONTH', 40, 12 * D)], 'antigravity': [('5H', 30, 3 * H)]}+# Independently pinned (ko.wikipedia 설날 (한국) for 2026-2030; KASI's lunar-to-solar conversion for 2031-2040, each the+# KST day of a new moon by Meeus's algorithm; read 2026-11-05): the Korean lunar new year, not China's (a day earlier in+# 2027 and 2028).+LUNAR_NEW_YEAR = {2026: (2, 17), 2027: (2, 7), 2028: (1, 27), 2029: (2, 13), 2030: (2, 3), 2031: (1, 23), 2032: (2, 11),+ 2033: (1, 31), 2034: (2, 19), 2035: (2, 8), 2036: (1, 28), 2037: (2, 15), 2038: (2, 4), 2039: (1, 24),+ 2040: (2, 12)}+HAT_INK = {'halloween': seasons.WITCH_INK['K'], 'christmas': seasons.SANTA_INK['R'], 'seollal': seasons.CAP_INK['Y']}+SEASONS = ('halloween', 'christmas', 'seollal')+SENTINEL = (1, 2, 3)+++def local(y, m, d, hh=14, mm=1, ss=0):+ """That moment on this computer's own clock."""+ return time.mktime((y, m, d, hh, mm, ss, 0, 0, -1))+++def account(provider, now, **row):+ key = f'{provider}_a'+ data = snapshot(now, [(key, f"{arcade.SHORT_NAME.get(provider, provider.upper())} A", provider, WINDOWS[provider])])+ data['accounts'][key].update(row)+ return data+++def frames(data, now, season, egg=None):+ """Arcade's pictures of `data` at `now`, dressed for `season` (None: as ever) whatever `now`'s date is."""+ with mock.patch.object(seasons, 'season_at', lambda at=None: season):+ return arcade.arcade_frames(data, now, egg)+++def gif(data, now, season, egg=None):+ with mock.patch.object(seasons, 'season_at', lambda at=None: season):+ return arcade.render_arcade(data, now, egg=egg)+++def palette(season):+ """Every colour the season's props are drawn in: its hats, its scenery, the snow, the kite's line, the little cloud+ Copilot's tree and pouch stand on."""+ names = {'halloween': ('witch', 'witch_small', 'pumpkin', 'pumpkin_small', 'bat_up', 'bat_down'),+ 'christmas': ('santa', 'santa_small', 'tree'), 'seollal': ('cap', 'cap_small', 'pouch', 'kite', 'yut')}[season]+ inks = {tuple(colour) for name in names for colour in seasons.PROP_INK[name].values()}+ return inks | {seasons.SNOW, seasons.SNOW_FAR, seasons.STRING, arcade.CLOUD_TOP, arcade.CLOUD_BASE}+++def stage(frame):+ """The scene's own 120 x 71 stage in a 240 x 240 picture (Arcade doubles it), back at one pixel a cell."""+ return frame.crop((0, 28, 240, 170)).resize((120, 71), Image.Resampling.NEAREST)+++def changed(a, b):+ """The colours `b` has where it differs from `a` (same size)."""+ mask = ImageChops.difference(a, b).point(lambda v: 255 if v else 0).convert('L').point(lambda v: 255 if v else 0)+ only = Image.composite(b, Image.new('RGB', b.size, SENTINEL), mask)+ return {c for _, c in only.getcolors(1 << 16)} - {SENTINEL}+++def count(image, colour):+ return sum(n for n, c in image.convert('RGB').getcolors(1 << 16) if c == colour)+++class Frozen:+ """The time module at one instant, for faces that read the time themselves."""+ def __init__(self, at):+ self.at = at++ def time(self):+ return self.at++ def __getattr__(self, name):+ return getattr(time, name)+++class SeasonDatesTests(unittest.TestCase):+ def test_halloween_and_christmas_take_in_every_date_through_their_last_in_any_year(self):+ for year in (2026, 2027, 2031):+ for name, (first, last) in (('halloween', ((10, 25), (11, 1))), ('christmas', ((12, 18), (12, 26)))):+ day = datetime.date(year, *first)+ self.assertIsNone(seasons.season_on(day - datetime.timedelta(days=1)))+ while (day.month, day.day) <= last:+ self.assertEqual(seasons.season_on(day), name, day)+ day += datetime.timedelta(days=1)+ self.assertIsNone(seasons.season_on(day), day) # the day after the last++ def test_seollal_is_the_day_before_the_korean_lunar_new_year_to_the_day_after(self):+ for year, (month, day) in LUNAR_NEW_YEAR.items():+ new_year = datetime.date(year, month, day)+ for offset in (-1, 0, 1):+ self.assertEqual(seasons.season_on(new_year + datetime.timedelta(days=offset)), 'seollal')+ for offset in (-2, 2):+ self.assertIsNone(seasons.season_on(new_year + datetime.timedelta(days=offset)))+ # China's comes a day earlier in 2027 and 2028: its first day is no Seollal here, Korea's last day is+ self.assertIsNone(seasons.season_on(datetime.date(2027, 2, 5)))+ self.assertEqual(seasons.season_on(datetime.date(2027, 2, 8)), 'seollal')+ self.assertIsNone(seasons.season_on(datetime.date(2028, 1, 25)))+ self.assertEqual(seasons.season_on(datetime.date(2028, 1, 28)), 'seollal')+ # a year's own date: last year's month and day mean nothing in the next+ self.assertIsNone(seasons.season_on(datetime.date(2027, 2, 17)))+ self.assertIsNone(seasons.season_on(datetime.date(2028, 2, 7)))+ # every year through 2040 has its three days, and only those; past the table, none+ for year in range(2026, 2041):+ days = [day for day in (datetime.date(year, 1, 1) + datetime.timedelta(n) for n in range(366))+ if day.year == year and seasons.season_on(day) == 'seollal']+ self.assertEqual(days, [datetime.date(year, *LUNAR_NEW_YEAR[year]) + datetime.timedelta(n) for n in (-1, 0, 1)])+ self.assertIsNone(seasons.season_on(datetime.date(2041, 2, 1))) # (2041's is Feb 1: no line, no Seollal props)++ def test_a_season_starts_at_local_midnight_and_ends_at_the_last_second_of_its_last_date(self):+ for (y, m, d), name in (((2026, 10, 25), 'halloween'), ((2026, 12, 18), 'christmas'), ((2027, 2, 6), 'seollal')):+ self.assertIsNone(seasons.season_at(local(y, m, d, 0, 0, 0) - 1))+ self.assertEqual(seasons.season_at(local(y, m, d, 0, 0, 0)), name)+ for (y, m, d), name in (((2026, 11, 1), 'halloween'), ((2026, 12, 26), 'christmas'), ((2027, 2, 8), 'seollal')):+ self.assertEqual(seasons.season_at(local(y, m, d, 23, 59, 59)), name)+ self.assertIsNone(seasons.season_at(local(y, m, d, 23, 59, 59) + 1))++ @unittest.skipUnless(hasattr(time, 'tzset'), 'needs a settable time zone')+ def test_the_date_is_this_computers_own_not_utcs(self):+ self.addCleanup(time.tzset) # (runs once the patched TZ is gone again)+ at = datetime.datetime(2026, 10, 24, 15, 30, tzinfo=datetime.timezone.utc).timestamp() # 10-25 00:30 in Seoul+ gone = datetime.datetime(2026, 11, 1, 15, 30, tzinfo=datetime.timezone.utc).timestamp() # 11-02 00:30 there+ for zone, first, second in (('Asia/Seoul', 'halloween', None), ('UTC', None, 'halloween')):+ with mock.patch.dict(os.environ, {'TZ': zone}), mock.patch.object(arcade, 'NIGHT_HOURS', ()):+ time.tzset()+ self.assertEqual((seasons.season_at(at), seasons.season_at(gone)), (first, second), zone)+ self.assertEqual(bool(count(stage(arcade.arcade_frames(account('claude', at), at)[0]),+ HAT_INK['halloween'])), first == 'halloween', zone)+ time.tzset()+++class OffSeasonTests(unittest.TestCase):+ """Off season, Arcade is as it was: no season code draws a thing, and the pets' tags change no pixel."""+ SCENES = [{}, {'active': True}, {'worry': True}, {'moment': {'kind': 'drink'}}, {'moment': {'kind': 'stretch'}},+ {'moment': {'kind': 'done', 'at': 5}}]+ CLAWD = [{'moment': {'kind': k}} for k in ('pet', 'snack', 'calm', 'failed', 'compact', 'rude')] + [+ {'moment': {'kind': 'needs', 'since': 0, 'level': 3}}, {'moment': {'kind': 'risky', 'style': 'verdict'}},+ {'moment': {'kind': 'risky', 'style': 'objection'}}, {'moment': {'kind': 'deleted', 'style': 'wave'}},+ {'word': 'PONDERING', 'active': True}]++ def renders(self, now):+ out = []+ for provider in PETS:+ for row in self.SCENES + (self.CLAWD if provider == 'claude' else []):+ out.append(arcade.render_arcade(account(provider, now, **row), now))+ return out++ def test_on_any_other_date_no_season_code_draws_anything(self):+ drew = []+ with mock.patch.object(seasons, 'scenery', lambda *a: drew.append('scenery')), \+ mock.patch.object(seasons, 'wear', lambda *a: drew.append('wear')):+ for now in (local(2026, 10, 24, 23, 59, 59), local(2026, 11, 2, 0, 0, 0), local(2026, 12, 17),+ local(2026, 12, 27), local(2027, 2, 5), local(2027, 2, 9), local(2027, 6, 1)):+ self.renders(now)+ self.assertEqual(drew, [])+ arcade.render_arcade(account('claude', local(2026, 12, 25)), local(2026, 12, 25)) # a positive control+ self.assertIn('scenery', drew)+ self.assertIn('wear', drew)++ def test_the_pets_tags_change_no_pixel(self):+ now = local(2027, 6, 1)+ cached = (arcade.clawd, arcade.clawd_spun, arcade.codex_art, arcade.grok_pose, arcade.copilot_pose,+ arcade.anti_art, pet_moments.clawd_art, pet_moments.leaning, pet_moments.taller, claude_moments.art,+ claude_moments.robed)++ def clear():+ for build in cached:+ build.cache_clear()+ self.addCleanup(clear)+ tagged = self.renders(now)+ clear()+ with mock.patch.object(arcade, 'tag', lambda art, pet: art):+ untagged = self.renders(now)+ clear()+ self.assertEqual(tagged, untagged)+++class InSeasonTests(unittest.TestCase):+ NOW = local(2026, 11, 5, 14, 1) # a day-time instant; each season is put on by hand, so the moves are the same++ def test_only_props_are_added_and_the_header_and_readout_stay_as_they_are(self):+ for season in SEASONS:+ inks = palette(season)+ for provider in PETS:+ for row in ({}, {'active': True}, {'moment': {'kind': 'drink'}}):+ plain = frames(account(provider, self.NOW, **row), self.NOW, None)+ dressed = frames(account(provider, self.NOW, **row), self.NOW, season)+ self.assertEqual(len(plain), len(dressed))+ seen = set()+ for a, b in zip(plain, dressed):+ self.assertEqual(a.crop((0, 0, 240, 28)).tobytes(), b.crop((0, 0, 240, 28)).tobytes())+ self.assertEqual(a.crop((0, 170, 240, 240)).tobytes(), b.crop((0, 170, 240, 240)).tobytes())+ seen |= changed(stage(a), stage(b))+ self.assertTrue(seen, (season, provider, row))+ self.assertLessEqual(seen, inks, (season, provider, row))++ def test_clawds_body_under_its_hats_brim_is_its_own(self):+ """Clawd standing still: below the top two rows of its head every pixel of its own is where it was (the hat+ sits on top; at Seollal only the kite's line starts in its hand)."""+ body = {tuple(int(c[i:i + 2], 16) for i in (1, 3, 5)) for c in arcade.clawd_data()['LookingAround']['palette']}+ for season in SEASONS:+ plain = stage(frames(account('claude', self.NOW), self.NOW, None)[0])+ dressed = stage(frames(account('claude', self.NOW), self.NOW, season)[0])+ spots = [(x, y) for y in range(71) for x in range(60) if plain.getpixel((x, y)) in body]+ top = min(y for _, y in spots)+ for x, y in spots:+ if y >= top + 2 and dressed.getpixel((x, y)) != plain.getpixel((x, y)):+ self.assertEqual((season, dressed.getpixel((x, y))), ('seollal', seasons.STRING), (x, y))++ def test_every_pet_wears_its_seasons_hat_through_its_usual_scene_and_its_moments(self):+ moments = {'claude': ['pet', 'snack', 'drink', 'stretch', 'done', 'needs', 'calm', 'failed', 'compact', 'rude',+ ('deleted', 'wave'), ('risky', 'objection')],+ 'codex': ['drink', 'stretch', 'done'], 'grok': ['drink', 'stretch'], 'copilot': ['drink', 'stretch'],+ 'antigravity': ['drink', 'stretch']}+ for season in SEASONS:+ for provider in PETS:+ for kind in [None, 'active'] + moments[provider]:+ row = {} if kind is None else {'active': True} if kind == 'active' else \+ {'moment': {'kind': kind[0], 'style': kind[1]}} if isinstance(kind, tuple) else \+ {'moment': {'kind': kind, 'at': self.NOW, 'since': self.NOW - 1000, 'level': 3}}+ pictures = frames(account(provider, self.NOW, **row), self.NOW, season)+ if (provider, kind) == ('copilot', 'active'): # it flies in from off the stage and out again+ pictures = pictures[len(pictures) // 5:len(pictures) * 4 // 5]+ hatted = sum(1 for f in pictures if count(stage(f), HAT_INK[season]))+ # (a bow's tilt or a leap may hide it a picture or two)+ self.assertGreater(hatted, len(pictures) * .8, (season, provider, kind))++ def test_judge_clawd_keeps_its_wig_and_the_clawd_in_the_dock_wears_the_hat(self):+ for season in SEASONS:+ pictures = frames(account('claude', self.NOW, moment={'kind': 'risky', 'style': 'verdict'}), self.NOW, season)+ for f in pictures:+ s = stage(f)+ self.assertTrue(count(s.crop((0, 0, 60, 71)), HAT_INK[season]), season)+ self.assertFalse(count(s.crop((66, 0, 120, 71)), HAT_INK[season]), season)++ def test_a_pet_turned_past_30_degrees_waits_for_its_hat_till_it_is_upright(self):+ for turn, hat in ((0, True), (20, True), (-28, True), (45, False), (315, False), (180, False), (350, True)):+ frame = Image.new('RGB', (120, 71), (0, 0, 0))+ art = arcade.rotsprite(arcade.clawd('LookingAround', 0, 1), turn) if turn else arcade.clawd('LookingAround', 0, 1)+ seasons.wear(seasons.Dress('christmas', 'claude', 0, 120, False, 4, frame), frame, art, 40, 30)+ self.assertEqual(bool(count(frame, HAT_INK['christmas'])), hat, turn)+ frame = Image.new('RGB', (120, 71), (0, 0, 0)) # another pet's art in this scene: none of its business+ seasons.wear(seasons.Dress('christmas', 'codex', 0, 120, False, 4, frame), frame,+ arcade.clawd('LookingAround', 0, 1), 40, 30)+ self.assertFalse(count(frame, HAT_INK['christmas']))++ def test_no_scenery_covers_a_gauge(self):+ """Every pixel of each pet's gauge (in its gauge's colours, where the gauge is) is the same with the season's+ scenery. (A hat goes where its pet goes: Anti on patrol passes over its corner pellets, as it always has.)"""+ gauges = {'claude': ((97, 0, 120, 28), {arcade.MOON_LIT, arcade.MOON_DARK, arcade.LABEL_INK}),+ 'codex': ((0, 40, 120, 71), {arcade.STEM, arcade.LEAF, arcade.BUD, arcade.PETAL, arcade.HEART,+ arcade.PLOT}),+ 'grok': ((0, 30, 20, 71), {arcade.TANK, arcade.TANK_DARK, arcade.FUEL, arcade.FUEL_TOP,+ arcade.FUEL_LOW, arcade.LABEL_INK}),+ 'copilot': ((0, 0, 120, 23), {arcade.CLOUD_TOP, arcade.CLOUD_BASE, arcade.CLOUD_SPOT}),+ 'antigravity': ((0, 0, 120, 71), {arcade.MAZE_DOT, (90, 70, 80)})}+ pellets = [(10, 14, 21, 25), (100, 14, 111, 25), (100, 46, 111, 57), (10, 46, 21, 57)]+ for season in SEASONS:+ for provider in PETS:+ box, inks = gauges[provider]+ for row in ({}, {'active': True}):+ plain = frames(account(provider, self.NOW, **row), self.NOW, None)+ with mock.patch.object(seasons, 'wear', lambda *a: None):+ dressed = frames(account(provider, self.NOW, **row), self.NOW, season)+ for a, b in zip(plain, dressed):+ sa, sb = stage(a), stage(b)+ for y in range(box[1], box[3]):+ for x in range(box[0], box[2]):+ if provider == 'antigravity' and not any(p[0] <= x < p[2] and p[1] <= y < p[3]+ for p in pellets):+ continue # (the maze's dots are no gauge; its four pellets are)+ if sa.getpixel((x, y)) in inks:+ self.assertEqual(sb.getpixel((x, y)), sa.getpixel((x, y)), (season, provider, x, y))++ def test_the_one_offs_are_drawn_as_ever(self):+ for season in SEASONS:+ for provider in PETS:+ for egg, used in ((f'reset@{provider}_a', None), (f'full@{provider}_a', 100)):+ data = account(provider, self.NOW)+ if used:+ for w in data['accounts'][f'{provider}_a']['windows']:+ w['used_percent'] = used+ self.assertEqual(gif(data, self.NOW, season, egg), gif(data, self.NOW, None, egg), (season, egg))++ def test_other_faces_wear_nothing(self):+ data = snapshot(self.NOW)+ with mock.patch.object(display, 'time', Frozen(self.NOW)), mock.patch.object(readout, 'time', Frozen(self.NOW)):+ for style in STYLES:+ if style == 'arcade':+ continue+ with mock.patch.object(seasons, 'season_at', lambda at=None: 'christmas'):+ dressed = render_page(data, style=style)+ self.assertEqual(dressed, render_page(data, style=style), style)++ def test_a_seasons_gif_still_fits_on_the_clock(self):+ for season in SEASONS:+ for provider in PETS:+ for row in ({}, {'active': True}):+ self.assertLessEqual(len(gif(account(provider, self.NOW, **row), self.NOW, season)), arcade.BUDGET)+ every = snapshot(self.NOW, [(f'{p}_a', 'A', p, WINDOWS[p]) for p in PETS])+ for row in every['accounts'].values():+ row['active'] = True+ self.assertLessEqual(len(gif(every, self.NOW, season)), arcade.BUDGET)++ def test_on_a_real_date_in_season_arcade_dresses_itself(self):+ for (y, m, d), season in (((2026, 10, 31), 'halloween'), ((2026, 12, 24), 'christmas'), ((2028, 1, 28), 'seollal')):+ now = local(y, m, d)+ self.assertEqual(arcade.render_arcade(account('claude', now), now), gif(account('claude', now), now, season))+ self.assertNotEqual(arcade.render_arcade(account('claude', now), now), gif(account('claude', now), now, None))+++class SeasonOnTheClockTests(unittest.TestCase):+ """Through live.main on a fake SD_PRO: crossing into a season, its first ordinary picture brings the props at the+ loop's end, one switch and at most one upload (the usual picture may still be on the clock's album); an interior+ date of the same season, nothing; out of it, one switch back to the usual."""+ def test_the_season_comes_and_goes_with_the_date_at_a_loops_end_one_upload_each(self):+ days = [local(2026, 10, 24, 12, 1, 5), local(2026, 10, 25, 12, 1, 5), local(2026, 10, 26, 12, 1, 5),+ local(2026, 11, 1, 12, 1, 5), local(2026, 11, 2, 12, 1, 5)]+ days = [t + (1 - int(t // 60) % 6) % 6 * 60 for t in days] # the same minute of keeping still in any zone+ rig = Rig(self, at=days[0], windows={'claude': [('5H', 40, 3 * H)]})+ shown, _ = rig.showing()+ self.assertEqual(count(Image.open(io.BytesIO(shown)), HAT_INK['halloween']), 0)+ polls = 1+ for k, day in enumerate(days[1:], 1):+ rig.frozen.at = day # the drawings' and TokenTV's own date+ before, switched = len(rig.uploads()), len(rig.switches())+ showing, began = rig.showing()+ reading = rig.poll_at(polls)+ due = loop_end({'at': began, 'loop': rig.loop(showing)}, reading)+ rig.clock.to(due + rig.loop(showing) + .5) # the reading, the loop's end and a loop more+ polls += 1+ image, on = rig.showing()+ wanted = seasons.season_on(datetime.date.fromtimestamp(day))+ previous = seasons.season_on(datetime.date.fromtimestamp(days[k - 1]))+ self.assertEqual(image, rig.picture(), day)+ self.assertEqual(bool(count(Image.open(io.BytesIO(image)), HAT_INK['halloween'])), wanted == 'halloween', day)+ self.assertEqual(len(rig.switches()) - switched, 0 if wanted == previous else 1, day)+ self.assertLessEqual(len(rig.uploads()) - before, 0 if wanted == previous else 1, day)+ if wanted != previous:+ self.assertGreaterEqual(on, due - 1e-6) # at the end of the loop the clock was playing+ self.assertLess(on, due + .25)+ for _ in range(2): # more readings, the same date: nothing more+ rig.clock.to(rig.poll_at(polls) + .5)+ polls += 1+ self.assertEqual(len(rig.switches()) - switched, 0 if wanted == previous else 1, day)+ self.assertLessEqual(len(rig.uploads()) - before, 0 if wanted == previous else 1, day)+ self.assertEqual(len(rig.uploads()), 2) # the usual picture, Halloween's; the usual one again was still there+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_sounds.py b/tests/test_sounds.pynew file mode 100644index 0000000..6cd5b30--- /dev/null+++ b/tests/test_sounds.py@@ -0,0 +1,40 @@+"""v2 phase 3a, x9: the Claude Code mod's two sounds are short clips of its own, made again byte for byte from the+numbers in scripts/make_sounds.py."""+import sys+import unittest+import wave+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent)) # helpers.py, however the tests are run+from helpers import temp_dir # noqa: E402++ROOT = Path(__file__).resolve().parent.parent+SOUNDS = ROOT / 'claude-plugin' / 'sounds'+LONGEST = 2.0 # seconds: a cue, never a tune+++class SoundTests(unittest.TestCase):+ def test_two_short_mono_clips_the_mod_names(self):+ mod = (ROOT / 'claude-plugin' / 'hooks' / 'register.ts').read_text(encoding='utf-8')+ for name in ('wait.wav', 'done.wav'):+ self.assertIn(f"'sounds/{name}'", mod)+ with wave.open(str(SOUNDS / name)) as clip:+ seconds = clip.getnframes() / clip.getframerate()+ self.assertEqual((clip.getnchannels(), clip.getsampwidth()), (1, 2))+ self.assertGreater(seconds, .1)+ self.assertLess(seconds, LONGEST)+ samples = clip.readframes(clip.getnframes())+ self.assertGreater(len(set(samples)), 50) # a sound, not silence++ def test_they_are_made_again_byte_for_byte(self):+ sys.path.insert(0, str(ROOT / 'scripts'))+ self.addCleanup(sys.path.remove, str(ROOT / 'scripts'))+ import make_sounds+ folder = temp_dir(self)+ make_sounds.make(folder)+ for name in ('wait.wav', 'done.wav'):+ self.assertEqual((folder / name).read_bytes(), (SOUNDS / name).read_bytes(), name)+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_survival.py b/tests/test_survival.pynew file mode 100644index 0000000..330486e--- /dev/null+++ b/tests/test_survival.py@@ -0,0 +1,291 @@+"""v2 phase 3b, x7: the Survival face (token_tv/survival.py), as the owner approved it (style A, drafts w30-w32): a face to+pick like the others, one row per account (four at most), ten hearts for what is LEFT of the 5-hour window and ten+drumsticks for what is left of the week (else a month or a budget), half icons for 5%, a bar for today's use (full at+an even day, a second lap in orange), the pet small. A missing reading is a dash or a word, an old one says OLD, and+on the clock it changes only with the readings."""+import http.client+import io+import json+import sys+import threading+import time+import unittest+from http.server import ThreadingHTTPServer+from pathlib import Path+from unittest import mock+from urllib.request import Request, urlopen++from PIL import Image, ImageDraw++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 Rig # noqa: E402++from token_tv import readout, survival # noqa: E402+from token_tv.catalog import theme_list # noqa: E402+from token_tv.display import STYLES, pixel_text, render_page # noqa: E402+from token_tv.live import DisplayPreferences, handler # noqa: E402+from token_tv.sample import D, H, snapshot # noqa: E402+from token_tv.sources import load_config # noqa: E402+from token_tv.state import UsageStore # noqa: E402++NOW = 1793854860 # 2026-11-05 14:01 KST+ROOT = Path(__file__).resolve().parent.parent+HEART, MEAT = survival.HEART, survival.MEAT+++def data(*accounts):+ """A snapshot of (key, alias, provider, windows, extra row fields) accounts."""+ snap = snapshot(NOW, [a[:4] for a in accounts])+ for a in accounts:+ if len(a) > 4:+ snap['accounts'][a[0]].update(a[4])+ return snap+++def face(snap):+ return survival.render_survival(snap, NOW)+++def icon_states(image, x0, y, ink, count=10, pitch=16):+ """Each icon from (x0, y), 'full', 'half' or 'spent', by the colour of its right and its left part."""+ out = []+ for k in range(count):+ x = x0 + k * pitch+ right = {image.getpixel((x + dx, y + dy)) for dx in (10, 11, 12) for dy in (4, 5, 6)}+ left = {image.getpixel((x + dx, y + dy)) for dx in (4, 5, 6) for dy in (4, 5, 6)}+ out.append('full' if ink in right else 'half' if ink in left else+ 'spent' if survival.EMPTY in left | right else 'none')+ return out+++def says(test, image, xy, text, scale=1, align='left', colour=None):+ """`text` is drawn at `xy` in the clock's pixel font, nothing else in its box (and in `colour`, if given)."""+ probe = Image.new('RGB', image.size, (0, 0, 0))+ pixel_text(ImageDraw.Draw(probe), xy, text, scale=scale, color=(255, 255, 255), align=align)+ box = probe.getbbox()+ for y in range(box[1], box[3]):+ for x in range(box[0], box[2]):+ got = image.getpixel((x, y))+ if probe.getpixel((x, y)) != (0, 0, 0):+ test.assertNotEqual(got, survival.PANEL, (text, x, y))+ if colour:+ test.assertEqual(got, colour, (text, x, y))+ else:+ test.assertEqual(got, survival.PANEL, (text, x, y))+++def stripe(image, box):+ return {image.getpixel((x, y)) for y in range(box[1], box[3]) for x in range(box[0], box[2])}+++class FaceTests(unittest.TestCase):+ def test_survival_is_a_face_to_pick_like_the_others(self):+ self.assertIn('survival', STYLES)+ image = Image.open(io.BytesIO(render_page(snapshot(NOW), style='survival')))+ self.assertEqual((image.format, image.size), ('JPEG', (240, 240)))+ listed = {t['id']: t for t in theme_list()['themes']}['survival']+ self.assertEqual((listed['name'], listed['local'], listed['installed'], listed['needs_update']),+ ('Survival HUD', False, True, False))+ self.assertNotIn('minecraft', json.dumps(listed).lower())+ self.assertIn("s === 'survival' ? 'Survival HUD'", (ROOT / 'token_tv' / 'web' / 'app.js').read_text(encoding='utf-8'))++ def test_the_dashboard_previews_applies_and_keeps_it_as_it_does_every_face(self):+ account = {'key': 'a', 'alias': 'CLAUDE A', 'provider': 'claude', 'email': '[email protected]'}+ row = dict(account, status='ok', windows=[{'label': 'WEEK', 'used_percent': 30, 'resets_at': None}], fetched_at=100)+ store = UsageStore([account], fetch=lambda a: dict(row))+ store.refresh()+ path = temp_dir(self) / 'config.json'+ path.write_text(json.dumps({'accounts': [account], 'display_style': 'arcade'}), encoding='utf-8')+ prefs = DisplayPreferences(path, load_config(path))+ server = ThreadingHTTPServer(('127.0.0.1', 0), handler(store, prefs))+ thread = threading.Thread(target=server.serve_forever)+ thread.start()+ self.addCleanup(thread.join)+ self.addCleanup(server.server_close)+ self.addCleanup(server.shutdown)+ root = f'http://127.0.0.1:{server.server_port}'+ with urlopen(root + '/frame/0.jpg?style=survival') as response: # a preview changes nothing+ self.assertEqual(Image.open(io.BytesIO(response.read())).size, (240, 240))+ self.assertEqual(prefs.snapshot()['style'], 'arcade')+ with urlopen(root + '/display') as response:+ self.assertIn('survival', json.load(response)['styles'])+ request = Request(root + '/display/style', data=b'{"style":"survival"}', headers={'Content-Type': 'application/json'})+ with urlopen(request) as response:+ self.assertEqual(json.load(response)['style'], 'survival')+ self.assertEqual(load_config(path)['display_style'], 'survival')+ self.assertEqual(DisplayPreferences(path, load_config(path)).snapshot()['style'], 'survival') # after a restart++ def test_hearts_are_what_is_left_of_the_5_hours_and_hunger_of_the_week(self):+ for five, week in ((25, 75), (75, 25)):+ image = face(data(('claude_a', 'CLAUDE A', 'claude', [('5H', five, 2 * H), ('WEEK', week, 3 * D)])))+ left5, leftw = (100 - five) / 10, (100 - week) / 10 # icons: whole ones, then a half+ self.assertEqual(icon_states(image, 30, 110, HEART), ['full'] * int(left5) + ['half'] + ['spent'] * (9 - int(left5)))+ self.assertEqual(icon_states(image, 30, 148, MEAT), ['full'] * int(leftw) + ['half'] + ['spent'] * (9 - int(leftw)))+ says(self, image, (230, 111), f'{100 - five}%', 2, 'right', survival.TEXT)+ says(self, image, (230, 149), f'{100 - week}%', 2, 'right', survival.TEXT)+ says(self, image, (10, 114), '5H', colour=survival.MUTED)+ says(self, image, (10, 152), 'WK', colour=survival.MUTED)+ swapped = face(data(('claude_a', 'CLAUDE A', 'claude', [('WEEK', 75, 3 * D), ('5H', 25, 2 * H)])))+ self.assertEqual(swapped.tobytes(), face(data(('claude_a', 'CLAUDE A', 'claude',+ [('5H', 25, 2 * H), ('WEEK', 75, 3 * D)]))).tobytes())++ def test_icons_step_in_halves_and_never_say_empty_while_anything_is_left(self):+ for used, states in ((0, ['full'] * 10), (100, ['spent'] * 10), (99.5, ['half'] + ['spent'] * 9),+ (96, ['half'] + ['spent'] * 9), (94, ['half'] + ['spent'] * 9), (92, ['full'] + ['spent'] * 9),+ (50, ['full'] * 5 + ['spent'] * 5),+ (47, ['full'] * 5 + ['half'] + ['spent'] * 4)):+ image = face(data(('claude_a', 'CLAUDE A', 'claude', [('5H', used, 2 * H)])))+ self.assertEqual(icon_states(image, 30, 110, HEART), states, used)+ full = face(data(('claude_a', 'CLAUDE A', 'claude', [('5H', 0, 2 * H)])))+ says(self, full, (236, 111), '100%', 2, 'right', survival.TEXT) # clear of the tenth heart++ def test_hunger_is_the_week_by_its_length_and_else_a_month_or_a_budget_with_its_name(self):+ alias = data(('codex_a', 'CODEX A', 'codex', [('5H', 50, 2 * H), ('WINDOW', 20, 3 * D)]))+ alias['accounts']['codex_a']['windows'][1]['duration_minutes'] = 10080+ image = face(alias)+ self.assertEqual(icon_states(image, 30, 148, MEAT), ['full'] * 8 + ['spent'] * 2)+ says(self, image, (10, 152), 'WK', colour=survival.MUTED)+ grok = face(data(('grok_a', 'GROK A', 'grok', [('BUDGET', 61, 6 * D)])))+ self.assertEqual(icon_states(grok, 30, 110, MEAT), ['full'] * 4 + ['spent'] * 6) # its only row (39%: 4)+ says(self, grok, (10, 114), 'BUD', colour=survival.MUTED)+ self.assertNotIn(HEART, stripe(grok, (0, 100, 240, 196))) # no hearts made up for it+ anti = face(data(('antigravity_a', 'ANTI A', 'antigravity', [('5H', 30, 3 * H)])))+ self.assertEqual(icon_states(anti, 30, 110, HEART), ['full'] * 7 + ['spent'] * 3)+ self.assertNotIn(MEAT, stripe(anti, (0, 100, 240, 196)))+ mixed = face(data(('claude_a', 'CLAUDE A', 'claude', [('5H', 50, 2 * H), ('WEEK', 50, 3 * D)]),+ ('codex_a', 'CODEX A', 'codex', [('5H', 50, 2 * H), ('MONTH', 50, 9 * D)]),+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 50, 6 * D)])))+ says(self, mixed, (236, 80 + 31 + 4), 'MO', align='right', colour=survival.MUTED) # a month beside 5 hours: named+ self.assertEqual(stripe(mixed, (220, 31 + 4, 240, 31 + 11)), {survival.PANEL}) # a week beside them: not++ def test_an_account_with_no_reading_says_why_and_an_old_one_says_old(self):+ login = face(data(('claude_a', 'CLAUDE A', 'claude', [], {'status': 'auth_required'})))+ says(self, login, (30, 111), 'LOGIN', 2, colour=survival.WARN)+ self.assertNotIn(HEART, stripe(login, (0, 100, 240, 196)))+ old = face(data(('claude_a', 'CLAUDE A', 'claude', [('5H', 40, 2 * H)], {'status': 'stale'})))+ says(self, old, (230, 8), 'OLD', 2, 'right', survival.WARN)+ says(self, old, (230, 111), '60%', 2, 'right', survival.MUTED)+ two = face(data(('grok_a', 'GROK A', 'grok', [], {'status': 'quota_unavailable'}),+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 40, 3 * D)], {'status': 'stale'})))+ says(self, two, (230, 30), 'OLD', align='right', colour=survival.WARN) # Codex first, in service order+ says(self, two, (30, 120 + 51), 'NO DATA', 2, colour=survival.WARN)+ four = face(data(('claude_a', 'CLAUDE A', 'claude', [('5H', 40, 2 * H)], {'status': 'stale'}),+ ('claude_b', 'CLAUDE B', 'claude', [], {'status': 'auth_required'}),+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 40, 3 * D)]),+ ('grok_a', 'GROK A', 'grok', [('BUDGET', 40, 3 * D)])))+ says(self, four, (234, 60 + 5), 'LOGIN', align='right', colour=survival.WARN)+ reset = '5H ' + readout.reset_clock(NOW + 2 * H, NOW)+ says(self, four, (234 - survival.width(reset) - 6, 5), 'OLD', align='right', colour=survival.WARN)++ def test_todays_bar_and_number_and_a_dash_while_it_is_not_known(self):+ def hero(today):+ extra = {} if today is None else {'today': today}+ return face(data(('claude_a', 'CLAUDE A', 'claude', [('5H', 40, 2 * H), ('WEEK', 40, 3 * D)], extra)))+ bar = (62, 200, 174, 208)+ self.assertEqual(stripe(hero(None), bar), {survival.TRACK})+ says(self, hero(None), (230, 198), '--', 2, 'right', survival.MUTED)+ self.assertEqual(stripe(hero(0.0), bar) - {survival.PANEL}, {survival.TRACK}) # (its quarter marks: panel)+ says(self, hero(0.0), (230, 198), '0%', 2, 'right', survival.TEXT)+ half = hero(.5)+ says(self, half, (230, 198), '50%', 2, 'right', survival.TEXT)+ self.assertIn(survival.GOLD, stripe(half, (62, 204, 117, 208)))+ self.assertEqual(stripe(half, (120, 204, 174, 208)) - {survival.PANEL}, {survival.TRACK})+ lap = hero(1.5)+ says(self, lap, (230, 198), '150%', 2, 'right', survival.TEXT)+ self.assertIn(survival.OVER, stripe(lap, (62, 204, 117, 208))) # a second lap, orange, half way+ self.assertIn(survival.GOLD, stripe(lap, (120, 204, 174, 208)))+ self.assertNotIn(survival.OVER, stripe(lap, (120, 204, 174, 208)))+ rows = [(f'{p}_a', f'{p.upper()} A', p, [('WEEK', 40, 3 * D)], {} if p == 'codex' else {'today': .4})+ for p in ('claude', 'codex', 'grok')]+ three = face(data(*rows))+ says(self, three, (70, 80 + 47), '--', colour=survival.MUTED) # Codex's day not known: a dash, no bar+ self.assertNotIn(survival.TRACK, stripe(three, (82, 80 + 49, 228, 80 + 53)))+ self.assertIn(survival.TRACK, stripe(three, (70, 47 + 2, 228, 47 + 6)))+ self.assertIn(survival.GOLD, stripe(three, (70, 47 + 2, 228, 47 + 6)))++ def test_every_account_gets_its_own_row_and_pet_four_at_most_the_busiest_first(self):+ rows = [('claude_a', 'CLAUDE A', 'claude', [('WEEK', 10, 3 * D)]), ('claude_b', 'CLAUDE B', 'claude', [('WEEK', 20, 3 * D)]),+ ('codex_a', 'CODEX A', 'codex', [('WEEK', 30, 3 * D)]), ('grok_a', 'GROK A', 'grok', [('BUDGET', 40, 3 * D)]),+ ('copilot_a', 'COPILOT A', 'copilot', [('MONTH', 50, 9 * D)], {'active': True})]+ image = face(data(*rows))+ names = ['CLAUDE B', 'CODEX A', 'GROK A', 'COPILOT A'] # the one at work, then the fullest; in service order+ for k, name in enumerate(names):+ says(self, image, (60, k * 60 + 5), name, colour=survival.TEXT)+ pets = {'claude': (217, 119, 87), 'grok': (242, 244, 248)}+ self.assertIn(pets['claude'], stripe(image, (0, 0, 56, 60)))+ self.assertIn(pets['grok'], stripe(image, (0, 120, 56, 180)))+ for k in range(4):+ self.assertGreaterEqual(len(stripe(image, (8, k * 60 + 8, 50, k * 60 + 58)) - {survival.PANEL}), 2, k) # a pet+ mine = face(data(('claude_a', 'CLAUDE WORK LAPTOP', 'claude', [('5H', 40, 2 * H), ('WEEK', 40, 3 * D)]),+ ('claude_b', 'CLAUDE B', 'claude', [('5H', 40, 2 * H), ('WEEK', 40, 3 * D)])))+ says(self, mine, (66, 10), 'WORK LAPTOP', 2, colour=survival.TEXT)+ says(self, mine, (66, 130), 'CLAUDE B', 2, colour=survival.TEXT) # one service, two rows++ def test_a_long_name_is_cut_clear_of_what_stands_beside_it(self):+ reset = survival.width('5H ' + readout.reset_clock(NOW + 2 * H, NOW))+ names = {1: [(0, 0, 230 - survival.width('CLAWD', 2) - 4, 24)], 2: [(60, y0, 236, y0 + 26) for y0 in (0, 120)],+ 4: [(56, y0, 234 - reset - 6, y0 + 13) for y0 in (0, 60, 120, 180)]} # where each name may go+ for count in (1, 2, 4):+ short = [(f'claude_{c}', f'CLAUDE {c.upper()}', 'claude', [('5H', 40, 2 * H), ('WEEK', 40, 3 * D)])+ for c in 'abcd'[:count]]+ long_ = [(k, 'CLAUDE ' + 'VERYLONGNAME' * 3, p, w) for k, _, p, w in short]+ a, b = face(data(*short)), face(data(*long_))+ self.assertNotEqual(a.tobytes(), b.tobytes())+ for image in (a, b):+ for box in names[count]:+ ImageDraw.Draw(image).rectangle((box[0], box[1], box[2] - 1, box[3] - 1), fill=(0, 0, 0))+ self.assertEqual(a.tobytes(), b.tobytes(), count) # everything else as it was++ def test_the_same_readings_draw_the_same_picture(self):+ snap = data(('claude_a', 'CLAUDE A', 'claude', [('5H', 40, 2 * H), ('WEEK', 40, 3 * D)], {'today': .3}))+ self.assertEqual(render_page(snap, style='survival'), render_page(snap, style='survival'))+ snap['accounts']['claude_a']['windows'][0]['used_percent'] = 45+ self.assertNotEqual(face(snap).tobytes(), face(data(('claude_a', 'CLAUDE A', 'claude',+ [('5H', 40, 2 * H), ('WEEK', 40, 3 * D)], {'today': .3}))).tobytes())+++class ClockTests(unittest.TestCase):+ """Through live.main on a fake SD_PRO, picked on the dashboard as a person would."""+ def pick(self, rig, style):+ conn = http.client.HTTPConnection('127.0.0.1', rig.port, timeout=5)+ conn.request('POST', '/display/style', json.dumps({'style': style}), {'Content-Type': 'application/json'})+ self.assertEqual(conn.getresponse().status, 200)+ rig.clock.settle()++ def held_face(self, rig):+ return render_page(rig.held(), 0, 'survival')++ def test_on_the_clock_it_changes_with_the_readings_only(self):+ rig = Rig(self, providers=('codex',)) # (read every minute, as a Claude account is not)+ arcade, began = rig.showing()+ self.pick(rig, 'survival')+ due = rig.end_of_loop()+ rig.clock.to(due + .5)+ image, on = rig.showing()+ self.assertEqual(Image.open(io.BytesIO(image)).format, 'JPEG')+ self.assertEqual(image, self.held_face(rig))+ self.assertGreaterEqual(on, due - 1e-6) # Arcade's loop played out first+ self.assertLess(on, due + .25)+ sent, switched = len(rig.uploads()), len(rig.switches())+ for n in range(1, 4): # readings with nothing new: nothing sent+ rig.clock.to(rig.poll_at(n) + .5)+ rig.say('claude.ask') # an agent's moment is Arcade's: nothing here either+ rig.clock.to(rig.clock.now() + 30)+ self.assertEqual((len(rig.uploads()), len(rig.switches())), (sent, switched))+ rig.set('codex_a', 'WEEK', 55) # a new reading: one picture, at once (a still face has no loop to wait for)+ rig.write()+ rig.clock.to(rig.poll_at(4) + .5)+ self.assertEqual(len(rig.uploads()), sent + 1)+ image, on = rig.showing()+ self.assertEqual(image, self.held_face(rig))+ self.assertLess(on, rig.poll_at(4) + .25)+ kept = json.loads((rig.state / 'snapshot.json').read_text(encoding='utf-8'))['accounts']['codex_a']['day']+ self.assertEqual(kept['used'], 55) # today's use goes into the state folder with the snapshot+ self.pick(rig, 'arcade') # and back: Arcade as before+ rig.clock.to(rig.clock.now() + 1)+ self.assertEqual(Image.open(io.BytesIO(rig.showing()[0])).format, 'GIF')+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_today.py b/tests/test_today.pynew file mode 100644index 0000000..4d3a2e0--- /dev/null+++ b/tests/test_today.py@@ -0,0 +1,366 @@+"""v2 phase 3b, x7: today's use for the Survival face (state.py), from the window it is read from (its week over its 5+hours) on this computer's local date: the sum over the day's windows (one reset period each) of each one's last reading+less its first that day. A window that began today counts from nothing; for the one the day began in, a reading in the+15 minutes before midnight stands for midnight. A new window is one whose reset time moved later (or, with none known,+whose use fell to under half and below 10 %); any other fall is a correction within the window. Today's use is a share+of an even day (a seventh of a week). It goes into the state folder with the snapshot, so a restart keeps it; not known+is None."""+import json+import os+import time+import unittest+from unittest import mock++from token_tv import state+from token_tv.state import DAY_EDGE, SAME_WINDOW, UsageStore, day_step, today_share, valid_day+from token_tv.usage import (even_day, five_hour, long_window, normalize_codex, reset_credits, today_window,+ window_minutes)++EVEN_WEEK = 100 / 7 # an even day's points of a week+++def local(y, m, d, hh=12, mm=0, ss=0):+ return time.mktime((y, m, d, hh, mm, ss, 0, 0, -1))+++def week(used, resets, label='WEEK', minutes=10080):+ return {'label': label, 'used_percent': used, 'resets_at': resets, 'duration_minutes': minutes}+++def five(used, resets):+ return {'label': '5H', 'used_percent': used, 'resets_at': resets, 'duration_minutes': 300}+++def walk(readings):+ """The day after `readings` [(at, window)], in turn."""+ day = None+ for at, value in readings:+ day = day_step(day, value, at)+ return day+++def points(readings):+ """Today's use in the window's points after each of `readings` [(at, window)], in turn."""+ day, out = None, []+ for at, value in readings:+ day = day_step(day, value, at)+ out.append(round(today_share(day, at) * even_day(day['minutes']), 9))+ return out+++class WindowsTests(unittest.TestCase):+ def test_todays_use_is_read_from_the_longest_window_of_a_known_length_in_any_order(self):+ a, b = five(30, 1), week(60, 2)+ self.assertIs(today_window([a, b]), b)+ self.assertIs(today_window([b, a]), b)+ month, chat = {'label': 'MONTH', 'used_percent': 40}, {'label': 'CHAT', 'used_percent': 90}+ self.assertIs(today_window([chat, month]), month)+ self.assertEqual(today_window([{'label': 'BUDGET', 'used_percent': 61}])['label'], 'BUDGET')+ self.assertIs(today_window([a]), a)+ self.assertIsNone(today_window([chat, {'label': 'WINDOW', 'used_percent': 3}])) # no length known: unknown++ def test_hearts_are_the_5_hour_window_and_hunger_the_week_else_the_longest_other(self):+ a, b = five(30, 1), week(60, 2)+ for order in ([a, b], [b, a]):+ self.assertIs(five_hour(order), a)+ self.assertIs(long_window(order), b)+ alias = {'label': 'WINDOW', 'used_percent': 5, 'duration_minutes': 10080} # a week by its length+ self.assertIs(long_window([{'label': 'MONTH', 'used_percent': 1}, alias]), alias)+ self.assertEqual(five_hour([{'label': 'WINDOW', 'used_percent': 5, 'duration_minutes': 300}])['label'], 'WINDOW')+ self.assertEqual(long_window([{'label': 'CHAT', 'used_percent': 9}, {'label': 'MONTH', 'used_percent': 1}])['label'],+ 'MONTH')+ self.assertIsNone(long_window([a]))+ self.assertIsNone(five_hour([b]))++ def test_an_even_day_is_a_seventh_of_a_week_a_thirtieth_of_a_month_and_one_whole_5_hour_window(self):+ self.assertAlmostEqual(even_day(window_minutes(week(0, 0))), 100 / 7)+ self.assertAlmostEqual(even_day(window_minutes({'label': 'MONTH'})), 100 / 30)+ self.assertAlmostEqual(even_day(window_minutes({'label': 'BUDGET'})), 100 / 30)+ self.assertEqual(even_day(window_minutes({'label': 'DAY'})), 100)+ self.assertEqual(even_day(window_minutes(five(0, 0))), 100)+ self.assertIsNone(even_day(window_minutes({'label': 'CHAT'})))+++class DayTests(unittest.TestCase):+ D = (2026, 11, 5)++ def at(self, hh, mm=0, ss=0, day=0):+ return local(2026, 11, 5 + day, hh, mm, ss)++ def test_a_day_counts_what_its_window_rose_since_it_began(self):+ resets = self.at(23) + 3 * 86400+ day = walk([(self.at(9), week(40, resets))])+ self.assertEqual(today_share(day, self.at(9, 1)), 0) # its first reading: nothing used since+ day = day_step(day, week(42, resets), self.at(10))+ self.assertAlmostEqual(today_share(day, self.at(10)), 2 / EVEN_WEEK)+ self.assertEqual(day_step(day, week(42, resets), self.at(10)), day) # the same reading again+ self.assertEqual(day_step(day, week(41, resets), self.at(9, 30)), day) # an older one+ day = day_step(day, week(55.5, resets), self.at(18))+ self.assertAlmostEqual(today_share(day, self.at(18)), 15.5 / EVEN_WEEK)++ def test_a_reset_is_never_use_and_the_new_window_counts_from_nothing(self):+ r1, r2 = self.at(10), self.at(15) # a 5-hour window resetting at 10:00, then at 15:00+ day = walk([(self.at(9), five(30, r1)), (self.at(9, 50), five(50, r1)), (self.at(10, 5), five(4, r2))])+ self.assertAlmostEqual(today_share(day, self.at(10, 5)), (20 + 4) / 100) # one 5-hour window is an even day+ idle = walk([(self.at(9), five(30, r1)), (self.at(9, 50), five(50, r1)), (self.at(10, 5), five(0, r2))])+ self.assertAlmostEqual(today_share(idle, self.at(10, 5)), 20 / 100) # a reset with no use since adds nothing+ unknown = walk([(self.at(9), {'label': 'BUDGET', 'used_percent': 60, 'resets_at': None}),+ (self.at(9, 30), {'label': 'BUDGET', 'used_percent': 70, 'resets_at': None}),+ (self.at(9, 40), {'label': 'BUDGET', 'used_percent': 3, 'resets_at': None})])+ self.assertAlmostEqual(today_share(unknown, self.at(10)), (10 + 3) / (100 / 30)) # no reset time: the fall++ def test_any_other_fall_is_a_correction_within_the_window(self):+ r = self.at(15) # the same reset time in every reading+ self.assertEqual(points([(self.at(9, i), five(used, r)) for i, used in enumerate((30, 50, 45, 50, 45, 50))]),+ [0, 20, 15, 20, 15, 20]) # its last reading less its first: a correction adds nothing+ self.assertEqual(points([(self.at(9), five(30, r)), (self.at(9, 55), five(25, r))]), [0, 0]) # never below 0++ def test_a_new_window_is_one_whose_reset_time_moved_later_else_one_that_fell_to_near_nothing(self):+ r = self.at(15)+ rose = [(self.at(9), five(30, r)), (self.at(10), five(50, r))]+ self.assertEqual(points(rose + [(self.at(10, 5), five(2, r + SAME_WINDOW + 1))])[-1], 20 + 2) # a new window+ for wobble in (SAME_WINDOW, -3600): # moved later by no more than SAME_WINDOW, or earlier: the same window+ self.assertEqual(points(rose + [(self.at(10, 5), five(2, r + wobble))])[-1], 0)++ def budget(used, resets=None):+ return {'label': 'BUDGET', 'used_percent': used, 'resets_at': resets}+ # with no reset time known, a new window is a fall to under half and below 10 %+ for before, after, new in ((30, 9.9, True), (30, 14, False), (12, 5.9, True), (12, 6, False), (12, 9, False)):+ got = points([(self.at(9), budget(0)), (self.at(10), budget(before)), (self.at(11), budget(after))])+ self.assertEqual(got[-1], before + after if new else after, (before, after))+ mixed = points([(self.at(9), budget(40, r)), (self.at(10), budget(60, r)), (self.at(11), budget(0)),+ (self.at(12), budget(3, r + 30 * 86400))]) # (one reading without a reset time)+ self.assertEqual(mixed, [0, 20, 20, 23])+ # a week re-dated later without a fall, begun days ago: nothing invented, and the day counts on+ week_end = self.at(12, day=3)+ self.assertEqual(points([(self.at(9), week(40, week_end)), (self.at(10), week(60, week_end)),+ (self.at(11), week(60, week_end + 86400)), (self.at(12), week(62, week_end + 86400))]),+ [0, 20, 20, 22])++ def test_a_spent_reset_credit_is_a_new_window_counted_from_nothing(self):+ week_end = self.at(23) + 3 * 86400 # the week as read at 9:00 has three days to go+ new_end = self.at(11) + 7 * 86400 # a reset credit spent at 11:00: a new week from then+ for first in (0, 5): # the new week's first reading, whatever was used of it by then+ readings = [(self.at(9), week(40, week_end)), (self.at(10), week(60, week_end)),+ (self.at(11, 5), week(first, new_end)), (self.at(12), week(10, new_end)),+ (self.at(13), week(15, new_end))]+ self.assertEqual(points(readings), [0, 20, 20 + first, 30, 35], first) # 0, 140, 140 or 175, 210, 245 %+ tomorrow = day_step(walk(readings), week(17, new_end), self.at(9, day=1))+ self.assertEqual(today_share(tomorrow, self.at(9, day=1)), 0) # the next day starts anew+ # first seen the next morning: from nothing if the new week began that day, else from its first reading+ day = walk([(self.at(9), week(40, week_end)), (self.at(22), week(60, week_end))])+ for spent, want in ((self.at(7, day=1), 5), (self.at(23), 0)):+ seen = day_step(day, week(5, spent + 7 * 86400), self.at(8, day=1))+ self.assertAlmostEqual(today_share(seen, self.at(8, day=1)), want / EVEN_WEEK)+ # just after midnight, from a reading that stands for midnight: the day counts from the new week's start+ new_end = self.at(0, 10, day=1) + 7 * 86400+ late = walk([(self.at(23, 50), week(60, week_end)), (self.at(0, 10, day=1), week(0, new_end)),+ (self.at(1, day=1), week(5, new_end))])+ self.assertAlmostEqual(today_share(late, self.at(1, day=1)), 5 / EVEN_WEEK)++ def test_a_reading_in_the_quarter_hour_before_midnight_stands_for_the_days_start(self):+ resets = self.at(12, day=3)+ late = walk([(self.at(23, 50), week(50, resets)), (self.at(0, 5, day=1), week(52, resets))])+ self.assertAlmostEqual(today_share(late, self.at(0, 6, day=1)), 2 / EVEN_WEEK)+ early = walk([(self.at(22), week(50, resets)), (self.at(8, day=1), week(60, resets))])+ self.assertEqual(today_share(early, self.at(8, day=1)), 0) # asleep at midnight: from its first reading+ self.assertEqual(today_share(walk([(self.at(23, 55), week(50, resets))]), self.at(0, 2, day=1)), 0)+ self.assertIsNone(today_share(walk([(self.at(22), week(50, resets))]), self.at(0, 2, day=1))) # not known yet+ midnight = self.at(0, day=1)+ self.assertEqual(today_share(walk([(midnight - DAY_EDGE, week(50, resets))]), midnight + 60), 0)+ self.assertIsNone(today_share(walk([(midnight - DAY_EDGE - 1, week(50, resets))]), midnight + 60))+ reset = self.at(0, 30, day=1) # the week itself resets at 00:30: the new one from nothing, no carry-over+ day = walk([(self.at(23, 55), week(70, reset)), (self.at(0, 35, day=1), week(1, reset + 7 * 86400))])+ self.assertAlmostEqual(today_share(day, self.at(0, 40, day=1)), 1 / EVEN_WEEK)+ day = day_step(day, week(3, reset + 7 * 86400), self.at(9, day=1))+ self.assertAlmostEqual(today_share(day, self.at(9, day=1)), 3 / EVEN_WEEK)++ def test_the_same_use_today_is_the_same_whatever_came_before(self):+ resets = self.at(12, day=4)+ a = walk([(self.at(23, 50, day=-1), week(10, resets)), (self.at(9), week(14, resets)), (self.at(18), week(20, resets))])+ b = walk([(self.at(23, 50, day=-1), week(70, resets)), (self.at(9), week(74, resets)), (self.at(18), week(80, resets))])+ self.assertAlmostEqual(today_share(a, self.at(18)), today_share(b, self.at(18)))+ c = walk([(self.at(23, 50, day=-1), week(70, resets)), (self.at(18), week(80, resets))])+ d = walk([(self.at(23, 50, day=-1), week(75, resets)), (self.at(18), week(80, resets))])+ self.assertNotAlmostEqual(today_share(c, self.at(18)), today_share(d, self.at(18))) # the same quota, not use++ def test_another_window_is_counted_from_its_first_reading(self):+ day = walk([(self.at(9), week(40, 1)), (self.at(10), week(45, 1))])+ day = day_step(day, five(20, 2), self.at(11)) # (the week went missing: the 5 hours now)+ self.assertEqual(today_share(day, self.at(11)), 0)+ self.assertEqual(day['label'], '5H')++ def test_a_kept_day_must_look_like_one(self):+ good = walk([(self.at(9), week(40, 1))])+ self.assertEqual(valid_day(json.loads(json.dumps(good))), good)+ for bad in (None, [], 'x', dict(good, used=True), dict(good, date=3), dict(good, minutes='10080'),+ {k: v for k, v in good.items() if k != 'base'}, dict(good, resets_at='soon'),+ dict(good, resets_at=False)):+ self.assertIsNone(valid_day(bad), bad)++ @unittest.skipUnless(hasattr(time, 'tzset'), 'needs a settable time zone')+ def test_the_day_is_this_computers_own(self):+ self.addCleanup(time.tzset)+ before = 1793890800 - 600 # 2026-11-05 15:00 UTC is midnight in Seoul: ten minutes before, and after+ after = 1793890800 + 600+ for zone, new_day in (('Asia/Seoul', True), ('UTC', False)):+ with mock.patch.dict(os.environ, {'TZ': zone}):+ time.tzset()+ day = walk([(before - 3600, week(40, after + 86400)), (before, week(45, after + 86400)),+ (after, week(47, after + 86400))])+ self.assertAlmostEqual(today_share(day, after), (2 if new_day else 7) / EVEN_WEEK, msg=zone)+ time.tzset()+++class Clock:+ """state.time on a hand-moved clock."""+ def __init__(self, at):+ self.t = at++ def time(self):+ return self.t++ def monotonic(self):+ return self.t++ def __getattr__(self, name):+ return getattr(time, name)+++class StoreTests(unittest.TestCase):+ """Through UsageStore, as live.main reads and keeps it."""+ def setUp(self):+ self.clock = Clock(local(2026, 11, 5, 9))+ patcher = mock.patch.object(state, 'time', self.clock)+ patcher.start()+ self.addCleanup(patcher.stop)+ self.used = {'claude_a': 40.0, 'codex_a': 10.0}+ self.status = 'ok'++ def fetch(self, account):+ windows = [{'label': '5H', 'used_percent': 20.0, 'resets_at': self.clock.t + 3600, 'duration_minutes': 300},+ {'label': 'WEEK', 'used_percent': self.used[account['key']], 'resets_at': local(2026, 11, 9, 12),+ 'duration_minutes': 10080}]+ return {'key': account['key'], 'alias': account['alias'], 'provider': account['provider'], 'status': self.status,+ 'windows': windows if self.status == 'ok' else [], 'fetched_at': self.clock.t}++ def store(self):+ return UsageStore([{'key': 'claude_a', 'alias': 'CLAUDE A', 'provider': 'claude'},+ {'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex'}], fetch=self.fetch)++ def test_each_account_has_its_own_today_and_a_restart_keeps_it(self):+ store = self.store()+ store.refresh()+ self.assertEqual(store.snapshot()['accounts']['claude_a']['today'], 0)+ for minutes, claude, codex in ((60, 42.0, 10.0), (120, 44.5, 13.0), (180, 44.5, 13.0)): # (a duplicate last)+ self.clock.t = local(2026, 11, 5, 9) + 60 * minutes+ self.used.update(claude_a=claude, codex_a=codex)+ store.refresh()+ shown = store.snapshot()['accounts']+ self.assertAlmostEqual(shown['claude_a']['today'], 4.5 / EVEN_WEEK)+ self.assertAlmostEqual(shown['codex_a']['today'], 3 / EVEN_WEEK)+ kept = json.loads(json.dumps(store.snapshot())) # as live.main writes snapshot.json and reads it back+ again = self.store()+ again.restore(kept)+ self.assertAlmostEqual(again.snapshot()['accounts']['claude_a']['today'], 4.5 / EVEN_WEEK) # still loading+ self.used.update(claude_a=46.0)+ self.clock.t += 600+ again.refresh()+ self.assertAlmostEqual(again.snapshot()['accounts']['claude_a']['today'], 6 / EVEN_WEEK)+ broken = json.loads(json.dumps(kept))+ broken['accounts']['claude_a']['day']['base'] = 'forty'+ third = self.store()+ third.restore(broken)+ self.assertIsNone(third.snapshot()['accounts']['claude_a']['today']) # a broken record is no day++ def test_a_reading_that_fails_keeps_the_day_and_the_next_day_starts_anew(self):+ store = self.store()+ store.refresh()+ self.clock.t += 3600+ self.used['claude_a'] = 47.0+ store.refresh()+ self.status = 'error'+ self.clock.t += 600+ store.refresh()+ row = store.snapshot()['accounts']['claude_a']+ self.assertEqual(row['status'], 'stale')+ self.assertAlmostEqual(row['today'], 7 / EVEN_WEEK)+ self.status = 'ok'+ self.clock.t = local(2026, 11, 6, 0, 2) # the next day, its first reading two minutes in; nothing read at 23:4x+ store.refresh()+ self.assertEqual(store.snapshot()['accounts']['claude_a']['today'], 0)+ self.clock.t = local(2026, 11, 6, 9)+ self.used['claude_a'] = 49.0+ store.refresh()+ self.assertAlmostEqual(store.snapshot()['accounts']['claude_a']['today'], 2 / EVEN_WEEK)++ def restart(self, store):+ """TokenTV started again, from the snapshot `store` wrote (as live.main writes snapshot.json and reads it)."""+ again = UsageStore(store.accounts, fetch=store.fetch)+ again.restore(json.loads(json.dumps(store.snapshot())))+ return again++ def test_a_spent_reset_credit_keeps_todays_use_through_restarts(self):+ """A Codex week read as sources.fetch_account reads it (usage.normalize_codex, usage.reset_credits): 40 % at 9,+ 60 % at 10, a reset credit spent at 11 (a new week from then) first read at 0 % or at 5 %, 10 % at 12:30 and+ 15 % at 13:30. Today: 0, 140 %, 140 % or 175 %, 210 %, 245 % (35 points), with TokenTV restarted before the+ reset and after it."""+ reading = {}++ def fetch(account):+ five_hours = {'usedPercent': 5, 'windowDurationMins': 300, 'resetsAt': self.clock.t + 3600}+ the_week = {'usedPercent': reading['used'], 'windowDurationMins': 10080, 'resetsAt': reading['resets']}+ reply = {'rateLimits': {'primary': five_hours, 'secondary': the_week},+ 'rateLimitResetCredits': {'availableCount': reading['credits'], 'credits': [+ {'status': 'available', 'expiresAt': local(2026, 12, 1)}] * reading['credits']}}+ return {'key': account['key'], 'alias': account['alias'], 'provider': 'codex', 'status': 'ok',+ 'windows': normalize_codex(reply), 'reset_credits': reset_credits(reply),+ 'fetched_at': self.clock.t}++ def shown(store):+ return store.snapshot()['accounts']['codex_a']['today'] * EVEN_WEEK++ for first in (0, 5):+ self.clock.t = local(2026, 11, 5, 9)+ reading.update(used=40, resets=local(2026, 11, 8, 12), credits=2)+ store = UsageStore([{'key': 'codex_a', 'alias': 'CODEX A', 'provider': 'codex'}], fetch=fetch)+ store.refresh()+ self.assertEqual(shown(store), 0)+ self.clock.t, reading['used'] = local(2026, 11, 5, 10), 60+ store.refresh()+ self.assertAlmostEqual(shown(store), 20) # 140 %+ store = self.restart(store)+ self.clock.t = local(2026, 11, 5, 11)+ reading.update(used=first, resets=self.clock.t + 7 * 86400, credits=1)+ store.refresh()+ self.assertAlmostEqual(shown(store), 20 + first) # 140 % or 175 %: the new week from nothing+ store = self.restart(store)+ self.assertAlmostEqual(shown(store), 20 + first)+ for at, used, want in ((local(2026, 11, 5, 12, 30), 10, 30), (local(2026, 11, 5, 13, 30), 15, 35)):+ self.clock.t, reading['used'] = at, used+ store.refresh()+ self.assertAlmostEqual(shown(store), want, msg=first) # 210 %, 245 %++ def test_a_correction_counts_within_its_window_through_restarts(self):+ """The week read at 30 %, 50 %, then corrected to 45 %, then 50 % again, with TokenTV restarted between every+ two readings: today is 0, 20, 15, 20 points, the week's last reading less its first."""+ self.used['codex_a'] = 30.0+ store = self.store()+ store.refresh()+ got = [store.snapshot()['accounts']['codex_a']['today'] * EVEN_WEEK]+ for hours, used in ((1, 50.0), (2, 45.0), (3, 50.0)):+ store = self.restart(store)+ self.clock.t, self.used['codex_a'] = local(2026, 11, 5, 9 + hours), used+ store.refresh()+ got.append(store.snapshot()['accounts']['codex_a']['today'] * EVEN_WEEK)+ self.assertEqual([round(p, 9) for p in got], [0, 20, 15, 20])++ def test_no_reading_today_yet_is_not_known(self):+ store = self.store()+ store.refresh()+ self.clock.t = local(2026, 11, 6, 10) # a day later, nothing read since+ self.assertIsNone(store.snapshot()['accounts']['claude_a']['today'])+++if __name__ == '__main__':+ unittest.main()diff --git a/token_tv/__init__.py b/token_tv/__init__.pyindex 1cd5573..36be654 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.5.0"+__version__ = "0.6.0"diff --git a/token_tv/arcade.py b/token_tv/arcade.pyindex e037c7b..1b14c08 100644--- a/token_tv/arcade.py+++ b/token_tv/arcade.py@@ -19,6 +19,7 @@ import ioimport jsonimport mathimport random+import threadingimport timefrom PIL import Image, ImageDraw, ImageEnhance@@ -120,8 +121,34 @@ def loop_offset(f, length, cycles):return (f * length * cycles / FRAMES) % length+SEASON = threading.local() # .dress: what the scene this thread draws wears (seasons.Dress), None as usual+++def dressed():+ """The season the scene being drawn in this thread is dressed for (a seasons.Dress), or None: Arcade as ever."""+ return getattr(SEASON, 'dress', None)+++def tag(art, pet):+ """`art` marked as `pet`'s own picture (in its info, not its pixels), so a season's hat finds its head."""+ art.info['pet'] = pet+ return art++def paste(frame, art, x, y):frame.paste(art, (round(x), round(y)), art)+ dress = dressed()+ if dress is not None and art.info.get('pet'): # a pet in season: its hat on (seasons.py)+ from token_tv import seasons+ seasons.wear(dress, frame, art, round(x), round(y))+++def season_scenery(draw, box, ground):+ """The season's scenery behind a scene's pet and gauge, as its backdrop ends; nothing off season (seasons.py)."""+ dress = dressed()+ if dress is not None:+ from token_tv import seasons+ seasons.scenery(dress, draw, box, ground)def band_color(used):@@ -171,7 +198,7 @@ def clawd(name, index, scale):palette = [tuple(int(c[i:i + 2], 16) for i in (1, 3, 5)) + (255,) for c in sheet['palette']]art = Image.new('RGBA', (sheet['w'], sheet['h']))art.putdata([(0, 0, 0, 0) if v == 255 else palette[v] for v in clawd_frames(name)[index]])- return art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST)+ return tag(art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST), 'claude')def place_clawd(frame, name, index, scale, foot_x, foot_y, flip=False):@@ -294,6 +321,7 @@ def claude_backdrop(frame, draw, box, f, s, active, pit=True):frame.paste(crop, (x, ground_y - hills.height), crop)crop = ground.crop((round(shift), 0, round(shift) + w, ground.height))frame.paste(crop, (x, ground_y), crop)+ season_scenery(draw, box, ground_y)return ground_y, period, pits, pit_w, shift@@ -318,12 +346,21 @@ def moon_gauge(draw, cx, cy, r, left):# 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.+# 'stretch' on every pet's, each once through its pet's turn. Phase 3a's (claude_moments.py), on Clawd's rows:+# {'kind': 'risky', 'style': 'verdict' or 'objection'} the courtroom, {'kind': 'deleted', 'style': 'drift' or 'wave'}+# the ghost, {'kind': 'rude'} the back turned ('ghost': a style, with the ghost about too), {'kind': 'calm'} the turn+# back round, {'kind': 'failed'} dizzy, {'kind': 'compact'} the squeeze; and a row's 'word' (x6), Claude Code's own+# thinking word, said by the readout in place of what Clawd is doing.NEEDS_LEVELS = ((15 * 60, 3), (5 * 60, 2), (0, 1)) # seconds waited -> how insistentMOMENT_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+ 'stretch': 'STRETCHING', 'risky': 'ORDER!', 'deleted': 'BOO!', 'rude': 'SULKING', 'calm': 'FORGIVEN',+ 'failed': 'DIZZY', 'compact': 'COMPACTING'}+STYLE_ACTION = {('risky', 'objection'): 'OBJECTION!'} # a variant that says its own word+CLAWD_3A = ('risky', 'deleted', 'rude', 'calm', 'failed', 'compact') # claude_moments.py draws these+# moments drawn once through the turn, a scene frame a frame (the ghost's lap and the sulk's glare a loop each)+ONCE_THROUGH = ('pet', 'snack', 'drink', 'stretch') + CLAWD_3A+JOINING = ('done', 'pet', 'snack') + CLAWD_3A # moments that bring their pet into the loop beside the ones at work+QUIET = ('deleted', 'rude', 'calm', 'failed', 'compact') # moments that leave the readout to SLOW when it is dueSIGN_INK, SIGN_BOARD, SIGN_EDGE = (34, 40, 120), (250, 244, 226), (150, 110, 70)@@ -408,6 +445,12 @@ def bow_style(moment):def claude_scene(frame, draw, box, f, span, active, s, plan):+ moment = plan.get('moment') if isinstance(plan, dict) else None+ if moment and moment.get('kind') in CLAWD_3A: # phase 3a's (claude_moments.py) draw the whole stage+ from token_tv import claude_moments+ scene = claude_moments.scene_of(moment)+ if scene:+ return scene(frame, draw, box, f, span, active, s, plan, claude_scene)x, y, w, h = boxground_y, period, pits, pit_w, shift = claude_backdrop(frame, draw, box, f, s, False) # the world stands stillif isinstance(plan, dict) and plan.get('moon') is not None:@@ -550,7 +593,7 @@ def codex_pose(eye='open', mouth='long', squash=0):@functools.lru_cache(maxsize=None)def codex_art(scale, eye='open', mouth='long', squash=0):art = codex_pose(eye, mouth, squash)- return art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST)+ return tag(art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST), 'codex')def rain_glyph(draw, char, x, y, scale, color):@@ -608,6 +651,7 @@ def garden_backdrop(draw, box, f, s):draw.line((x, ground, x + w - 1, ground), fill=SOIL_TOP)for i in range(3, w, 7 * s):draw.point((x + i, ground + 2 * s + (i // 7) % 2 * s), fill=SOIL_DOT)+ season_scenery(draw, box, ground)return ground@@ -868,7 +912,10 @@ def rotsprite(art, degrees):"""`art` turned clockwise by `degrees`, RotSprite style (EPX ×8, turn, back down) so edges stay clean."""big = scale2x(scale2x(scale2x(art)))big = big.rotate(-degrees, resample=Image.Resampling.NEAREST, expand=True)- return big.resize((max(1, big.width // 8), max(1, big.height // 8)), Image.Resampling.NEAREST)+ out = big.resize((max(1, big.width // 8), max(1, big.height // 8)), Image.Resampling.NEAREST)+ if art.info.get('pet'): # a turned pet (a bow's tilt, a break-dance spin) is still the pet, turned+ out.info.update(pet=art.info['pet'], turn=degrees)+ return out@functools.lru_cache(maxsize=None)@@ -898,7 +945,7 @@ def grok_pose(size, eyes='open', squash=0):art = art.resize((max(1, round(art.width * scale)), max(1, round(art.height * scale))), Image.Resampling.NEAREST)if squash:art = art.resize((art.width + 2 * squash, art.height - 2 * squash), Image.Resampling.NEAREST)- return art+ return tag(art, 'grok')def stars(w, h, count):@@ -965,6 +1012,7 @@ def grok_backdrop(draw, box, f, s):(rx + sep, step // 2 + round(3 * u))):draw.rectangle((cx - half, deck, cx + half - 1, ground - 1), fill=DECK)draw.line((cx - half, deck, cx + half - 1, deck), fill=DECK_EDGE)+ season_scenery(draw, box, ground)return u, ground, deck, hr, rx, rest_art, max(12, round(31 * u)), x + round(w * .2), sep@@ -1185,7 +1233,7 @@ def copilot_pose(size, eyes='open'):for x, key in enumerate(line):if key in COPILOT_INK:art.putpixel((x, y), COPILOT_INK[key] + (255,))- return art+ return tag(art, 'copilot')with Image.open(ASSETS / 'copilot-pixel.png') as source:art = source.convert('RGBA')art = art.crop(art.getbbox())@@ -1202,7 +1250,7 @@ def copilot_pose(size, eyes='open'):for x, y in eye:if y < bottom:px[x, y] = COPILOT_INK['N'] + (255,)- return art+ return tag(art, 'copilot')def cloud(draw, cx, cy, r, top=CLOUD_TOP, base=CLOUD_BASE):@@ -1260,6 +1308,7 @@ def copilot_backdrop(draw, box, f, s, far=0, clouds=True):for i, (fx, fy, r) in enumerate(((.15, .3, 7), (.6, .22, 6), (.95, .36, 8)) if clouds else ()): # far, driftingcx = x + (round(fx * period) - far) % period - round(40 * u)cloud(draw, cx, y + round(fy * h), max(3, round(r * u)))+ season_scenery(draw, box, y + round(h * .78)) # (its ground: the cloud it rests on)return period@@ -1474,7 +1523,8 @@ def anti_art(face='normal', body='logo', dx=0, dy=0, flip=False, scale=1, pose='anti_face(draw, face, dx, dy, pad, tops[2] - 4)if flip:art = art.transpose(Image.Transpose.FLIP_TOP_BOTTOM)- return art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST) if scale != 1 else art+ return tag(art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST) if scale != 1 else art,+ 'antigravity')@functools.lru_cache(maxsize=None)@@ -1528,6 +1578,7 @@ def anti_maze(draw, box, f, s, left, middle='wall', label='', wall=MAZE_WALL, dodraw.rectangle((x + dx, y + dy, x + dx + 1, y + dy + 1), fill=MAZE_DOT)if pellets:anti_pellets(draw, box, left, label)+ season_scenery(draw, box, y + ANTI_FLOOR + 1)def anti_on_loop(s_):@@ -1879,7 +1930,8 @@ FULL_ACTION = {'claude': 'WIPED OUT', 'codex': 'PANTING', 'grok': 'OUT OF FUEL',def action_label(row, plan, egg, f, span):- """What `row`'s pet is doing at scene frame `f` (the frame its scene draws), in at most eleven letters."""+ """What `row`'s pet is doing at scene frame `f` (the frame its scene draws), in at most eleven letters; Claude+ Code's thinking word (x6) can take fourteen, the last two in the readout's small letters."""provider = row['provider']if egg is not None and egg_scene(egg, row):if hasattr(egg, 'frames'): # a hidden one-off: the name it was sealed with@@ -1888,10 +1940,13 @@ 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']]+ moment = plan.get('moment') if isinstance(plan, dict) else None+ if moment and not (moment['kind'] in QUIET and row.get('slow')): # a ghost or a dizzy Clawd leaves SLOW be+ return STYLE_ACTION.get((moment['kind'], moment.get('style')), MOMENT_ACTION[moment['kind']])if row.get('slow'): # x3: a window would run out within half an hour at its pace (state.py); the pet goes onreturn 'SLOW'+ if says_word(row, plan): # x6: what Claude Code says it is doing, in place of the pet's+ return row['word']worried = isinstance(plan, dict) and plan.get('mood') == 'worried'if row.get('active'):if worried:@@ -1910,6 +1965,21 @@ def action_label(row, plan, egg, f, span):return IDLE_ACTION.get(idle_now(plan, f, span), 'RESTING')+def says_word(row, plan):+ """Whether `row`'s readout says Claude Code's thinking word (x6) with no one-off on the clock (action_label):+ Clawd's row with a word, no moment of its own (BOO! and SULKING say theirs) and no SLOW due."""+ moment = plan.get('moment') if isinstance(plan, dict) else None+ return bool(row.get('word')) and row['provider'] == 'claude' and not moment and not row.get('slow')+++def word_readable(snapshot, now=None):+ """Whether the Arcade picture of `snapshot` says Claude Code's thinking word in a readout: on a Claude row the+ clock takes its turn on (shown_rows), in the battery look (the others draw no label). A word's minute on the clock+ starts only then (live.py tells moments.Moments.shown)."""+ return readout_look.STYLE == 'battery' and any(+ row.get('word') and says_word(row, scene_plan(row, now)) for row in shown_rows(snapshot, now))++def shown_rows(snapshot, now=None):"""The accounts Arcade takes turns on: the working ones, or every one while all are idle. Four at most sharea loop; with more, the four move on with each round of the rest flow (six minutes), so every account gets its@@ -1921,11 +1991,12 @@ def shown_rows(snapshot, now=None):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))# 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.+ # once it is answered); a bow, a pet or a snack gets its turn beside the working ones, when some work, and so do+ # Clawd's phase-3a moments and its thinking word. 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+ joins = lambda row: (row.get('moment') or {}).get('kind') in JOINING or bool(row.get('word')) # noqa: E731pool = 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@@ -2113,6 +2184,7 @@ def pace_share(value, at):def arcade_frames(snapshot, now, egg=None):+ from token_tv import seasonsshown = shown_rows(snapshot, now)# a one-off plays for its own account even when that account is not among the rows the clock cycles throughevery = [dict(row, key=key) for key, row in snapshot.get('accounts', {}).items()]@@ -2122,6 +2194,7 @@ 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+ season = seasons.season_at(time.time() if now is None else now) # Halloween, Christmas or Seollal: the props# 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)@@ -2142,8 +2215,14 @@ def arcade_frames(snapshot, now, egg=None):local = (f - starts[index]) * scene_speed(row, eggy)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])+ # In season every scene but a one-off's is dressed: its backdrop adds the scenery, its pet the hat.+ SEASON.dress = (seasons.Dress(season, row['provider'], scene_f, span, bool(row.get('active')),+ scene_speed(row, eggy) * PLAYBACK, stage) if season and not oneoff else None)+ try:+ scene(stage, ImageDraw.Draw(stage), (0, 0, SIZE // 2, 71), scene_f, span,+ bool(row.get('active')), 1, plans[index])+ finally:+ SEASON.dress = Noneif not oneoff and row.get('trace_prop'):leave_prop(stage, row)if night: # late at night the stage glows lower, so nothing flares in a dark roomdiff --git a/token_tv/assets/theme-catalog.json b/token_tv/assets/theme-catalog.jsonindex 689314b..3adff6a 100644--- a/token_tv/assets/theme-catalog.json+++ b/token_tv/assets/theme-catalog.json@@ -90,6 +90,16 @@"source_url": "https://github.com/click6067-ship-it/token-tv/pull/11","license": "MIT","like_issue": null+ },+ {+ "id": "survival",+ "name": "Survival HUD",+ "author": "TokenTV",+ "added_at": "2026-11-05T00:00:00Z",+ "min_version": "0.4.0",+ "source_url": "https://github.com/click6067-ship-it/token-tv",+ "license": "MIT",+ "like_issue": null}]}diff --git a/token_tv/claude_moments.py b/token_tv/claude_moments.pynew file mode 100644index 0000000..118f2ae--- /dev/null+++ b/token_tv/claude_moments.py@@ -0,0 +1,599 @@+"""Clawd's phase-3a moments on the Arcade stage, as the owner approved them (drafts w17-w23, 2026-11-05): the courtroom+for a risky command (e3: Judge Clawd's verdict on Clawd in the dock, or Clawd's own OBJECTION!, one of the two at+random each time), the ghost of a deleted file (e4: drifting round Clawd's usual scene, or with Clawd watching it and+waving), Clawd's back turned for a rude prompt and its turn back round (e7), dizzy after a failed tool and squeezing+its head on a compaction (x5). The thinking word (x6) is the readout's alone (arcade.action_label).++A once-through moment (the courtroom, the turn back round, the two tool faces) plays once through Clawd's turn, a+scene frame a frame, as phase 2's do. The ghost and the sulk are states that last a minute: their GIF loops, so each+is drawn to meet its own start (one lap of the ghost, one glare over the shoulder a loop). Whatever is meant to last+keeps something moving (darting eyes, a sweat drop, a tapping foot, a twinkle): drawn when the clock was thought to+show every picture for one 142 ms tick, a still pose flashing by; it shows each for its delay, at least a tick (m1).+Clawd's poses are its own frames from Clawd's Quest; new are the props (the dock, the bench, the gavel, the wig, the+cards, the ghost, the steam, the stars, the thought bubbles), a few eye pixels (none from behind, a frown, squeezed+shut) and the arms put to its head. With its back turned and a ghost about at once, the ghost drifts round the sulk.++arcade.py draws them: claude_scene hands the row's moment to SCENES ({'kind': 'risky', 'style': 'objection'}, say).+Everything is drawn on the scene's 120 x 71 stage, which Arcade doubles.+"""+import functools+import math++from PIL import Image++from token_tv import arcade+from token_tv import pet_moments as pm+from token_tv.arcade import paste+from token_tv.display import pixel_text+from token_tv.moments import COURTS, GHOSTS++BODY, SHADE, DARK = '#d97757', '#be684d', '#141413'+++# --- Clawd's own frames, a few pixels changed ---------------------------------------------------------------------+[email protected]_cache(maxsize=None)+def grid(name, index):+ """Clawd's frame as rows of colours ('#d97757'), None where clear; Thinking's bubble left out."""+ sheet = arcade.clawd_data()[name]+ keys = [c.lower() for c in sheet['palette']]+ w = sheet['w']+ values = arcade.clawd_frames(name)[index]+ return tuple(tuple(None if v == 255 or keys[v] == pm.THOUGHT else keys[v] for v in values[y * w:(y + 1) * w])+ for y in range(sheet['h']))+++def eyes_of(g):+ """The eye pixels of a frame, (left eye, right eye), each a list of (x, y)."""+ w = len(g[0])+ spots = [(x, y) for y, row in enumerate(g) for x, c in enumerate(row) if c == DARK]+ return [p for p in spots if p[0] < w / 2], [p for p in spots if p[0] >= w / 2]++[email protected]_cache(maxsize=None)+def edited(g, look):+ """`g` with its eyes changed: 'none' (from behind: body where the eyes were), 'squeeze' (squeezed shut: > <),+ 'shut' (a line on the eye's lowest row), 'frown' (Disappointed's own look: a brow and the eye under its outer+ end)."""+ rows = [list(r) for r in g]+ for side, eye in enumerate(eyes_of(g)):+ if not eye:+ continue+ top, low = min(y for _, y in eye), max(y for _, y in eye)+ x0, x1 = min(x for x, _ in eye), max(x for x, _ in eye)+ for x, y in eye:+ rows[y][x] = BODY+ if look == 'squeeze': # '>' on the left, '<' on the right, three rows tall+ tip, back = (x1, x0) if side == 0 else (x0, x1)+ for y, x in ((top - 1, back), (top, tip), (low, back)):+ rows[y][x] = DARK+ elif look == 'shut':+ for x in range(x0 - (side == 1), x1 + 1 + (side == 0)):+ rows[low][x] = DARK+ elif look == 'frown': # Disappointed's own look: a brow three wide, the eye a pixel under its outer end+ for x in range(x0 - (side == 0), x1 + 1 + (side == 1)):+ rows[top][x] = DARK+ rows[low][x0 if side == 0 else x1] = DARK+ return tuple(tuple(r) for r in rows)+++def flipped(g):+ return tuple(tuple(reversed(r)) for r in g)+++ELBOW = ((1, 7), (2, 7), (0, 6), (1, 6), (2, 6), (0, 5), (1, 5), (2, 5), (1, 4), (2, 4), (3, 4), (2, 3), (3, 3),+ (3, 2), (3, 1)) # the left arm bent up, elbow out, its hand at the temple (the right one mirrors it)++[email protected]_cache(maxsize=None)+def hands_on_head(g, press=False):+ """A standing frame holding its head: both arms bent up, elbows out, hands at its temples (the hands in the shade,+ so they read apart from the head); `press` squeezes: the arms up a pixel and in at the hands, the head's top+ corners pinched in."""+ rows = [list(r) for r in g]+ w = len(rows[0])+ for y in range(4, 8): # the arms leave their place+ for x in list(range(0, 4)) + list(range(w - 4, w)):+ rows[y][x] = None+ for x, y in ELBOW:+ if press:+ x, y = x + (y <= 4), y - 1+ ink = SHADE if y <= 3 and x >= 3 else BODY+ rows[y][x] = rows[y][w - 1 - x] = ink+ if press:+ for y in (0, 1):+ rows[y][4] = rows[y][w - 5] = None+ return tuple(tuple(r) for r in rows)++[email protected]_cache(maxsize=None)+def tap(g, up):+ """One leg (the outer one on the right) lifted a pixel: its lowest pixels cleared, a foot tapping."""+ if not up:+ return g+ rows = [list(r) for r in g]+ low = max(y for y, r in enumerate(rows) if any(r))+ right = [x for x, c in enumerate(rows[low]) if c]+ for x in right[-2:]:+ rows[low][x] = None+ return tuple(tuple(r) for r in rows)++[email protected]_cache(maxsize=None)+def art(g):+ out = Image.new('RGBA', (len(g[0]), len(g)))+ out.putdata([(0, 0, 0, 0) if c is None else tuple(int(c[i:i + 2], 16) for i in (1, 3, 5)) + (255,)+ for row in g for c in row])+ return arcade.tag(out, 'claude')++[email protected]_cache(maxsize=None)+def robed(g):+ """Judge Clawd's frame: its own, untagged, so in season its wig is all it wears on its head (seasons.py)."""+ out = art(g).copy()+ out.info.pop('pet', None)+ return out+++def pivot(name):+ x, y, w, h = arcade.clawd_data()[name]['a0']+ return round(x + w / 2), y + h+++def put(frame, name, g, foot_x, foot_y, lean=0, lift=0):+ """Stand frame `g` of animation `name` on (foot_x, foot_y) as place_clawd does, leaning `lean` at its top."""+ pm.put_leaning(frame, art, (g,), pivot(name), lean, foot_x, foot_y - lift)+++def clawd(frame, name, index, foot_x, foot_y, look=None, lean=0, lift=0):+ g = grid(name, index)+ put(frame, name, edited(g, look) if look else g, foot_x, foot_y, lean, lift)+++def backdrop(frame, draw, box, f, s, plan):+ """Clawd's world standing still, with its moon (the 5-hour window), as claude_scene draws it for a moment;+ returns where Clawd stands."""+ x, y, w, h = box+ ground_y = arcade.claude_backdrop(frame, draw, box, f, s, False)[0]+ if isinstance(plan, dict) and plan.get('moon') is not None:+ arcade.moon_gauge(draw, x + w - 12 * s, y + 11 * s, 8 * s, plan['moon'])+ if s == 1:+ arcade.gauge_label(draw, x + w - 12, y + 21, '5H', 'centre')+ return x + round(w * .3), ground_y+++def sweat(draw, x, y, k):+ """A drop of sweat sliding down beside a head: `k` (0..1) how far it has slid."""+ yy = y + round(5 * k)+ draw.point((x, yy), fill=(220, 240, 255))+ draw.rectangle((x - 1, yy + 1, x + 1, yy + 2), fill=arcade.SWEAT_INK)+++DARTING = (0, 9, 10, 9, 0, 6, 7, 6, 0, 13) # LookingAround: ahead, up left, left, ..., right, down: eyes darting+++# --- e3: the courtroom ---------------------------------------------------------------------------------------------++WOOD, WOOD_DARK, WOOD_LIGHT, WOOD_EDGE = (124, 76, 46), (82, 50, 32), (160, 104, 62), (204, 150, 92)+GOLD = (232, 186, 74)+CARD, CARD_EDGE, CARD_INK = (250, 244, 226), (196, 40, 52), (206, 30, 46)+IMPACT = (255, 236, 160)+++def dock(draw, cx, ground, half=14, top=9):+ """The dock: a wooden box Clawd stands in, its rail at `top` pixels over the ground."""+ x0, x1, y0 = cx - half, cx + half, ground - top+ draw.rectangle((x0, y0 + 2, x1, ground - 1), fill=WOOD)+ for px in range(x0 + 4, x1 - 2, 6): # the panels' grooves+ draw.line((px, y0 + 4, px, ground - 2), fill=WOOD_DARK)+ draw.rectangle((x0 - 1, y0, x1 + 1, y0 + 1), fill=WOOD_LIGHT) # the rail+ draw.line((x0 - 1, y0, x1 + 1, y0), fill=WOOD_EDGE)+++SCALES = ('....#....', '.#######.', '.#..#..#.', '###.#.###', '....#....', '...###...')+++def bench(frame, draw, x0, x1, top, ground, shake=0):+ """The judge's bench: a tall desk, its top a lighter board, the scales of justice in gold on its front."""+ x0, x1 = x0 + shake, x1 + shake+ draw.rectangle((x0, top + 2, x1, ground - 1), fill=WOOD)+ draw.rectangle((x0 + 3, top + 5, x1 - 3, ground - 4), outline=WOOD_DARK)+ draw.rectangle((x0 - 2, top, x1 + 2, top + 1), fill=WOOD_LIGHT)+ draw.line((x0 - 2, top, x1 + 2, top), fill=WOOD_EDGE)+ scales = pm.sprite(SCALES, {'#': GOLD})+ paste(frame, scales, (x0 + x1) // 2 - 4, top + 8)+++WIG, WIG_CURL = (244, 242, 236), (176, 176, 186)+++def wig(draw, left, top):+ """A judge's white wig on a head whose top row is `top` and whose left edge is `left` (a 16-wide head): a cap+ two rows over it and rows of curls down both sides."""+ for x in range(left, left + 16):+ draw.point((x, top - 2), fill=WIG if 1 <= x - left <= 14 else WIG_CURL)+ draw.point((x, top - 1), fill=WIG_CURL if (x - left) % 3 == 1 else WIG)+ draw.point((x, top), fill=WIG)+ for y in range(top, top + 6):+ for x in (left - 2, left - 1, left + 16, left + 17):+ curl = (y - top + (x > left)) % 2+ draw.point((x, y), fill=WIG_CURL if curl else WIG)+++GAVEL_UP = ('BHHHHHB', 'BHHHHHB', '...h...', '...h...', '...h...', '...h...', '...h...') # held up by its handle's end+GAVEL_DOWN = ('BB.....', 'HH.....', 'HHhhhhh', 'HH.....', 'HH.....', 'BB.....') # struck: the head down on the block+GAVEL_INK = {'H': (150, 92, 54), 'B': (226, 186, 120), 'h': (110, 68, 40)}+++def judge(frame, draw, jx, jy, strike, nod=0, startled=False):+ """Judge Clawd, in a wig, behind the bench at (jx, jy), turned to the dock on its left, the gavel in its left+ hand: raised, or `strike`: down on the block, with a few lines off it; `startled`, its wig jumps off its head.+ Its own frame (Turning's three quarters to the left); the wig and the gavel are new."""+ g = grid('Turning', 20)+ pm.put_leaning(frame, robed, (edited(g, 'shut') if startled else g,), pivot('Turning'), 0, jx, jy + nod)+ left, top = jx - 12 + 3, jy + nod - 17 + 1 # the head's left edge and top row in that frame+ wig(draw, left, top - (4 if startled else 0))+ hand_x, hand_y = jx - 12, jy + nod - 17 + 6 # the end of its left arm+ if strike:+ paste(frame, pm.sprite(GAVEL_DOWN, GAVEL_INK), hand_x - 7, hand_y - 2)+ for dx, dy in ((-4, -1), (-5, 1), (3, -2), (4, 0)):+ draw.point((hand_x - 6 + dx, hand_y + 4 + dy), fill=IMPACT)+ else:+ paste(frame, pm.sprite(GAVEL_UP, GAVEL_INK), hand_x - 4, hand_y - 7)+++def card(draw, cx, top, text, ink=CARD_INK):+ """A placard with `text` in red: cream board, a red rim."""+ w = len(text) * 6 - 1+ x0 = cx - w // 2 - 4+ draw.rectangle((x0, top, x0 + w + 7, top + 12), fill=CARD_EDGE)+ draw.rectangle((x0 + 1, top + 1, x0 + w + 6, top + 11), fill=CARD)+ pixel_text(draw, (x0 + 4, top + 3), text, color=ink)+++GUILTY = (('nervous', .12), ('order', .46), ('verdict', .52), ('slump', 1.0))+BANG = (0, 0, 1, 1, 0, 0) # each bang a picture at a time: up, up, down, down (lines), up, up+++def court_guilty(frame, draw, box, f, span, active, s, plan, base):+ """The verdict: Clawd in the dock, eyes darting; Judge Clawd, in a wig at its bench, bangs the gavel three times+ (ORDER!) and Clawd flinches at each; the GUILTY card slams down; Clawd slumps, eyes shut, sweating."""+ foot_x, ground = backdrop(frame, draw, box, f, s, plan)+ p = f / span+ step, q = pm.step_of(p, GUILTY)+ pic = f // 2 # the picture, 0-59+ jx, jy = 86, 50+ strike = step == 'order' and BANG[(pic - 7) % len(BANG)] == 1+ first_down = step == 'order' and BANG[(pic - 7) % len(BANG)] == 1 and BANG[(pic - 8) % len(BANG)] == 0+ draw.rectangle((jx - 21, 40, jx - 16, 41), fill=WOOD_DARK) # the block the gavel strikes+ judge(frame, draw, jx, jy, strike, nod=1 if first_down else 0)+ bench(frame, draw, 72, 100, 42, ground, 1 if first_down else 0)+ if step == 'nervous':+ clawd(frame, 'LookingAround', DARTING[pic % len(DARTING)], foot_x, ground)+ sweat(draw, foot_x + 11, ground - 15, q)+ elif step == 'order':+ if strike:+ clawd(frame, 'Turning', 4, foot_x, ground) # flinching, eyes shut+ else:+ clawd(frame, 'LookingAround', (6, 7)[pic % 2], foot_x, ground) # eyes on the judge+ elif step == 'verdict':+ clawd(frame, 'LookingAround', 8, foot_x, ground, lift=1) # up at the card+ else:+ index = 12 + min(8, int(q * 24)) # Disappointed: eyes shut, slumping down+ clawd(frame, 'Disappointed', index, foot_x, ground)+ sweat(draw, foot_x + 12, ground - 12, (q * 3) % 1)+ dock(draw, foot_x, ground)+ if step in ('verdict', 'slump'): # the card slams down from above and stays, swinging a pixel+ k = pic - round(GUILTY[1][1] * span / 2) # pictures since it fell+ top = (-12, -2, 7, 4, 5)[k] if k < 5 else 5 + (pic // 3) % 2+ card(draw, 50, top, 'GUILTY')+++OBJECT = (('look', .12), ('gasp', .20), ('jump', .32), ('lunge', .38), ('shout', .94), ('settle', 1.0))+JUMP = (4, 4, 5, 6, 7, 8, 10, 11, 13, 14) # Jumping's frames: crouch, up, at the top, down, the landing squash+BURST_FILL, BURST_EDGE, BURST_INK = (255, 255, 255), (196, 40, 52), (206, 30, 46)++[email protected]_cache(maxsize=None)+def burst_points(cx, cy, rx, ry, spikes, phase):+ pts = []+ for k in range(spikes * 2):+ a = math.pi * k / spikes + phase+ r = 1 if k % 2 == 0 else .8+ pts.append((cx + math.cos(a) * rx * r, cy + math.sin(a) * ry * r))+ return tuple(pts)+++def objection(draw, cx, cy, grow):+ """The shout: a jagged white burst with a red rim, OBJECTION! in red across it once it is full size."""+ pts = burst_points(cx, cy, round(42 * grow), round(12 * grow), 14, .1)+ draw.polygon(pts, fill=BURST_FILL, outline=BURST_EDGE)+ if grow >= 1:+ pixel_text(draw, (cx - 29, cy - 3), 'OBJECTION!', color=BURST_INK)+++def court_objection(frame, draw, box, f, span, active, s, plan, base):+ """Clawd's own objection, before Judge Clawd at its bench: it looks about, starts (!), leaps, lands in a lunge+ with a frown, and OBJECTION! bursts over the court, shaking at first, so hard the judge's wig jumps off; Clawd+ holds the lunge, trembling with it, then straightens up, pleased."""+ foot_x, ground = backdrop(frame, draw, box, f, s, plan)+ step, q = pm.step_of(f / span, OBJECT)+ pic = f // 2+ k = pic - round(OBJECT[3][1] * span / 2) # pictures since the shout burst+ judge(frame, draw, 86, 50, False, startled=step == 'shout' and 1 <= k < 4)+ bench(frame, draw, 72, 100, 42, ground)+ if step == 'look':+ clawd(frame, 'LookingAround', DARTING[pic % len(DARTING)], foot_x, ground)+ elif step == 'gasp':+ clawd(frame, 'Excited', 3 if q < .25 else 4 if q < .5 else 0, foot_x, ground)+ arcade.alert_mark(draw, foot_x + 9, ground - 26, 1, 0)+ elif step == 'jump':+ clawd(frame, 'Jumping', JUMP[min(len(JUMP) - 1, int(q * len(JUMP)))], foot_x, ground)+ elif step in ('lunge', 'shout'):+ lean = 2 if step == 'lunge' and q < .5 else 4 + (pic % 2 if step == 'shout' else 0)+ clawd(frame, 'Disappointed', 9, foot_x, ground, lean=lean)+ else:+ clawd(frame, 'Excited', 6 if q < .7 else 0, foot_x, ground)+ if step == 'shout':+ grow = (.45, .8)[k] if k < 2 else 1+ shake = (0, 0, 2, -2, 1, -1)[k] if k < 6 else 0+ objection(draw, 54 + shake, 15, grow)+++# --- e4: the ghost of a deleted file ---------------------------------------------------------------------------------++GHOST_INK = {'W': (236, 241, 252), 'F': (166, 182, 214), 'E': (34, 38, 64), 'L': (190, 204, 230)}+GHOST = ('WWWWWWF...', 'WWWWWWFF..', 'WWWWWWWWF.', 'WWWWWWWWWW', 'WWWWWWWWWW', 'WWWWWWWWWW', 'WWWWWWWWWW',+ 'WLLLLLWWWW', 'WWWWWWWWWW', 'WLLLLWWWWW', 'WWWWWWWWWW') # a page, its corner folded, two lines on it+HEMS = ('W.WW.WW.WW', 'WW.WW.WW.W') # the hem's two shapes, a flutter++[email protected]_cache(maxsize=None)+def ghost_art(hem, look, down, flip):+ """The ghost of a deleted file: a page with its corner folded, two eyes (`look` -1, 0, 1: to its left, ahead,+ to its right; `down` a row lower) and a wavy hem; flipped when it floats to the left."""+ rows = [list(r) for r in GHOST] + [list(HEMS[hem])]+ for y in (3 + down, 4 + down):+ for x in (2, 6):+ rows[y][x + look] = 'E'+ out = pm.sprite([''.join(r) for r in rows], GHOST_INK)+ return out.transpose(Image.Transpose.FLIP_LEFT_RIGHT) if flip else out+++GHOST_PATH = (54, 27, 32, 6) # its lap: an oval's middle and half widths, clear of the moon+++def ghost_at(p):+ """Where the ghost is at `p` (0..1) through its lap, and whether it floats right: a slow oval over the scene, its+ left end (over Clawd) halfway through the loop, along the high side leftwards and the low side back, bobbing."""+ cx, cy, rx, ry = GHOST_PATH+ a = 2 * math.pi * (p - .5)+ return cx - rx * math.cos(a), cy + ry * math.sin(a) + 2 * math.sin(4 * a), math.sin(a) >= 0+++def draw_ghost(frame, f, span, down=0):+ x, y, right = ghost_at(f / span)+ g = ghost_art((f // 2) % 2, 1, down, not right)+ paste(frame, g, x - g.width / 2, y - g.height / 2)+++def ghost_drift(frame, draw, box, f, span, active, s, plan, base):+ """The ghost of a deleted file drifting round the scene, once round a loop, while Clawd does what it was doing+ (its usual scene, at its usual pace)."""+ base(frame, draw, box, (f * arcade.SPEED) % span, span, active, s, dict(plan, moment=None))+ draw_ghost(frame, f, span)+++def ghost_wave(frame, draw, box, f, span, active, s, plan, base):+ """Clawd stops to watch the ghost go round, its eyes on it, and waves at it as it floats by overhead; the ghost+ looks down at Clawd as it passes."""+ foot_x, ground = backdrop(frame, draw, box, f, s, plan)+ gx = ghost_at(f / span)[0]+ near = abs(gx - foot_x) < 13+ if near:+ clawd(frame, 'Waving', 6 + (f // 2) % 10, foot_x, ground)+ else:+ clawd(frame, 'LookingAround', 9 if gx < foot_x - 4 else 8 if gx < foot_x + 20 else 7, foot_x, ground)+ draw_ghost(frame, f, span, down=1 if near else 0)+++# --- e7: the back turned --------------------------------------------------------------------------------------------++def back():+ """Clawd from behind: its standing frame with no eyes."""+ return edited(grid('LookingAround', 0), 'none')+++def back_quarter():+ """Turned three quarters away: Turning's quarter turn (its side in the shade) with no eyes."""+ return edited(grid('Turning', 20), 'none')+++STEAM = (214, 218, 228)+++def puff(draw, x, y, age, side):+ """A puff of steam blown out sideways (`side` -1 or 1) off the head, `age` pictures old (gone at 5)."""+ if not 0 <= age < 5:+ return+ cx, cy = x + side * 2 * age, y - (age // 2)+ if age == 0:+ draw.rectangle((cx, cy, cx + 1, cy + 1), fill=STEAM)+ elif age < 3:+ draw.rectangle((cx - 1, cy, cx + 1, cy + 1), fill=STEAM)+ draw.point((cx, cy - 1), fill=STEAM)+ draw.point((cx + side * 2, cy + 1), fill=STEAM)+ else:+ for dx, dy in ((-1, 0), (1, -1), (side * 2, 1)):+ draw.point((cx + dx, cy + dy), fill=STEAM)+++ANGER = ('.##.##.', '##...##', '.......', '##...##', '.##.##.')+ANGER_INK = (238, 64, 72)++SULK = (('back', .40), ('turn', .44), ('glare', .66), ('hmph', .72), ('again', 1.0))+++def sulk(frame, draw, box, f, span, active, s, plan, base):+ """Its back to you, a foot tapping, a huff of steam now and then; once a loop it turns round to glare at you+ (Disappointed's frown, an anger mark by its head) and turns its back again with a puff each side: hmph."""+ foot_x, ground = backdrop(frame, draw, box, f, s, plan)+ step, q = pm.step_of(f / span, SULK)+ pic = f // 2+ up = pic % 2 == 1+ head = ground - 13 # beside the head, a row under its eyes' level+ if step in ('back', 'again'):+ put(frame, 'LookingAround', tap(back(), up), foot_x, ground)+ for start, side in (((4, 1), (15, -1)) if step == 'back' else ((50, 1),)): # huffs, now one side, now the other+ puff(draw, foot_x + side * 13, head, pic - start, side)+ elif step == 'turn':+ put(frame, 'Turning', back_quarter(), foot_x, ground)+ elif step == 'glare':+ put(frame, 'Turning', tap(edited(grid('Turning', 20), 'frown'), up), foot_x, ground)+ if pic % 4 != 3:+ paste(frame, pm.sprite(ANGER, {'#': ANGER_INK}), foot_x + 9, ground - 22)+ else: # hmph: a squash, eyes shut, then the hop back round+ k = pic - round(SULK[2][1] * span / 2)+ if k < 2:+ clawd(frame, 'Turning', 28, foot_x, ground)+ else:+ put(frame, 'Turning', edited(grid('Turning', 17), 'none'), foot_x, ground)+ for side in (-1, 1):+ puff(draw, foot_x + side * 13, head, k, side)+++CALM = (('back', .12), ('peek', .30), ('turn', .36), ('happy', .80), ('settle', 1.0))+WONDER = (240, 240, 250)+++def calm(frame, draw, box, f, span, active, s, plan, base):+ """A calm prompt: the tapping slows, Clawd looks round over its shoulder (?), hops round to face you, and is+ happy again, a heart rising; then it settles into its usual stance."""+ foot_x, ground = backdrop(frame, draw, box, f, s, plan)+ p = f / span+ step, q = pm.step_of(p, CALM)+ pic = f // 2+ if step == 'back':+ put(frame, 'LookingAround', tap(back(), pic in (1, 4)), foot_x, ground)+ elif step == 'peek':+ k = pic - round(CALM[0][1] * span / 2)+ if k < 1:+ put(frame, 'Turning', back_quarter(), foot_x, ground)+ else:+ clawd(frame, 'Turning', 20, foot_x, ground, look='shut' if k == 6 else None)+ if k % 4 != 0: # a question mark over its head, blinking: is it over?+ pixel_text(draw, (foot_x - 6, ground - 27), '?', color=WONDER)+ elif step == 'turn':+ clawd(frame, 'Turning', 28 if q < .5 else 0, foot_x, ground)+ elif step == 'happy':+ clawd(frame, 'Excited', 3 if q < .06 else 4 if q < .12 else 5 + int(q * 32) % 16, foot_x, ground)+ else:+ clawd(frame, 'Excited', 21 if q < .2 else 22 if q < .4 else 6 if q < .8 else 0, foot_x, ground)+ pm.sparkle(draw, foot_x + 12, ground - 19, pm.twinkle(q))+ if step in ('happy', 'settle'): # one heart, big then small, rising+ a = (p - CALM[2][1]) / .45+ if 0 <= a < 1:+ h = pm.HEART_BIG if a < .6 else pm.HEART_SMALL+ x = foot_x + 2 + round(math.sin(a * math.pi * 2) * 1.5)+ paste(frame, h, x - h.width // 2, ground - 22 - round(16 * a) - h.height)+++# --- x5: a failed tool, a compaction --------------------------------------------------------------------------------++STAR, STAR_CORE = (255, 216, 92), (255, 250, 220)+++def stars_round(draw, cx, cy, f, n=3):+ """Little stars going round over a dizzy head, a step on each picture."""+ for k in range(n):+ a = 2 * math.pi * (k / n + f / 24)+ x, y = round(cx + 10 * math.cos(a)), round(cy + 2.5 * math.sin(a))+ draw.point((x, y), fill=STAR_CORE)+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):+ draw.point((x + dx, y + dy), fill=STAR)+++DIZZY = (('stand', .05), ('spin', .72), ('shake', .86), ('back', 1.0))+++def dizzy(frame, draw, box, f, span, active, s, plan, base):+ """A tool failed: Clawd's own Dizzy (spiral eyes, wobbling), stars going round over its head; it shakes it off+ with its eyes shut and stands again."""+ foot_x, ground = backdrop(frame, draw, box, f, s, plan)+ step, q = pm.step_of(f / span, DIZZY)+ if step == 'stand':+ clawd(frame, 'Dizzy', min(5, int(q * 6)), foot_x, ground)+ elif step == 'spin':+ clawd(frame, 'Dizzy', 6 + int(q * 40) % 24, foot_x, ground)+ stars_round(draw, foot_x + 1, ground - 21, f)+ elif step == 'shake':+ clawd(frame, 'Dizzy', 30 + min(5, int(q * 6)), foot_x, ground)+ else:+ clawd(frame, 'Dizzy', 36 + min(4, int(q * 5)), foot_x, ground)+++BUBBLE = ('.###.', '#####', '#####', '.###.', '.#...') # Clawd's own thought bubble, small+BUBBLE_SMALL = ('.#.', '###', '.#.')+SQUEEZE = (('stand', .06), ('hands', .12), ('squeeze', .72), ('drop', .78), ('fresh', 1.0))+++def squeeze(frame, draw, box, f, span, active, s, plan, base):+ """A compaction: Clawd puts its hands to its head and squeezes, eyes shut tight, trembling, three squeezes; each+ squeezes a thought bubble out of the top of its head (its own bubble's blue), which floats off and shrinks away;+ then hands down and a fresh ^ ^."""+ foot_x, ground = backdrop(frame, draw, box, f, s, plan)+ step, q = pm.step_of(f / span, SQUEEZE)+ stand = grid('LookingAround', 0)+ pic = f // 2+ if step == 'stand':+ clawd(frame, 'LookingAround', (0, 8)[pic % 2], foot_x, ground)+ elif step == 'hands':+ put(frame, 'LookingAround', hands_on_head(edited(stand, 'squeeze')), foot_x, ground)+ elif step == 'squeeze':+ k = (q * 3) % 1 # three squeezes: press (trembling), then ease+ press = k < .55+ jitter = (pic % 2) * 2 - 1 if press else 0+ put(frame, 'LookingAround', hands_on_head(edited(stand, 'squeeze'), press), foot_x + jitter, ground)+ if press and pic % 2 == 0: # the strain, flickering+ pm.stretch_marks(draw, foot_x, ground - 16, 12, 0)+ elif step == 'drop':+ put(frame, 'LookingAround', edited(stand, 'squeeze'), foot_x, ground)+ else:+ clawd(frame, 'Excited', 3 if q < .1 else 6, foot_x, ground)+ pm.sparkle(draw, foot_x + 12, ground - 19, pm.twinkle(q))+ start = round(SQUEEZE[1][1] * span / 2) # the bubbles: one a squeeze, popping at its height+ for n in range(3):+ age = pic - (start + 3 + n * 10)+ if 0 <= age < 9:+ side = (-1, 1, -1)[n]+ x = foot_x + side * (2 + age * 2)+ y = ground - 22 - age * 2+ b = pm.sprite(BUBBLE if age < 5 else BUBBLE_SMALL, {'#': (105, 154, 203)})+ if age < 8:+ paste(frame, b, x - b.width // 2, y - b.height)+++# --- which scene draws a moment ---------------------------------------------------------------------------------------++def sulk_haunted(frame, draw, box, f, span, active, s, plan, base):+ """Its back turned and a ghost about at once: the sulk, the ghost drifting round it (Clawd has no eyes for it)."""+ sulk(frame, draw, box, f, span, active, s, plan, base)+ draw_ghost(frame, f, span)+++# The two variants of each (moments.COURTS, moments.GHOSTS), one picked at random each time one begins, as the bows+# are: the courtroom's A, Judge Clawd's verdict on Clawd in the dock, or B, Clawd's own OBJECTION!; the ghost's A,+# drifting round Clawd's usual scene, or B, Clawd watching it go and waving.+SCENES = {('risky', COURTS[0]): court_guilty, ('risky', COURTS[1]): court_objection,+ ('deleted', GHOSTS[0]): ghost_drift, ('deleted', GHOSTS[1]): ghost_wave, ('rude', None): sulk,+ ('calm', None): calm, ('failed', None): dizzy, ('compact', None): squeeze}+++def scene_of(moment):+ """The scene that draws Clawd's phase-3a `moment` (a row's {'kind', 'style'?, 'ghost'?}), or None for any other.+ A moment without its style draws the first variant; the sulk with a ghost about, the two together."""+ kind = moment.get('kind')+ if kind == 'rude' and moment.get('ghost'):+ return sulk_haunted+ style = moment.get('style') or {'risky': COURTS[0], 'deleted': GHOSTS[0]}.get(kind)+ return SCENES.get((kind, style if kind in ('risky', 'deleted') else None))diff --git a/token_tv/display.py b/token_tv/display.pyindex 3582668..8329cb9 100644--- a/token_tv/display.py+++ b/token_tv/display.py@@ -27,7 +27,7 @@ BRAND = {'claude': ('#d97757',), 'codex': ('#2f3aa8', '#9aa0ff'), 'grok': ('#f2f'copilot': ('#36d8b4', '#1fa7e2', '#2563eb'), 'antigravity': ('#e77345', '#94c45f', '#4f83f2')}FONT_MAIN = '/usr/share/fonts/truetype/dejavu/DejaVuSans'FONT_NUMBERS = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono'-STYLES = ('pixel', 'digital', 'neon', 'retro', 'hud', 'space', 'gameboy', 'arcade', 'retro-dual')+STYLES = ('pixel', 'digital', 'neon', 'retro', 'hud', 'space', 'gameboy', 'arcade', 'retro-dual', 'survival')# Gauge-only levels; labels/percentages always use TEXT, logos retain provider ink.GAUGE_LEVELS = ((50, '#76a99a'), (80, '#93c9b9'), (90, '#d1b275'), (101, '#d8877e'))STATUS = {'loading': 'WAIT', 'auth_required': 'LOGIN', 'identity_mismatch': 'CHECK',diff --git a/token_tv/live.py b/token_tv/live.pyindex 68b6dc1..db28562 100644--- a/token_tv/live.py+++ b/token_tv/live.py@@ -24,10 +24,11 @@ from urllib.parse import parse_qs, urlparsefrom token_tv.device import FILES, BackupMismatch, open_displayfrom token_tv.catalog import payload as theme_payloadfrom token_tv.display import STYLES, overview_rows, render_page, watch_payload-from token_tv.arcade import LOOP_SECONDS, gif_delays, gif_seconds+from token_tv.arcade import LOOP_SECONDS, gif_delays, gif_seconds, word_readablefrom token_tv.events import EGG_SECONDSfrom token_tv.lockbox import Lockboxfrom token_tv import moments+from token_tv.seasons import season_at# 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,@@ -40,7 +41,8 @@ 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;+# ~142 ms (two 120 fps films); a GIF of red for 3000 ms then blue for 100 ms showed the owner red, then a blue flash+# (t1g, 2026-11-05); the first test GIF's "only red" was a broken GIF (its blue in a local colour table), not timing;# 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@@ -474,10 +476,10 @@ def unique_keys(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)."""+ """The moment a request body names: exactly {"moment": <one of moments.MOMENTS, or moments.WORD and one word of+ letters>}, 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:+ if not isinstance(data, dict) or set(data) != {'moment'} or not moments.known(data['moment']):raise ValueError('Not a moment')return data['moment']@@ -934,8 +936,9 @@ def main(argv=None, ready=None):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']+ """What a picture waiting for its loop's end was drawn from: the moments due, the readings in and Arcade's+ season (x8: one drawn as a season begins or ends is drawn again with the new date's props)."""+ return agents.count, readings['count'], season_at(time.time())def follow_clock():"""The clock to drive: the address in the config, read again each minute (`start` finding the clock, or@@ -1015,10 +1018,11 @@ def main(argv=None, ready=None):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):+ def show(image, name, digest, what, receipts, where, paced, readable):"""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."""+ agent's moment in it, `paced` when its pace ticks stand, `readable` whether its readout says the thinking+ word in `what` (said()). 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_uploadbegun, on = moments.CLOCK.now(), {}try:@@ -1032,7 +1036,7 @@ def main(argv=None, ready=None):last_upload = None # what the clock shows is unknown: the next picture goes in full, even this onedisplayed['what'] = unsureif 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'])+ agents.shown(what, on['at'], on['wall'], readable)elif what and what[0] == 'break': # still due: once more as the next loop ends (sync_moments), not beforefailed['break'] += 1failed['again'] = moments.loop_end(shown, moments.CLOCK.now() + .001) if failed['break'] == 1 else None@@ -1046,7 +1050,12 @@ def main(argv=None, ready=None):last_upload = (name, digest)pace['at'] = paceddisplayed['what'] = what- agents.shown(what, shown['at'], wall)+ agents.shown(what, shown['at'], wall, readable)++ def said(drawn, what):+ """Whether the picture of `drawn` (the snapshot with `what` on it) says the thinking word in `what` in a+ readout: not behind SLOW, BOO! or SULKING. A word's minute on the clock starts only once it does."""+ return bool(what and what[0] == 'state' and what[3]) and word_readable(drawn)def picture(snapshot, style, egg=None):"""(image, its file name, digest, when its pace ticks stand) for `snapshot` on `style`. Time passing alone@@ -1090,16 +1099,20 @@ def main(argv=None, ready=None):for _ in range(25): # a storm of moments still ends in a pictureseen = 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)+ # (The usual face's states, a ghost, the back turned or the thinking word, take nothing from a+ # one-off: it hides them for its loop.)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+ egg = None if style == 'arcade' and moments.urgent(agents.wanted()[0]) else quiet_loop+ elif entry and style == 'arcade' and moments.urgent(agents.wanted()[0]): # it came meanwhile: firstreturn Nonefollows = style == 'arcade' and egg is None # a one-off takes the whole loop: no moment in itwhat, since, mark = agents.wanted() if follows else (None, None, None)- image, name, digest, paced = picture(moments.overlay(snapshot, what, mark), style, egg)+ drawn = moments.overlay(snapshot, what, mark)+ image, name, digest, paced = picture(drawn, style, egg)+ readable = said(drawn, what)if (name, digest) == last_upload: # identical frames are not rewritten to flashdisplayed['what'] = what- agents.shown(what, shown['at'])+ agents.shown(what, shown['at'], readable=readable)breakif what is None: # a picture with an agent's moment in it is never keptwrite_private(state_dir / name, image)@@ -1113,7 +1126,7 @@ def main(argv=None, ready=None):if stopping.is_set():return deliveredcontinue # a moment or a reading changed while the loop played out: draw it in- show(image, name, digest, what, receipts, where, paced)+ show(image, name, digest, what, receipts, where, paced, readable)breakif what is None: # receipts say nothing of the agents' momentswrite_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "uploads": receipts})@@ -1206,7 +1219,9 @@ def main(argv=None, ready=None):if last_upload is None: # nothing of this run's on the clock yet (its first reading not in), or what itcycle(False) # shows is not known (a send failed): one in full, drawn from what TokenTV has, with thecontinue # moment, at once or as the loop it holds ends- image, name, digest, paced = picture(moments.overlay(base(), what, mark), 'arcade')+ drawn = moments.overlay(base(), what, mark)+ image, name, digest, paced = picture(drawn, 'arcade')+ readable = said(drawn, what)due = switch_at(shown, since, moments.CLOCK.now()) # the end of the loop that was playing when it became dueif due is not None and not hold(due, seen, what):if stopping.is_set():@@ -1214,10 +1229,10 @@ def main(argv=None, ready=None):continue # changed again while the loop played out: draw the newest insteadif (name, digest) == last_upload:displayed['what'] = what- agents.shown(what, shown['at'])+ agents.shown(what, shown['at'], readable=readable)continuetry:- show(image, name, digest, what, [], {}, paced)+ show(image, name, digest, what, [], {}, paced, readable)except (OSError, ValueError, KeyError, HTTPException) as error:agents.drop_bow() # (a break stays due)reason = problem_of(error)@@ -1230,15 +1245,15 @@ def main(argv=None, ready=None):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."""+ break included, which comes due with time alone (the usual face's states wait for the quiet loop's end)."""end = moments.CLOCK.now() + secondswhile not stopping.is_set() and moments.CLOCK.now() < end:kick.clear()- if agents.wanted()[0] != displayed['what']:+ if moments.urgent(agents.wanted()[0]):return Trueturn = 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']+ return stopping.is_set() or moments.urgent(agents.wanted()[0])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.@@ -1269,6 +1284,11 @@ def main(argv=None, ready=None):print("TokenTV easter egg skipped.", flush=True)return bool(went)+ def moment_on():+ """Whether an agent's moment is due or on the clock: no hidden one-off or replay starts then. The usual+ face's states (a ghost, the back turned, the thinking word) are no such moment: a one-off hides them."""+ return agents.busy() or (displayed['what'] is not unsure and moments.urgent(displayed['what']))+def read_usage():"""Read every account (a provider may take its time) apart from the clock's work, so that no agent's momentwaits for it: the moments keep their loop ends with the last reading. The clock is told once it is in."""@@ -1333,7 +1353,7 @@ def main(argv=None, ready=None):streaks[key] = 1 # history out of reach: the event still playspending.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)+ busy = moment_on()try:egg = (pending.pop(0) if pending else locks.pick(snap)) if arcade_on and not busy else Noneexcept (OSError, ValueError):@@ -1352,7 +1372,7 @@ def main(argv=None, ready=None):# 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)):+ while device and replays and not moment_on():check = replays.pop(0)egg = locks.replay(check)if egg and play(egg, mark=False) is None:@@ -1361,7 +1381,7 @@ def main(argv=None, ready=None):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)):+ if device and replays and not moment_on():continue # a replay waited for a moment that is over nowdue = 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)diff --git a/token_tv/moments.py b/token_tv/moments.pyindex 0757293..be94e8b 100644--- a/token_tv/moments.py+++ b/token_tv/moments.py@@ -1,17 +1,20 @@"""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.+the pets' break once an hour of work, and Clawd's phase-3a moments: the courtroom for a risky command, the ghost of a+deleted file, its back turned for a rude prompt, dizzy after a failed tool, squeezing its head on a compaction, and+Claude Code's own thinking word in the readout.++A moment arrives as its name and nothing else (MOMENTS, or WORD and one word of letters): 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 (a word included). 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 bisectimport jsonimport mathimport osimport random+import reimport socketimport sysimport threading@@ -19,7 +22,9 @@ import timefrom http.client import HTTPConnection, HTTPExceptionfrom pathlib import Path-MOMENTS = ('claude.ask', 'claude.answered', 'claude.end', 'codex.end', 'claude.pet', 'claude.snack')+MOMENTS = ('claude.ask', 'claude.answered', 'claude.end', 'codex.end', 'claude.pet', 'claude.snack',+ 'claude.risky', 'claude.deleted', 'claude.rude', 'claude.calm', 'claude.failed', 'claude.compact',+ 'claude.stop')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 notCOOLDOWN = 60 # at most one bow in any 60 s, Claude's and Codex's together; one asked for inside it is dropped@@ -31,6 +36,40 @@ RANDOM = random.Random() # picks each reminder's break, once (a test or a gradeBODY_LIMIT = 256 # bytes: the most a moment's request may carryWINDOWS = os.name == 'nt' # no TokenTV socket there: its port on this computer instead+# Phase 3a, from Claude Code (each name from the mod; nothing else of the call, the prompt or the session comes):+COURT_LIMIT = 24 * 60 * 60 # e3: one courtroom in any 24 hours, from the last one's start on the clock+COURT_STALE = 2 * 60 # a courtroom not on the clock this long after its command is dropped (a prompt left open)+COURTS = ('verdict', 'objection') # its two variants (claude_moments.py), one picked at random each time+GHOST = 60 # e4: a ghost floats a minute from the deletion; a fresh one meanwhile makes it a minute from that one+GHOSTS = ('drift', 'wave') # its two variants, one picked at random as it appears+BACK = 60 # e7: the back turned a minute from the rude prompt (a fresh one: from that one), or till a calm prompt+FACES = {'claude.failed': 'failed', 'claude.compact': 'compact'} # x5: one loop of dizzy, or of the squeeze...+FACE_COOLDOWN = 60 # ...at most one of the two in any 60 s, from the last one's start on the clock+WORD = 'claude.word:' # x6: Claude Code's own thinking word, one word of 1 to WORD_MAX letters A-Z after it+WORD_MAX = 14+WORD_FORM = re.compile(r'claude\.word:([A-Za-z]{1,%d})' % WORD_MAX)+WORD_INTERVAL = 60 # a new word on the clock at most once a minute, from one word's start to the next's+WORD_STALE = 30 * 60 # a word not said again for this long is let go (a session that ended without saying so)+++def word_of(name):+ """The thinking word a moment's name carries, in capitals ('claude.word:Pondering' -> 'PONDERING'), or None: one+ word of WORD_MAX ASCII letters at most, nothing before or after it."""+ found = WORD_FORM.fullmatch(name) if isinstance(name, str) else None+ return found.group(1).upper() if found else None+++def known(name):+ """Whether `name` is a moment TokenTV takes: one of MOMENTS, or WORD and its word."""+ return isinstance(name, str) and (name in MOMENTS or word_of(name) is not None)+++def urgent(what):+ """Whether `what` (as Moments.due() says it, or as the clock shows it) takes the clock from a one-off: any moment+ but the usual face and its states (a ghost, the back turned, the thinking word), which a one-off hides for its+ loop, their minutes running on meanwhile."""+ return what is not None and what[0] != 'state'+# 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.)@@ -266,9 +305,25 @@ class Moments: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.+ Phase 3a. A risky command brings the courtroom, one loop, at most once in COURT_LIMIT from the last one's start on+ the clock; one asked for while one is to show, or inside that day, is dropped (never kept for the day's end). It+ comes after a bow and a treat and before the break, and waits out a wait (a risky command is mostly one Claude+ Code asks you about), but only for COURT_STALE from its command: one not on the clock by then is dropped, and+ takes nothing of the day. A failed tool or a compaction brings one loop of a tool face, the lowest of the one-offs:+ under everything above, at most one in any FACE_COOLDOWN from the last one's start; one while another is to show+ or inside that minute is dropped, and so is one while Claude waits (a wait drops one not shown yet). The ghost+ (a minute from the last deletion), the back turned (a minute from the last rude prompt, or till a calm one) and+ the thinking word are states of the usual face, drawn together: every one-off hides them for its loop, their+ minutes running on; one over meanwhile is simply gone. When the back turned ends on the clock (not hidden), one+ loop of Clawd turning back round follows (dropped if anything else goes on first). Clawd does not bow while its+ back is turned: a turn's end then brings no bow, and a bow still to show goes as the back turns. The word shows+ from the moment it is said, a new one at most once in WORD_INTERVAL from the last new one's start readable on the+ clock (the newest waits for it, no others); a turn's end (claude.end, or claude.stop for one cut short) takes it+ away at once.+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)."""+ then; shown() is told when a picture went on the clock (a bow, a treat, the break or a phase-3a one-off 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@@ -284,23 +339,44 @@ class Moments:self.work = Work(active) # the hour of work toward the pets' breakself.calm = 0.0 # when the usual face last became dueself.count = 0 # goes up with every change of what is due, so a waiting publisher knows to look again+ self.court = None # (when the risky command came, which courtroom): one loop of it due at the loop's end+ self.courted = None # when the last courtroom went on the clock: COURT_LIMIT runs from there+ self.ghost = None # [when its minute is up, which ghost] while one floats about+ self.back = None # when the back turned's minute is up, while Clawd sulks+ self.forgiven = None # when Clawd turning back round fell due: one loop of it at the loop's end+ self.face = None # ('failed' or 'compact', when it came): one loop of a tool face due at the loop's end+ self.faced = None # when the last tool face went on the clock: FACE_COOLDOWN runs from there+ self.word = None # Claude Code's thinking word to show now, in capitals+ self.word_next = None # a newer one, waiting for WORD_INTERVAL from the last new word's start+ self.word_at = None # when the last new word went on the clock, readable in the readout...+ self.word_shown = None # ...and which word that was+ self.heard = None # when the word (or the newer one) was last said: let go WORD_STALE after+ self.settled = 0.0 # when the usual face's states (the ghost, the back turned, the word) last changeddef 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:+ """Take one moment by name; True when it changed what the clock should show. Unknown names: ValueError. The+ publisher is woken for a change, and for one that changes nothing yet but comes sooner than it would look+ again (next_change(): a newer word waiting for its minute)."""+ word = word_of(name)+ if name not in MOMENTS and word is None: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 laterreturn Falsewith self.lock:now = CLOCK.now()- self.expire(now)- before = self.due(now)[0]- if name == 'claude.ask':+ wall = self.walls(now)+ self.expire(now, wall)+ before, soon = self.due(now)[0], self.soonest(now, wall)+ if word is not None:+ self.say(word, now)+ elif 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+ # A wait outranks them; one put off is dropped, not kept for later (a courtroom waits it out, for+ # COURT_STALE at most).+ self.bow = self.treat = self.face = self.forgiven = Noneelif name == 'claude.answered':if self.waits: # (an answer with none counted, from a wait already let go, closes nothing)self.waits -= 1@@ -310,12 +386,42 @@ class Moments: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())+ elif name == 'claude.risky':+ if not (self.court or (self.courted is not None and now - self.courted < COURT_LIMIT)):+ self.court = (now, RANDOM.choice(COURTS))+ elif name == 'claude.deleted':+ if self.ghost: # still about: a minute from this one, the same ghost and picture+ self.ghost[0] = now + GHOST+ else:+ self.ghost = [now + GHOST, RANDOM.choice(GHOSTS)]+ self.settled = max(self.settled, now)+ elif name == 'claude.rude':+ if self.back is None:+ self.settled = max(self.settled, now)+ self.back = now + BACK # (a fresh one: a minute from this one)+ self.forgiven = None+ if self.bow and self.bow[0] == 'claude': # a sulking Clawd does not bow, not even for a turn before+ self.bow = None+ elif name == 'claude.calm':+ if self.back is not None:+ self.turn_round(now)+ elif name in FACES:+ if not (self.waits or self.face or (self.faced is not None and now - self.faced < FACE_COOLDOWN)):+ self.face = (FACES[name], now)+ elif name == 'claude.stop': # a turn cut short: its word goes, and nothing bows+ self.unsay(now)+ else: # a turn done: its word goes, and its pet bows unless a wait or the bows' minute says no (or Clawd+ # sulks: its back turned, the rude prompt's own turn included)+ if name == 'claude.end':+ self.unsay(now)+ if not (self.waits or self.bow or self.cooling(now) or (service == 'claude' and self.back is not None)):+ self.bow = (service, now, time.time())changed = self.due(now)[0] != beforeif changed:self.count += 1- if changed and self.wake:+ sooner = self.soonest(now, wall)+ woken = changed or (sooner is not None and (soon is None or sooner < soon))+ if woken and self.wake:self.wake()return changed@@ -338,6 +444,34 @@ class Moments:"""The wall clock's time at CLOCK's `now`: the readings' times are its."""return time.time() - (CLOCK.now() - now)+ def say(self, word, now):+ """Claude Code's thinking word `word` (a turn is going): in place of the usual one from now, or, inside+ WORD_INTERVAL of the last new word's start on the clock, once that is up (the newest only). The same word+ again changes nothing (and a newer one waiting gives way to it)."""+ self.heard = now+ if word == self.word:+ self.word_next = None+ elif self.word_at is None or now - self.word_at >= WORD_INTERVAL:+ self.word, self.word_next = word, None+ self.settled = max(self.settled, now)+ else:+ self.word_next = word++ def unsay(self, at):+ """The turn is over at `at`: its word goes, whatever WORD_INTERVAL says, and one waiting goes with it. The+ next word on the clock, the same one again included, is a new word's start (WORD_INTERVAL from this one's)."""+ if self.word is not None:+ self.settled = max(self.settled, at)+ self.word = self.word_next = self.word_shown = None++ def turn_round(self, at):+ """The back turned is over at `at` (a calm prompt, or its minute up): Clawd turns back round for one loop if+ the clock was showing the sulk; not for a sulk it never showed, nor one a moment had hidden."""+ self.back = None+ self.settled = max(self.settled, at)+ if self.on and self.on[0] == 'state' and self.on[2]:+ self.forgiven = at+def expire(self, now, wall=None):if self.waits and self.since + EXPIRE <= now: # waited EXPIRE in all: every wait counted is let goself.calm = self.since + EXPIRE # due from the deadline itself, however late it is looked at@@ -347,6 +481,24 @@ class Moments:self.work.advance(self.walls(now) if wall is None else wall)if self.work.due != due: # the hour of work is doneself.count += 1+ if self.court and self.court[0] + COURT_STALE <= now: # not on the clock in time: news no more+ self.court = None+ self.count += 1+ # The usual face's states, each changed from its own deadline, however late it is looked at.+ if self.ghost and self.ghost[0] <= now:+ self.settled = max(self.settled, self.ghost[0])+ self.ghost = None+ self.count += 1+ if self.back is not None and self.back <= now:+ self.turn_round(self.back)+ self.count += 1+ if self.word_next is not None and self.word_at + WORD_INTERVAL <= now:+ self.settled = max(self.settled, self.word_at + WORD_INTERVAL)+ self.word, self.word_next = self.word_next, None+ self.count += 1+ if (self.word or self.word_next) and self.heard + WORD_STALE <= now:+ self.unsay(self.heard + WORD_STALE)+ self.count += 1def cooling(self, now):return self.bowed is not None and now - self.bowed < COOLDOWN@@ -360,8 +512,10 @@ class Moments:return now - (wall - at), kinddef due(self, now):- """(what, since when): ('needs', level), ('done', service), ('treat', 'pet' or 'snack'), ('break', 'drink' or- 'stretch'), or None for the usual face."""+ """(what, since when): ('needs', level), ('done', service), ('treat', 'pet' or 'snack'), ('risky', which+ courtroom), ('break', 'drink' or 'stretch'), ('calm',) for the turn back round, ('face', 'failed' or+ 'compact'), or the usual face: ('state', which ghost or None, the back turned?, the word or None) with any+ of those on it, else None."""if self.waits:waited = now - self.sincelevel = 3 if waited >= SIGN else 2 if waited >= HOP else 1@@ -370,10 +524,19 @@ class Moments:return ('done', self.bow[0]), self.bow[1]if self.treat:return ('treat', self.treat[0]), self.treat[1]+ if self.court:+ return ('risky', self.court[1]), self.court[0]rest = self.resting(now)if rest: # due since the hour was done, or since what kept it off the clock endedreturn ('break', rest[1]), max(rest[0], self.calm)- return None, self.calm+ if self.forgiven is not None:+ return ('calm',), self.forgiven+ if self.face:+ return ('face', self.face[0]), self.face[1]+ ghost = self.ghost[1] if self.ghost else None+ if ghost or self.back is not None or self.word:+ return ('state', ghost, self.back is not None, self.word), max(self.calm, self.settled)+ return None, max(self.calm, self.settled)def wanted(self, now=None):"""(what, since when, the row's `moment` for the drawing or None) for the clock now."""@@ -387,6 +550,15 @@ class Moments:mark = {'kind': 'needs', 'since': self.started, 'level': what[1]}elif what[0] == 'done':mark = {'kind': 'done', 'at': self.bow[2]}+ elif what[0] == 'risky':+ mark = {'kind': 'risky', 'style': what[1]}+ elif what[0] == 'calm':+ mark = {'kind': 'calm'}+ elif what[0] == 'state': # what goes on Clawd's rows: the sulk (with the ghost round it) or the ghost+ _, ghost, back, word = what+ moment = (dict({'kind': 'rude'}, **({'ghost': ghost} if ghost else {})) if back else+ {'kind': 'deleted', 'style': ghost} if ghost else None)+ mark = {'moment': moment, 'word': word}else:mark = {'kind': what[1]}return what, since, mark@@ -401,30 +573,51 @@ class Moments:return now - self.since if self.waits else Nonedef 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."""+ """When what is due changes by itself (a wait grows more insistent or is let go, the hour of work is done, a+ courtroom not shown in time is dropped, a ghost's or the back turned's minute is up, a newer word's minute has+ come, a word goes stale); None when nothing will."""with self.lock:now = CLOCK.now() if now is None else nowwall = 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+ return self.soonest(now, wall)++ def soonest(self, now, wall):+ """next_change() at `now` (`wall` on the wall clock), with the lock held and expire() done."""+ 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))+ if self.court:+ times.append(self.court[0] + COURT_STALE)+ if self.ghost:+ times.append(self.ghost[0])+ if self.back is not None:+ times.append(self.back)+ if self.word_next is not None:+ times.append(self.word_at + WORD_INTERVAL)+ if self.word or self.word_next:+ times.append(self.heard + WORD_STALE)+ return min(times) if times else Nonedef busy(self):- """Whether a wait, a bow, a treat or the break is due: the hidden one-offs keep out of their way."""+ """Whether a wait, a bow, a treat, the break or one of phase 3a's one-offs is due: the hidden one-offs keep+ out of their way (not out of the usual face's states: a one-off hides those for its loop)."""with self.lock:now = CLOCK.now()self.expire(now)- return bool(self.waits or self.bow or self.treat or self.resting(now))+ return bool(self.waits or self.bow or self.treat or self.resting(now) or self.court or self.face+ or self.forgiven is not None)- 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."""+ def shown(self, what, at, wall=None, readable=True):+ """The clock started showing `what` at `at` (CLOCK; `wall`, the wall clock then): a bow, a treat, the break or+ a phase-3a one-off plays that one loop, and what follows is due after it; a new word on it starts its minute,+ if it is `readable` there: a readout's label (the publisher knows from the picture: SLOW may take the label)."""with self.lock:self.on = what+ if self.forgiven is not None and what != ('calm',): # something else went on first: no turning round+ self.forgiven = None+ self.count += 1if not what:returnif what[0] == 'done' and self.bow and self.bow[0] == what[1]:@@ -437,24 +630,48 @@ class Moments:self.work.shown(self.walls(at) if wall is None else wall)self.calm = atself.count += 1+ elif what[0] == 'risky' and self.court and self.court[1] == what[1]:+ self.court, self.courted, self.calm = None, at, at+ self.count += 1+ elif what == ('calm',):+ self.forgiven, self.calm = None, at+ self.count += 1+ elif what[0] == 'face' and self.face and self.face[0] == what[1]:+ self.face, self.faced, self.calm = None, at, at+ self.count += 1+ elif (what[0] == 'state' and what[3] and what[3] != self.word_shown and not (what[1] or what[2])+ and readable):+ self.word_at, self.word_shown = at, what[3] # a new word's start on the clock, readable there (the+ # ghost's BOO!, the sulk's SULKING and SLOW say their own word instead: it starts once it shows)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)."""+ hold the next one back; so is a pet or a snack, and a phase-3a one-off (a courtroom not shown takes nothing+ of its day). 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). The ghost, the back turned and the word stay, their minutes+ running on."""with self.lock:- if self.bow or self.treat:- self.bow = self.treat = None+ if self.bow or self.treat or self.court or self.face or self.forgiven is not None:+ self.bow = self.treat = self.court = self.face = self.forgiven = Noneself.count += 1def 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."""+ """`snapshot` with the moment on the rows of its service (Claude's wait, treat or phase-3a moments, or the+ service that bows), or on every row for the break: a copy, for drawing only. The usual face's states go on+ Claude's rows as their moment and the thinking word as the row's 'word'. 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]+ if what[0] == 'state':+ def marked(row):+ row = dict(row, moment=dict(mark['moment'])) if mark.get('moment') else dict(row)+ return dict(row, word=mark['word']) if mark.get('word') else row+ accounts = {key: marked(row) if row.get('provider') == 'claude' else row+ for key, row in snapshot.get('accounts', {}).items()}+ return dict(snapshot, accounts=accounts)+ claude = ('needs', 'treat', 'risky', 'calm', 'face')+ service = None if what[0] == 'break' else 'claude' if what[0] in claude else what[1]accounts = {key: dict(row, moment=dict(mark)) if service in (None, row.get('provider')) else rowfor key, row in snapshot.get('accounts', {}).items()}return dict(snapshot, accounts=accounts)diff --git a/token_tv/pet_moments.py b/token_tv/pet_moments.pyindex 90aa35e..50012f8 100644--- a/token_tv/pet_moments.py+++ b/token_tv/pet_moments.py@@ -63,6 +63,8 @@ def leaning(build, args, pivot, dx):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)+ if art.info.get('pet'): # a leaning pet is still the pet (its season's hat: seasons.py)+ out.info['pet'] = art.info['pet']return out, (pivot[0] + (abs(dx) if dx < 0 else 0), pivot[1])@@ -248,7 +250,7 @@ def clawd_art(name, index, eyes=None):values[low * w + x] = darkart = Image.new('RGBA', (w, h))art.putdata([(0, 0, 0, 0) if v == 255 else palette[v] + (255,) for v in values])- return art+ return arcade.tag(art, 'claude')def clawd_pivot(name, index, eyes=None, grounded=False):diff --git a/token_tv/sample.py b/token_tv/sample.pyindex 72fb997..eccd55e 100644--- a/token_tv/sample.py+++ b/token_tv/sample.py@@ -10,6 +10,8 @@ SAMPLE = [('grok_a', 'GROK A', 'grok', [('BUDGET', 61, 6 * D + 2 * H)]),('grok_b', 'GROK B', 'grok', [('BUDGET', 18, 12 * D + 3 * H)]),]+# The sample accounts' use today, as a share of an even day (the Survival face's bar; a live one counts it, state.py).+TODAY = {'claude_a': 1.3, 'claude_b': .45, 'claude_c': .8, 'codex_a': .6, 'codex_b': .2, 'grok_a': .35, 'grok_b': .1}def snapshot(now=None, sample=SAMPLE):@@ -21,5 +23,7 @@ def snapshot(now=None, sample=SAMPLE):row['fetched_at'] = row['last_success_at'] = nowfor window in row['windows']:window['resets_at'] = None if window['resets_in'] is None else now + window['resets_in']+ if sample is SAMPLE and key in TODAY:+ row['today'] = TODAY[key]accounts[key] = rowreturn {'schema': 1, 'updated_at': now or 0, 'accounts': accounts}diff --git a/token_tv/seasons.py b/token_tv/seasons.pynew file mode 100644index 0000000..03ff6ad--- /dev/null+++ b/token_tv/seasons.py@@ -0,0 +1,274 @@+"""Arcade's seasonal props (x8), as the owner approved them (drafts w34-w37, 2026-11-05): on Halloween (10-25 to+11-01), Christmas (12-18 to 12-26) and Seollal (the day before the Korean lunar new year to the day after), endpoints+included, on the computer's local date, Arcade dresses its pets for the season by itself. Behind each scene's pet and+gauge goes the season's scenery (bats and pumpkin lanterns; falling snow and a small tree; a yut set and a lucky+pouch), clear of every gauge, and on each pet its hat (a witch's, Santa's, a saekdong cap); at Seollal Clawd, the+cloud and Copilot fly a shield kite. The pets keep their own form: only props are added. Every moment keeps the+season on (a hat waits while its pet spins), Judge Clawd keeps its wig; the hidden one-offs and the two events (a+reset's fireworks, a flop) are drawn as ever. On any other day Arcade is as it always was, byte for byte.++arcade.py draws them: arcade_frames dresses each scene it draws (Dress, in arcade.SEASON for its thread), each+backdrop then calls scenery(), and arcade.paste() calls wear() for art tagged with its pet (its info['pet']).+Everything is drawn on the scene's 120 x 71 stage, which Arcade doubles; every moving prop meets its loop's start.+"""+import datetime+import functools+import math+import random+import time++from PIL import ImageDraw++from token_tv import arcade+from token_tv.pet_moments import sprite++HALLOWEEN = ((10, 25), (11, 1))+CHRISTMAS = ((12, 18), (12, 26))+# The lunar new year in Korea (설날), by the Korean calendar, not China's: the new moon can fall either side of+# midnight between the two, and in 2027 (CN 02-06) and 2028 (CN 01-26, the new moon at 00:12 KST on 01-27) China's+# comes a day earlier. From KASI (한국천문연구원, Korea's official calendar), its lunar-to-solar conversion of each year's+# first lunar day (astro.kasi.re.kr/life/lunc?yyyy=<year>&mm=01&dd=01), read 2026-11-05. A year after 2040 needs its+# line here: until then it has no Seollal props.+SEOLLAL = {year: datetime.date(year, month, day) for year, (month, day) in {+ 2026: (2, 17), 2027: (2, 7), 2028: (1, 27), 2029: (2, 13), 2030: (2, 3), 2031: (1, 23), 2032: (2, 11),+ 2033: (1, 31), 2034: (2, 19), 2035: (2, 8), 2036: (1, 28), 2037: (2, 15), 2038: (2, 4), 2039: (1, 24),+ 2040: (2, 12)}.items()}+SEOLLAL_DAYS = (-1, 0, 1) # the day before the lunar new year, the day, the day after+++def season_on(day):+ """The season Arcade dresses for on `day` (a date): 'halloween', 'christmas', 'seollal', or None for every other+ day."""+ if HALLOWEEN[0] <= (day.month, day.day) <= HALLOWEEN[1]:+ return 'halloween'+ if CHRISTMAS[0] <= (day.month, day.day) <= CHRISTMAS[1]:+ return 'christmas'+ new_year = SEOLLAL.get(day.year)+ if new_year and (day - new_year).days in SEOLLAL_DAYS:+ return 'seollal'+ return None+++def season_at(now=None):+ """The season of this computer's local date at `now` (time.time() when None), as the night's dimming reads it."""+ return season_on(datetime.date.fromtimestamp(time.time() if now is None else now))+++class Dress:+ """What the scene being drawn wears: the `season`, and the scene's own `provider`, frame `f` of its turn of `span`+ frames, at work or not (`active`), how many scene frames each picture moves (`speed`), and the `stage` image."""+ __slots__ = ('season', 'provider', 'f', 'span', 'active', 'speed', 'stage')++ def __init__(self, season, provider, f, span, active, speed, stage):+ self.season, self.provider, self.f, self.span = season, provider, f, span+ self.active, self.speed, self.stage = active, speed, stage+++# --- the props, one pixel a cell on the 120 x 71 stage, each drawn for TokenTV in colour -----------------------------++WITCH_INK = {'K': (92, 56, 150), 'k': (132, 92, 200), 'B': (255, 150, 50), 'Y': (255, 220, 90)}+SANTA_INK = {'R': (226, 48, 60), 'W': (248, 248, 252)}+CAP_INK = {'T': (230, 50, 70), 'R': (236, 70, 90), 'Y': (255, 206, 70), 'G': (84, 186, 108), 'B': (70, 128, 230),+ 'P': (255, 140, 180)}+PUMPKIN_INK = {'O': (240, 128, 40), 'Y': (255, 226, 110), 'G': (100, 160, 60)}+BAT_INK = {'B': (130, 92, 186), 'E': (255, 210, 90)}+TREE_INK = {'Y': (255, 214, 80), 'G': (60, 170, 90), 'g': (40, 128, 72), 'r': (240, 70, 80), 'b': (90, 150, 255),+ 'T': (130, 84, 50)}+POUCH_INK = {'R': (236, 72, 108), 'r': (186, 44, 80), 'Y': (255, 205, 80)}+KITE_INK = {'W': (248, 246, 236), 'R': (230, 50, 70), 'B': (70, 128, 230), 'S': (196, 170, 120)}+YUT_INK = {'L': (236, 204, 150), 'K': (120, 70, 40), 'D': (178, 118, 66), 'd': (210, 150, 92)}+SNOW, SNOW_FAR = (240, 244, 255), (150, 160, 190)+STRING = (210, 210, 220)++PROPS = {+ 'witch': ('.......kK..', '......kKK..', '.....kKKK..', '....kKKKK..', '....kKKKKK.', '...BBBYBBB.', 'KKKKKKKKKKK'),+ 'witch_small': ('....K..', '...KK..', '..KKK..', '..BYBB.', 'KKKKKKK'),+ 'santa': ('........WW.', '.......RWW.', '......RR...', '....RRRR...', '...RRRRRR..', '..RRRRRRRR.', '.WWWWWWWWW.'),+ 'santa_small': ('.....W.', '...RRW.', '..RRR..', '.RRRRR.', 'WWWWWWW'),+ 'cap': ('...TTT...', '..RRRRR..', '.RYYYYYR.', 'PGGGGGGGP', 'BBBBBBBBB'),+ 'cap_small': ('..T..', '.RRR.', 'YYYYY', 'BBBBB'),+ 'pumpkin': ('....G....', '.OOOGOOO.', 'OOYOOOYOO', 'OYYOOOYYO', 'OOOOOOOOO', 'OYOYYYOYO', 'OOYYYYYOO', '.OOOOOOO.'),+ 'pumpkin_small': ('...G...', '.OOGOO.', 'OYOOOYO', 'OOOOOOO', 'OYYYYYO', '.OOOOO.'),+ 'bat_up': ('B.......B', 'BB.B.B.BB', '.BBEBEB..', '...BBB...'),+ 'bat_down': ('...B.B...', '..BEBEB..', '.BBBBBBB.', 'B.......B'),+ 'tree': ('....Y....', '...YYY...', '....G....', '...GGg...', '..GGrGg..', '...GGg...', '..GGGGg..', '.GGbGGGg.',+ '..GGGGg..', '.GGGGGGg.', 'GGGGGGrGg', '....T....'),+ 'pouch': ('..Y.Y..', '.RRYRR.', '..rRr..', '.RRRRR.', 'RRRYRRR', 'RRYYYRR', 'RRRYRRr', '.rRRRr.'),+ 'kite': ('WWWWWWWWW', 'WWWRRRWWW', 'WWRRRRRWW', 'WWWRRRWWW', 'WWS...SWW', 'WS.....SW', 'WWS...SWW', 'WWWWWWWWW',+ 'BBWWWWWBB', 'BBBWWWBBB'),+ 'yut': ('LLL.DDD.LLL.DDD', 'KLK.DdD.KLK.DdD', 'LKL.DdD.LKL.DdD', 'KLK.DdD.KLK.DdD', 'LLL.DdD.LLL.DdD',+ 'KLK.DdD.KLK.DdD', 'LKL.DdD.LKL.DdD', 'KLK.DdD.KLK.DdD', 'LLL.DDD.LLL.DDD'),+}+PROP_INK = {'witch': WITCH_INK, 'witch_small': WITCH_INK, 'santa': SANTA_INK, 'santa_small': SANTA_INK, 'cap': CAP_INK,+ 'cap_small': CAP_INK, 'pumpkin': PUMPKIN_INK, 'pumpkin_small': PUMPKIN_INK, 'bat_up': BAT_INK,+ 'bat_down': BAT_INK, 'tree': TREE_INK, 'pouch': POUCH_INK, 'kite': KITE_INK, 'yut': YUT_INK}+HATS = {'halloween': 'witch', 'christmas': 'santa', 'seollal': 'cap'}++[email protected]_cache(maxsize=None)+def prop(name):+ return sprite(PROPS[name], PROP_INK[name])+++def put(frame, art, x, y):+ frame.paste(art, (round(x), round(y)), art)+++def stamp(frame, name, cx, bottom):+ """A prop standing with its bottom middle at (cx, bottom)."""+ art = prop(name)+ put(frame, art, round(cx - art.width / 2), bottom - art.height)+++SKIP = {'claude': ((97, 0, 119, 27),), 'grok': ((100, 2, 119, 20),), 'copilot': ((0, 0, 119, 22),),+ 'antigravity': ((10, 14, 20, 24), (100, 14, 110, 24), (100, 46, 110, 56), (10, 46, 20, 56))}+# what the snow and the bats keep clear of: Claude's moon and its 5H, Grok's Earth, Copilot's five clouds, Anti's four+# pellets+++def clear_of(provider, x0, y0, x1, y1):+ return not any(x0 <= b[2] and b[0] <= x1 and y0 <= b[3] and b[1] <= y1 for b in SKIP.get(provider, ()))+++def laps(dress, pictures):+ """How many times something that takes `pictures` pictures goes round in the scene's turn: a whole number, so the+ loop meets its start (at least once)."""+ return max(1, round(dress.span / (pictures * dress.speed)))+++def snow(dress, draw, box):+ """Snow falling the stage's height in about 30 pictures (4 s on an SD_PRO), a whole number of times a turn so the+ loop meets its start; a third of the flakes far off (dim), a few big (a small plus); none on the gauges."""+ x, y, w, h = box+ f, span, provider = dress.f, dress.span, dress.provider+ rnd = random.Random(7)+ cycles = laps(dress, 30)+ for k in range(26):+ fx0, fy0, far = rnd.randrange(w), rnd.randrange(h), k % 3 == 0+ fall = (fy0 + f * h * cycles / span) % h+ drift = round(math.sin(2 * math.pi * (f / span * cycles + k / 7)) * 1.5)+ fx, fy = x + (fx0 + drift) % w, y + int(fall)+ if not clear_of(provider, fx - 1, fy - 1, fx + 1, fy + 1):+ continue+ if far:+ draw.point((fx, fy), fill=SNOW_FAR)+ elif k % 4 == 1: # a bigger flake: a small plus+ draw.point((fx, fy), fill=SNOW)+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):+ draw.point((fx + dx, fy + dy), fill=SNOW_FAR)+ else:+ draw.point((fx, fy), fill=SNOW)+++def bats(dress, frame, lanes):+ """Bats crossing the sky along `lanes` [(height, start, direction)], one crossing a lap of about 40 pictures, the+ wings up and down about every other picture (an even number of flaps a turn, so the loop meets its start)."""+ f, span = dress.f, dress.span+ cycles = laps(dress, 40)+ flaps = 2 * laps(dress, 4)+ for k, (ly, start, way) in enumerate(lanes):+ p = (f / span * cycles + start) % 1+ bx = round(-10 + p * 140) if way > 0 else round(130 - p * 140)+ by = ly + round(math.sin(2 * math.pi * (p * 3 + k / 3)) * 2)+ art = prop('bat_up' if (int(f / span * flaps) + k) % 2 else 'bat_down')+ if clear_of(dress.provider, bx - 5, by - 4, bx + 5, by + 1):+ put(frame, art, bx - art.width // 2, by - art.height)+++def kite(dress, frame, draw, at, hand):+ """The shield kite (방패연: the hole in its middle, the red disc on top) swaying at `at` (its top middle), its line+ sagging down to `hand`."""+ f, span = dress.f, dress.span+ cycles = laps(dress, 60)+ sway = round(math.sin(2 * math.pi * f / span * cycles) * 1.5)+ kx, ky = at[0] + sway, at[1] + round(math.sin(2 * math.pi * f / span * cycles + 1) * 1)+ art = prop('kite')+ tail = (kx, ky + art.height - 1)+ steps = 12+ for k in range(steps + 1): # the line, sagging a little between the kite and the hand+ t = k / steps+ lx = tail[0] + (hand[0] - tail[0]) * t+ ly = tail[1] + (hand[1] - tail[1]) * t + math.sin(math.pi * t) * 3+ draw.point((round(lx), round(ly)), fill=STRING)+ put(frame, art, kx - art.width // 2, ky)+++HALLOWEEN_LANES = {'claude': ((16, 0, 1), (30, .55, 1)), 'codex': ((38, 0, -1), (30, .5, 1)),+ 'grok': ((12, .2, 1), (26, .7, 1)), 'copilot': ((28, 0, 1), (34, .5, -1)),+ 'antigravity': ((14, 0, 1),)}+TREE_SPOT = {'claude': 86, 'codex': 96, 'grok': 44, 'antigravity': 34} # where each scene's tree stands, clear of it+++def scenery(dress, draw, box, ground):+ """Behind the pet and its gauge, as a backdrop ends (`ground`: where its scene's ground is): the season's things in+ this scene, each clear of the gauge."""+ frame, provider = dress.stage, dress.provider+ x, y, w, h = box+ if dress.season == 'christmas':+ snow(dress, draw, box)+ if provider == 'copilot': # its tree on a little cloud of its own+ arcade.cloud(draw, x + 98, y + 62, 4)+ stamp(frame, 'tree', x + 98, y + 61)+ elif provider in TREE_SPOT:+ stamp(frame, 'tree', x + TREE_SPOT[provider], ground)+ elif dress.season == 'halloween':+ bats(dress, frame, HALLOWEEN_LANES.get(provider, ()))+ if provider == 'claude':+ stamp(frame, 'pumpkin', x + 80, ground + 1)+ stamp(frame, 'pumpkin_small', x + 92, ground + 1)+ elif provider == 'codex':+ stamp(frame, 'pumpkin', x + 24, ground + 1)+ stamp(frame, 'pumpkin_small', x + 96, ground + 1)+ elif provider == 'grok':+ stamp(frame, 'pumpkin', x + 44, ground)+ elif provider == 'antigravity': # the maze's bonus fruit this week: a pumpkin on the floor+ stamp(frame, 'pumpkin', x + 86, ground)+ elif dress.season == 'seollal':+ if provider == 'claude':+ stamp(frame, 'yut', x + 84, ground + 1)+ elif provider == 'codex':+ stamp(frame, 'pouch', x + 24, ground + 1)+ elif provider == 'grok':+ stamp(frame, 'pouch', x + 44, ground)+ elif provider == 'copilot':+ arcade.cloud(draw, x + 98, y + 62, 4)+ stamp(frame, 'pouch', x + 98, y + 61)+ elif provider == 'antigravity': # a game of yut on the maze floor, and the pouch by it+ stamp(frame, 'yut', x + 32, ground)+ stamp(frame, 'pouch', x + 88, ground)+++def crown(art):+ """Where a pet's head is in its art: the middle of its top and the top row, found in the middle of its width (so+ Clawd's arms up in the air are not taken for its head)."""+ w, h = art.size+ alpha = art.getchannel('A')+ band = alpha.crop((round(w * .3), 0, round(w * .7), h)).getbbox()+ top = band[1] if band else 0+ row = alpha.crop((0, top, w, top + 2)).getbbox() or (0, 0, w, 2)+ return (row[0] + row[2]) / 2, top+++def wear(dress, frame, art, x, y):+ """On the pet `art` just pasted at (x, y): its hat, the brim over the top row of its head; and, at Seollal, the kite+ on a line held by Clawd, the cloud or Copilot. Only the scene's own pet; a pet spinning past 30 degrees (a+ break-dance) has its hat back once it is upright again."""+ provider = art.info.get('pet')+ if provider != dress.provider:+ return+ turn = art.info.get('turn', 0) % 360+ if min(turn, 360 - turn) > 30:+ return+ cx, top = crown(art)+ hat = prop(HATS[dress.season] + ('' if art.width >= 14 else '_small'))+ sink = 1 if provider != 'antigravity' else 0+ put(frame, hat, round(x + cx - hat.width / 2), y + top + sink - hat.height + (1 if provider == 'claude' else 0))+ if dress.season == 'seollal' and provider in ('claude', 'codex', 'copilot') and art.width >= 14:+ draw = ImageDraw.Draw(frame)+ if provider == 'claude': # held in its right hand (the arm at the side of its body)+ hand = (x + art.width - 2, y + art.height - 9)+ kite(dress, frame, draw, (min(hand[0] + 22, 84), 4), hand)+ elif provider == 'codex': # tied under the cloud+ kite(dress, frame, draw, (min(x + art.width + 18, 108), 24), (x + art.width - 6, y + art.height - 3))+ else:+ kite(dress, frame, draw, (106, 22), (x + art.width - 2, y + art.height - 6))diff --git a/token_tv/state.py b/token_tv/state.pyindex d4dae3e..1cce182 100644--- a/token_tv/state.py+++ b/token_tv/state.py@@ -6,6 +6,7 @@ from concurrent.futures import ThreadPoolExecutorfrom fractions import Fractionfrom token_tv.sources import STALE_SECONDS, fetch_account+from token_tv.usage import even_day, today_window, window_minutes# An account counts as working for this long after its used % last went up. It outlasts the slowest# fetch below, so a steady worker keeps running between readings.@@ -130,6 +131,86 @@ def lasting(row, slow, now, good):return kept+# x7: today's use, for the survival HUD's bar, read from one window (usage.today_window: its week over its 5 hours) on+# this computer's local date. It is the sum over the day's windows (a window is one reset period, new_window) of each+# one's last reading less its first that day, in the window's points: a window that began today counts from nothing,+# and for the one the day began in, a reading taken within DAY_EDGE before midnight (TokenTV was reading then) stands+# for midnight. Any fall within a window is a correction. The row's 'today' is that as a share of an even day+# (usage.even_day: a seventh of a week). It goes into the state folder with the snapshot, so a restart mid-day keeps it.+DAY_EDGE = 15 * 60+DAY_FIELDS = {"date": str, "label": str, "minutes": int, "base": (int, float), "used": (int, float),+ "at": (int, float), "carried": (int, float)}+++def day_start(at):+ """The local midnight that began `at`'s day."""+ t = time.localtime(at)+ return time.mktime((t.tm_year, t.tm_mon, t.tm_mday, 0, 0, 0, 0, 0, -1))+++def day_of(at):+ return time.strftime("%Y-%m-%d", time.localtime(at))+++def new_window(day, value):+ """Whether the reading `value` is of a new window, not the one `day` follows: its reset time moved later than+ same_window allows, or, with no reset time known, its use fell to under half and below 10 %."""+ was, resets = day.get("resets_at"), value.get("resets_at")+ if was is not None and resets is not None:+ return resets - was > SAME_WINDOW+ return value["used_percent"] < min(10, day["used"] / 2)+++def day_step(day, value, at):+ """An account's day after a good reading `value` of the window today's use is read from (of a known length),+ measured at `at`: {'date', 'label', 'minutes', 'resets_at', 'base', 'used', 'at', 'carried'}. Today's use is+ 'used' (the window's last reading) less 'base' (its first today, or nothing for one begun today), plus 'carried'+ (the day's windows before it). An older reading changes nothing."""+ if value is None or value.get("used_percent") is None:+ return day+ used, resets, start = value["used_percent"], value.get("resets_at"), day_start(at)+ fresh = {"date": day_of(at), "label": value["label"], "minutes": window_minutes(value), "resets_at": resets,+ "base": used, "used": used, "at": at, "carried": 0}+ if not day or day.get("label") != value["label"]:+ return fresh # the first reading, or another window read now: counted from here+ if at < day["at"]:+ return day+ today = day["date"] == fresh["date"]+ if new_window(day, value): # begun its length before its reset time, else after the old one's last reading+ began = resets - 60 * fresh["minutes"] if resets is not None else day["at"]+ return dict(fresh, base=0 if began >= start - DAY_EDGE else used,+ carried=day["carried"] + max(0, day["used"] - day["base"]) if today else 0)+ if today: # the same window, risen or corrected+ return dict(day, used=used, at=at, resets_at=resets, minutes=fresh["minutes"])+ watched = day["at"] >= start - DAY_EDGE # read just before midnight: that reading stands for it+ return dict(fresh, base=day["used"] if watched else used)+++def today_share(day, now):+ """Today's use at `now` as a share of an even day (1.0: a seventh of the week), or None when it is not known: no+ reading of the window today, nor one in the DAY_EDGE before midnight (that one stands for the day's start)."""+ if not day or not even_day(day.get("minutes")):+ return None+ if day["date"] == day_of(now):+ points = day["carried"] + max(0, day["used"] - day["base"])+ elif day_start(now) - DAY_EDGE <= day["at"] < day_start(now):+ points = 0 # the day has only just begun, and nothing read since+ else:+ return None+ return points / even_day(day["minutes"])+++def valid_day(day):+ """A day kept in the state folder, as day_step makes them, or None."""+ if not isinstance(day, dict) or not all(isinstance(day.get(k), t) and not isinstance(day.get(k), bool)+ for k, t in DAY_FIELDS.items()):+ return None+ resets = day.get("resets_at")+ if resets is not None and (isinstance(resets, bool) or not isinstance(resets, (int, float))):+ return None+ return {k: day[k] for k in (*DAY_FIELDS, "resets_at")}++def trail_of(row):"""The good readings behind `row` for rates, oldest first: [(measured at, {label: used %})], the ones in theten minutes before it and its own (a stale row keeps the windows and the time they were measured)."""@@ -189,13 +270,16 @@ class UsageStore:for a in accounts}def restore(self, snapshot):- """Carry over when each account last rose (and its run's start) from the snapshot the last run wrote,- so a restart does not make a second 'first use of the day' or forget a break."""+ """Carry over when each account last rose (and its run's start) and its day (today's use) from the snapshot+ the last run wrote, so a restart does not make a second 'first use of the day', forget a break or start today+ over."""for key, old in (snapshot or {}).get("accounts", {}).items():if key in self.rows and isinstance(old, dict):for field in ("rose_at", "active_since"):if isinstance(old.get(field), (int, float)) and not isinstance(old.get(field), bool):self.rows[key][field] = old[field]+ if valid_day(old.get("day")):+ self.rows[key]["day"] = valid_day(old["day"])def fetch_one(self, account):"""This account's reading. Whatever goes wrong while reading it is its own error, named by its type only (a@@ -267,6 +351,9 @@ class UsageStore:# 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" elselasting(row, previous.get("slow") or [], wall, self.good(row["key"])))+ # x7: today's use goes on from a reading that came in; one that did not keeps the day as it was+ row["day"] = (day_step(previous.get("day"), today_window(row["windows"]), row["last_success_at"])+ if row["status"] == "ok" else previous.get("day"))self.rows[row["key"]] = rowself.updated_at = int(time.time())@@ -331,6 +418,7 @@ class UsageStore:if row["status"] != "ok": # OLD: the last good reading's SLOW, only while it is under HORIZON oldrow["slow"] = lasting(row, row.get("slow") or [], now, good[key])row["active"] = bool(row.get("rose_at")) and now - row["rose_at"] < ACTIVE_SECONDS+ row["today"] = today_share(row.get("day"), now) # a share of an even day; None while not knownby_label = {w["label"]: w for w in row["windows"]}for prefix, label in (("session", "5H"), ("weekly", "WEEK")):value = by_label.get(label, {})diff --git a/token_tv/survival.py b/token_tv/survival.pynew file mode 100644index 0000000..e1a227b--- /dev/null+++ b/token_tv/survival.py@@ -0,0 +1,304 @@+"""Survival: a still face in a game HUD's look, as the owner approved it (x7, style A of the drafts w30-w32, 2026-11-05).++One row per account (four at most, the rows overview_rows picks, as on every still face): ten hearts for what is left of+its 5-hour window and ten drumsticks for what is left of its long one (the week; else a month or a budget), a tenth+each, half icons for the last 5% (a little left still shows half an icon); a star and a bar for today's use, full at an+even day's share of the long window (a seventh of a week) and past it a second lap in orange; the pet small beside+them, sweating when nearly out. The numbers are what is LEFT, as the battery's are. An account with one window shows+only its row of that kind. A window with no reading shows a dash, not empty icons; an old reading says OLD; an account+with no reading says why (LOGIN, NO DATA, ...); today's use not known yet is a dash too. Every icon is drawn for+TokenTV (no game's names, pictures or layout). A JPEG like the other still faces: it changes only with the readings.+"""+import functools+import math++from PIL import Image, ImageDraw++from token_tv import arcade+from token_tv import readout+from token_tv.display import MAX_ROWS, STATUS, account_label, fit_pixel, overview_rows, pixel_text, quota_period+from token_tv.pet_moments import sprite+from token_tv.usage import five_hour, long_window, window_minutes++SIZE = 240+PANEL, DIVIDER, TEXT, MUTED = (11, 13, 19), (30, 34, 46), (226, 230, 238), (128, 138, 160)+TRACK = (40, 46, 62)+WARN = arcade.WARN # OLD, and why an account has no reading++# --- the icons (each drawn for TokenTV, one pixel a cell, doubled on the clock's 2 px grid) ---------------------------++HEART, HEART_SHINE = (255, 92, 136), (255, 200, 214)+MEAT, MEAT_HI, MEAT_LO, BONE = (214, 128, 58), (246, 178, 96), (150, 80, 36), (246, 236, 214)+GOLD, GOLD_HI, OVER = (255, 200, 70), (255, 236, 160), (255, 140, 60)+EMPTY = (44, 50, 66) # an icon spent: its shape in the track's tone, so the ten places always read++HEART_7 = ('.HH.HH.', 'HSHHHHH', 'HHHHHHH', 'HHHHHHH', '.HHHHH.', '..HHH..', '...H...')+DRUM_7 = ('...MMM.', '..MSMMM', '..MMMMM', '..MMMMm', '..MMmm.', '.BB....', 'B.B....')+STAR_5 = ('..G..', '.GGG.', 'GGGGG', '.GGG.', '.G.G.')+INK_HEART = (('H', HEART), ('S', HEART_SHINE))+INK_DRUM = (('M', MEAT), ('S', MEAT_HI), ('m', MEAT_LO), ('B', BONE))+INK_STAR = (('G', GOLD),)++[email protected]_cache(maxsize=None)+def icon(rows, ink, part=1.0, scale=2):+ """An icon `part` full (0 to 1), its left part filled and the rest spent, doubled."""+ art = sprite(rows, dict(ink))+ if part < 1:+ px = art.load()+ cut = round(art.width * part) if part > 0 else 0+ for y in range(art.height):+ for x in range(cut, art.width):+ if px[x, y][3]:+ px[x, y] = EMPTY + (255,)+ return art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST)+++def put(frame, art, x, y):+ frame.paste(art, (round(x), round(y)), art)+++def icon_row(frame, x, y, rows, ink, left, pitch, count=10):+ """`count` icons from x, `left` (0..1) of them full: whole ones, then the one in part (to the nearest half),+ then spent ones."""+ units = math.floor(left * count * 2 + .5) / 2 if left > 0 else 0 # 5% steps; a little left still shows half+ if 0 < left and units == 0:+ units = .5+ for k in range(count):+ put(frame, icon(rows, ink, round(max(0.0, min(1.0, units - k)), 2)), x + k * pitch, y)+++# --- the pets, small and still --------------------------------------------------------------------------------------+[email protected]_cache(maxsize=None)+def pet_still(provider, small=False):+ """Each pet's own resting picture at one pixel a cell (Arcade's art): Clawd's Quest's Clawd standing, the cloud, the+ white Grok bot, Copilot's face, Anti; a service with no pet of its own, Arcade's plain one."""+ if provider == 'claude':+ return arcade.clawd('LookingAround', 0, 1)+ if provider == 'codex':+ return arcade.codex_cloud(20, 18) if small else arcade.codex_cloud()+ if provider == 'grok':+ return arcade.grok_pose(14 if small else 16)+ if provider == 'copilot':+ return arcade.copilot_pose(14 if small else 20)+ if provider == 'antigravity':+ return arcade.anti_art()+ return arcade.plain_pet()+++def put_pet(frame, draw, provider, cx, bottom, scale, used=None, small=False):+ """The pet standing on `bottom`, centred on cx, `scale` screen pixels a cell; sweating when nearly out (Arcade's+ 'worried', 90% used or more)."""+ art = pet_still(provider, small)+ art = art.resize((art.width * scale, art.height * scale), Image.Resampling.NEAREST)+ left, top = round(cx - art.width / 2) // 2 * 2, bottom - art.height+ put(frame, art, left, top)+ if used is not None and used >= 90:+ s = max(1, scale // 2) * 2+ for k, side in enumerate((1, -1)):+ arcade.sweat_drop(draw, round(cx + side * (art.width / 2 + 2 + 2 * k)), top + 2 + 6 * k, s // 2 + 1)+++# --- what a row shows -----------------------------------------------------------------------------------------------++def windows_of(row):+ """(the 5-hour window, the long one: the week, else a month or a budget), None where missing; whatever order they+ come in."""+ windows = row.get('windows') or []+ return five_hour(windows), long_window(windows)+++def left_of(value):+ """What is left of a window (0..1), None without a reading."""+ if not value or value.get('used_percent') is None:+ return None+ return max(0.0, min(1.0, 1 - value['used_percent'] / 100))+++def short_left(value):+ left = left_of(value)+ return '--' if left is None else f'{round(left * 100)}%'+++def label_of(value):+ """A window's name as the clock writes it (5H, WK, MO, BUD), three letters at most to keep clear of its icons: a+ longer one by its length when known, else its first three."""+ if not value:+ return ''+ name = quota_period(value)+ if len(name) <= 3:+ return name+ minutes = window_minutes(value)+ return {300: '5H', 1440: 'DAY', 10080: 'WK'}.get(minutes) or ('MO' if minutes and minutes >= 28 * 1440 else name[:3])+++def worst_used(row):+ used = [w['used_percent'] for w in row.get('windows', []) if w.get('used_percent') is not None]+ return max(used) if used else None+++def old(row):+ """Whether the row's reading is an old one (it is shown as it was, marked OLD)."""+ return bool(row.get('windows')) and row.get('status') != 'ok'+++def why(row):+ """Why an account shows no window at all ('LOGIN', 'NO DATA', ...), else ''."""+ return '' if row.get('windows') else STATUS.get(row.get('status'), 'NO DATA')+++def icons(frame, draw, x, y, value, rows, ink, pitch):+ """A window's ten icons from (x, y), or a dash in their place when it has no reading (never empty icons, which+ would say it is used up)."""+ left = left_of(value)+ if left is None:+ pixel_text(draw, (x, y + 4), '--', color=MUTED)+ else:+ icon_row(frame, x, y, rows, ink, left, pitch)+++def xp_bar(draw, x, y, w, h, today, track=TRACK):+ """Today's use: gold up to an even day's share, and past it a second lap in orange over the gold."""+ draw.rectangle((x, y, x + w - 1, y + h - 1), fill=track)+ if today is None:+ return+ first = min(1.0, today)+ if first > 0:+ fx = x + max(2, round(w * first / 2) * 2) - 1+ draw.rectangle((x, y, fx, y + h - 1), fill=GOLD)+ draw.rectangle((x, y, fx, y + (1 if h > 4 else 0)), fill=GOLD_HI)+ second = min(1.0, max(0.0, today - 1))+ if second > 0:+ draw.rectangle((x, y, x + max(2, round(w * second / 2) * 2) - 1, y + h - 1), fill=OVER)+ for k in range(1, 4): # quarter marks, so a glance reads a quarter of a day from a half+ mx = x + round(w * k / 4)+ draw.line((mx, y, mx, y + h - 1), fill=PANEL)+++def today_text(today):+ return '--' if today is None else f'{round(today * 100)}%'+++def soonest_reset(five, long, now):+ """The reset a row's top line names: the 5-hour window's (the hearts come back first), else the long one's."""+ value = five or long+ return f'{label_of(value)} {readout.reset_clock(value.get("resets_at"), now)}' if value else ''+++def width(text, scale=1):+ return readout.text_width(str(text), scale)+++ICONS_END = 30 + 9 * 16 + 14 # where a row of ten icons from x 30 ends+++def left_number(draw, y, value, row):+ """What is left of a window, big, at the end of its icons: its right edge at 230, or past it when it would touch+ the icons (100%)."""+ text = short_left(value)+ pixel_text(draw, (max(230, ICONS_END + 2 + width(text, 2)), y), text, scale=2, color=MUTED if old(row) else TEXT,+ align='right')+++# --- the face: style A, rows of ten small icons -------------------------------------------------------------------++def hero(frame, draw, row, now):+ """One account: its name and its pet's on top, the pet big, a line of icons for each window with what is left+ and its reset, today's bar at the bottom."""+ five, long = windows_of(row)+ name, ink = readout.PETS.get(row['provider'], (row['provider'].upper()[:8], TEXT))+ right, right_ink = ('OLD', WARN) if old(row) else (name, ink)+ pixel_text(draw, (230, 8), right, scale=2, color=right_ink, align='right')+ pixel_text(draw, (10, 8), fit_pixel(account_label(row), 2, 220 - width(right, 2) - 8), scale=2, color=TEXT)+ draw.line((20, 99, 220, 99), fill=DIVIDER)+ put_pet(frame, draw, row['provider'], 120, 98, 4 if row['provider'] in ('claude', 'antigravity', 'grok') else 2,+ worst_used(row))+ y = 110+ if why(row):+ pixel_text(draw, (30, y + 1), why(row), scale=2, color=WARN)+ for value, art, ink_ in ((five, HEART_7, INK_HEART), (long, DRUM_7, INK_DRUM)):+ if value is None:+ continue+ pixel_text(draw, (10, y + 4), label_of(value), color=MUTED)+ icons(frame, draw, 30, y, value, art, ink_, 16)+ left_number(draw, y + 1, value, row)+ pixel_text(draw, (30, y + 20), 'RESET', color=MUTED)+ pixel_text(draw, (230, y + 20), readout.reset_clock(value.get('resets_at'), now), color=MUTED, align='right')+ y += 38+ put(frame, icon(STAR_5, INK_STAR), 10, 198)+ pixel_text(draw, (26, 200), 'TODAY', color=MUTED)+ xp_bar(draw, 62, 200, 112, 8, row.get('today'))+ pixel_text(draw, (230, 198), today_text(row.get('today')), scale=2, color=TEXT if row.get('today') is not None+ else MUTED, align='right')+++def pair(frame, draw, row, y0, now):+ """One of two accounts: the pet and the name on top, the rows of icons the whole width under them with what is+ left at their end, today's bar under those."""+ five, long = windows_of(row)+ put_pet(frame, draw, row['provider'], 34, y0 + 42, 2, worst_used(row), small=True)+ pixel_text(draw, (66, y0 + 10), fit_pixel(account_label(row), 2, 164), scale=2, color=TEXT)+ pixel_text(draw, (66, y0 + 30), soonest_reset(five, long, now), color=MUTED)+ if old(row):+ pixel_text(draw, (230, y0 + 30), 'OLD', color=WARN, align='right')+ y = y0 + 50+ if why(row):+ pixel_text(draw, (30, y + 1), why(row), scale=2, color=WARN)+ for value, art, ink_ in ((five, HEART_7, INK_HEART), (long, DRUM_7, INK_DRUM)):+ if value is not None:+ pixel_text(draw, (10, y + 4), label_of(value), color=MUTED)+ icons(frame, draw, 30, y, value, art, ink_, 16)+ left_number(draw, y + 1, value, row)+ y += 20+ put(frame, icon(STAR_5, INK_STAR, scale=1), 12, y + 2)+ xp_bar(draw, 30, y + 3, 158, 4, row.get('today'))+ pixel_text(draw, (230, y + 1), today_text(row.get('today')), color=GOLD if row.get('today') is not None else MUTED,+ align='right')+++def compact(frame, draw, row, y0, h, now):+ """One of three or four accounts: the pet small at the left, the name and the soonest reset on top, icons only."""+ five, long = windows_of(row)+ put_pet(frame, draw, row['provider'], 28, y0 + h // 2 + 16, 2, worst_used(row), small=True)+ x = 60+ note = why(row) or soonest_reset(five, long, now)+ pixel_text(draw, (234, y0 + 5), note, color=WARN if why(row) else MUTED, align='right')+ room = 234 - width(note) - (6 if note else 0)+ if old(row):+ pixel_text(draw, (room, y0 + 5), 'OLD', color=WARN, align='right')+ room -= width('OLD') + 6+ pixel_text(draw, (x, y0 + 5), fit_pixel(account_label(row), 1, room - x), color=TEXT)+ y = y0 + 15+ for value, art, ink_ in ((five, HEART_7, INK_HEART), (long, DRUM_7, INK_DRUM)):+ if value is not None:+ icons(frame, draw, x, y, value, art, ink_, 16)+ if value is long and five is not None and window_minutes(long) != 10080: # not a week: say which it is+ pixel_text(draw, (236, y + 4), label_of(long), color=MUTED, align='right')+ y += 16+ put(frame, icon(STAR_5, INK_STAR, scale=1), x, y + 1)+ if row.get('today') is None: # not known yet: a dash, not an empty bar+ pixel_text(draw, (x + 10, y), '--', color=MUTED)+ else:+ xp_bar(draw, x + 10, y + 2, 228 - x - 10, 4, row.get('today'))+++def render_survival(snapshot, now=None):+ """The Survival face for `snapshot` as the clock shows it (240 x 240, RGB)."""+ frame = Image.new('RGB', (SIZE, SIZE), PANEL)+ draw = ImageDraw.Draw(frame)+ rows = overview_rows(snapshot)[:MAX_ROWS]+ if len(rows) == 1:+ hero(frame, draw, rows[0], now)+ return frame+ h = SIZE // len(rows)+ for i, row in enumerate(rows):+ y0 = i * h+ if i:+ for x in range(8, 233, 4):+ draw.point((x, y0), fill=DIVIDER)+ if len(rows) == 2:+ pair(frame, draw, row, y0, now)+ else:+ compact(frame, draw, row, y0, h, now)+ return framediff --git a/token_tv/themes.py b/token_tv/themes.pyindex 3e7717f..9084379 100644--- a/token_tv/themes.py+++ b/token_tv/themes.py@@ -766,5 +766,12 @@ def render_gameboy(data):return to_four_shades(cv.finish())+def render_survival(snapshot):+ """The Survival face (token_tv/survival.py: hearts, hunger and today's use, a row per account), imported as it is+ first drawn, since it draws Arcade's pets."""+ from token_tv.survival import render_survival as render+ return render(snapshot)++RENDERERS = {'digital': render_digital, 'neon': render_neon, 'retro': render_retro, 'hud': render_hud, 'gameboy': render_gameboy,- 'retro-dual': render_retro_dual}+ 'retro-dual': render_retro_dual, 'survival': render_survival}diff --git a/token_tv/usage.py b/token_tv/usage.pyindex c4c5169..ef0cb35 100644--- a/token_tv/usage.py+++ b/token_tv/usage.py@@ -42,6 +42,48 @@ def window(label, percent, reset=None, duration=None):"resets_at": timestamp(reset), "duration_minutes": duration}+NAMED_DAYS = {"WEEK": 7, "MONTH": 30, "BUDGET": 30, "DAY": 1} # a window's length by its name, when it gives none+++def window_minutes(value):+ """How long a window is, in minutes: as its service says, else by its name (5H, WEEK, DAY; a month or a budget as+ 30 days); None when neither says (CHAT, WINDOW)."""+ minutes = value.get("duration_minutes")+ if isinstance(minutes, int) and not isinstance(minutes, bool) and minutes > 0:+ return minutes+ label = str(value.get("label", "")).rstrip("2")+ return 300 if label == "5H" else NAMED_DAYS[label] * 1440 if label in NAMED_DAYS else None+++def five_hour(windows):+ """The 5-hour window among `windows`, or None."""+ return min((w for w in windows if window_minutes(w) == 300), key=lambda w: str(w.get("label")), default=None)+++def long_window(windows):+ """The long window among `windows` (a survival HUD's hunger): the week, else the longest other one but the 5-hour+ one (a month, a budget), else any other; None when there is none. The same whatever order they come in."""+ def rank(w):+ minutes = window_minutes(w)+ return minutes != 10080, minutes is None, -(minutes or 0), str(w.get("label"))+ return min((w for w in windows if window_minutes(w) != 300), key=rank, default=None)+++def today_window(windows):+ """The window today's use is read from: the longest of a known length (a week over a 5-hour one), None when no+ window says how long it is."""+ return min((w for w in windows if window_minutes(w)), key=lambda w: (-window_minutes(w), str(w.get("label"))),+ default=None)+++def even_day(minutes):+ """The used % an even day takes of a window `minutes` long: a seventh of a week, a thirtieth of a month, and of+ a window of a day or less (5 hours) all of it, one a day; None for a window of unknown length."""+ if not minutes:+ return None+ return 100 * 1440 / minutes if minutes >= 1440 else 100++def normalize_claude(data):result = []for key, label, duration in (("five_hour", "5H", 300), ("seven_day", "WEEK", 10080)):diff --git a/token_tv/web/app.js b/token_tv/web/app.jsindex 3ce50cd..9ed632f 100644--- a/token_tv/web/app.js+++ b/token_tv/web/app.js@@ -313,7 +313,7 @@ $('#get-copy').onclick = async () => {};$('#get-runner').onclick = () => {runner = runner === 'npx' ? 'uvx' : 'npx'; paintSetup()};$('#get-it').oninput = paintSetup;-const styleName = s => s === 'retro' ? 'Pixel Retro' : s === 'retro-dual' ? 'Pixel Retro Dual' : s === 'hud' ? 'Sci-Fi HUD' : s === 'gameboy' ? 'Game Boy' : s ? s[0].toUpperCase() + s.slice(1) : 'Unknown';+const styleName = s => s === 'retro' ? 'Pixel Retro' : s === 'retro-dual' ? 'Pixel Retro Dual' : s === 'hud' ? 'Sci-Fi HUD' : s === 'survival' ? 'Survival HUD' : s === 'gameboy' ? 'Game Boy' : s ? s[0].toUpperCase() + s.slice(1) : 'Unknown';let displayPolling = false;async function refreshDisplay(forceImage = false) {if (displayPolling) return; displayPolling = true; try {const r = await fetch(DEMO ? '/demo-display.json' : '/display', {cache:'no-store'}); if (!r.ok) throw Error(); const data = await r.json(); const dirty = displayInfo && clockChoice !== displayInfo.style; displayInfo = data; if (!clockChoice || !dirty) clockChoice = data.style; const select = $('#clock-style'); if (!select.options.length) for (const s of [...data.styles].sort((a, b) => (b === 'arcade') - (a === 'arcade'))) {const o = el('option', styleName(s)); o.value = s; select.append(o)} select.value = clockChoice; paintClock(forceImage); if (DEMO && themeData && !lastThumbFrames) {lastThumbFrames = true; paintThemes()}} catch {$('#display-state').textContent = 'Clock status unavailable'} finally {displayPolling = false}}$('#clock-style').onchange = e => {clockChoice = e.target.value; clockError = false; paintClock(true); paintThemes()};