A dock above the prompt: plan usage windows, main and subagent context fill, and the shells running now with what each one is doing.

A live dashboard that lives right above your Claude Code prompt.
Your plan's limits, this chat's context, the shells you have running, the model and its effort, all in one band that updates as you work. Plus a small companion who has opinions.
<img src="assets/reveal.gif" alt="Claude Dock appearing above the Claude Code prompt right after install, with the mascot saying hello" width="900">
This is the dock exactly as it draws in a 210-column terminal, mid-session:
────────────────────────────────────────────────────────────────────────────────────────────────────────
Max 20x · Running hot · pace exceeds Sunday's reset
PLAN ▾ usage windows on your subscription
Session █████████░░░░░░░░░░░░░░░░░░░ 32% resets 5:20 PM PDT
Week █████████████████░░░░░░░░░░░ 60% resets Sun 10:00 PM PDT
THIS CHAT ▾ context window of this conversation
Context ▸ █░░░░░░░░░░░░░░░░░░░░░░░░░░░ 5% 54k of 1000k tokens used · $0.30 spent
Model claude-opus-5-5 [ low ] [ medium ] [ high ] [ xhigh ] [ max ] [ ultracode ]
▐█▜██▛█ SHELLS ▸ 1 running · 4 just finished
▝▜██████▀
▝▝ ▝▝ [ Settings ] [ Fast ] [ Compact ] [ Slim ]
<img src="assets/hero-dock.png" alt="The dock: plan usage bars, this chat's context and cost, the model with effort chips, shells, and the button row" width="900">
/model switch shows within a second.<img src="assets/shells.gif" alt="The shells view: a dev server and a test watcher running in the background, each opened to show its latest output" width="900">
Press SHELLS to see every background shell and task this session is running, with how long each has been going. Open one to read its latest output, like a dev server's request log or a test watcher's results, without leaving your prompt.
Turn on Settings → Dock → SHELLS → Background servers and watchers, and commands that never finish on their own run in the background automatically, so Claude keeps answering while they run. That covers dev servers, watch modes, tail -f and local web servers. Everything else runs exactly as Claude asked. It's off by default.
<img src="assets/effort.gif" alt="Clicking the effort chips from low to max, then switching ultracode on" width="900">
The chips run from low to max, each in its own colour, and the lit one is the level the engine is really using. Pressing one runs /effort for you, waiting for the current turn to finish if one is running. Ultracode is a chip too, and when it's on your companion holds the sparkler.
<img src="assets/settings.gif" alt="The Settings pane's Dock tab: changing the top line's colour, style, shimmer and alternating colours" width="900">
Settings → Dock holds the dock's own look, every row stepped with the arrow keys and saved for every session:
The other tabs mirror Claude Code itself, to read. Config lists every /config setting and its value; change them with /config. Status, Usage and Stats show what their commands show. File shows your settings.json as a tree.
The dock can chime when Claude finishes, when Claude needs you, and when a subagent finishes. "Needs you" covers a permission prompt or a question. Each moment has its own sound, picked from ten, or off. Success, Ping and Bubble were made for the dock, and the other seven are from Kenney's public-domain Interface Sounds:
| Sound | Character |
|---|---|
| Success | a rising three-note jingle |
| Ping | a crisp UI ping |
| Bubble | a round bloop |
| Chime | a bright two-tone confirmation |
| Glass | a clean glass tap |
| Confirm | a soft confirming blip |
| Question | a curious rising query |
| Rise | an upward sweep |
| Drop | a low drop |
| Pluck | a short pluck |
Everything lives under Settings → Dock → SOUND:
The finished sound waits until no background work is still running, so you hear it once, when it's really done.
<img src="assets/slim.gif" alt="Slim folds the dock to a single strip of buttons, and Bulk brings it back" width="900">
One click folds the dock to a single strip, with the companion and the buttons. Bulk brings the whole dock back, every section open.
He climbs. He gets rained on. He has other moods too, which we'll leave for you to find.
<img src="assets/ladder.gif" alt="The mascot climbs a ladder and parachutes back down" width="900">
<img src="assets/storm.gif" alt="Tapping the mascot a few times brings a storm cloud, and he pulls out an umbrella" width="900">
Everything stays on your machine except one request to Anthropic, described below. The full privacy policy says the same in one place.
Network. The dock contacts one host, api.anthropic.com. About once a minute while the session is open, and at most once a minute after each model response (longer after a rate-limit response), it sends a GET request to https://api.anthropic.com/api/oauth/usage, the endpoint Claude Code's /usage command uses, to read your plan's usage windows and plan tier. The request carries your Claude Code login as a bearer token and sends nothing else. There is no other network destination.
Your login. That request needs the Claude Code login already on this machine, so the dock reads it from the macOS keychain entry Claude Code-credentials, or from ~/.claude/.credentials.json where there is no keychain. Asking you to paste the token into a setting instead would mean copying a secret by hand. The token is held in memory for that one request and is never logged, drawn or stored. Without a login, the dock draws the limits Claude Code itself reports.
Programs it runs. Two fixed commands, nothing else:
security find-generic-password -s "Claude Code-credentials" -w, on macOS, to read the login above.id -u, once per session, to find the folder where Claude Code keeps background shell output (/private/tmp/claude-<uid>/…/tasks), so the shells view can show each shell's latest line.Claude Code commands it runs. Only when you press the matching control:
/effort <level>, including /effort ultracode on|off, when you press an effort chip. Claude Code saves the level as it normally does./fast when you press Fast./compact does.Apart from the optional Bypass probe described below, it runs no tools and starts no agents.
Files it reads. ~/.claude/settings.json, ~/.claude/stats-cache.json, ~/.claude/sessions/*.json, the account block of ~/.claude.json, and background shell output files, to draw settings, stats, session names, your account's display name, and shell output. It never draws or stores tokens.
Files it writes. None of its own, apart from the optional Bypass probe described below, which creates an empty /tmp/cc-dock-bypass-probe and never removes it. Its settings (look, sounds, folded sections, the last plan reading) are kept in Claude Code's plugin store on your machine. It changes no configuration and sets no environment variables.
What each hook does:
tool.call on Bash: lists each shell command in the dock, except the Bypass probe below, and returns the tool's own result unchanged. With Background servers and watchers switched on (off by default), it changes one input: it sets run_in_background to true for a command that never ends on its own, such as a dev server or a watch mode. It changes nothing else.turn.step: reads the model and effort of each request. After you press an effort chip, and only until /effort has run, it sets that effort on the main conversation's requests so the chip takes effect at once.command.run on /model, /effort and /fast: passes each command on unchanged and reads its reply to keep the dock current. On /ladder, /snake and /chatter, the dock's own commands, it plays that animation.classic.Stop, classic.SubagentStop and classic.Notification: play the chime you picked and update the shells list. They decide nothing and pass every event on unchanged.ui.render: draws the dock above the prompt (AbovePrompt) and its Settings pane (Pane). On the footer (PromptHint) it only reads the permission mode, the shell count and whether a turn is running, and draws it unchanged.classic.PermissionRequest: answers only the Bypass probe's own prompt, and only right after you confirmed Bypass. It passes every other permission prompt on unchanged.session.start, session.measure, turn.complete and ui.message: read session figures and your clicks in the dock. They change nothing.Bypass, only once you show the button: when you confirm it, the dock asks the permission check whether a harmless touch /tmp/cc-dock-bypass-probe would prompt. If the footer already shows bypass, or the check would allow the command, nothing runs and the button says so. If the check refuses it, nothing runs and the button says it is blocked. Otherwise the dock runs that one Bash command, which creates an empty /tmp/cc-dock-bypass-probe and leaves it there, and answers the prompt it raises with a session mode change to bypass; the footer confirms it. That probe is the only command it ever runs for this, and the shells list does not show it.
Sound. It plays its bundled sounds through Claude Code's audio player, which is afplay on macOS. Other platforms stay silent.
Claude Code in the terminal only, version 2.1.292 or later. It draws nothing in the desktop app, VS Code, claude.ai chat or Cowork.
hooks/register.tsx 2767 lines1import type { MenuRow, Seg } from './menu'
2import { VOICE_FRAMES, VOICE_STEP_MS } from './voice-envelope'
3import type { Elements, EngineInterface, Register, ModelEffort, SessionContextUsage, SessionCost, SessionRateLimit, SessionContextBreakdown, ConfigRow } from 'claude-code'
4
5type Shell = {
6 toolUseId: string
7 description: string
8 command: string
9 startedAt: number
10 taskId?: string
11 agentId?: string
12 endedAt?: number
13 failed?: boolean
14}
15const LINGER_MS = 20_000
16type Limit = { kind: string; label: string; percent: number; resetsAt?: string; dollars?: { used: number; limit: number } }
17type Plan = { tier: string; limits: Limit[]; codeShare?: number; fetchedAt: number }
18
19// Module state resets on reload; the next measurement, fetch and tool call refill it.
20let context: SessionContextUsage | null = null
21let rateLimits: SessionRateLimit[] = []
22// True when the last response's own rate limits are newer than the usage endpoint's reading.
23let rateLimitsFresh = false
24let cost: SessionCost | undefined
25let plan: Plan | null = null
26let planError = ''
27let frame = 0
28let tasksDir = ''
29const expanded = new Set<string>()
30let view: 'dash' | 'shells' | 'context' | 'fast' = 'dash'
31let planOpen = true
32let slim = false // the ultra-compact band: the mascot and the buttons, nothing else
33// The dock's own look, chosen on the Dock tab and kept in the store.
34const COLORS: readonly { id: string; name: string }[] = [
35 { id: 'claude', name: 'orange' }, { id: 'warning', name: 'yellow' }, { id: 'success', name: 'green' }, { id: 'ide', name: 'blue' },
36 { id: 'permission', name: 'lavender' }, { id: '#827dbd', name: 'purple' }, { id: 'error', name: 'red' }, { id: 'text', name: 'white' }, { id: 'inactive', name: 'grey' },
37]
38const RULE_STYLES: readonly { id: string; name: string }[] = [
39 { id: '─', name: 'thin' }, { id: '━', name: 'thick' }, { id: '═', name: 'double' }, { id: '-', name: 'dashes' }, { id: '=', name: 'equals' }, { id: '+', name: 'plus' }, { id: '·', name: 'dots' }, { id: '╌', name: 'broken' },
40]
41// Writes a setting in the background, so the change is drawn at once and a failed write is ignored.
42const save = ($: EngineInterface, key: string, value: unknown): void => {
43 void Promise.resolve()
44 .then(() => $.store.set(key, value as never))
45 .catch(() => {
46 // remembered for this session only
47 })
48}
49type DockLook = { ruleColor: number; ruleAltColor: number; ruleStyle: number; ruleShimmer: boolean; rulePattern: boolean; uiColor: number; avatar: boolean; header: boolean }
50let look: DockLook = { ruleColor: 0, ruleAltColor: 0, ruleStyle: 0, ruleShimmer: false, rulePattern: false, uiColor: 0, avatar: true, header: true }
51let ruleFrame = 0
52const colorOf = (i: number) => COLORS[i]?.id ?? 'text'
53let chatOpen = true
54let usageNote = ''
55// True while a compaction runs; the avatar's bubble shows it, with dots that move.
56let compacting = false
57// The 90% question is asked once per crossing of the line.
58let compactAsked = false
59let breakdown: SessionContextBreakdown | null = null
60let breakdownNote = ''
61let breakdownBusy = false
62let bandColumns = 0 // the band's width as last drawn, for recounting the breakdown without a click
63let compactNote = '' // why a compaction did not run, beside the buttons
64let compactArmedAt = 0 // the Compact button asks "Yes?" until this plus CONFIRM_MS
65// The session's permission mode, read from the footer line the engine draws under the prompt
66// (`⏵⏵ bypass permissions on (shift+tab to cycle)`), so Shift+Tab changes show up too.
67let permissionMode = ''
68const MODE_WORDS: readonly [RegExp, string][] = [
69 [/bypass permissions on/i, 'bypass'],
70 [/manual mode on/i, 'manual'],
71 [/accept edits on/i, 'accept edits'],
72 [/plan mode on/i, 'plan'],
73 [/auto mode on/i, 'auto'],
74 [/don'?t ask on/i, "don't ask"],
75]
76const CONFIRM_MS = 6_000
77let compactions = 0
78// Bypass: the button shows only when Settings → Dock → PERMISSIONS turns it on, which is off by default.
79let showBypass = false
80// MCP servers the model may not call, switched off in the MCP pane.
81let bypassArmedAt = 0 // the Bypass button asks "Yes?" until this plus CONFIRM_MS
82let bypassWanted = false // confirmed: the next permission prompt switches this session to bypass
83let bypassNote = ''
84let compactWhenIdle = false // Compact pressed mid-turn: runs the moment the turn ends, no prompt queued
85let model = ''
86let effort = ''
87let fastMode = false
88let ultracode = false // the session's ultracode mode, as /effort last reported it
89let ultraPending: 'on' | 'off' | '' = '' // a switch to hand /effort once idle
90let fastNote = ''
91// The mascot's speech bubble: who it is talking to and what it is saying right now.
92let userName = ''
93let bubble = ''
94const QUIPS = {
95 hello: ['Hi {name}!', 'Yo {name}.', '{name}!', 'Hey.'],
96 thinking: ['Hmm.', 'On it.', 'Brb.', 'Shh.'],
97 done: ['Done.', 'Ta-da.', 'Easy.', 'Next?'],
98 idle: ['Boop.', 'Tea?', 'Psst.', 'Hi.', 'Zzz.', 'Nice.'],
99 compact: ['Tidy.', 'Roomy.'],
100 fast: ['Zoom.', 'Whee.'],
101 full: ['Full-ish.'],
102}
103let fastQuipDue = false
104// A burst of clicks on the mascot rolls a reaction: a dizzy shake, pacman, a chef's hat, a storm, a spider
105// dropping from a web, a starry night with fireflies, or the snake chase on the band. The
106// shirt colour is chosen on the Dock tab and remembered across sessions.
107const SHIRTS = ['claude', 'warning', 'success', 'ide', 'permission', '#827dbd', 'error', 'text']
108
109// Notification sounds, files in sounds/: one choice per moment by id, '' meaning off, kept in the store.
110// Chime, Glass, Confirm, Question, Rise, Drop and Pluck are Kenney's CC0 Interface Sounds (KENNEY-LICENSE.txt).
111const SOUNDS = [
112 { id: 'success', name: 'Success' },
113 { id: 'ping', name: 'Ping' },
114 { id: 'bubble', name: 'Bubble' },
115 { id: 'chime', name: 'Chime' },
116 { id: 'glass', name: 'Glass' },
117 { id: 'confirm', name: 'Confirm' },
118 { id: 'question', name: 'Question' },
119 { id: 'rise', name: 'Rise' },
120 { id: 'drop', name: 'Drop' },
121 { id: 'pluck', name: 'Pluck' },
122] as const
123const VOLUMES = [0.25, 0.5, 0.75, 1] as const
124type SoundMoment = 'done' | 'needs' | 'agent'
125// `notify` mutes every chime at once; `voice` is the idle chatter.
126type SoundPrefs = Record<SoundMoment, string> & { volume: number; notify: boolean; voice: boolean }
127let sounds: SoundPrefs = { done: 'success', needs: 'ping', agent: '', volume: 1, notify: true, voice: true }
128
129// Commands that never finish on their own. With autoBackground on, the dock runs them in the background so the
130// main agent stays free to answer; anything else runs as Claude asked.
131const NEVER_ENDS: readonly RegExp[] = [
132 /\b(npm|pnpm|yarn|bun)\s+(run\s+)?(dev|start|serve|watch)\b/,
133 /\b(next|nuxt|astro|remix|vite)\s+dev\b/,
134 /\bnodemon\b/,
135 /--watch\b/,
136 /\btsc\b.*\s-w\b/,
137 /\btail\s+-[a-zA-Z]*f/,
138 /\bpython3?\s+-m\s+http\.server\b/,
139 /\b(uvicorn|gunicorn)\b|\bflask\s+run\b|\brails\s+s(erver)?\b|\bartisan\s+serve\b/,
140 /\bdocker[-\s]compose\s+up\b(?![^|;&]*\s-d\b)/,
141]
142const neverEnds = (command: string): boolean => NEVER_ENDS.some(re => re.test(command))
143let autoBackground = false
144
145// Idle chatter: after fifteen quiet minutes, and every fifteen minutes of quiet after that, one roll at one
146// in four. A win makes him talk in every open dock, his head lifting in step with the clip; only the dock that
147// rolled it plays the clip.
148const IDLE_VOICE_MS = 15 * 60_000
149const ACTIVE_WRITE_MS = 60_000 // how often a dock records that it is busy or in use, for the others to read
150const SPEECH_LIVE_MS = 15_000 // a speech this recent is still shown by a dock that has not yet shown it
151const VOICE_STORE_KEY = 'chatter'
152// Tells this dock's roll apart from another dock's that landed on the same window.
153const voiceToken = String(Math.random())
154// Shared by every dock of this user: when anything was last active, the last roll, and the last speech.
155type Chatter = { active?: number; roll?: { window: number; by: string }; spokeAt?: number }
156// When a turn last showed life, a model request or the footer saying it works; a turn silent for a long time is over.
157let lastStepAt = 0
158let talk: { id: number; frames: readonly number[]; stepMs: number; startedAt?: number } | null = null
159// A reaction or clip the mascot never played (he was not drawn) is dropped after this, or it would block every later one.
160const REACT_MAX_MS = 15_000
161const TALK_MAX_MS = VOICE_FRAMES.length * VOICE_STEP_MS + 1_000
162let reactSeen = { id: 0, at: 0 } // when the 700 ms tick first saw the current reaction
163let talkId = 0
164let lastActivityAt = 0
165let lastActiveWrite = 0
166let lastShownSpeech = 0
167
168async function readChatter($: EngineInterface): Promise<Chatter> {
169 const value = await $.store.get(VOICE_STORE_KEY).catch(() => undefined)
170 return value && typeof value === 'object' ? (value as Chatter) : {}
171}
172
173async function writeChatter($: EngineInterface, patch: Chatter): Promise<void> {
174 const current = await readChatter($)
175 await $.store.set(VOICE_STORE_KEY, { ...current, ...patch }).catch(() => {})
176}
177
178// Starts his talk. Only the dock that rolled it plays the clip; `startedAt` is shared, so every mouth moves in step.
179function startChatter($: EngineInterface, startedAt: number, speak: boolean): void {
180 if (talk) return
181 talkId += 1
182 talk = { id: talkId, frames: VOICE_FRAMES, stepMs: VOICE_STEP_MS, startedAt }
183 if (speak) {
184 // The clip is far quieter than the chimes already; it plays a touch under their volume setting.
185 const gain = Math.min(1, (VOLUMES[sounds.volume] ?? 0.5) * 0.9)
186 void $.audio.play({ asset: 'sounds/idle-voice.mp3' }, { gain }).catch(() => {})
187 }
188 redraw($)
189}
190
191// Speaks in this dock and records it, so the other docs start their mouths at the same moment.
192async function speakNow($: EngineInterface): Promise<void> {
193 if (talk) return
194 const now = await $.clock.now()
195 lastShownSpeech = now
196 await writeChatter($, { spokeAt: now })
197 startChatter($, now, true)
198}
199
200async function noteActivity($: EngineInterface): Promise<void> {
201 lastActivityAt = await $.clock.now()
202 if (lastActivityAt - lastActiveWrite >= ACTIVE_WRITE_MS) {
203 lastActiveWrite = lastActivityAt
204 await writeChatter($, { active: lastActivityAt })
205 }
206}
207
208// A fixed hash of the window's start: every dock reads the same coin for a window, heads one window in four.
209function windowCoinHeads(windowAt: number): boolean {
210 let x = (Math.floor(windowAt / 1000) ^ 0x9e3779b9) | 0
211 x = Math.imul(x ^ (x >>> 16), 0x85ebca6b)
212 x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35)
213 x ^= x >>> 16
214 return (x >>> 0) / 4294967296 < 0.25
215}
216
217// Once a second: shows another dock's speech, records that this dock is busy, and at each fifteen-minute window
218// of quiet rolls to speak. The roll is claimed in the shared store first, so each window is rolled once.
219async function chatterTick($: EngineInterface): Promise<void> {
220 const now = await $.clock.now()
221 if (turnRunning && now - lastActiveWrite >= ACTIVE_WRITE_MS) {
222 lastActiveWrite = now
223 await writeChatter($, { active: now })
224 }
225 const shared = await readChatter($)
226 if (shared.spokeAt && shared.spokeAt > lastShownSpeech && now - shared.spokeAt < SPEECH_LIVE_MS && look.avatar && !slim && !talk) {
227 lastShownSpeech = shared.spokeAt
228 startChatter($, shared.spokeAt, false)
229 }
230 if (!sounds.voice || turnRunning || !look.avatar || slim || talk) return
231 const quietSince = Math.max(lastActivityAt, lastTurnEndAt, shared.active ?? 0)
232 if (now - quietSince < IDLE_VOICE_MS) return
233 const windowAt = quietSince + Math.floor((now - quietSince) / IDLE_VOICE_MS) * IDLE_VOICE_MS
234 if ((shared.roll?.window ?? 0) >= windowAt) return
235 await writeChatter($, { roll: { window: windowAt, by: voiceToken } })
236 if ((await readChatter($)).roll?.by !== voiceToken) return
237 if (windowCoinHeads(windowAt)) await speakNow($)
238}
239
240let lastChimeAt = 0
241const soundName = (id: string): string => SOUNDS.find(x => x.id === id)?.name ?? 'off'
242// Off, then each sound in order, wrapping both ways.
243function stepSound(id: string, step: number): string {
244 const order = ['', ...SOUNDS.map(x => x.id)]
245 const at = Math.max(0, order.indexOf(id))
246 return order[(at + step + order.length) % order.length] ?? ''
247}
248
249function playSound($: EngineInterface, id: string): void {
250 const gain = VOLUMES[sounds.volume] ?? 0.5
251 let played: Promise<unknown> | undefined
252 switch (id) {
253 case 'success': played = $.audio.play({ asset: 'sounds/success.mp3' }, { gain }); break
254 case 'ping': played = $.audio.play({ asset: 'sounds/ping.mp3' }, { gain }); break
255 case 'bubble': played = $.audio.play({ asset: 'sounds/bubble.mp3' }, { gain }); break
256 case 'chime': played = $.audio.play({ asset: 'sounds/chime.mp3' }, { gain }); break
257 case 'glass': played = $.audio.play({ asset: 'sounds/glass.mp3' }, { gain }); break
258 case 'confirm': played = $.audio.play({ asset: 'sounds/confirm.mp3' }, { gain }); break
259 case 'question': played = $.audio.play({ asset: 'sounds/question.mp3' }, { gain }); break
260 case 'rise': played = $.audio.play({ asset: 'sounds/rise.mp3' }, { gain }); break
261 case 'drop': played = $.audio.play({ asset: 'sounds/drop.mp3' }, { gain }); break
262 case 'pluck': played = $.audio.play({ asset: 'sounds/pluck.mp3' }, { gain }); break
263 }
264 void played?.catch(() => {})
265}
266
267// A burst (a workflow's agents finishing together) chimes once.
268async function chime($: EngineInterface, moment: SoundMoment): Promise<void> {
269 const id = sounds[moment]
270 if (!id || !sounds.notify) return
271 const now = await $.clock.now()
272 if (now - lastChimeAt < 1_200) return
273 lastChimeAt = now
274 playSound($, id)
275}
276let shirt = 0
277type ReactionKind = 'shake' | 'pacman' | 'chef' | 'storm' | 'spider' | 'night'
278let react: { kind: ReactionKind; id: number } | null = null
279let reactId = 0
280let taps: number[] = [] // recent clicks on the mascot; a burst of them rolls a reaction
281const TAP_BURST = 4
282const TAP_WINDOW_MS = 1_800
283let lastTurnEndAt = 0
284// A shuffle bag, the way games deal pieces: every item comes out once, in a random order, before any
285// repeats, and the first of a fresh bag is never the last of the one before, so nothing plays twice in a row.
286class Bag<T> {
287 private left: T[] = []
288 private last: T | undefined
289 constructor(private readonly items: readonly T[]) {}
290 draw(): T {
291 if (this.left.length === 0) {
292 const order = [...this.items]
293 for (let i = order.length - 1; i > 0; i -= 1) {
294 const j = Math.floor(Math.random() * (i + 1))
295 ;[order[i], order[j]] = [order[j]!, order[i]!]
296 }
297 if (order.length > 1 && order[0] === this.last) [order[0], order[order.length - 1]] = [order[order.length - 1]!, order[0]!]
298 this.left = order
299 }
300 const pick = this.left.shift()!
301 this.last = pick
302 return pick
303 }
304}
305type RollKind = ReactionKind | 'snake'
306const reactionBag = new Bag<RollKind>(['shake', 'pacman', 'chef', 'storm', 'spider', 'night', 'snake'])
307// One of the six reactions from the bag: five in the column, the snake chase on the band.
308const rollReaction = (): void => {
309 const kind = reactionBag.draw()
310 if (kind === 'snake') scene = { t: 0 }
311 else {
312 reactId += 1
313 react = { kind, id: reactId }
314 }
315}
316let climb = 0 // bumped to send the mascot up the ladder
317let climbAt = 0 // when it was last bumped, so a mascot remounted by Bulk still climbs
318let lastQuipKind = ''
319let bubbleSince = 0 // when the quip went up (clock ms)
320let bubbleHold = 0 // how long it stays before it fades
321// How often each kind of moment earns a word at all: rare, so a bubble is an easter egg.
322const CHANCE: Record<keyof typeof QUIPS, number> = { hello: 1, thinking: 0.15, done: 0.2, idle: 0.2, compact: 0.6, fast: 0.8, full: 0.5 }
323const HOLD: Record<keyof typeof QUIPS, number> = { hello: 6_000, thinking: 4_000, done: 4_000, idle: 4_000, compact: 4_000, fast: 4_000, full: 5_000 }
324const quipBags = new Map<string, Bag<string>>()
325// Maybe says something: by chance, the next line from that kind's shuffle bag, only when the bubble is empty.
326const say = (kind: keyof typeof QUIPS, now: number): void => {
327 if (slim || bubble || Math.random() > CHANCE[kind]) return
328 let bag = quipBags.get(kind)
329 if (!bag) {
330 bag = new Bag(QUIPS[kind])
331 quipBags.set(kind, bag)
332 }
333 const pick = bag.draw()
334 bubble = pick.replace('{name}', userName || 'you')
335 lastQuipKind = kind
336 bubbleHold = HOLD[kind]
337 bubbleSince = now
338}
339let fastReply = '' // what /fast last answered, shown on the Fast page
340let effortOverride: ModelEffort | '' = '' // a level pressed on a chip, forced on each request only until /effort has run
341const EFFORTS: readonly ModelEffort[] = ['low', 'medium', 'high', 'xhigh', 'max']
342const EFFORT_COLOR: Record<ModelEffort, string> = { low: 'success', medium: 'ide', high: 'warning', xhigh: 'claude', max: 'error' }
343let configNote = ''
344let turnRunning = false
345let spinnerWord = ''
346const CONFIG_PANE = 'cc-dock-config'
347// Client instances live on across reloads while their key holds, old module code and all; a key stamped
348// per load makes every reload mount fresh ones.
349const LOAD = Date.now().toString(36)
350const MENU_ID = `config-menu-${LOAD}`
351const ULTRA_ID = `ultracode-chip-${LOAD}`
352const FAST_CHIP_ID = `fast-chip-${LOAD}`
353const MASCOT_ID = `mascot-${LOAD}`
354const shells = new Map<string, Shell>()
355
356// The usage endpoint is rate limited: about once a minute at most, and after a 429 it waits as retry-after says.
357const REFRESH_MS = 60_000 // idle poll
358const AFTER_TURN_MS = 60_000 // a response just landed: refresh unless one did within this window
359const BACKOFF_MIN_MS = 60_000
360const BACKOFF_MAX_MS = 15 * 60_000
361let tier = ''
362let lastFetchAt = 0
363let backoffUntil = 0
364let backoffMs = 0
365let fetching = false
366
367const TIER_LABEL: Record<string, string> = {
368 default_claude_max_20x: 'Max 20x',
369 default_claude_max_5x: 'Max 5x',
370 default_claude_pro: 'Pro',
371}
372
373// The mascot frames Claude Code itself ships (its front pose, then its turn-left and turn-right
374// sprites), cycled so it looks side to side.
375const DANCE: readonly (readonly string[])[] = [
376 [' ▐▛███▜▌ ', '▝▜█████▛▘', ' ▘▘ ▝▝ '],
377 [' ▐▛███▜█ ', '▝▜██████▀', ' ▝▝ ▝▝ '],
378 [' ▛██▛█▌ ', ' ▝█████▛ ', ' ▘▘ ▘▘ '],
379 [' ▐▛███▜█ ', '▝▜██████▀', ' ▝▝ ▝▝ '],
380 [' ▐▛███▜▌ ', '▝▜█████▛▘', ' ▘▘ ▝▝ '],
381 [' ▐█▜██▛█ ', '▝▜██████▀', ' ▝▝ ▝▝ '],
382 [' █▛██▛▌ ', ' ▝█████▛ ', ' ▘▘ ▘▘ '],
383 [' ▐█▜██▛█ ', '▝▜██████▀', ' ▝▝ ▝▝ '],
384]
385
386// The snake chase: a rare scene on the empty stage right of the sections. Act one, the mascot runs
387// after a wriggling snake and gains on it; act two, it stops and opens an alien mouth far too big for
388// its head; act three, the snake is gone in three gulps and the mascot looks pleased.
389let scene: { t: number } | null = null
390const MOUTH: readonly (readonly string[])[] = [
391 [' ▐▛███▜▌ ', '▝▜▙▄▄▄▟▛▘', ' ▘▘ ▝▝ '],
392 ['▐▛▀▀▀▀▀▜▌', '▐▌ᴠᴠᴠᴠᴠ▐▌', '▝▜▄▄▄▄▄▛▘'],
393 ['▐▛▀▀▀▀▀▜▌', '▐▌ᴠᴠᴠᴠᴠ▐▌', '▝▜▄▄▄▄▄▛▘'],
394]
395const STAGE_H = 9
396const PINK = '#ff5fa2'
397// A coloured cell canvas: art is blitted at (x, y) with one colour per art row; spaces are transparent.
398type Cell = { ch: string; c: string }
399const canvas = (width: number): Cell[][] => Array.from({ length: STAGE_H }, () => Array.from({ length: width }, () => ({ ch: ' ', c: 'text' })))
400const blit = (c: Cell[][], art: readonly string[], x: number, y: number, colors: string | readonly string[]): void => {
401 art.forEach((row, i) => {
402 const line = c[y + i]
403 if (!line) return
404 const color = typeof colors === 'string' ? colors : colors[i] ?? colors[colors.length - 1] ?? 'text'
405 ;[...row].forEach((ch, j) => {
406 const col = x + j
407 if (ch !== ' ' && col >= 0 && col < line.length) line[col] = { ch, c: color }
408 })
409 })
410}
411// A row of cells as runs of one colour, for drawing.
412const runs = (row: Cell[]): { t: string; c: string }[] => {
413 const out: { t: string; c: string }[] = []
414 for (const cell of row) {
415 const last = out[out.length - 1]
416 if (last && last.c === cell.c) last.t += cell.ch
417 else out.push({ t: cell.ch, c: cell.c })
418 }
419 return out
420}
421const ULTRA = '#a78bfa' // the banner mascot's purple while ultracode is on (idle only)
422const SPARK = '#e8c547' // the sparkler's gold
423// The mascot's colours by row on the stage: head and legs orange, the shirt on the body.
424const mascotColors = (shirtColor: string): string[] => ['claude', shirtColor, 'claude']
425// The snake: two rows, a short skinny wave with an eye, two wriggle frames.
426const SNAKE: readonly (readonly string[])[] = [
427 ['▄▀▄ ▄▀▄ ▄▀▖', ' ▀▀▀ ▀▀▀ ◉▘'],
428 [' ▄▀▄ ▄▀▄ ▄▖', '▀▀▀ ▀▀▀ ▀ ◉▘'],
429]
430const SNAKE_W = 17
431
432// A long zig-zag: the runner climbs and dives across the stage's rows, one row every two frames.
433const zig = (t: number): number => {
434 const span = STAGE_H - 4
435 const k = Math.floor(t / 2) % (span * 2)
436 return k <= span ? k : span * 2 - k
437}
438// The chase across the whole band: the mascot leaves its spot at the left edge and runs right; the snake,
439// lower down, flees almost as fast, so the two travel a long way before the gap closes or the snake is
440// cornered at the right edge. Then: stop, an arm reaches out and lifts the snake, the top of the head
441// unscrews over a row of teeth, the snake goes down in bites, the head screws back, `gulp.`, a pink heart.
442const snakeFrame = (t: number, width: number, shirtColor: string): { t: string; c: string }[][] | null => {
443 const c = canvas(width)
444 const SPEED = 2
445 const FLEE = 1.85
446 const snakeX = (f: number) => Math.min(width - SNAKE_W - 1, 18 + Math.floor(f * FLEE))
447 let chaseFrames = 0
448 while (chaseFrames * SPEED + 9 < snakeX(chaseFrames) && chaseFrames < 900) chaseFrames += 1
449 const mc = mascotColors(shirtColor)
450 const snakeY = 7
451 if (t < chaseFrames) {
452 blit(c, DANCE[t % 2 === 0 ? 0 : 1]!, t * SPEED, zig(t), mc)
453 blit(c, SNAKE[t % 2]!, snakeX(t), snakeY - (Math.floor(t / 3) % 2), shirtColor)
454 return c.map(runs)
455 }
456 const u = t - chaseFrames
457 const sx = snakeX(chaseFrames)
458 const mx = Math.max(1, sx - 9) // nose to tail
459 const y = 4 // the head's row once he stops
460 const body = DANCE[0]![1]!
461 const legs = DANCE[0]![2]!
462 const lower = () => blit(c, [body, legs], mx, y + 1, [shirtColor, 'claude'])
463 const still = () => blit(c, DANCE[0]!, mx, y, mc)
464 // The lid is the head, hinged at its back-left corner; it cracks, stands half open on a diagonal,
465 // then swings right back and grows into a big block with teeth along its underside.
466 const lidCrack = () => {
467 blit(c, ['▗▟▌'], mx + 6, y - 1, 'claude')
468 blit(c, [' ▐▛██▀▀ '], mx, y, 'claude')
469 }
470 const lidHalf = () => {
471 blit(c, ['▗▟█▌'], mx + 5, y - 2, 'claude')
472 blit(c, ['▗▟█▀'], mx + 3, y - 1, 'claude')
473 blit(c, [' ▐▀▘'], mx, y, 'claude')
474 blit(c, ['▐'], mx + 7, y, 'claude')
475 }
476 const lidOpen = () => {
477 // A low lid: one row of head swung back, the open cavity beneath it.
478 blit(c, ['▗▟█████▙▖'], mx - 1, y - 1, 'claude')
479 blit(c, ['▌'], mx + 1, y, 'claude')
480 blit(c, ['▐'], mx + 7, y, 'claude')
481 }
482 // The snake held at mouth level to the right of the head; `into` columns of it have gone in past the
483 // right cheek, so only what is still outside is drawn.
484 const held = (f: number, x: number, into: number) => {
485 const art = SNAKE[f % 2]!.map(row => row.slice(into))
486 blit(c, art, x, y - 1, shirtColor)
487 }
488 if (u < 2) {
489 still()
490 blit(c, SNAKE[0]!, sx, snakeY, shirtColor)
491 } else if (u < 4) {
492 // A short, thick arm out of the body.
493 still()
494 blit(c, [u === 2 ? '▆' : '▆▆'], mx + 9, y + 1, shirtColor)
495 blit(c, SNAKE[u % 2]!, sx, snakeY, shirtColor)
496 } else if (u < 8) {
497 // Lifted straight up on the arm to mouth level, just right of the head.
498 const lift = u - 4 // 0..3
499 const sy = snakeY - lift
500 still()
501 blit(c, ['▆▆'], mx + 9, y + 1, shirtColor)
502 for (let r = sy + 2; r <= y + 1; r += 1) blit(c, ['▐'], mx + 10, r, shirtColor)
503 blit(c, SNAKE[u % 2]!, mx + 10, Math.max(0, sy), shirtColor)
504 } else if (u === 8) {
505 lower()
506 lidCrack()
507 blit(c, SNAKE[0]!, mx + 10, y - 1, shirtColor)
508 } else if (u === 9) {
509 lower()
510 lidHalf()
511 blit(c, SNAKE[1]!, mx + 10, y - 1, shirtColor)
512 } else if (u < 16) {
513 // Wide open; the snake slides in tail first, four columns a frame, and what passes the cheek is gone.
514 lower()
515 lidOpen()
516 const into = (u - 10) * 4
517 if (into < SNAKE_W) held(u, mx + 8, into)
518 } else if (u === 16) {
519 lower()
520 lidHalf()
521 } else if (u === 17) {
522 lower()
523 lidCrack()
524 } else if (u < 22) {
525 still()
526 blit(c, ['gulp.'], mx + 2, y - 1, 'text')
527 } else if (u < 30) {
528 still()
529 blit(c, ['♥'], mx + 4, y - 1, PINK)
530 } else return null
531 return c.map(runs)
532}
533
534
535const bar = (percent: number, width: number): string => {
536 const filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
537 return '█'.repeat(filled) + '░'.repeat(width - filled)
538}
539const barColor = (percent: number): 'error' | 'warning' | 'success' =>
540 percent >= 90 ? 'error' : percent >= 70 ? 'warning' : 'success'
541
542// The short zone name the system runs in (PDT, PST, CET), from the formatter's own parts.
543const zoneName = (d: Date): string => {
544 try {
545 const part = new Intl.DateTimeFormat([], { timeZoneName: 'short' }).formatToParts(d).find(x => x.type === 'timeZoneName')
546 return part?.value ?? ''
547 } catch {
548 return ''
549 }
550}
551const fmtTime = (d: Date): string => {
552 const zone = zoneName(d)
553 return `${d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}${zone ? ` ${zone}` : ''}`
554}
555const resetText = (iso: string | undefined, now: number): string => {
556 if (!iso) return ''
557 try {
558 const d = new Date(iso)
559 const days = (d.getTime() - now) / 86_400_000
560 if (days < 1 && d.getDate() === new Date(now).getDate()) return `resets ${fmtTime(d)}`
561 if (days < 7) return `resets ${d.toLocaleDateString([], { weekday: 'short' })} ${fmtTime(d)}`
562 return `expires ${d.toLocaleDateString([], { month: 'short', day: 'numeric' })}`
563 } catch {
564 return ''
565 }
566}
567const kTokens = (n: number): string => (n >= 1000 ? `${Math.round(n / 1000)}k` : String(n))
568const elapsed = (startedAt: number, now: number): string => {
569 const s = Math.max(0, Math.round((now - startedAt) / 1000))
570 return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`
571}
572
573// "On track" the way the desktop usage page says it: used share vs. elapsed share of the weekly window.
574// The per-model weeks come from the last usage reading; the engine's own windows name only the session and the week.
575const currentLimits = (): Limit[] => {
576 if (plan && !(rateLimitsFresh && rateLimits.length > 0)) return plan.limits
577 const perModel = (plan?.limits ?? []).filter(l => l.kind === 'weekly_scoped')
578 return rateLimits
579 .map((w): Limit => ({
580 kind: w.kind,
581 label: w.kind === 'five_hour' ? 'Session' : w.kind === 'seven_day' ? 'Week' : w.kind,
582 percent: w.percentUsed,
583 resetsAt: w.resetsAt,
584 }))
585 .concat(perModel)
586}
587
588type ConfigTab = 'dock' | 'settings' | 'status' | 'config' | 'usage' | 'stats'
589const CONFIG_TABS: readonly { id: ConfigTab; label: string }[] = [
590 { id: 'dock', label: 'Dock' },
591 { id: 'config', label: 'Config' },
592 { id: 'status', label: 'Status' },
593 { id: 'usage', label: 'Usage' },
594 { id: 'stats', label: 'Stats' },
595 { id: 'settings', label: 'File' },
596]
597let configTab: ConfigTab = 'dock'
598let sessionStartedAt = 0
599
600type Els = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
601type BracketOpts = {
602 key: string
603 label: string
604 color?: string // bracket colour when lit; dim when not
605 lit?: boolean // default true
606 width?: number // pad the label to this width, equally each side
607 onPress: () => void
608}
609// The one button shape the dock draws: `[ label ]`, brackets coloured, the whole inside pressable.
610// Padding rides inside the label as no-break spaces, which the Button keeps, so the click lands anywhere
611// between the brackets.
612const bracket = (els: Els, o: BracketOpts) => {
613 const { Box, Text, Button } = els
614 const lit = o.lit !== false
615 const side = o.width ? Math.floor(Math.max(0, o.width - o.label.length) / 2) : 0
616 const label = `\u00a0${'\u00a0'.repeat(side)}${o.label}${'\u00a0'.repeat(side)}\u00a0`
617 return (
618 <Box key={`${o.key}-wrap`} flexDirection="row" flexShrink={0}>
619 <Text bold={lit} color={lit ? o.color ?? colorOf(look.uiColor) : undefined} dimColor={!lit}>[</Text>
620 <Button key={o.key} label={label} plain dimColor={!lit} onPress={o.onPress} />
621 <Text bold={lit} color={lit ? o.color ?? colorOf(look.uiColor) : undefined} dimColor={!lit}>]</Text>
622 </Box>
623 )
624}
625
626// ~/.claude/stats-cache.json: what the engine's own /stats screen draws from.
627type StatsCache = {
628 dailyActivity?: { date: string; messageCount: number; sessionCount: number; toolCallCount: number }[]
629 dailyModelTokens?: { date: string; tokensByModel: Record<string, number> }[]
630 modelUsage?: Record<string, { inputTokens: number; outputTokens: number; cacheReadInputTokens: number; cacheCreationInputTokens: number }>
631 totalSessions?: number
632 totalMessages?: number
633 longestSession?: { duration: number; timestamp: string }
634 firstSessionDate?: string
635}
636type StatsPeriod = 'all' | '30' | '7'
637let statsPeriod: StatsPeriod = 'all'
638const PERIOD_LABEL: Record<StatsPeriod, string> = { all: 'All time', '30': 'Last 30 days', '7': 'Last 7 days' }
639
640const bigNumber = (n: number): string =>
641 n >= 1e9 ? `${(n / 1e9).toFixed(1)}b` : n >= 1e6 ? `${(n / 1e6).toFixed(1)}m` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n)
642const duration = (ms: number): string => {
643 const m = Math.floor(ms / 60000)
644 const d = Math.floor(m / 1440)
645 const hours = Math.floor((m % 1440) / 60)
646 return [d ? `${d}d` : '', hours ? `${hours}h` : '', `${m % 60}m`].filter(Boolean).join(' ')
647}
648const dayKey = (t: number): string => new Date(t).toISOString().slice(0, 10)
649const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
650const DAY_MS = 86_400_000
651
652// The /stats overview as header lines: the year's activity grid, its legend, the period line and the figures.
653const statsHeader = (cache: StatsCache, now: number, period: StatsPeriod, accent: string): Seg[][] => {
654 const activity = cache.dailyActivity ?? []
655 const byDay = new Map(activity.map(a => [a.date, a]))
656 const cutoff = period === 'all' ? 0 : now - Number(period) * DAY_MS
657 const inPeriod = (date: string) => new Date(`${date}T12:00:00Z`).getTime() >= cutoff
658 const lines: Seg[][] = []
659
660 // Grid: 53 week columns ending this week, rows Monday to Sunday, one cell per day.
661 const today = new Date(now)
662 const todayUtc = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate())
663 const weekday = (new Date(todayUtc).getUTCDay() + 6) % 7 // Monday 0
664 const thisMonday = todayUtc - weekday * DAY_MS
665 const WEEKS = 53
666 const firstMonday = thisMonday - (WEEKS - 1) * 7 * DAY_MS
667 const counts = activity.map(a => a.messageCount).filter(n => n > 0).sort((a, b) => a - b)
668 const q = (i: number) => counts[Math.min(counts.length - 1, Math.floor(counts.length * i))] ?? 0
669 const level = (n: number) => (n <= 0 ? 0 : n <= q(0.25) ? 1 : n <= q(0.5) ? 2 : n <= q(0.75) ? 3 : 4)
670 const GLYPH = ['·', '░', '▒', '▓', '█']
671 const months: Seg[] = [{ t: ' ' }]
672 let lastMonth = -1
673 for (let w = 0; w < WEEKS; w += 1) {
674 const monday = new Date(firstMonday + w * 7 * DAY_MS)
675 const m = monday.getUTCMonth()
676 if (m !== lastMonth && monday.getUTCDate() <= 7) {
677 months.push({ t: MONTHS[m]!.slice(0, 1), c: 'text' })
678 lastMonth = m
679 } else months.push({ t: ' ' })
680 }
681 lines.push(months)
682 const labels = ['Mon', '', 'Wed', '', 'Fri', '', '']
683 for (let d = 0; d < 7; d += 1) {
684 const row: Seg[] = [{ t: `${labels[d]!.padEnd(3)} `, c: 'text' }]
685 for (let w = 0; w < WEEKS; w += 1) {
686 const t = firstMonday + w * 7 * DAY_MS + d * DAY_MS
687 if (t > todayUtc) {
688 row.push({ t: ' ' })
689 continue
690 }
691 const a = byDay.get(dayKey(t))
692 const lv = level(a?.messageCount ?? 0)
693 row.push(lv === 0 ? { t: GLYPH[0]!, d: true } : { t: GLYPH[lv]!, c: accent })
694 }
695 lines.push(row)
696 }
697 lines.push([{ t: ' Less ', c: 'text' }, { t: '░▒▓█', c: accent }, { t: ' More', c: 'text' }])
698 lines.push([])
699
700 // Figures for the chosen period.
701 const days = activity.filter(a => inPeriod(a.date))
702 const tokenDays = (cache.dailyModelTokens ?? []).filter(a => inPeriod(a.date))
703 const perModel = new Map<string, number>()
704 for (const day of tokenDays) for (const [m, n] of Object.entries(day.tokensByModel)) perModel.set(m, (perModel.get(m) ?? 0) + n)
705 const favourite = [...perModel.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '—'
706 const totalTokens = [...perModel.values()].reduce((a, b) => a + b, 0)
707 const sessions = period === 'all' ? cache.totalSessions ?? days.reduce((a, d) => a + d.sessionCount, 0) : days.reduce((a, d) => a + d.sessionCount, 0)
708 const first = cache.firstSessionDate ? new Date(cache.firstSessionDate).getTime() : now
709 const span = Math.max(1, Math.floor((todayUtc - Math.max(first, cutoff)) / DAY_MS) + 1)
710 const activeDays = days.length
711 const busiest = [...days].sort((a, b) => b.messageCount - a.messageCount)[0]
712 const dateLabel = (date: string) => {
713 const dt = new Date(`${date}T12:00:00Z`)
714 return `${MONTHS[dt.getUTCMonth()]} ${dt.getUTCDate()}`
715 }
716 // Streaks over the active dates.
717 const active = new Set(activity.map(a => a.date))
718 let longest = 0
719 let current = 0
720 for (let t = todayUtc; t >= first - DAY_MS; t -= DAY_MS) {
721 if (active.has(dayKey(t))) current += 1
722 else break
723 }
724 let run = 0
725 for (let t = first; t <= todayUtc; t += DAY_MS) {
726 run = active.has(dayKey(t)) ? run + 1 : 0
727 longest = Math.max(longest, run)
728 }
729 const usage = Object.values(cache.modelUsage ?? {})
730 const sum = (k: 'inputTokens' | 'outputTokens' | 'cacheReadInputTokens' | 'cacheCreationInputTokens') => usage.reduce((a, u) => a + (u[k] ?? 0), 0)
731 const periodLine: Seg[] = []
732 for (const p of ['all', '30', '7'] as const) {
733 if (periodLine.length) periodLine.push({ t: ' · ', d: true })
734 periodLine.push(p === period ? { t: PERIOD_LABEL[p], c: accent, b: true } : { t: PERIOD_LABEL[p], d: true })
735 }
736 periodLine.push({ t: ' (←→ on the Period row switches)', d: true })
737 lines.push(periodLine)
738 lines.push([])
739 const COL = Math.max(28, `Favorite model: ${favourite}`.length + 3)
740 const pair = (l1: string, v1: string, l2: string, v2: string): Seg[] => [
741 { t: `${l1}: `, c: 'text' }, { t: v1.padEnd(Math.max(1, COL - l1.length - 2)), c: accent, b: true },
742 { t: `${l2}: `, c: 'text' }, { t: v2, c: accent, b: true },
743 ]
744 lines.push(pair('Favorite model', favourite, 'Total tokens', bigNumber(totalTokens)))
745 lines.push([])
746 lines.push(pair('Sessions', String(sessions), 'Longest session', cache.longestSession ? duration(cache.longestSession.duration) : '—'))
747 lines.push([
748 { t: 'Active days: ', c: 'text' }, { t: `${activeDays}`, c: accent, b: true }, { t: `/${span}`.padEnd(Math.max(1, COL - 13 - String(activeDays).length)), d: true },
749 { t: 'Longest streak: ', c: 'text' }, { t: `${longest} days`, c: accent, b: true },
750 ])
751 lines.push(pair('Most active day', busiest ? dateLabel(busiest.date) : '—', 'Current streak', `${current} days`))
752 if (period === 'all') {
753 lines.push([{ t: `Input ${bigNumber(sum('inputTokens'))} · Output ${bigNumber(sum('outputTokens'))} · Cache read ${bigNumber(sum('cacheReadInputTokens'))} · Cache write ${bigNumber(sum('cacheCreationInputTokens'))}`, d: true }])
754 } else {
755 lines.push([{ t: 'token split by kind is kept for all time only', d: true }])
756 }
757 return lines
758}
759
760const headline = (limits: Limit[], now: number): string => {
761 const week = limits.find(l => l.kind === 'weekly_all' || l.kind === 'seven_day')
762 if (!week?.resetsAt) return ''
763 const resets = new Date(week.resetsAt).getTime()
764 const elapsedShare = Math.max(0, Math.min(1, 1 - (resets - now) / (7 * 86_400_000)))
765 const day = new Date(resets).toLocaleDateString([], { weekday: 'long' })
766 if (week.percent >= 95) return `Weekly limit nearly used · resets ${day}`
767 if (week.percent <= elapsedShare * 100 + 15) return `On track · room to spare before ${day}'s reset`
768 return `Running hot · pace exceeds ${day}'s reset`
769}
770
771// The probe is a harmless write to the temp folder. It is only ever run to make the permission check ask.
772const BYPASS_PROBE = 'touch /tmp/cc-dock-bypass-probe'
773
774// Bypass. The engine has no call that changes the session's mode, but a permission prompt's answer can carry a
775// "set mode for this session" update. So a confirmed press runs the probe: if the permission check would ask,
776// the prompt is answered with that update; if it would allow the probe, there is no prompt to ride on and the
777// dock says so rather than claiming a switch it did not make.
778async function bypassPress($: EngineInterface): Promise<void> {
779 const now = await $.clock.now()
780 if (bypassWanted) {
781 bypassWanted = false
782 bypassNote = ''
783 redraw($)
784 return
785 }
786 if (!(bypassArmedAt && now - bypassArmedAt < CONFIRM_MS)) {
787 bypassArmedAt = now
788 redraw($)
789 return
790 }
791 bypassArmedAt = 0
792 let verdict = 'ask'
793 if (permissionMode === 'bypass') verdict = 'allow'
794 else {
795 try {
796 verdict = (await $.tool.check({ tool: 'Bash', input: { command: BYPASS_PROBE } })).decision
797 } catch {
798 verdict = 'ask'
799 }
800 }
801 if (verdict === 'deny') {
802 bypassNote = 'bypass: blocked'
803 redraw($)
804 return
805 }
806 if (verdict === 'allow') {
807 bypassNote = 'already enabled'
808 void $.clock.sleep(2_500).then(() => { bypassNote = ''; redraw($) }).catch(() => {})
809 redraw($)
810 return
811 }
812 bypassWanted = true
813 bypassNote = 'switching…'
814 redraw($)
815 // Runs the probe and reports how it ended; the checker cannot follow the engine's tool types through a chain here.
816 const ran = await runProbe($)
817 if (ran.ok) {
818 // The probe finished without the prompt the switch rides on: nothing switched.
819 if (bypassWanted) {
820 bypassWanted = false
821 bypassNote = 'already enabled'
822 void $.clock.sleep(2_500).then(() => { bypassNote = ''; redraw($) }).catch(() => {})
823 redraw($)
824 }
825 return
826 }
827 bypassWanted = false
828 bypassNote = `bypass: ${ran.message}`
829 redraw($)
830}
831
832async function runProbe($: EngineInterface): Promise<{ ok: true } | { ok: false; message: string }> {
833 try {
834 // The engine's tool.call overloads exceed TypeScript's depth limit (TS2589) in this engine version; the call itself is valid.
835 // @ts-expect-error TS2589 from the engine's tool.call overloads
836 const ran = (await $.tool.call({ tool: 'Bash', command: BYPASS_PROBE, description: 'Dock permission probe' } as never)) as { deny?: string; isError?: boolean; text?: string } | undefined
837 // A refused or failed probe resolves rather than throws; it must not read as a probe that ran clean.
838 if (ran?.deny !== undefined) return { ok: false, message: ran.deny }
839 if (ran?.isError) return { ok: false, message: ran.text || 'the probe failed' }
840 return { ok: true }
841 } catch (err) {
842 return { ok: false, message: err instanceof Error ? err.message : 'the probe did not run' }
843 }
844}
845
846function redraw($: EngineInterface): void {
847 $.ui.invalidate('ui.render')
848}
849
850// The login record holds the plan tier and the token the usage endpoint wants. The token stays in
851// this function's scope and is never logged, drawn or stored.
852async function readLogin($: EngineInterface): Promise<{ token: string; tier: string } | null> {
853 let raw = ''
854 try {
855 // The login is filed under the account name; an older entry under another account can hold only the MCP tokens.
856 const user = await $.env.get('USER').then(v => v ?? '', () => '')
857 const r = await $.process.run(['security', 'find-generic-password', '-s', 'Claude Code-credentials', ...(user ? ['-a', user] : []), '-w'])
858 if (r.exitCode === 0) raw = r.stdout.trim()
859 } catch {
860 raw = ''
861 }
862 if (!raw) {
863 try {
864 const home = (await $.env.get('HOME')) ?? ''
865 raw = await $.fs.read(`${home}/.claude/.credentials.json`)
866 } catch {
867 return null
868 }
869 }
870 try {
871 const o = JSON.parse(raw) as { claudeAiOauth?: { accessToken?: string; rateLimitTier?: string; subscriptionType?: string } }
872 const auth = o.claudeAiOauth
873 if (!auth?.accessToken) return null
874 return { token: auth.accessToken, tier: auth.rateLimitTier ?? auth.subscriptionType ?? '' }
875 } catch {
876 return null
877 }
878}
879
880type UsageJson = {
881 limits?: { kind: string; percent: number; resets_at?: string; scope?: { model?: { display_name?: string } } | null }[]
882 seven_day_breakdown?: { rows?: { key: string; percent: number }[] }
883} & Record<string, unknown>
884
885function parseUsage(json: UsageJson, tier: string, now: number): Plan {
886 const limits: Limit[] = []
887 for (const l of json.limits ?? []) {
888 const scoped = l.kind === 'weekly_scoped' ? l.scope?.model?.display_name : undefined
889 const label = l.kind === 'session' ? 'Session' : l.kind === 'weekly_all' ? 'Week' : scoped ? scoped : l.kind
890 limits.push({ kind: l.kind, label, percent: l.percent, resetsAt: l.resets_at })
891 }
892 const code = json.seven_day_breakdown?.rows?.find(r => r.key === 'claude_code')
893 return { tier: TIER_LABEL[tier] ?? tier, limits, codeShare: code?.percent, fetchedAt: now }
894}
895
896// Panes open at once, mid-turn or not; a slash command would wait in the prompt queue.
897const DOCK_PANES = [CONFIG_PANE]
898async function openPane($: EngineInterface, id: string, title: string): Promise<void> {
899 try {
900 // One dock pane at a time, so the engine draws no tab row above it; the dock's own buttons switch.
901 for (const other of DOCK_PANES) {
902 if (other === id) continue
903 try {
904 await $.ui.close({ id: other })
905 } catch {
906 // not open
907 }
908 }
909 const opened = await $.ui.open({ id, title, focus: true, closeOnEscape: true })
910 usageNote = opened.isPlaced ? '' : `widen the terminal to see ${title}`
911 } catch (err) {
912 usageNote = err instanceof Error ? err.message : `could not open ${title}`
913 }
914 redraw($)
915}
916
917async function loadBreakdown($: EngineInterface, columns: number): Promise<void> {
918 if (breakdownBusy) return
919 breakdownBusy = true
920 breakdownNote = 'counting…'
921 const started = conversationEpoch
922 redraw($)
923 try {
924 const usage = await $.session.usage({ breakdown: 'full', columns })
925 // A count that finishes after /clear belongs to the conversation it started in, so it is dropped.
926 if (started !== conversationEpoch) return
927 context = usage.context
928 breakdown = usage.context.breakdown ?? null
929 breakdownNote = breakdown ? '' : 'no breakdown available'
930 } catch (err) {
931 if (started === conversationEpoch) breakdownNote = err instanceof Error ? err.message : 'could not count the context'
932 } finally {
933 breakdownBusy = false
934 redraw($)
935 }
936}
937// Bumped at each new conversation, so late replies from the old one can be recognised and dropped.
938let conversationEpoch = 0
939
940// First press arms the button (it reads "Yes?"), the second within CONFIRM_MS compacts; a stray click does nothing.
941async function compactPress($: EngineInterface): Promise<void> {
942 const now = await $.clock.now()
943 if (compactArmedAt && now - compactArmedAt < CONFIRM_MS) {
944 compactArmedAt = 0
945 await compactNow($)
946 return
947 }
948 compactArmedAt = now
949 redraw($)
950}
951
952// The engine compacts only between turns; mid-turn the request is queued so it runs the moment the turn ends.
953async function compactNow($: EngineInterface): Promise<void> {
954 const started = await $.clock.now()
955 compacting = true
956 compactAsked = false
957 compactNote = ''
958 bubble = 'compacting.'
959 bubbleSince = started
960 bubbleHold = 10 * 60_000
961 startStars($)
962 redraw($)
963 try {
964 const result = await $.session.compact()
965 compacting = false
966 if (result.skip !== undefined) {
967 refuseCompact($, String(result.skip))
968 } else {
969 compactions += 1
970 setBubble($, 'success!', 3_000)
971 await readUsage($)
972 }
973 } catch (err) {
974 compacting = false
975 // A press that landed mid-turn waits for the turn to end; any other failure is shown, not retried later.
976 const message = err instanceof Error ? err.message : 'did not run'
977 if (turnRunning || /turn/i.test(message)) {
978 compactWhenIdle = true
979 setBubble($, 'compacts after this turn', 4_000)
980 } else {
981 refuseCompact($, message)
982 }
983 }
984 redraw($)
985}
986
987// The bubble says it did not run; the reason, too long for its few words, goes beside the buttons for a while.
988function refuseCompact($: EngineInterface, reason: string): void {
989 setBubble($, 'not compacted', 4_000)
990 compactNote = reason
991 void $.clock.sleep(8_000).then(() => {
992 if (compactNote !== reason) return
993 compactNote = ''
994 redraw($)
995 }).catch(() => {})
996}
997
998// Shows a line in the avatar's bubble for a set time.
999function setBubble($: EngineInterface, text: string, holdMs: number): void {
1000 void $.clock.now().then(now => {
1001 bubble = text
1002 bubbleSince = now
1003 bubbleHold = holdMs
1004 redraw($)
1005 })
1006}
1007
1008// Reads the live figures for the current conversation.
1009async function readUsage($: EngineInterface): Promise<void> {
1010 try {
1011 const usage = await $.session.usage()
1012 context = usage.context
1013 rateLimits = usage.rateLimits
1014 rateLimitsFresh = usage.rateLimits.length > 0
1015 cost = usage.cost
1016 sessionStartedAt = usage.startedAt
1017 breakdown = null
1018 breakdownNote = ''
1019 // An open Context view draws the breakdown just cleared; count it again rather than leave it on "counting…".
1020 if (view === 'context' && bandColumns > 0) void loadBreakdown($, bandColumns)
1021 } catch {
1022 // the figures refresh on the next response
1023 }
1024}
1025
1026async function syncModel($: EngineInterface): Promise<void> {
1027 try {
1028 const now = await $.session.model()
1029 if (now && now !== model) {
1030 model = now
1031 redraw($)
1032 }
1033 } catch {
1034 // keep the last reading
1035 }
1036}
1037
1038// The model, its reasoning level and fast mode, as /model and /config show them.
1039async function loadModelInfo($: EngineInterface): Promise<void> {
1040 try {
1041 model = await $.session.model()
1042 } catch {
1043 // keep the last reading
1044 }
1045}
1046
1047// A chip press: the lit level again clears the override, another sets it; the store keeps it across sessions.
1048let effortPending: ModelEffort | '' = ''
1049// Usage by model, summed from every turn.complete since the dock loaded (the engine's own totals since
1050// session start are not exposed).
1051type ModelTally = { input: number; output: number; cacheRead: number; cacheWrite: number; turns: number }
1052const tally = new Map<string, ModelTally>()
1053let requests = 0
1054let apiMs = 0 // a level to hand /effort once the session is idle
1055
1056// Runs /effort <level> as typed: the only way the running session's own level changes. Idle it runs at
1057// once; mid-turn it waits for turn.complete, so nothing queues behind a prompt.
1058// One /effort run at a time. A pick made while one runs waits for it and goes next; an older run never undoes a newer pick.
1059// A pick waits this long before it is sent, so quick clicks replace each other and only the last one is sent.
1060const SETTLE_MS = 400
1061let effortTimer: { cancel: () => void } | null = null
1062let ultraTimer: { cancel: () => void } | null = null
1063// The level the engine last confirmed, so picking it again can cancel a switch that has not gone out yet.
1064let engineEffort: ModelEffort | '' = ''
1065let effortRunning = false
1066async function applyEffortLive($: EngineInterface): Promise<void> {
1067 if (effortRunning || turnRunning) return
1068 const level = effortPending
1069 if (!level) return
1070 effortPending = ''
1071 effortRunning = true
1072 try {
1073 const result = await ownCommand($, { command: 'effort', args: level })
1074 readEffortText(result.text)
1075 engineEffort = level
1076 if (effortOverride === level) {
1077 if (!result.text) effort = level
1078 effortOverride = ''
1079 }
1080 if (effortBusy?.level === level) effortBusy.carried = true
1081 configNote = ''
1082 } catch (err) {
1083 if (effortBusy?.level === level) effortBusy = null
1084 configNote = `effort: ${err instanceof Error ? err.message : '/effort did not run'}`
1085 } finally {
1086 effortRunning = false
1087 }
1088 if (effortPending) await applyEffortLive($)
1089 redraw($)
1090}
1091
1092// /effort's own words carry the state: "Ultracode on (this session only) … Effort stays high.",
1093// "Ultracode off. Effort stays high.", "Effort set to xhigh". A level the person chose there is the
1094// real one, so it also clears any level the dock had been forcing. Answers whether the reply named a level.
1095function readEffortText(text: string | undefined): boolean {
1096 if (!text) return false
1097 if (/ultracode\s+on/i.test(text)) ultracode = true
1098 else if (/ultracode\s+off/i.test(text)) ultracode = false
1099 // "Effort stays high", "Set effort level to low (…)", "Effort set to xhigh", "effort: medium".
1100 const m = /effort(?:\s+level)?\s*(?:stays|set to|is now|is|to|:)?\s*(low|medium|high|xhigh|max)\b/i.exec(text)
1101 if (!m) return false
1102 const level = m[1]!.toLowerCase() as ModelEffort
1103 engineEffort = level
1104 // A newer pick still waiting keeps the requests and the chip; an older run's reply must not undo it.
1105 if (!effortPending) {
1106 effort = level
1107 effortOverride = ''
1108 }
1109 return true
1110}
1111
1112// Whatever the dock still meant to switch is moot once the person has settled it with a typed /effort.
1113function dropPendingSwitches(): void {
1114 if (effortTimer) effortTimer.cancel()
1115 if (ultraTimer) ultraTimer.cancel()
1116 effortTimer = null
1117 ultraTimer = null
1118 effortPending = ''
1119 ultraPending = ''
1120 effortBusy = null
1121 ultraBusy = null
1122 effortOverride = ''
1123}
1124
1125// Ultracode is session state the engine switches only through `/effort ultracode on|off`; run it idle, or
1126// after the running turn ends, never queued behind a prompt.
1127let ultraRunning = false
1128async function applyUltracodeLive($: EngineInterface): Promise<void> {
1129 if (ultraRunning || turnRunning) return
1130 const want = ultraPending
1131 if (!want) return
1132 ultraPending = ''
1133 ultraRunning = true
1134 try {
1135 const result = await ownCommand($, { command: 'effort', args: `ultracode ${want}` })
1136 readEffortText(result.text)
1137 if (!result.text) ultracode = want === 'on'
1138 if (ultraBusy?.want === want) ultraBusy = null
1139 configNote = ''
1140 } catch (err) {
1141 if (ultraBusy?.want === want) ultraBusy = null
1142 configNote = `ultracode: ${err instanceof Error ? err.message : '/effort did not run'}`
1143 } finally {
1144 ultraRunning = false
1145 }
1146 if (ultraPending) await applyUltracodeLive($)
1147 redraw($)
1148}
1149
1150// The mascot's word of warning when bypass comes on: five seconds, over anything else he was saying.
1151const careful = (now: number): void => {
1152 if (slim) return
1153 bubble = 'Careful!'
1154 bubbleHold = 5_000
1155 bubbleSince = now
1156}
1157
1158// UltraCode is a queued /effort command too: its chip shows the star until the engine confirms the switch.
1159// A click while one waits flips what was asked for, so the last click always wins.
1160async function toggleUltracode($: EngineInterface): Promise<void> {
1161 const want = ultraBusy ? (ultraBusy.want === 'on' ? 'off' : 'on') : ultracode ? 'off' : 'on'
1162 // Asking for what the engine already holds cancels whatever was waiting; nothing is sent.
1163 if ((want === 'on') === ultracode && !ultraRunning) {
1164 if (ultraTimer) ultraTimer.cancel()
1165 ultraTimer = null
1166 ultraPending = ''
1167 ultraBusy = null
1168 configNote = ''
1169 redraw($)
1170 return
1171 }
1172 ultraBusy = { want, since: await $.clock.now() }
1173 startStars($)
1174 ultraPending = want
1175 configNote = ''
1176 if (ultraTimer) ultraTimer.cancel()
1177 ultraTimer = $.clock.after(SETTLE_MS, () => {
1178 ultraTimer = null
1179 void applyUltracodeLive($)
1180 })
1181 redraw($)
1182}
1183
1184// Whatever the dock still means to switch, done the moment the session is idle; called after each turn and
1185// again on the idle checks, so a switch pressed during back-to-back turns is never left hanging.
1186// A turn that never reports its end (a dropped call, a crash inside a hook) must not hold pending switches forever.
1187async function watchTurn($: EngineInterface): Promise<void> {
1188 if (!turnRunning) return
1189 if ((await $.clock.now()) - lastStepAt > 10 * 60_000) {
1190 turnRunning = false
1191 void flushPending($)
1192 redraw($)
1193 }
1194}
1195
1196async function flushPending($: EngineInterface): Promise<void> {
1197 if (turnRunning) return
1198 if (effortPending) await applyEffortLive($)
1199 if (ultraPending) await applyUltracodeLive($)
1200 if (fastPending) await toggleFast($)hooks/menu.tsx 269 lines1import type { ClientModule } from 'claude-code'
2
3// A row the menu draws: `action` says what Enter does (`toggle`, `cycle`, `expand`, or nothing).
4export type MenuRow = {
5 id: string
6 label: string
7 value: string
8 action: 'toggle' | 'cycle' | 'expand' | 'none'
9 note?: string
10 details?: string[]
11 heading?: boolean // a bold section title the cursor skips
12 muted?: boolean // drawn dim: a value nothing can change
13}
14
15export type MenuTab = { id: string; label: string }
16
17// One coloured piece of a header line.
18export type Seg = { t: string; c?: string; d?: boolean; b?: boolean }
19
20export type MenuProps = {
21 rows: MenuRow[]
22 labelWidth: number
23 tabs?: MenuTab[]
24 activeTab?: string
25 hint?: string
26 header?: Seg[][] // free-form coloured lines drawn between the hint and the rows
27 accent?: string // the colour of ‹ ›, ▸ ▾, the tab brackets and the animated selector
28}
29
30type MenuState = {
31 zone: 'list' | 'tabs'
32 cursor: number
33 tab: number
34 top: number
35 open: string[]
36 frame: number
37}
38
39// The listeners are set once per instance; they read the newest props and layout through this ref
40// instead of the closure of the render that set them.
41type Latest = { props: MenuProps; rows: MenuRow[]; tabs: MenuTab[]; count: number; room: number; headerLines: number; lines: { row: MenuRow; detail?: string; index: number }[] }
42const latestBySurface = new WeakMap<object, Latest>()
43
44// The engine's own spinner frames, turning on whatever has the keyboard.
45const SPIN = ['·', '✢', '✳', '✶', '✻', '✽']
46const fresh = (): MenuState => ({ zone: 'list', cursor: 0, tab: 0, top: 0, open: [], frame: 0 })
47
48// The rows a text takes wrapped to `width` columns: words kept whole, one longer than a row broken across rows.
49const wrappedRows = (text: string, width: number): number => {
50 if (!(width > 0)) return 1
51 let rows = 1
52 let used = 0
53 for (const word of text.split(' ')) {
54 let len = word.length
55 if (used > 0 && used + 1 + len <= width) {
56 used += 1 + len
57 continue
58 }
59 if (used > 0) rows += 1
60 while (len > width) {
61 rows += 1
62 len -= width
63 }
64 used = len
65 }
66 return rows
67}
68// A header line is a row of coloured pieces; one longer than the pane spills onto further rows.
69const lineRows = (segs: Seg[], width: number): number =>
70 width > 0 ? Math.max(1, Math.ceil(segs.reduce((w, sg) => w + sg.t.length, 0) / width)) : 1
71
72// Click the list to give it the keyboard. ↑↓ move through the rows; ↑ past the first row reaches the tab
73// bar, where ←→ pick a tab and Enter opens it, ↓ returns to the list. On a row, Enter/→ go forward and ←
74// back. A change posts `{ select, dir }` or `{ tab }` to the hooks module, which performs it.
75const Menu: ClientModule<MenuProps, MenuState> = (props, surface) => {
76 const { Box, Text } = surface.elements
77 const state = surface.state ?? fresh()
78 const rows = props.rows
79 const tabs = props.tabs ?? []
80 const count = rows.length
81 const header = props.header ?? []
82 // The hint and the header lines wrap in a narrow pane; a click's row is counted from the real height above the list.
83 const headerLines =
84 (tabs.length > 0 ? 2 : 0) +
85 (props.hint ? wrappedRows(props.hint, surface.columns) + 1 : 0) +
86 header.reduce((n, segs) => n + lineRows(segs, surface.columns), 0)
87
88 const lines: { row: MenuRow; detail?: string; index: number }[] = []
89 rows.forEach((row, index) => {
90 lines.push({ row, index })
91 if (state.open.includes(row.id)) for (const d of row.details ?? []) lines.push({ row, detail: d, index })
92 })
93 const room = Math.max(3, (surface.rows || lines.length + headerLines) - headerLines)
94 if (count > 0 && state.cursor > count - 1 && surface.state !== undefined) surface.setState({ ...state, cursor: count - 1 })
95 if (surface.state !== undefined && rows[state.cursor]?.heading) {
96 const firstRow = rows.findIndex((r, i) => i > state.cursor && !r.heading)
97 if (firstRow >= 0) surface.setState({ ...state, cursor: firstRow })
98 }
99 const cursorLine = lines.findIndex(l => l.index === Math.min(state.cursor, Math.max(0, count - 1)) && l.detail === undefined)
100 let top = state.top
101 if (cursorLine < top) top = cursorLine
102 if (cursorLine >= top + room) top = cursorLine - room + 1
103 top = Math.max(0, Math.min(top, Math.max(0, lines.length - room)))
104
105 latestBySurface.set(surface, { props, rows, tabs, count, room, headerLines, lines })
106 const now = (): Latest => latestBySurface.get(surface) ?? { props, rows, tabs, count, room, headerLines, lines }
107 const tabAt = (x: number): number => {
108 const { tabs: ts } = now()
109 let col = 0
110 for (let i = 0; i < ts.length; i += 1) {
111 const w = ts[i]!.label.length + 4
112 if (x >= col && x < col + w) return i
113 col += w + 2
114 }
115 return -1
116 }
117 const openRow = (s: MenuState, row: MenuRow, back: boolean) => {
118 if (row.action === 'expand') {
119 const isOpen = s.open.includes(row.id)
120 if (back && !isOpen) return
121 if (!back && isOpen) return
122 surface.setState({ ...s, open: isOpen ? s.open.filter(id => id !== row.id) : [...s.open, row.id] })
123 } else if (row.action === 'cycle') surface.post({ select: row.id, dir: back ? 'prev' : 'next' })
124 else if (row.action === 'toggle') surface.post({ select: row.id })
125 }
126
127 if (surface.state === undefined) {
128 surface.setState(fresh())
129 surface.every(150, () => {
130 const s = surface.state ?? fresh()
131 surface.setState({ ...s, frame: (s.frame + 1) % SPIN.length })
132 })
133 surface.onKey(event => {
134 const s = surface.state ?? fresh()
135 const { props, rows, tabs, count, room } = now()
136 if (s.zone === 'tabs') {
137 if (event.key === 'left') surface.setState({ ...s, tab: Math.max(0, s.tab - 1) })
138 else if (event.key === 'right') surface.setState({ ...s, tab: Math.min(tabs.length - 1, s.tab + 1) })
139 else if (event.key === 'down') surface.setState({ ...s, zone: 'list' })
140 else if (event.key === 'return' || event.key === ' ') {
141 const t = tabs[s.tab]
142 if (t) surface.post({ tab: t.id })
143 }
144 return
145 }
146 // Headings are skipped in whichever direction the cursor moves.
147 const skip = (from: number, dir: 1 | -1): number => {
148 // An empty tab has no row to move to: the cursor stays at the top.
149 if (count <= 0) return 0
150 let i = from
151 while (i >= 0 && i < count && rows[i]?.heading) i += dir
152 return i < 0 || i >= count ? Math.min(count - 1, Math.max(0, from - dir)) : i
153 }
154 if (event.key === 'up') {
155 const first = rows.findIndex(r => !r.heading)
156 if (s.cursor <= Math.max(0, first) && tabs.length > 0) {
157 const active = Math.max(0, tabs.findIndex(t => t.id === props.activeTab))
158 surface.setState({ ...s, zone: 'tabs', tab: active })
159 } else surface.setState({ ...s, cursor: skip(Math.max(0, s.cursor - 1), -1) })
160 } else if (event.key === 'down') surface.setState({ ...s, cursor: skip(Math.min(count - 1, s.cursor + 1), 1) })
161 else if (event.key === 'pageup') surface.setState({ ...s, cursor: Math.max(0, s.cursor - room) })
162 else if (event.key === 'pagedown') surface.setState({ ...s, cursor: Math.min(count - 1, s.cursor + room) })
163 else if (event.key === 'home') surface.setState({ ...s, cursor: 0 })
164 else if (event.key === 'end') surface.setState({ ...s, cursor: count - 1 })
165 else if (event.key === 'return' || event.key === ' ' || event.key === 'right' || event.key === 'left') {
166 const row = rows[s.cursor]
167 if (row) openRow(s, row, event.key === 'left')
168 }
169 })
170 surface.onPointer(event => {
171 if (event.type !== 'down') return
172 const s = surface.state ?? fresh()
173 const { tabs, headerLines, lines } = now()
174 if (tabs.length > 0 && event.y === 0) {
175 const i = tabAt(event.x)
176 if (i >= 0) {
177 surface.setState({ ...s, zone: 'tabs', tab: i })
178 surface.post({ tab: tabs[i]!.id })
179 }
180 return
181 }
182 const y = event.y - headerLines
183 if (y < 0) return
184 const hit = lines[s.top + y]
185 if (!hit) return
186 if (hit.index !== s.cursor || s.zone !== 'list') {
187 surface.setState({ ...s, zone: 'list', cursor: hit.index })
188 return
189 }
190 openRow(s, hit.row, false)
191 })
192 } else if (top !== state.top) {
193 surface.setState({ ...state, top })
194 }
195
196 const glyph = SPIN[state.frame] ?? '·'
197 const accent = props.accent ?? 'claude'
198 const shown = lines.slice(top, top + room)
199 return (
200 <Box flexDirection="column">
201 {tabs.length > 0 ? (
202 <Box flexDirection="row" columnGap={2}>
203 {tabs.map((t, i) => {
204 const active = t.id === props.activeTab
205 const focused = state.zone === 'tabs' && state.tab === i
206 // `[ Name ]`: the active page's name bold white in orange brackets, the rest dim; the focused
207 // one alternates its word with the spinner glyph.
208 const showGlyph = focused && state.frame % 4 >= 2
209 const inner = t.label.length
210 const left = Math.floor((inner - 1) / 2)
211 const word = showGlyph ? ' '.repeat(left) + glyph + ' '.repeat(inner - 1 - left) : t.label
212 const lit = active || focused
213 return (
214 <Box key={`tab-${t.id}`} flexDirection="row">
215 <Text bold={lit} color={lit ? accent : undefined} dimColor={!lit}>[ </Text>
216 <Text bold={lit} color={showGlyph ? accent : lit ? 'text' : undefined} dimColor={!lit}>{word}</Text>
217 <Text bold={lit} color={lit ? accent : undefined} dimColor={!lit}> ]</Text>
218 </Box>
219 )
220 })}
221 </Box>
222 ) : null}
223 {tabs.length > 0 ? <Text> </Text> : null}
224 {props.hint ? <Text dimColor>{props.hint}</Text> : null}
225 {props.hint ? <Text> </Text> : null}
226 {header.map((segs, i) => (
227 <Box key={`h-${i}`} flexDirection="row">
228 {segs.length === 0 ? <Text> </Text> : segs.map((sg, j) => <Text key={`h-${i}-${j}`} color={sg.c} dimColor={sg.d} bold={sg.b}>{sg.t}</Text>)}
229 </Box>
230 ))}
231 {shown.map((line, i) => {
232 const here = state.zone === 'list' && line.index === state.cursor && line.detail === undefined
233 if (line.detail !== undefined) {
234 return (
235 <Box key={`d-${line.row.id}-${i}`} flexDirection="row">
236 <Text dimColor>{' · '}{line.detail}</Text>
237 </Box>
238 )
239 }
240 const row = line.row
241 if (row.heading) {
242 return (
243 <Box key={`r-${row.id}`} flexDirection="row" paddingLeft={1}>
244 <Text> </Text>
245 <Text bold color={row.label.trim() ? 'text' : undefined}>{row.label ? ` ${row.label}` : ' '}</Text>
246 </Box>
247 )
248 }
249 const steps = row.action === 'cycle' || row.action === 'toggle'
250 const mark = row.action === 'expand' ? (state.open.includes(row.id) ? '▾' : '▸') : ''
251 return (
252 <Box key={`r-${row.id}`} flexDirection="row" columnGap={1} paddingLeft={1}>
253 <Text bold={here} color={here ? accent : undefined}>{here ? glyph : ' '}</Text>
254 <Text bold={here} color="text" dimColor={row.muted && !here} wrap="truncate-end">{row.label.padEnd(props.labelWidth)}</Text>
255 {steps ? <Text color={accent}>‹</Text> : null}
256 <Text bold={here} color={row.muted ? undefined : 'text'} dimColor={row.muted}>{row.value}</Text>
257 {steps ? <Text color={accent}>›</Text> : null}
258 {mark ? <Text color={accent}>{mark}</Text> : null}
259 {row.note ? <Text dimColor wrap="truncate-end">{row.note}</Text> : null}
260 </Box>
261 )
262 })}
263 {lines.length > room ? <Text dimColor>{` ${top + shown.length} of ${lines.length} · ↑↓ scroll`}</Text> : null}
264 </Box>
265 )
266}
267
268export default Menu
269hooks/voice-envelope.ts 5 lines1// The mouth for sounds/idle-voice.mp3: one value per 70 ms (0 closed, 1 open, 2 wide), from its loudness.
2// Regenerate with the launch project's tools/voice-envelope.mjs when the clip changes.
3export const VOICE_STEP_MS = 70
4export const VOICE_FRAMES: readonly number[] = [0,0,0,0,0,0,2,2,1,1,2,2,1,1,1,0,0,0,0,1,1,1,2,1,2,2,2,1,1,1,0,0,1,2,1,1,1,1,2,2,1,1,1,1,1,1,2,2,2,0,0,0,0,0,1,2,2,1,1,1,1,1,1,2,1,1,1,2,2,1,1,2,2,2,2,2,2,1,2,1,1,1,2,2,2,2,0,0,1,2,2,1,1,1,1,1,1,2,2,2,1,1,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,2,1,1,0,0,0,1,1,1,0,0,0,1,2,2,2,1,2,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,2,2,2,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,1,2,2,1,1,1,0,0,0,0,0,1,1,2,1,1,2,2,1,1,1,1,0,0,1,1,1,1,1,1,2,2,1,1,1,1,1,2,2,1,1,0,0,1,1,1,1,0,0,0,0,1,1,1,2,1,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,1,2,2,2,1,2,0,0,0,0,1,1,1,0,0,2,2,1,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,1,2,1,1,1,1,0,0,0,1,2,1,0,0,1,1,1,2,2,2,1,1,1,1,1,1,1,2,1,0,0,0,0,1,0,0,0]
5hooks/chip.tsx 46 lines1import type { ClientModule } from 'claude-code'
2
3// A coloured `[ label ]` chip whose word and brackets share one colour (a Button cannot). While lit, a
4// highlight sweeps across the letters, the shimmer Claude Code gives the word "ultracode". A click
5// posts `{ press: true }`.
6export type ChipProps = { label: string; color: string; glow?: string; lit: boolean; width?: number; bracketColor?: string }
7type ChipState = { frame: number }
8
9const Chip: ClientModule<ChipProps, ChipState> = (props, surface) => {
10 const { Box, Text } = surface.elements
11 const state = surface.state ?? { frame: 0 }
12 const span = props.label.length + 6 // the sweep runs off both ends before it comes round
13 if (surface.state === undefined) {
14 surface.setState({ frame: 0 })
15 surface.every(90, () => {
16 const s = surface.state ?? { frame: 0 }
17 surface.setState({ frame: (s.frame + 1) % span })
18 })
19 surface.onPointer(event => {
20 if (event.type === 'down') surface.post({ press: true })
21 })
22 }
23 const glow = props.glow ?? props.color
24 const head = state.frame - 3
25 // Centred to `width` when given, so the chip lines up with bracket buttons beside it.
26 const pad = Math.max(0, (props.width ?? props.label.length) - props.label.length)
27 const padL = ' '.repeat(Math.floor(pad / 2))
28 const padR = ' '.repeat(pad - Math.floor(pad / 2))
29 const letters = props.lit
30 ? [...props.label].map((ch, i) => {
31 const d = Math.abs(i - head)
32 // The letter under the sweep glows, its two neighbours a little, the rest hold the base colour.
33 return <Text key={`c${i}`} bold color={d === 0 ? glow : props.color} dimColor={false}>{ch}</Text>
34 })
35 : [<Text key="w" dimColor>{props.label}</Text>]
36 return (
37 <Box flexDirection="row">
38 <Text bold={props.lit} color={props.lit ? props.bracketColor ?? props.color : undefined} dimColor={!props.lit}>{`[ ${padL}`}</Text>
39 {letters}
40 <Text bold={props.lit} color={props.lit ? props.bracketColor ?? props.color : undefined} dimColor={!props.lit}>{`${padR} ]`}</Text>
41 </Box>
42 )
43}
44
45export default Chip
46hooks/mascot.tsx 413 lines1import type { ClientModule } from 'claude-code'
2
3// The mascot column: his floating words, the mascot in his shirt colour, and whatever reaction he is
4// in the middle of. A click posts `{ tap: true }` and the hooks roll a reaction, handed back as `react`
5// (a new `id` starts it): `shake` (a dizzy WHOOAH), `pacman`, `chef`, `storm`, or `spider` (one spins a web
6// in the top-left corner and drops down on a thread while he looks up), or `night` (a scarf, a dark sky with a
7// moon, twinkling stars and fireflies); the snake chase plays on the band. `climb` is a counter:
8// each new value starts the ladder gag. During a storm, a click pops the umbrella early.
9export type Reaction = { kind: 'shake' | 'pacman' | 'chef' | 'storm' | 'spider' | 'night'; id: number }
10export type MascotProps = {
11 pose: string[]
12 bubble: string[]
13 bubbleColor?: string
14 color: string
15 climb: number
16 // When the last climb was asked for (ms). A mascot mounted fresh, after Slim, climbs if the request is recent.
17 climbAt?: number
18 rows: number
19 leanPoses: string[][]
20 dancePoses: string[][]
21 react: Reaction | null
22 ultra?: boolean // ultracode is on: he is the purple sparkler mascot from the engine's own banner
23 // A voice clip playing now: each new id starts it, and his head lifts off his body by frames[i] rows every stepMs.
24 talk: { id: number; frames: readonly number[]; stepMs: number; startedAt?: number } | null
25}
26type MascotState = {
27 seenClimb: number
28 climbTick: number
29 climbing: boolean
30 seenReact: number
31 tick: number
32 reacting: Reaction['kind'] | null
33 umbrellaAt: number
34 seenTalk: number
35 talkTick: number
36 talking: boolean
37 talkStartedAt: number
38}
39
40const latestBySurface = new WeakMap<object, MascotProps>()
41const TICK_MS = 140
42const PINK = '#ff5fa2'
43const ULTRA = '#a78bfa' // the banner mascot's purple while ultracode is on
44const SPLASH = ['·', '✢', '✳', '✶', '✻', '✽'] // the menus' spinner frames, as rain splashing on the umbrella
45const SPARK = '#e8c547' // the sparkler's gold
46// The ladder needs room above him; a climb asked for in the last few seconds plays on a fresh mount too.
47const ladderEnd = (room: number): number => {
48 const TOP = Math.max(1, room - 1)
49 return 3 + TOP * 2 + 2 + 4 + TOP * 2 + 3 + 1
50}
51const fresh = (p: MascotProps): MascotState => ({ seenClimb: p.climb, climbTick: 0, climbing: Math.max(0, p.rows - p.pose.length) >= 3 && (p.climbAt ?? 0) > 0 && Date.now() - (p.climbAt ?? 0) < 3000, seenReact: p.react?.id ?? 0, tick: 0, reacting: null, umbrellaAt: -1, seenTalk: p.talk?.id ?? 0, talkTick: 0, talking: false, talkStartedAt: 0 })
52const REACT_TICKS: Record<Reaction['kind'], number> = { shake: 18, pacman: 26, chef: 30, storm: 96, spider: 70, night: 80 }
53
54const Mascot: ClientModule<MascotProps, MascotState> = (props, surface) => {
55 const { Box, Text } = surface.elements
56 latestBySurface.set(surface, props)
57 const state = surface.state ?? fresh(props)
58 const rows = props.rows
59 const roomAbove = Math.max(0, rows - props.pose.length) // rows free above him at rest
60
61 // Ladder gag timeline, in ticks.
62 const H = roomAbove
63 const APPEAR = 3
64 const TOP = Math.max(1, H - 1)
65 const CLIMB = APPEAR + TOP * 2
66 const HOLD = CLIMB + 2
67 const GONE = HOLD + 4
68 const FLOAT = GONE + TOP * 2
69 const LAND = FLOAT + 3
70 const END = LAND + 1
71
72 if (surface.state === undefined) {
73 surface.setState(fresh(props))
74 surface.every(TICK_MS, () => {
75 const s = surface.state ?? fresh(props)
76 const p = latestBySurface.get(surface) ?? props
77 let n = { ...s }
78 // Start a ladder when a new climb arrives and nothing else is playing.
79 // The room comes from the latest props, not the first render's, so a Bulk after Slim gets the full height.
80 const room = Math.max(0, p.rows - p.pose.length)
81 if (p.climb !== s.seenClimb) {
82 n = { ...n, seenClimb: p.climb, climbTick: 0, climbing: room >= 3 && !s.reacting }
83 } else if (s.climbing) {
84 const t = s.climbTick + 1
85 n = { ...n, climbTick: t, climbing: t < ladderEnd(room) }
86 }
87 // Start a reaction when a new one arrives and nothing is playing; one in progress always plays out.
88 const id = p.react?.id ?? 0
89 if (s.reacting) {
90 const t = s.tick + 1
91 const still = t < REACT_TICKS[s.reacting]
92 n = { ...n, tick: t, reacting: still ? s.reacting : null }
93 if (!still) surface.post({ done: true })
94 } else if (id !== s.seenReact) {
95 n = { ...n, seenReact: id, tick: 0, reacting: !n.climbing && p.react ? p.react.kind : null, umbrellaAt: -1 }
96 if (!n.reacting) surface.post({ done: true })
97 }
98 surface.setState(n)
99 })
100 // The mouth follows the clip by elapsed time, not by ticks, so a timer running late never lets it drift.
101 surface.every(50, () => {
102 const s = surface.state ?? fresh(props)
103 const p = latestBySurface.get(surface) ?? props
104 const id = p.talk?.id ?? 0
105 if (s.talking && p.talk) {
106 const t = Math.floor((Date.now() - s.talkStartedAt) / p.talk.stepMs)
107 const still = t < p.talk.frames.length
108 if (t !== s.talkTick || !still) surface.setState({ ...s, talkTick: t, talking: still })
109 if (!still) surface.post({ talked: true })
110 } else if (id !== s.seenTalk) {
111 surface.setState({ ...s, seenTalk: id, talkTick: 0, talking: id !== 0 && !s.reacting && !s.climbing, talkStartedAt: p.talk?.startedAt ?? Date.now() })
112 }
113 })
114 surface.onPointer(event => {
115 if (event.type !== 'down') return
116 const s = surface.state ?? fresh(props)
117 // In the rain, a click pops the umbrella; otherwise the hooks roll a reaction.
118 if (s.reacting === 'storm' && s.tick >= 12 && s.umbrellaAt < 0) {
119 surface.setState({ ...s, umbrellaAt: s.tick })
120 return
121 }
122 surface.post({ tap: true })
123 })
124 }
125
126 const pad = (s: string) => {
127 const gap = Math.max(0, surface.columns - s.length)
128 const left = Math.floor(gap / 2)
129 return ' '.repeat(left) + s + ' '.repeat(gap - left)
130 }
131 const nudge = (l: string, dir: number) => (dir === 0 ? l : dir < 0 ? `${l.slice(1)} ` : ` ${l}`.slice(0, l.length))
132
133 // ---- the ladder gag: where he stands and what shows
134 let lift = 0
135 let ladder = false
136 let startled = false
137 let chute: 'open' | 'crumpled' | null = null
138 let sway = 0
139 let pose = props.pose
140 if (state.climbing) {
141 const t = state.climbTick
142 if (t < APPEAR) ladder = true
143 else if (t < CLIMB) {
144 ladder = true
145 lift = Math.min(TOP, Math.floor((t - APPEAR) / 2) + 1)
146 const step = Math.floor((t - APPEAR) / 2)
147 const lean = props.leanPoses[step % Math.max(1, props.leanPoses.length)] ?? props.pose
148 pose = lean.map(l => nudge(l, step % 2 === 0 ? 1 : -1))
149 } else if (t < HOLD) {
150 ladder = true
151 lift = TOP
152 } else if (t < GONE) {
153 lift = TOP
154 startled = true
155 } else if (t < FLOAT) {
156 chute = 'open'
157 lift = Math.max(0, TOP - Math.floor((t - GONE) / 2) - 1)
158 sway = Math.floor((t - GONE) / 2) % 2 === 0 ? -1 : 1
159 } else if (t < LAND) chute = 'crumpled'
160 }
161 if (sway !== 0) pose = pose.map(l => nudge(l, sway))
162
163 // A row of cells with a colour each, as runs of one colour.
164 const runsOf = (chars: string[], cols: string[], dims?: boolean[]): { t: string; c: string; d?: boolean }[] => {
165 const out: { t: string; c: string; d?: boolean }[] = []
166 chars.forEach((ch, x) => {
167 const c = cols[x] ?? 'text'
168 const d = dims?.[x] ?? false
169 const last = out[out.length - 1]
170 if (last && last.c === c && (last.d ?? false) === d) last.t += ch
171 else out.push({ t: ch, c, d })
172 })
173 return out
174 }
175 // ---- reactions: lines drawn above him, and his own pose while it plays
176 type Line = { t: string; c?: string; d?: boolean; b?: boolean; segs?: { t: string; c: string; d?: boolean }[] }
177 let overhead: Line[] = []
178 let poseColors: (string | undefined)[] = [undefined, undefined, undefined] // per row; undefined = usual
179 let words: Line | null = null
180 const k = state.tick
181 if (state.reacting === 'shake') {
182 // Shaken, not tickled: a fast run through the poses, a column each way, and a dizzy WHOOAH.
183 pose = (props.dancePoses[k % Math.max(1, props.dancePoses.length)] ?? pose).map(l => nudge(l, k % 2 === 0 ? 1 : -1))
184 words = { t: k < 12 ? 'WHOOAH' : '@_@', c: 'text', b: true }
185 } else if (state.reacting === 'pacman') {
186 // He turns into a pacman and chomps.
187 const open = k % 2 === 0
188 pose = open ? ['▗▟█████▙▖', '▐█████▀▘ ', '▝▜█████▛▘'] : ['▗▟█████▙▖', '▐███████▌', '▝▜█████▛▘']
189 poseColors = ['warning', 'warning', 'warning']
190 } else if (state.reacting === 'chef') {
191 // A chef's hat, and three ingredients tossed up and caught in turn: a red tomato, a green pepper, a die.
192 const hatRows: Line[] = [{ t: '▗▄▄▄▄▄▖', c: 'text' }, { t: '▐█████▌', c: 'text' }, { t: ' ▀▀▀▀▀ ', c: 'text', d: true }]
193 const items: { ch: string; c: string; x: number; phase: number }[] = [
194 { ch: '●', c: 'error', x: 2, phase: 0 },
195 { ch: '▲', c: 'success', x: 5, phase: 3 },
196 { ch: '⚄', c: 'text', x: 8, phase: 6 },
197 ]
198 const flight = Math.max(1, Math.min(4, roomAbove - hatRows.length))
199 const sky: string[][] = Array.from({ length: flight }, () => Array.from({ length: 11 }, () => ' '))
200 const skyColors: string[][] = Array.from({ length: flight }, () => Array.from({ length: 11 }, () => 'text'))
201 for (const it of items) {
202 const u = (k + it.phase) % 9 // 0..8: up 4, down 4
203 const height = u <= 4 ? u : 8 - u
204 const y = flight - 1 - Math.min(flight - 1, height)
205 if (u === 0) continue // in the hand
206 const row = sky[y]
207 if (row) {
208 row[it.x] = it.ch
209 skyColors[y]![it.x] = it.c
210 }
211 }
212 overhead = [...sky.map((row, i) => ({ t: row.join(''), c: skyColors[i]!.find(c => c !== 'text') ?? 'text' })), ...hatRows]
213 } else if (state.reacting === 'spider') {
214 // A web is spun stroke by stroke in the top-left corner, then the spider, the spinner glyph, drops
215 // on a thin thread to just above his head, dangles, and climbs back up. He looks up the whole time.
216 const SPIN = ['·', '✢', '✳', '✶', '✻', '✽']
217 const W = 11
218 const blank = () => Array.from({ length: W }, () => ' ')
219 const grid: string[][] = Array.from({ length: Math.max(0, roomAbove) }, blank)
220 const colors: string[][] = Array.from({ length: Math.max(0, roomAbove) }, () => Array.from({ length: W }, () => 'inactive'))
221 const put = (x: number, y: number, ch: string, c = 'inactive') => {
222 if (y >= 0 && y < grid.length && x >= 0 && x < W) {
223 grid[y]![x] = ch
224 colors[y]![x] = c
225 }
226 }
227 // The web: nine strokes around a hub at (1, 1), one stroke a tick.
228 const strokes: [number, number, string][] = [[1, 1, '┼'], [0, 0, '╲'], [2, 0, '╱'], [0, 1, '─'], [2, 1, '─'], [1, 0, '│'], [0, 2, '╱'], [2, 2, '╲'], [1, 2, '│']]
229 const SPIN_END = strokes.length
230 const dropRows = Math.max(1, roomAbove - 2) // from under the hub to just above his head
231 const DROP_END = SPIN_END + dropRows * 2
232 const DANGLE_END = DROP_END + 10
233 const CLIMB_END = DANGLE_END + dropRows * 2
234 const fade = k >= CLIMB_END
235 const drawn = Math.min(strokes.length, k + 1)
236 if (!fade) for (const [x, y, ch] of strokes.slice(0, drawn)) put(x, y, ch)
237 let spiderRow = -1
238 if (k >= SPIN_END && k < DROP_END) spiderRow = 1 + Math.floor((k - SPIN_END) / 2) + 1
239 else if (k >= DROP_END && k < DANGLE_END) spiderRow = 1 + dropRows - ((k - DROP_END) % 6 >= 3 ? 1 : 0)
240 else if (k >= DANGLE_END && k < CLIMB_END) spiderRow = 1 + dropRows - Math.floor((k - DANGLE_END) / 2) - 1
241 if (spiderRow >= 2) {
242 for (let r = 2; r < spiderRow; r += 1) put(1, r, '│')
243 put(1, spiderRow, SPIN[k % SPIN.length] ?? '·', 'text')
244 }
245 overhead = grid.map((row, i) => ({ t: row.join(''), c: colors[i]!.includes('text') ? undefined : 'inactive' }))
246 // Per-cell colour is not available on a line, so the spider's row is drawn in the plain text colour.
247 overhead = overhead.map((line, i) => (colors[i]!.includes('text') ? { ...line, c: 'text' } : line))
248 // Looking up while the web is spun and the spider comes down; once it reaches the bottom his look
249 // returns to normal.
250 const still = props.dancePoses[0] ?? props.pose
251 pose = k < DROP_END ? still.map((l, i) => (i === 0 ? l.replace('▛', '▄').replace('▜', '▄') : l)) : still
252 } else if (state.reacting === 'night') {
253 // Night falls: a thin scarf, a moon in the top-left corner, stars twinkling across the sky, and three
254 // fireflies drifting about as pulsing dots.
255 const W = 11
256 const rows = Math.max(0, roomAbove)
257 const chars: string[][] = Array.from({ length: rows }, () => Array.from({ length: W }, () => ' '))
258 const cols: string[][] = Array.from({ length: rows }, () => Array.from({ length: W }, () => 'text'))
259 const dims: boolean[][] = Array.from({ length: rows }, () => Array.from({ length: W }, () => false))
260 const dusk = Math.min(1, k / 8) // the sky fills in over the first beats
261 for (let y = 0; y < rows; y += 1) {
262 for (let x = 0; x < W; x += 1) {
263 const seed = (x * 13 + y * 7) % 17
264 // Stars come out a few at a time as dusk falls, each in a fixed place.
265 if (seed < 4 && dusk >= (seed + 1) / 4) {
266 // Each star keeps its own twinkle rhythm.
267 const twinkle = (k + seed * 3) % 9
268 chars[y]![x] = twinkle < 2 ? '✦' : twinkle < 5 ? '·' : ' '
269 cols[y]![x] = 'text'
270 dims[y]![x] = twinkle >= 2
271 }
272 }
273 }
274 if (rows > 0 && dusk >= 0.5) {
275 chars[0]![1] = '☾'
276 cols[0]![1] = 'text'
277 dims[0]![1] = false
278 }
279 // Fireflies wander on slow loops and pulse through the spinner frames.
280 const SPINF = ['·', '✢', '✳', '✶', '✻', '✽']
281 const flies = [
282 { phase: 0, cx: 5, cy: Math.max(1, rows - 2) },
283 { phase: 2.1, cx: 8, cy: Math.max(1, Math.floor(rows / 2)) },
284 { phase: 4.2, cx: 3, cy: Math.max(1, rows - 3) },
285 ]
286 if (rows > 1 && k >= 6) {
287 flies.forEach((f, i) => {
288 const x = Math.round(f.cx + 2.5 * Math.sin(k / 6 + f.phase))
289 const y = Math.round(f.cy + 1.2 * Math.cos(k / 9 + f.phase))
290 if (y >= 0 && y < rows && x >= 0 && x < W) {
291 chars[y]![x] = SPINF[(k + i * 2) % SPINF.length] ?? '·'
292 cols[y]![x] = i === 1 ? 'success' : 'warning'
293 dims[y]![x] = false
294 }
295 })
296 }
297 overhead = chars.map((row, y) => ({ t: row.join(''), segs: runsOf(row, cols[y]!, dims[y]!) }))
298 // The scarf: a thin knitted row between head and body, with a tail off to one side.
299 const still = props.dancePoses[0] ?? props.pose
300 pose = [still[0] ?? '', ' ≈≈≈≈≈≈≈▖', still[1] ?? '', still[2] ?? '']
301 poseColors = ['claude', 'error', undefined, 'claude']
302 } else if (state.reacting === 'storm') {
303 // A white cloud darkens to grey, then rains blue drops on him; later, or on a click, an umbrella
304 // opens over his head and the drops bounce off to the sides.
305 const grey = k >= 8
306 const raining = k >= 12
307 // The umbrella always comes out: a dozen ticks into the rain, or at once on a click.
308 const umbrellaAt = state.umbrellaAt >= 0 ? state.umbrellaAt : 30
309 const umbrella = k >= umbrellaAt
310 // He glances up at the sky for a few beats before the umbrella comes out, then looks down again.
311 const lookingUp = k >= umbrellaAt - 4 && k < umbrellaAt
312 // A blank row above the cloud keeps it a little lower in the column.
313 const cloud: Line[] = [{ t: ' ' }, { t: ' ▗▄▄▟▙▄▖ ', c: grey ? 'inactive' : 'text' }, { t: '▐███████▌', c: grey ? 'inactive' : 'text' }]
314 const brollyRows = umbrella ? 2 : 0
315 const rainRows = Math.max(1, roomAbove - cloud.length - brollyRows)
316 // Rain falls across the whole width down to the umbrella. On the row just above the canopy, a few
317 // white dots flicker where drops splash on it.
318 const rain: Line[] = Array.from({ length: rainRows }, (_, r) => {
319 if (!raining) return { t: ' ' }
320 const lastRow = r === rainRows - 1
321 const cells = Array.from({ length: 11 }, (_, x) => {
322 if (umbrella && lastRow && (x * 3 + k) % 5 === 0 && x > 0 && x < 10) return SPLASH[(x + k) % SPLASH.length] ?? '·'
323 const falling = (x * 7 + r * 3 + k) % 4 === 0
324 return falling ? '╎' : ' '
325 })
326 const splashy = umbrella && lastRow && cells.some(ch => SPLASH.includes(ch))
327 if (!splashy) return { t: cells.join(''), c: 'ide' }
328 return { t: cells.join(''), segs: runsOf(cells, cells.map(ch => (SPLASH.includes(ch) ? 'text' : 'ide'))) }
329 })
330 const brolly: Line[] = umbrella ? [{ t: '▗▄▟█████▙▄▖', c: 'error' }, { t: ' ┃ ', c: 'text' }] : []
331 const stack = [...cloud, ...rain, ...brolly]
332 overhead = stack.length > roomAbove ? stack.slice(stack.length - roomAbove) : stack
333 // He stands dead still in the weather, looking up just before the umbrella.
334 const still = props.dancePoses[0] ?? props.pose
335 pose = lookingUp ? still.map((l, i) => (i === 0 ? l.replace('▛', '▄').replace('▜', '▄') : l)) : still
336 }
337
338 // ---- talking: his head lifts one row off his body while the voice is loud enough, an empty gap between
339 let mouthRows = 0
340 if (state.talking && props.talk) {
341 const still = props.dancePoses[0] ?? props.pose
342 mouthRows = rows > still.length && (props.talk.frames[state.talkTick] ?? 0) > 0 ? 1 : 0
343 pose = still
344 }
345
346 // ---- the parachute canopy sized to the room above him
347 const roomNow = Math.max(0, rows - props.pose.length - lift)
348 const canopyRows = chute === 'open' ? Math.max(1, Math.min(4, roomNow)) : 0
349 const CANOPY = [' ▄▟█████▙▄ ', '▐█▓▒░▒▓█▌', ' ╲ ╲ │ ╱ ╱ ', ' ╲ ╲│╱ ╱ ']
350 const CANOPY_COLORS = ['error', 'text', 'text', 'text']
351 const canopy = CANOPY.slice(4 - canopyRows)
352 const canopyColors = CANOPY_COLORS.slice(4 - canopyRows)
353 if (startled && roomNow < 1) startled = false
354
355 // Only the idle mascot wears ultracode's purple and sparkler; reactions and the ladder use his usual colours.
356 const ultraIdle = props.ultra === true && !state.reacting && !state.climbing && !state.talking
357 // ---- what sits above him this frame, newest reason first
358 const bubbleLines: Line[] = words ? [words, { t: ' ' }] : props.bubble.map(l => ({ t: l, c: props.bubbleColor ?? 'text', b: true }))
359 const aboveLines: Line[] = chute === 'open'
360 ? canopy.map((t, i) => ({ t, c: canopyColors[i], d: i >= canopy.length - 2 && canopy.length > 2 }))
361 : chute === 'crumpled'
362 ? [{ t: '▁▂▃▂▁▂▃▂▁', c: 'error', d: true }]
363 : overhead.length > 0
364 ? overhead.slice(-roomAbove)
365 : bubbleLines
366 const stackAbove = aboveLines.length + (startled ? 1 : 0)
367 // Filler rows are emitted only while the ladder plays, so at rest the column takes the row's height.
368 const above = state.climbing ? Math.max(0, rows - stackAbove - props.pose.length - lift) : 0
369 const below = lift
370 const belowStart = above + stackAbove + props.pose.length
371 const rung = (row: number) => (row % 2 === 0 ? '┣━┫' : '┃ ┃')
372 return (
373 <Box flexDirection="column" justifyContent="flex-end" width="100%" height="100%">
374 {Array.from({ length: above }, (_, i) => (
375 <Text key={`a${i}`} color="claude" dimColor>{pad(ladder ? rung(i) : ' ')}</Text>
376 ))}
377 {startled ? <Text color="error" bold>{pad('!')}</Text> : null}
378 {aboveLines.map((line, i) =>
379 line.segs ? (
380 <Box key={`o${i}`} flexDirection="row">
381 {line.segs.map((sg, j) => <Text key={`o${i}-${j}`} color={sg.c} dimColor={sg.d}>{sg.t}</Text>)}
382 </Box>
383 ) : (
384 <Text key={`o${i}`} color={line.c} dimColor={line.d} bold={line.b}>{pad(line.t)}</Text>
385 ),
386 )}
387 {pose.map((line, i) =>
388 i === 1 && mouthRows > 0 ? (
389 <Box key={`m${i}`} flexDirection="column">
390 {Array.from({ length: mouthRows }, (_, j) => (
391 <Text key={`mouth${j}`}>{pad('')}</Text>
392 ))}
393 <Text color={poseColors[i] ?? (i === pose.length - 2 ? props.color : 'claude')}>{pad(line)}</Text>
394 </Box>
395 ) : i === 0 && ultraIdle ? (
396 // The head stays where it is; the gold sparkler sits in the two cells after it.
397 <Box key={`m${i}`} flexDirection="row">
398 <Text color={ULTRA}>{pad(line).slice(0, pad(line).length - 2)}</Text>
399 <Text color={SPARK}>/✦</Text>
400 </Box>
401 ) : (
402 <Text key={`m${i}`} color={poseColors[i] ?? (ultraIdle ? ULTRA : i === pose.length - 2 ? props.color : 'claude')} bold={state.reacting === 'shake'}>{pad(line)}</Text>
403 ),
404 )}
405 {Array.from({ length: below }, (_, i) => (
406 <Text key={`u${i}`} color="claude" dimColor>{pad(ladder ? rung(belowStart + i) : ' ')}</Text>
407 ))}
408 </Box>
409 )
410}
411
412export default Mascot
413