SLOPSHOPPER

pixel-pet

An animated pixel-art companion above your prompt that reacts to your session and your typing, with a live context meter.

bandguardcommandpromptprocesstimer
★ 13v0.3.1MITupdated 2026-10-14lakmadev/pixel-pet
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pixel-pet
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /pet ⎿ pixel-pet: Noodle · teal ⎿ pixel-pet: 1 turns together · petted 0 times · 0 helpers hatched · 0 green test runs · 0 days old ⎿ pixel-pet: Click it to pet it. /pet color, rename, outfit, card, calm, breaks, sound, project. ▣ client module ./pet-view.tsx ▣ client module ./status-view.tsx ▣ client module ./meter-view.tsx ⓘ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▣ client module ./pet-view.tsx ▣ client module ./status-view.tsx ▣ client module ./meter-view.tsx ⓘ
README

pixel-pet

A tiny animated pixel pet that lives above your Claude Code prompt, in a little pixel world that follows your day. It naps when things are quiet, tells you what Claude is doing without becoming noise, cheers when your tests pass, waves when Claude needs you, and hatches little helpers for subagents, with a live context meter beside it.

pixel-pet in action

▶ Watch the 50-second tour with sound · What's new in 0.3

the band: the pet in its world, its status line and the context meter

What it does

It's alive

  • Sleeps and wakes. A new session finds it fast asleep: eyes closed, breathing slowly, z's drifting up and a snore bubble that swells and pops. Your first keystroke wakes it slowly (blinks, a yawn, a little stretch). After a quiet minute it nods off again.
  • Watches you type. Its eyes follow your caret as if reading along. A backspace makes it wince, deleting a big chunk makes it gasp, a huge paste gets a "whoa", and please or thanks makes it blush.
  • Click it to pet it. A heart pops and it blushes.
  • Lives in a little world that changes through your day: a meadow in the morning, the desert in the afternoon, a savanna sunset in the evening, the city skyline at night and the moon after midnight. While Claude works the scenery scrolls past in layers (far mountains slow, near hills fast), so it looks like it's running through it. The scenes are original pixel art drawn in code.
  • Dresses for the date. A pumpkin hat the week before Halloween, a Santa hat over Christmas, and a party hat at New Year and on its birthday.
  • Feels the context. As the context fills past 60% it slows down; after /compact it stretches, "feels light again ✨".

It's useful, quietly

  • Narrates Claude's work without becoming noise. One line when the kind of work changes ("is reading auth.ts…", "is editing app.ts ✏️", "is running the tests 🧪"), not one per call: five reads in a row are one line. Deep in a long turn it settles into one quiet summary ("is deep in it · 23 steps · 4 files changed"). Its name stays put while the words after it slide.
  • Reacts to what matters, in colour. "cheers: all 42 tests pass ✅" in green with a happy dance; "saw 3 tests fail ❌" in red with a groan (and a moment in a lava cave); "watched it ship 🚀" after a push; "saw the build break 🔨". Other errors just get a flinch.
  • Waves when Claude needs you. On a permission prompt it jumps up waving with a "!" ("needs your OK ✋", in amber); when a long turn (30 seconds or more) is done it waves until you're back ("is done · 4 files changed · come take a look 👀"). Optional chirp: /pet sound on.
  • Hatches helpers for subagents. Each subagent gets a mini pet half its size, in the agent's own colour (the color: in its definition) or a stable random one. Helpers slide into the meter line one by one, bob while their agent works, and wave bye when it's done.
  • Context meter on its second line: a gradient bar (mint → amber → red) that glides to each reading, then your plan's 5-hour and weekly usage (or the dollars billed on the API, Bedrock, Vertex or Foundry). Point at ⓘ for tokens, reset times and how you're billed. When a plan limit passes 80% it says so once, calmly ("notes your 5-hour limit is at 82% · resets in 38m"), and once more at 95%.

It's yours

  • One pet everywhere. Its name, colour, stats and settings live in one file (~/.claude/pixel-pet.json) shared by every session and every window, terminal or desktop; a rename shows up everywhere within seconds. Or give each project its own pet with /pet project on. A new pet hatches with a random name (Mochi, Pixel, Pip, Nibbles…).
  • 28 colours. /pet color pink; it tries each colour on as you type the name.
  • Your background, or none. /pet scene off for just the pet, /pet scene on for the one that follows your day, or /pet scene jungle (meadow, desert, city, skyline, snow, moon, savanna, lava, mountains) to keep one.
  • Share card. /pet card saves a 1200×630 picture of your pet in its world, with your days together, turns, pets and green test runs, to your Downloads folder.
  • Calm, breaks, sound (all off by default): /pet calm on keeps motion small (no bobbing or scrolling, lines fade instead of sliding); /pet breaks on suggests a stretch after two hours and sleep after midnight; /pet sound on chirps when it calls you.
  • Smooth everywhere. In the terminal everything animates on the terminal's own frame clock; in the desktop app the pet, its world and the meter are SVGs with the motion built in.

Install

Requires Claude Code 2.1.293 or later: mods are an early-access feature and gain events with each release. Check with claude --version; update with claude update.

/plugin marketplace add lakmadev/pixel-pet
/plugin install pixel-pet@pixel-pet

Commands

Command
/petIts name, colour, hat, what's switched on, and your stats together
/pet color <name>teal, red, orange, yellow, green, blue, purple, pink, white, gray, black, brown, cyan, mint, lime, sky, navy, indigo, violet, lavender, magenta, rose, peach, coral, gold, lava, ghost, midnight
/pet rename <name>Rename it (a new pet gets a random name)
`/pet outfit <auto\none\pumpkin\santa\party>`Its hat; auto (the default) dresses for the date
`/pet scene on\off`Its background: on (the default) changes through the day, off is just the pet
`/pet scene <meadow\desert\jungle\city\skyline\snow\moon\savanna\lava\mountains>`Keep one background all day
/pet cardSave a picture of it to share
`/pet project on\off`Its own name and colour in each project, so windows tell apart; rename and color then change the current project only
`/pet calm on\off`Small motion: it stays still and blinks, and lines fade instead of sliding
`/pet breaks on\off`A stretch-break nudge after two hours without a pause, and one after midnight to go to sleep
`/pet sound on\off`A soft chirp when it calls you
/pet hide / /pet showTuck it away or bring it back

Settings (/config): name (empty for a random one) and color, used when a pet first hatches.

What it reads

Hook events (tool calls, prompts, turns, subagent starts) and the usage figures Claude Code reports, plus a custom agent's definition file for its colour. It reads the CLAUDE_CODE_USE_BEDROCK / _VERTEX / _FOUNDRY switches to name who bills you, never an API key. It runs date +%z once per session to learn your time zone, so hats and late-night nudges follow your clock. Nothing leaves your machine; its name, colour, settings and counts are kept in ~/.claude/pixel-pet.json (shared by every session) and in Claude Code's plugin store. /pet card writes one SVG file to your Downloads folder (or home folder).

Part of lakmadev/claude-mods, a pack of eleven Claude Code mods. MIT licensed.

Source 14 files
hooks/register.tsx 896 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { ContextMeter, Mini, Mood, PetView, Tone } from '../types'
5import { petCard } from './card'
6import { TONES, cardLines, hex, resetIn, segments } from './meter'
7import type { Source } from './meter'
8import type { MeterViewProps } from './meter-view'
9import type { PetViewProps } from './pet-view'
10import { COLOR_NAMES, COLORS, DEFAULT_COLOR, OUTFITS, colorName, localDate, outfitFor, petSvg } from './sprite'
11import type { Outfit } from './sprite'
12import { LINE_COLORS, actionKind, actionLine, focusLine, lineSvg, lineWidth, outcomeOf, toneColor } from './status'
13import { LEAVE_MS, colorFromDefinition, miniColor } from './mini'
14import { lineTwoSvg } from './line2'
15import { HABITAT_HEIGHT, HABITAT_WIDTH, SCENES, TIMES_OF_DAY, habitatSvg, isScene, sceneFor, whereIn } from './scene'
16import type { Scene } from './scene'
17import { HABITAT_COLUMNS, HABITAT_ROWS } from './pet-view'
18import type { Layout } from './line2'
19import type { MinisViewProps } from './minis-view'
20import type { StatusViewProps } from './status-view'
21
22// `xp` is a leftover field from when the pet had levels; old records keep it, nothing reads it.
23type Pet = { name: string; born: number; turns: number; pets: number; color?: string; xp?: number; helpers?: number; greens?: number }
24// Opt-ins, kept across sessions: smaller motion, break nudges, a chirp when it calls you, a name
25// and colour per project, and which hat (auto: the one the date calls for).
26type Prefs = { calm: boolean; breaks: boolean; sound: boolean; perProject: boolean; outfit: 'auto' | 'none' | Outfit; scene: 'auto' | 'none' | Scene }
27type Project = { name?: string; color?: string }
28
29const LINES: Record<Mood, string[]> = {
30  idle: ['is waiting for you', 'is vibing', 'is counting pixels', 'is guarding your repo', 'is humming quietly'],
31  working: ['is typing furiously…', 'is reading your code…', 'is thinking very hard…', 'is chasing a bug…', 'is consulting the docs…'],
32  happy: ['did a happy dance!', 'is proud of you!', 'says: ship it!', 'high-fives the terminal!'],
33  oops: ["saw an error. it's fine. everything's fine.", 'is sweating nervously', "says: that wasn't supposed to happen"],
34  sleepy: ['is fast asleep… zzz', 'is snoring softly', 'dreams of green tests', 'is napping on your keyboard'],
35  dozing: ['is getting sleepy…', 'yawns…', 'is fighting to stay awake'],
36  waking: ['is waking up… ☀️', 'stretches and yawns', 'rubs its eyes'],
37  loved: ['loves you back ♥', 'purrs in binary', 'is blushing in pixels'],
38  reading: ['is reading along…', 'is peeking at what you type 👀', 'is following every keystroke', 'is taking notes'],
39  wince: ['winces at the typo', 'pretends not to see that', 'says: backspace, backspace'],
40  shocked: ['gasps: where did it all go?!', 'is shocked by the delete', 'clutches its pixels'],
41  calling: ['wants your attention!', 'is waving at you 👋'],
42}
43
44const pick = (list: readonly string[]) => list[Math.floor(Math.random() * list.length)]!
45const SLEEP_AFTER_MS = 60_000
46const METER_CELLS = 14
47
48// The configured colour, used until /pet color picks one; and the one being tried on while typing it.
49let defaultColor = DEFAULT_COLOR
50let previewColor: string | undefined
51let meter: ContextMeter = {}
52// The helpers on screen, one per running subagent, and which agent each stands for.
53let minis: Mini[] = []
54// Helpers that start together arrive one by one, this far apart.
55const HATCH_GAP_MS = 450
56let lastHatchAt = 0
57// Where the desktop's second line last put each helper and the bar, to glide from.
58let lineTwoLayout: Layout | undefined
59const miniOf = new Map<string, string>()
60
61// The desktop scenery's scroll so far: time moved before, and since when it's been moving now.
62let scrolledBefore = 0
63let movingSince: number | null = null
64
65let prefs: Prefs = { calm: false, breaks: false, sound: false, perProject: false, outfit: 'auto', scene: 'auto' }
66// The session's project, and the names and colours given per project.
67let cwd = ''
68let projects: Record<string, Project> = {}
69// The clock as of the last tick, for what the date decides (today's hat), and the person's UTC
70// offset in minutes: asked of the system once (`date +%z`), since the sandbox's own time zone
71// may not be theirs; JavaScript's guess until then, or where there's no `date`.
72let today = 0
73let utcOffsetMin = -new Date().getTimezoneOffset()
74
75export function parseOffset(text: string): number | undefined {
76  const m = /^([+-])(\d{2})(\d{2})$/.exec(text.trim())
77  return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) : undefined
78}
79
80const project = () => (prefs.perProject ? projects[cwd] : undefined)
81const nameNow = (pet: Pet) => project()?.name ?? pet.name
82// Per project, a project with no colour of its own still gets a steady one, so windows tell apart.
83const colorNow = (pet: Pet) => previewColor ?? (prefs.perProject ? colorName(project()?.color) ?? miniColor(cwd, '') : colorName(pet.color) ?? defaultColor)
84// Until the clock is first read there's no date to dress for.
85const outfitNow = (pet: Pet): Outfit | undefined => (prefs.outfit === 'auto' ? (today ? outfitFor(today, pet.born, utcOffsetMin) : undefined) : prefs.outfit === 'none' ? undefined : prefs.outfit)
86
87// Its world: the one picked with /pet scene, or on auto the one the clock and the moment call
88// for (a lava cave while it groans over failing tests).
89const sceneNow = (mood: Mood, tone: Tone): Scene | 'none' => {
90  if (prefs.scene !== 'auto') return prefs.scene
91  if (!today) return 'meadow'
92  const d = localDate(today, utcOffsetMin)
93  return sceneFor(d.getUTCHours(), mood === 'oops' && tone === 'bad')
94}
95
96export function viewOf(pet: Pet, mood: Mood, line: string, isHidden: boolean, tone: Tone = 'plain'): PetView {
97  return { mood, line, name: nameNow(pet), color: colorNow(pet), isHidden, meter, minis, tone, outfit: outfitNow(pet) ?? 'none', calm: prefs.calm, scene: sceneNow(mood, tone) }
98}
99
100const view = atom({ plugin: 'pixel-pet', key: 'view' } as const, viewOf({ name: 'Pip', born: 0, turns: 0, pets: 0 }, 'sleepy', 'is fast asleep… zzz', false))
101
102// Module state between hooks; the pet's record is read back from the shared file on reload.
103let pet: Pet = { name: 'Pip', born: 0, turns: 0, pets: 0 }
104
105// A new pet hatches with one of these names, unless the `name` setting gives one.
106const NAMES = ['Mochi', 'Pixel', 'Pip', 'Nibbles', 'Byte', 'Biscuit', 'Sprout', 'Dot', 'Pebble', 'Noodle', 'Bean', 'Comet']
107
108// Everything the pet keeps (its record, your settings, the per-project names) lives in one file
109// that every session and every installed copy shares, so it's the same pet everywhere. Each
110// change re-reads the file first and applies itself to that, so two sessions counting at once
111// don't undo each other. The plugin's own store keeps a copy too, for when there's no home folder.
112type Kept = { pet: Pet; prefs: Prefs; projects: Record<string, Project> }
113let keptPath: string | undefined
114let lastSync = 0
115
116async function readKept($: EngineInterface): Promise<Partial<Kept> | undefined> {
117  if (!keptPath) return undefined
118  const text = await $.fs.read(keptPath).catch(() => undefined)
119  try {
120    return text ? (JSON.parse(text) as Partial<Kept>) : undefined
121  } catch {
122    return undefined
123  }
124}
125
126async function keep($: EngineInterface, change: (kept: Kept) => Kept) {
127  const latest = await readKept($)
128  const next = change({ pet: latest?.pet ?? pet, prefs: { ...prefs, ...latest?.prefs }, projects: latest?.projects ?? projects })
129  pet = next.pet
130  prefs = next.prefs
131  projects = next.projects
132  if (keptPath) await $.fs.write(keptPath, `${JSON.stringify(next, null, 2)}\n`).catch(() => undefined)
133  await $.store.set('pet', pet)
134  await $.store.set('prefs', prefs)
135  await $.store.set('projects', projects)
136}
137
138// Picks up what another session changed (a rename, a colour, a setting) every few seconds.
139async function sync($: EngineInterface, now: number) {
140  if (!keptPath || now - lastSync < 10_000) return
141  lastSync = now
142  const kept = await readKept($)
143  if (!kept?.pet) return
144  const before = JSON.stringify([nameNow(pet), colorNow(pet), prefs])
145  pet = kept.pet
146  prefs = { ...prefs, ...kept.prefs }
147  projects = kept.projects ?? projects
148  if (JSON.stringify([nameNow(pet), colorNow(pet), prefs]) !== before) await update($, view, current => viewOf(pet, current.mood, current.line, current.isHidden, current.tone))
149}
150// A new session finds the pet asleep; the first keystroke wakes it.
151let mood: Mood = 'sleepy'
152let moodUntil = 0
153let isWorking = false
154let lastActive = 0
155// Where the eyes point while reading along (-1 left … 1 right), and what the band last said.
156let look = 0
157let lastLine = ''
158// What the desktop last drew, so a change of mood or colour fades from it and the meter glides.
159let shown: { mood: Mood; color: string } | undefined
160let fadeFrom: { mood: Mood; color: string; at: number } | undefined
161let drawnPercent = 0
162let shownLine: string | undefined
163let slideFrom: { line: string; at: number } | undefined
164// The desktop draws its line as SVG text, which can't follow the theme by itself.
165let theme: 'dark' | 'light' = 'dark'
166// Who bills the tokens when no plan limits come back: the API, or a cloud provider.
167let provider: Source = 'api'
168// A line stays up at least this long, so a burst of tool calls reads as a story, not a flicker.
169const HOLD_MS = 1200
170let lineShownAt = 0
171let pendingLine: string | undefined
172let isLineQueued = false
173
174// The turn in progress. Narration tells each new kind of work once (five reads in a row are one
175// line), and once a turn runs long it settles into one quiet summary, refreshed now and then, so
176// it never becomes a stream to tune out. What matters still breaks through at once: tests passing
177// or failing, a push, a broken build, and anything that needs you.
178const FOCUS_AFTER_STEPS = 12
179const FOCUS_AFTER_MS = 40_000
180const SUMMARY_EVERY_MS = 10_000
181let turnAt = 0
182let steps = 0
183let lastKind: string | undefined
184const touched = new Set<string>()
185let lastSummaryAt = -Infinity
186
187// Calling you: a turn that ran this long has finished, or Claude waits on you; it keeps waving
188// until you're back (any key, a prompt) or this long has passed.
189const LONG_TURN_MS = 30_000
190const CALL_MS = 5 * 60_000
191
192// Breaks (opt-in): a stretch after two hours with no ten-minute pause, then hourly; and once a
193// night after midnight, a reminder to sleep.
194const BREAK_AFTER_MS = 2 * 3600_000
195const NUDGE_EVERY_MS = 3600_000
196const PAUSE_MS = 10 * 60_000
197let workStart = 0
198let lastNudgeAt = 0
199let nightNudgedOn = ''
200
201function active(now: number) {
202  if (!workStart || now - lastActive > PAUSE_MS) workStart = now
203  lastActive = now
204}
205
206function baseMood(now: number): Mood {
207  if (isWorking) return 'working'
208  return now - lastActive > SLEEP_AFTER_MS ? 'sleepy' : 'idle'
209}
210
211async function setMood($: EngineInterface, next: Mood, forMs = 0, line?: string, tone: Tone = 'plain') {
212  const now = await $.clock.now()
213  moodUntil = forMs ? now + forMs : 0
214  if (next === mood && !forMs && line === undefined) return
215  mood = next
216  lineShownAt = now
217  lastLine = line ?? (next === 'working' ? 'is thinking… 💭' : next === 'idle' && (meter.percent ?? 0) >= 80 ? `is stuffed with tokens (${meter.percent}% context)` : pick(LINES[next]))
218  await update($, view, current => viewOf(pet, next, lastLine, current.isHidden, tone))
219}
220
221// News that can't wait for the line's hold: shown at once, in its colour, with the mood that fits,
222// and held a few seconds so the next bit of narration doesn't push it straight off.
223async function announce($: EngineInterface, next: Mood, line: string, tone: Tone, forMs: number) {
224  pendingLine = undefined
225  await setMood($, next, forMs, line, tone)
226  lineShownAt += Math.min(forMs, 5000) - HOLD_MS
227}
228
229// A plan limit getting close: one calm line as it crosses 80%, another at 95%, nothing more (no
230// mood, no waving, no sound); a window that resets re-arms it. Undefined when there's nothing new.
231const LIMIT_NAMES: Record<string, string> = { five_hour: '5-hour limit', seven_day: 'weekly limit', seven_day_opus: 'weekly Opus limit' }
232const NOTICE_AT = [80, 95]
233const notedLimits = new Set<string>()
234
235export function limitNotice(limits: readonly { kind: string; percent: number; resetsAt?: string }[], noted: Set<string>, now: number): string | undefined {
236  let line: string | undefined
237  for (const limit of limits) {
238    const name = LIMIT_NAMES[limit.kind]
239    if (!name) continue
240    for (const at of NOTICE_AT) {
241      const key = `${limit.kind}:${at}`
242      if (limit.percent < at) noted.delete(key)
243      else if (!noted.has(key)) {
244        noted.add(key)
245        const reset = resetIn(limit.resetsAt, now)
246        line = `notes your ${name} is at ${Math.round(limit.percent)}%${reset ? ` · resets in ${reset}` : ''}`
247      }
248    }
249  }
250  return line
251}
252
253// It calls you over: waves with a "!" beside it, and chirps if you asked it to.
254async function call($: EngineInterface, line: string, tone: Tone) {
255  await announce($, 'calling', line, tone, CALL_MS)
256  if (prefs.sound) $.audio.play({ asset: 'assets/chirp.wav' }, { gain: 0.6 }).catch(() => undefined)
257}
258
259type Reading = { context: { percent?: number; tokens?: number; window: number }; cost?: { usd: number }; rateLimits: { kind: string; percentUsed: number; resetsAt?: string }[] }
260
261// Plan windows (5-hour, weekly) only come back on a Claude subscription; a gateway reports a spend
262// limit; with neither, once a reply has come back, the tokens are billed by the API or the provider.
263export function sourceOf(reading: Reading, fallback: Source): Source | undefined {
264  if (reading.rateLimits.some(r => r.kind === 'five_hour' || r.kind.startsWith('seven_day'))) return 'plan'
265  if (reading.rateLimits.some(r => r.kind === 'spend_limit')) return 'gateway'
266  return reading.context.percent !== undefined ? fallback : undefined
267}
268
269async function setMeter($: EngineInterface, reading: Reading) {
270  const limits = reading.rateLimits.map(r => (r.resetsAt ? { kind: r.kind, percent: r.percentUsed, resetsAt: r.resetsAt } : { kind: r.kind, percent: r.percentUsed }))
271  const source = sourceOf(reading, provider) ?? meter.source
272  const next: ContextMeter = {}
273  const percent = reading.context.percent ?? meter.percent
274  const tokens = reading.context.tokens ?? meter.tokens
275  const usd = reading.cost?.usd ?? meter.usd
276  if (percent !== undefined) next.percent = percent
277  if (tokens !== undefined) next.tokens = tokens
278  if (reading.context.window || meter.window) next.window = reading.context.window || meter.window!
279  if (usd !== undefined) next.usd = usd
280  if (limits.length || meter.limits) next.limits = limits.length ? limits : meter.limits!
281  if (source) next.source = source
282  meter = next
283  await update($, view, current => ({ ...current, meter }))
284  // Asleep, it leaves the notice for when it's up; the meter shows the number either way.
285  if (mood === 'sleepy' || mood === 'dozing') return
286  const notice = limitNotice(meter.limits ?? [], notedLimits, await $.clock.now())
287  if (notice) await announce($, mood, notice, 'ask', 6000)
288}
289
290// How worn out a full context makes it: nothing until 60%, slowest at 95%.
291export const tiredness = (percent: number | undefined) => Math.min(1, Math.max(0, ((percent ?? 0) - 60) / 35))
292
293// Show a working line, holding the current one for HOLD_MS first; only the latest waiting line
294// is kept, so a burst of calls skips straight to what's happening now.
295async function say($: EngineInterface, line: string) {
296  const now = await $.clock.now()
297  const wait = HOLD_MS - (now - lineShownAt)
298  if (wait > 0) {
299    pendingLine = line
300    if (!isLineQueued) {
301      isLineQueued = true
302      $.clock.after(wait, () => {
303        isLineQueued = false
304        const queued = pendingLine
305        pendingLine = undefined
306        if (queued && isWorking) say($, queued).catch(() => undefined)
307      })
308    }
309    return
310  }
311  lineShownAt = now
312  lastLine = line
313  await update($, view, current => (current.line === line && current.tone === 'plain' ? current : { ...current, line, tone: 'plain' as const }))
314}
315
316// One step of Claude's work: a line when the kind of work changes, or the quiet summary once deep in.
317async function narrate($: EngineInterface, tool: string, args: Record<string, unknown>) {
318  const now = await $.clock.now()
319  steps++
320  const kind = actionKind(tool, args)
321  if (kind === 'edit' && typeof args.file_path === 'string') touched.add(args.file_path)
322  // A passing mood (a test result, a stretch) has the line until it wears off.
323  if (moodUntil > now && mood !== 'working') return
324  if (steps > FOCUS_AFTER_STEPS || now - turnAt > FOCUS_AFTER_MS) {
325    if (now - lastSummaryAt < SUMMARY_EVERY_MS) return
326    lastSummaryAt = now
327    return say($, focusLine(steps, touched.size))
328  }
329  if (kind === undefined || kind === lastKind) return
330  lastKind = kind
331  const line = actionLine(tool, args)
332  if (line) await say($, line)
333}
334
335// What a finished call means to the pet: back to work after a permission, a cheer or a groan
336// for a result worth one, a flinch at any other error.
337async function afterCall($: EngineInterface, tool: string, args: Record<string, unknown>, isError: boolean, text: string) {
338  if (mood === 'calling' && isWorking) await setMood($, 'working')
339  const outcome = outcomeOf(tool, args, isError, text)
340  if (outcome) {
341    await announce($, outcome.tone === 'good' ? 'happy' : 'oops', outcome.line, outcome.tone, outcome.tone === 'good' ? 4000 : 6000)
342    if (outcome.tone === 'good' && /tests? pass/.test(outcome.line)) {
343      await keep($, kept => ({ ...kept, pet: { ...kept.pet, greens: (kept.pet.greens ?? 0) + 1 } }))
344    }
345  } else if (isError) await setMood($, 'oops', 3000, lastLine) // a flinch, not news: the line stays
346}
347
348// React first, save after: the blush shouldn't wait on a disk write.
349async function petIt($: EngineInterface) {
350  await setMood($, 'loved', 4000)
351  await keep($, kept => ({ ...kept, pet: { ...kept.pet, pets: kept.pet.pets + 1 } }))
352}
353
354const COLOR_COMMAND = /^\s*\/pet\s+colou?r\s+(\S*)$/i
355const PET_COMMAND = /^\s*\/pet\s+(\S*)$/i
356const OUTFIT_COMMAND = /^\s*\/pet\s+outfit\s+(\S*)$/i
357const SCENE_COMMAND = /^\s*\/pet\s+scene\s+(\S*)$/i
358// The occasion a hat is for works as its name too: `/pet outfit christmas`.
359const OCCASIONS: Record<string, Outfit> = { halloween: 'pumpkin', christmas: 'santa', xmas: 'santa', birthday: 'party', newyear: 'party' }
360const VERBS: [string, string][] = [
361  ['color', 'change its colour'], ['rename', 'give it a new name'], ['scene', 'its background: on (changes through the day), off, or meadow, desert, jungle…'], ['outfit', 'auto, none, pumpkin, santa or party'], ['card', 'save a picture of it to share'],
362  ['calm', 'keep its motion small (on/off)'], ['breaks', 'nudge me to take breaks (on/off)'], ['sound', 'chirp when it needs me (on/off)'],
363  ['project', 'its own name and colour in each project (on/off)'], ['hide', 'tuck it away'], ['show', 'bring it back'],
364]
365
366// While the draft reads `/pet color <partial>`, the colour to try on: the exact name, else the
367// first that starts with what's typed.
368export function previewFor(draft: string): string | undefined {
369  const partial = COLOR_COMMAND.exec(draft)?.[1]?.toLowerCase()
370  if (!partial) return undefined
371  return colorName(partial) ?? COLOR_NAMES.find(name => name.startsWith(partial))
372}
373
374const afterEdit = (e: { text: string; start: number; end: number; inputText: string }) => e.text.slice(0, e.start) + e.inputText + e.text.slice(e.end)
375
376async function preview($: EngineInterface, color: string | undefined) {
377  if (color === previewColor) return
378  previewColor = color
379  const line = color ? `is trying on ${color}… press Enter to keep it` : pick(LINES.idle)
380  await update($, view, current => viewOf(pet, current.mood, line, current.isHidden))
381}
382
383const CODEY = /[{}();=<>[\]`]|=>|\b(function|const|def|class|import|return)\b/
384
385// How the pet reacts to one edit of the draft: what changed, where the caret is, and what the draft says.
386export function reactionTo(e: { text: string; cursor: number; start: number; end: number; inputText: string; key?: unknown }) {
387  const removed = e.end - e.start
388  const draft = e.text.slice(0, e.start) + e.inputText + e.text.slice(e.end)
389  const caret = e.start + e.inputText.length
390  // The eyes sweep left to right across each 30 characters, like reading a line.
391  const look = Math.round(((caret % 30) / 30) * 2 - 1)
392  if (removed >= 10 || (removed > 0 && draft.trim() === '')) return { mood: 'shocked' as const, look, line: undefined }
393  if (removed > 0) return { mood: 'wince' as const, look, line: undefined }
394  if (e.inputText.length > 40 && e.key === undefined) return { mood: 'shocked' as const, look, line: "whoa, that's a lot of text" }
395  if (e.inputText === '') return undefined // a bare caret move
396  const lastWords = draft.slice(-24).toLowerCase()
397  if (/\b(please|thanks|thank you|ty)\s?$/.test(lastWords)) return { mood: 'loved' as const, look, line: 'appreciates your manners ♥' }
398  if (/\bbug\s?$/.test(lastWords)) return { mood: 'reading' as const, look, line: 'spots the bug 👀' }
399  return { mood: 'reading' as const, look, line: CODEY.test(draft) ? 'is reading your code…' : undefined }
400}
401
402// Typing moods hold while the keys keep coming and fade ~2s after the last one. Only a change of
403// mood, gaze or words touches the band, so a run of keystrokes costs a handful of redraws. Typing
404// also answers a pet that was calling you.
405async function react($: EngineInterface, reaction: NonNullable<ReturnType<typeof reactionTo>>) {
406  const now = await $.clock.now()
407  active(now)
408  // Asleep or nodding off, the first keys wake it gently; reactions resume once it's up.
409  if (mood === 'sleepy' || mood === 'dozing') return wake($)
410  if (mood === 'waking' && now < moodUntil) return
411  moodUntil = now + 2000
412  const isSame = mood === reaction.mood && look === reaction.look && (reaction.line === undefined || reaction.line === lastLine)
413  look = reaction.look
414  if (isSame) return
415  const isNewMood = mood !== reaction.mood
416  mood = reaction.mood
417  if (reaction.line !== undefined || isNewMood) lastLine = reaction.line ?? pick(LINES[reaction.mood])
418  await update($, view, current => viewOf(pet, reaction.mood, lastLine, current.isHidden))
419}
420
421const WAKE_MS = 1600
422const DOZE_MS = 2800
423
424// Blinks, a yawn and a little rise, then on with whatever comes next.
425async function wake($: EngineInterface) {
426  if (mood === 'waking') return
427  await setMood($, 'waking', WAKE_MS)
428}
429
430const isLateNight = (now: number) => localDate(now, utcOffsetMin).getUTCHours() < 5
431const dayOf = (now: number) => localDate(now, utcOffsetMin).toISOString().slice(0, 10)
432
433// A passing mood (happy, oops, loved, waking, calling) wears off; a long quiet nods off into sleep,
434// through a few heavy-lidded seconds of dozing. The motion itself runs on the surface's clock or in
435// the SVG. Breaks get their nudge here too.
436async function checkMood($: EngineInterface) {
437  const now = await $.clock.now()
438  const was = `${outfitNow(pet)}:${sceneNow(mood, 'plain')}`
439  today = now
440  if (`${outfitNow(pet)}:${sceneNow(mood, 'plain')}` !== was) await update($, view, current => viewOf(pet, current.mood, current.line, current.isHidden, current.tone))
441  if (moodUntil && now > moodUntil) {
442    const next = baseMood(now)
443    // Drifting off from an awake mood goes through dozing first.
444    if (next === 'sleepy' && mood !== 'dozing') await setMood($, 'dozing', DOZE_MS)
445    else await setMood($, next)
446  } else if (mood === 'idle' && baseMood(now) === 'sleepy') await setMood($, 'dozing', DOZE_MS)
447  else if (prefs.breaks && !moodUntil && (mood === 'idle' || mood === 'working')) await nudge($, now)
448  await tendMinis($, now)
449  await sync($, now)
450}
451
452async function nudge($: EngineInterface, now: number) {
453  if (now - workStart >= BREAK_AFTER_MS && now - lastNudgeAt >= NUDGE_EVERY_MS) {
454    lastNudgeAt = now
455    const hours = Math.floor((now - workStart) / 3600_000)
456    await announce($, 'waking', `has been at it for ${hours}h · stretch break? 🧘`, 'ask', WAKE_MS * 2)
457  } else if (mood === 'idle' && isLateNight(now) && nightNudgedOn !== dayOf(now)) {
458    nightNudgedOn = dayOf(now)
459    await announce($, 'dozing', "yawns · it's late, don't forget to sleep 🌙", 'plain', DOZE_MS)
460  }
461}
462
463// Helpers whose agents have finished wave bye; ones that have waved long enough leave.
464async function tendMinis($: EngineInterface, now: number) {
465  if (minis.length === 0) return
466  const here = minis.filter(m => m.state === 'here' && now - m.at > 3000)
467  if (here.length) {
468    const agents = await $.agent.list().catch(() => [])
469    const finished = new Set(agents.filter(a => ['completed', 'failed', 'killed'].includes(a.status)).map(a => a.id))
470    for (const [agentId, miniId] of miniOf) if (finished.has(agentId)) await sayBye($, miniId)
471  }
472  const kept = minis.filter(m => m.state === 'here' || now - m.at < LEAVE_MS)
473  if (kept.length !== minis.length) {
474    minis = kept
475    await update($, view, current => ({ ...current, minis }))
476  }
477}
478
479async function hatch($: EngineInterface, id: string, type: string) {
480  const name = type.split(':').pop() ?? type
481  const color = (await definedColor($, name)) ?? miniColor(id, colorNow(pet))
482  const now = await $.clock.now()
483  const at = Math.max(now, lastHatchAt + HATCH_GAP_MS)
484  lastHatchAt = at
485  minis = [...minis.filter(m => m.id !== id), { id, name, color, state: 'here' as const, at }].slice(-6)
486  await update($, view, current => ({ ...current, minis }))
487  // A queued helper's turn: draw again when it's due, so its slot starts opening on time.
488  if (at > now) $.clock.after(at - now, () => void update($, view, current => ({ ...current, minis })).catch(() => undefined))
489  await keep($, kept => ({ ...kept, pet: { ...kept.pet, helpers: (kept.pet.helpers ?? 0) + 1 } }))
490}
491
492async function sayBye($: EngineInterface, id: string) {
493  const mini = minis.find(m => m.id === id)
494  if (!mini || mini.state === 'bye') return
495  const now = await $.clock.now()
496  minis = minis.map(m => (m.id === id ? { ...m, state: 'bye' as const, at: now } : m))
497  await update($, view, current => ({ ...current, minis }))
498  if (isWorking) say($, `${mini.name} is back with answers 👋`).catch(() => undefined)
499}
500
501// A custom agent may name its colour in its definition (`color: blue`): the project's, then the person's.
502async function definedColor($: EngineInterface, name: string): Promise<string | undefined> {
503  if (!/^[\w-]+$/.test(name)) return undefined
504  const home = await $.env.get('HOME').catch(() => undefined)
505  const dir0 = await $.session.cwd().catch(() => undefined)
506  for (const dir of [dir0 && `${dir0}/.claude/agents`, home && `${home}/.claude/agents`]) {
507    if (!dir) continue
508    const text = await $.fs.read(`${dir}/${name}.md`).catch(() => undefined)
509    const color = text ? colorFromDefinition(text) : undefined
510    if (color) return color
511  }
512  return undefined
513}
514
515const baseName = (path: string) => path.split('/').filter(Boolean).pop() ?? path
516const onOff = (arg: string | undefined, current: boolean) => (arg === 'on' ? true : arg === 'off' ? false : !current)
517
518const cardScene = () => {
519  const scene = sceneNow('happy', 'plain')
520  return scene === 'none' ? undefined : scene
521}
522
523// `/pet card`: the picture goes to Downloads (or home), named after the pet.
524async function saveCard($: EngineInterface): Promise<string> {
525  const now = await $.clock.now()
526  const home = await $.env.get('HOME').catch(() => undefined)
527  if (!home) return 'No home folder to save the card in.'
528  const dir = (await $.fs.exists(`${home}/Downloads`).catch(() => false)) ? `${home}/Downloads` : home
529  const name = nameNow(pet)
530  const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'pet'
531  const path = `${dir}/${slug}-pixel-pet.svg`
532  await $.fs.write(path, petCard({
533    name, color: colorNow(pet), outfit: outfitNow(pet), scene: cardScene(), days: Math.max(0, Math.floor((now - pet.born) / 86_400_000)),
534    turns: pet.turns, pets: pet.pets, helpers: pet.helpers ?? 0, greens: pet.greens ?? 0,
535  }))
536  return `Saved ${name}'s card to ${path.replace(home, '~')}. Open it in a browser to share it.`
537}
538
539export const register: Register = (on, options) => {
540  defaultColor = colorName(String(options.color)) ?? DEFAULT_COLOR
541
542  on('session.start', async ($, e, next) => {
543    await $.command.register({ name: 'pet', description: 'Your pixel pet: stats, or color / rename / outfit / card / calm / breaks / sound / project / hide / show', argumentHint: '[color|rename|outfit|card|calm|breaks|sound|project|hide|show]' })
544    const now = await $.clock.now()
545    today = now
546    cwd = e.cwd
547    const offset = await $.process.run(['date', '+%z'], { timeoutMs: 2000 }).then(r => parseOffset(r.stdout)).catch(() => undefined)
548    if (offset !== undefined) utcOffsetMin = offset
549    const home = await $.env.get('HOME').catch(() => undefined)
550    keptPath = home ? `${home}/.claude/pixel-pet.json` : undefined
551    const kept = await readKept($)
552    const saved = kept?.pet ? undefined : ((await $.store.get('pet')) as Pet | undefined)
553    if (kept?.pet) {
554      pet = kept.pet
555      prefs = { ...prefs, ...kept.prefs }
556      projects = kept.projects ?? {}
557    } else {
558      // The first time with the shared file: carry over this copy's own pet, or hatch one.
559      const configured = String(options.name ?? '').trim()
560      pet = saved ?? { name: configured || NAMES[Math.floor(Math.random() * NAMES.length)]!, born: now, turns: 0, pets: 0 }
561      prefs = { ...prefs, ...((await $.store.get('prefs')) as Partial<Prefs> | undefined) }
562      projects = ((await $.store.get('projects')) as Record<string, Project> | undefined) ?? {}
563      await keep($, () => ({ pet, prefs, projects }))
564    }
565    active(now)
566    // Which provider bills the tokens, from the switches Claude Code reads (never a key).
567    if (await $.env.get('CLAUDE_CODE_USE_BEDROCK').catch(() => undefined)) provider = 'bedrock'
568    else if (await $.env.get('CLAUDE_CODE_USE_VERTEX').catch(() => undefined)) provider = 'vertex'
569    else if (await $.env.get('CLAUDE_CODE_USE_FOUNDRY').catch(() => undefined)) provider = 'foundry'
570    const themeRow = (await $.config.list().catch(() => [])).find(row => row.key === 'theme')
571    theme = /light/i.test(String(themeRow?.value ?? '')) ? 'light' : 'dark'
572    const usage = await $.session.usage().catch(() => undefined)
573    if (usage) await setMeter($, usage)
574    mood = 'sleepy'
575    const isNew = !kept?.pet && !saved
576    await update($, view, current => viewOf(pet, 'sleepy', isNew ? 'just hatched and fell asleep… type to wake it' : pick(LINES.sleepy), current.isHidden))
577    $.clock.every(1000, () => void checkMood($).catch(() => undefined))
578    return next(e)
579  })
580
581  // Keystrokes in the prompt box: answer at once, react off the typing path.
582  on('prompt.edit', async ($, e, next) => {
583    const box = await next(e)
584    // Typing `/pet color …` tries the colour on; anything else reacts to the typing.
585    const color = previewFor(afterEdit(e))
586    if (color || previewColor) preview($, color).catch(() => undefined)
587    else {
588      const reaction = reactionTo(e)
589      if (reaction) react($, reaction).catch(() => undefined)
590    }
591    return box
592  })
593
594  // Typeahead for /pet: its verbs, the colour names (each with its swatch), and the hats.
595  on('prompt.autocomplete', async ($, e, next) => {
596    const offered = await next(e)
597    const before = e.text.slice(0, e.cursor)
598    const partial = e.token.toLowerCase()
599    let rows: { text: string; description?: string }[] = []
600    if (COLOR_COMMAND.test(before)) rows = COLOR_NAMES.filter(name => name.startsWith(partial)).map(name => ({ text: name, description: hex(COLORS[name]!.body) }))
601    else if (SCENE_COMMAND.test(before)) rows = ['on', 'off', ...SCENES].filter(name => name.startsWith(partial)).map(text => ({ text }))
602    else if (OUTFIT_COMMAND.test(before)) rows = ['auto', 'none', ...OUTFITS].filter(name => name.startsWith(partial)).map(text => ({ text }))
603    else if (PET_COMMAND.test(before)) rows = VERBS.filter(([verb]) => verb.startsWith(partial)).map(([text, description]) => ({ text, description }))
604    return rows.length ? { suggestions: [...offered.suggestions, ...rows] } : offered
605  })
606
607  // A click on the sprite (terminal) or on the layer over it (desktop) pets it.
608  on('ui.message', async ($, e, next) => {
609    if ((e.element === 'pet' || e.element === 'pet-hit') && (e.data as { pet?: boolean } | null)?.pet) petIt($).catch(() => undefined)
610    return next(e)
611  })
612
613  on('prompt.submit', async ($, e, next) => {
614    active(await $.clock.now())
615    look = 0
616    if (mood === 'sleepy' || mood === 'dozing') await wake($)
617    else if (mood === 'reading' || mood === 'wince' || mood === 'shocked' || mood === 'calling') await setMood($, 'idle')
618    return next(e)
619  })
620
621  on('turn.start', async ($, e, next) => {
622    isWorking = true
623    const now = await $.clock.now()
624    active(now)
625    turnAt = now
626    steps = 0
627    lastKind = undefined
628    touched.clear()
629    lastSummaryAt = -Infinity
630    // Asleep, it wakes first; once up, the waking mood wears off into working.
631    if (mood === 'sleepy' || mood === 'dozing') await wake($)
632    else if (!moodUntil || mood === 'calling') await setMood($, 'working')
633    return next(e)
634  })
635
636  // Each subagent hatches a little helper beside the pet, in its own colour; it waves bye when done.
637  on('agent.spawn', async ($, e, next) => {
638    if (!e.parentAgentId) say($, `sent ${e.subagentType.split(':').pop()} off on a side quest 🧭`).catch(() => undefined)
639    await hatch($, e.tool_use_id, e.subagentType).catch(() => undefined)
640    const started = await next(e)
641    if (started.deny !== undefined || !started.agentId) await sayBye($, e.tool_use_id).catch(() => undefined)
642    else miniOf.set(started.agentId, e.tool_use_id)
643    return started
644  })
645
646  // Tidying its memory; once the context is light again, a big stretch.
647  on('session.compact', async ($, e, next) => {
648    say($, 'is tidying its memory 🧹').catch(() => undefined)
649    const compacted = await next(e)
650    if (compacted.skip !== undefined) return compacted
651    // The fill comes from a reply, and the compacted window has had none yet: drop the old number
652    // rather than keep showing the pre-compact one.
653    const { percent: _p, tokens: _t, ...rest } = meter
654    meter = rest
655    await update($, view, current => ({ ...current, meter }))
656    await announce($, 'waking', 'stretches · feels light again ✨', 'good', WAKE_MS).catch(() => undefined)
657    return compacted
658  })
659
660  // Claude is waiting on you: a permission, a question, or your next message.
661  on('classic.Notification', async ($, e, next) => {
662    if (/permission|elicitation/i.test(e.notification_type)) call($, 'needs your OK ✋', 'ask').catch(() => undefined)
663    else if (/idle/i.test(e.notification_type) && mood !== 'calling' && mood !== 'sleepy') call($, 'is waiting for you 💬', 'ask').catch(() => undefined)
664    return next(e)
665  })
666
667  on('turn.complete', async ($, e, next) => {
668    const done = await next(e)
669    if (e.agentId !== undefined) {
670      const miniId = miniOf.get(e.agentId)
671      if (miniId) await sayBye($, miniId).catch(() => undefined)
672      return done
673    }
674    isWorking = false
675    const now = await $.clock.now()
676    active(now)
677    if (e.isAborted) {
678      await setMood($, 'idle')
679      return done
680    }
681    await keep($, kept => ({ ...kept, pet: { ...kept.pet, turns: kept.pet.turns + 1 } }))
682    // A long turn calls you back to look; a quick one just gets a happy bounce.
683    if (now - turnAt >= LONG_TURN_MS) await call($, `is done${touched.size ? ` · ${touched.size} file${touched.size === 1 ? '' : 's'} changed` : ''} · come take a look 👀`, 'good')
684    else await setMood($, 'happy', 6000)
685    return done
686  })
687
688  on('tool.call', async ($, e, next) => {
689    const isMine = e.agentId === undefined
690    const args = e as unknown as Record<string, unknown>
691    if (isMine && isWorking) narrate($, String(e.tool), args).catch(() => undefined)
692    const ran = await next(e)
693    if (isMine && ran.deny === undefined) await afterCall($, String(e.tool), args, ran.isError === true, typeof ran.text === 'string' ? ran.text : '').catch(() => undefined)
694    return ran
695  })
696
697  on('session.measure', async ($, e, next) => {
698    const measured = await next(e)
699    await setMeter($, e)
700    return measured
701  })
702
703  on('command.run', { command: 'pet' }, async ($, e) => {
704    const [verb, ...rest] = e.args.trim().split(/\s+/)
705    const arg = rest[0]?.toLowerCase()
706    const redraw = () => update($, view, current => viewOf(pet, current.mood, current.line, current.isHidden, current.tone))
707    const savePrefs = async (next: Partial<Prefs>) => {
708      await keep($, kept => ({ ...kept, prefs: { ...kept.prefs, ...next } }))
709      await redraw()
710    }
711    const where = prefs.perProject ? ` in ${baseName(cwd)}` : ''
712    if (verb === 'hide' || verb === 'show') {
713      await update($, view, current => ({ ...current, isHidden: verb === 'hide' }))
714      return { text: verb === 'hide' ? `${nameNow(pet)} is resting off-screen. /pet show brings it back.` : `${nameNow(pet)} is back!` }
715    }
716    if (verb === 'color' || verb === 'colour') {
717      const choice = colorName(arg)
718      if (!choice) {
719        await preview($, undefined)
720        return { text: `Colours: ${COLOR_NAMES.join(', ')}. Try /pet color pink.` }
721      }
722      previewColor = undefined
723      if (prefs.perProject) await keep($, kept => ({ ...kept, projects: { ...kept.projects, [cwd]: { ...kept.projects[cwd], color: choice } } }))
724      else await keep($, kept => ({ ...kept, pet: { ...kept.pet, color: choice } }))
725      await redraw()
726      return { text: `${nameNow(pet)} is now ${choice}${where}.` }
727    }
728    if (verb === 'rename' && rest.length) {
729      const name = rest.join(' ').slice(0, 24)
730      if (prefs.perProject) await keep($, kept => ({ ...kept, projects: { ...kept.projects, [cwd]: { ...kept.projects[cwd], name } } }))
731      else await keep($, kept => ({ ...kept, pet: { ...kept.pet, name } }))
732      await redraw()
733      return { text: `Your pet is now called ${name}${where}.` }
734    }
735    if (verb === 'outfit') {
736      const named = OCCASIONS[arg ?? ''] ?? arg
737      const choice = named === 'auto' || named === 'none' || OUTFITS.includes(named as Outfit) ? (named as Prefs['outfit']) : undefined
738      if (!choice) return { text: `Outfits: auto (dresses up for Halloween, Christmas, New Year and its birthday), none, ${OUTFITS.join(', ')}.` }
739      await savePrefs({ outfit: choice })
740      const wearing = outfitNow(pet)
741      return { text: choice === 'auto' ? `${nameNow(pet)} dresses for the date${wearing ? `: today it's wearing a ${wearing} hat` : ''}.` : choice === 'none' ? 'No hats.' : `${nameNow(pet)} is wearing a ${choice} hat until you change it (/pet outfit auto goes back to dressing for the date).` }
742    }
743    if (verb === 'scene') {
744      // `off` and `on` are the plain words for no background and the automatic one.
745      const named = arg === 'off' ? 'none' : arg === 'on' ? 'auto' : arg
746      const choice = named === 'auto' || named === 'none' || isScene(named) ? (named as Prefs['scene']) : undefined
747      if (!choice) return { text: `Scenes: on (changes through the day: ${TIMES_OF_DAY.map(([, time, scene]) => `${time} ${scene}`).join(', ')}), off, or one of ${SCENES.join(', ')}.` }
748      await savePrefs({ scene: choice })
749      return { text: choice === 'auto' ? `${nameNow(pet)}'s world changes through the day: ${TIMES_OF_DAY.map(([, time, scene]) => `${time} ${scene}`).join(', ')}.` : choice === 'none' ? 'No background: just the pet. /pet scene on brings it back.' : `${nameNow(pet)} now lives ${whereIn(choice)}.` }
750    }
751    if (verb === 'card') return { text: await saveCard($) }
752    if (verb === 'calm' || verb === 'breaks' || verb === 'sound' || verb === 'project') {
753      const key = verb === 'project' ? 'perProject' : verb
754      const value = onOff(arg, prefs[key])
755      const change: Partial<Prefs> = {}
756      change[key] = value
757      await savePrefs(change)
758      const said: Record<string, string> = {
759        calm: value ? 'Calm: it keeps its motion small and lines fade instead of sliding.' : 'Calm off: full motion.',
760        breaks: value ? 'Breaks on: a stretch after two hours without a pause, and a nudge to sleep after midnight.' : 'Breaks off.',
761        sound: value ? 'Sound on: it chirps when it calls you.' : 'Sound off.',
762        project: value ? `Per project on: each project has its own name and colour (this one: ${nameNow(pet)}, ${colorNow(pet)}). /pet rename and /pet color now change it here only.` : 'Per project off: one pet everywhere.',
763      }
764      return { text: said[verb]! }
765    }
766    const days = Math.max(0, Math.floor(((await $.clock.now()) - pet.born) / 86_400_000))
767    const toggles = (['calm', 'breaks', 'sound', 'perProject'] as const).filter(k => prefs[k]).map(k => (k === 'perProject' ? 'per project' : k))
768    return {
769      text: [
770        `${nameNow(pet)} · ${colorNow(pet)}${outfitNow(pet) ? ` · ${outfitNow(pet)} hat` : ''}${toggles.length ? ` · ${toggles.join(', ')}` : ''}`,
771        `${pet.turns} turns together · petted ${pet.pets} times · ${pet.helpers ?? 0} helpers hatched · ${pet.greens ?? 0} green test runs · ${days} days old`,
772        'Click it to pet it. /pet color, rename, outfit, card, calm, breaks, sound, project.',
773      ].join('\n'),
774    }
775  })
776
777  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
778    const current = await read($, view)
779    if (e.props.hasSurvey || current.isHidden || e.props.maxRows < 4) return next(e)
780    const { Box, Text } = $.ui.resolve(e)
781    const now = await $.clock.now()
782    const percent = current.meter.percent
783    const parts = segments(current.meter, now)
784    const tired = tiredness(percent)
785    const outfit = current.outfit === 'none' ? undefined : current.outfit
786    const colors = LINE_COLORS[theme]
787    // Calm keeps the meter's shimmer still too.
788    const isShimmering = isWorking && !current.calm
789    // The helpers' ages at this draw: each one's story (pop in, bob, wave, fade) runs from its age.
790    // Newest first, so a new helper takes the leftmost slot and pushes the rest along; one still
791    // queued has a negative age and no slot yet.
792    const helpers = [...current.minis].sort((a, b) => b.at - a.at).map(m => ({ id: m.id, color: m.color, state: m.state, age: now - m.at }))
793    // Point at the meter for the details the line leaves out: tokens, resets, how you're billed.
794    // Hidden until hovered; it opens over the band, which clips it, so it stays within four rows.
795    const card = cardLines(current.meter, now)
796    const details = card.length > 0 && (
797      <Box position="absolute" top={-2} left={0} display="none" hover={{ display: 'flex' }} flexDirection="column" paddingX={1} backgroundColor={theme === 'light' ? '#f3f3f5' : '#2b2b30'}>
798        {card.map(text => <Text wrap="truncate">{text}</Text>)}
799      </Box>
800    )
801    const hint = card.length > 0 && <Text dimColor> ⓘ</Text>
802
803    // The terminal draws pixels as half-block text on its grid and animates the line and the meter
804    // there too; anywhere else text doesn't line up into pixels, so pet, line and meter are SVGs
805    // with their motion built in.
806    if (e.surface === 'terminal') {
807      const { Client } = $.ui.resolve(e)
808      // In its world, the scenery scrolls while Claude works (still in calm mode).
809      const pet: PetViewProps = { mood: current.mood, look, color: current.color, outfit: current.outfit, tired, calm: current.calm, scene: current.scene, isMoving: isWorking && !current.calm }
810      const status: StatusViewProps = { name: current.name, line: current.line, calm: current.calm, ...(current.tone === 'plain' ? {} : { color: toneColor(colors, current.tone) }) }
811      const gauge: MeterViewProps = { ...(percent === undefined ? {} : { percent }), segments: parts, isWorking: isShimmering, width: METER_CELLS }
812      return (
813        <Box gap={2} alignItems="center">
814          <Client key="pet" module="./pet-view.tsx" width={current.scene === 'none' ? 10 : HABITAT_COLUMNS} height={current.scene === 'none' ? 4 : HABITAT_ROWS} props={pet} />
815          <Box flexDirection="column" justifyContent="center">
816            <Client key="status" module="./status-view.tsx" props={status} />
817            <Box key="meter-row" alignItems="flex-end">
818              {helpers.length > 0 && <Client key="minis" module="./minis-view.tsx" props={{ minis: helpers, stamp: now } satisfies MinisViewProps} />}
819              <Client key="meter" module="./meter-view.tsx" props={gauge} />
820              {hint}
821              {details}
822            </Box>
823          </Box>
824        </Box>
825      )
826    }
827
828    if (shown && (shown.mood !== current.mood || shown.color !== current.color)) fadeFrom = { ...shown, at: now }
829    shown = { mood: current.mood, color: current.color }
830    if (shownLine !== undefined && shownLine !== current.line) slideFrom = { line: shownLine, at: now }
831    shownLine = current.line
832    const from = drawnPercent
833    if (percent !== undefined) drawnPercent = percent
834    const { Svg } = $.ui.resolve(e)
835    // An invisible layer over the sprite (and its world) catches the click; the SVG itself can't.
836    const hitColumns = current.scene === 'none' ? 6 : 9
837    let hit: RenderChildren = null
838    if (e.surface === 'desktop') {
839      const { Client } = $.ui.resolve(e)
840      hit = (
841        <Box position="absolute" top={0} left={0}>
842          <Client key="pet-hit" module="./hit.tsx" width={hitColumns} height={2} props={{ columns: hitColumns, rows: 2 }} />
843        </Box>
844      )
845    }
846    const previous = slideFrom && now - slideFrom.at < 600 ? slideFrom.line : undefined
847    // The second line, helpers and all, as one SVG that glides from where the last draw left it.
848    const resets = parts.filter(p => p.text.startsWith(' resets')).map(p => p.text.trim()).join(' · ')
849    const bill = parts.find(p => p.text.startsWith('$'))?.text
850    const two = lineTwoSvg({
851      minis: helpers,
852      ...(percent === undefined ? {} : { percent }),
853      from,
854      isWorking: isShimmering,
855      limits: current.meter.limits ?? [],
856      ...(resets ? { resets } : {}),
857      ...(bill ? { bill } : {}),
858      hasInfo: card.length > 0,
859      tones: { ...TONES[theme], text: colors.text },
860      calm: current.calm,
861    }, lineTwoLayout)
862    lineTwoLayout = two.layout
863    const helpersAlt = current.minis.map(m => `${m.name} helper${m.state === 'bye' ? ' waving bye' : ''}`)
864    const style = { outfit, tired, calm: current.calm }
865    // How long its world has scrolled in all, so each redraw carries on from the same spot.
866    const isMoving = isWorking && !current.calm
867    if (isMoving && movingSince === null) movingSince = now
868    if (!isMoving && movingSince !== null) {
869      scrolledBefore += now - movingSince
870      movingSince = null
871    }
872    const scrolledMs = scrolledBefore + (movingSince === null ? 0 : now - movingSince)
873    // The pet, standing in its world when it has one; the scenery scrolls while Claude works.
874    const sprite = petSvg(current.mood, fadeFrom && now - fadeFrom.at < 500 ? fadeFrom : undefined, look, current.color, 5, style)
875    const petAlt = `${current.name}, a pixel pet, ${current.mood}${outfit ? `, wearing a ${outfit} hat` : ''}`
876    const petImage = current.scene === 'none'
877      ? <Svg source={sprite} alt={petAlt} width={50} height={40} />
878      : <Svg source={habitatSvg(current.scene, isMoving, sprite, scrolledMs)} alt={`${petAlt}, ${whereIn(current.scene)}`} width={HABITAT_WIDTH} height={HABITAT_HEIGHT} />
879    return (
880      <Box gap={2} alignItems="center">
881        <Box>
882          {petImage}
883          {hit}
884        </Box>
885        <Box flexDirection="column" justifyContent="center">
886          <Svg source={lineSvg(current.name, current.line, previous, colors, { tone: current.tone, calm: current.calm })} alt={`${current.name} ${current.line}`} width={lineWidth(current.name, current.line, previous)} height={20} />
887          <Box key="meter-row">
888            <Svg source={two.svg} alt={[...helpersAlt, ...card].join('; ') || 'context meter'} width={two.width} height={26} />
889            {details}
890          </Box>
891        </Box>
892      </Box>
893    )
894  })
895}
896
hooks/card.ts 44 lines
1// `/pet card`: a share-sized picture (1200x630, the size social sites preview) of the pet, cheering,
2// in its colour and today's hat, with a few things you've done together.
3import { HEIGHT, WIDTH, draw, hex, paletteFor } from './sprite'
4import type { Outfit } from './sprite'
5import { groundOf, sceneSvgLayers } from './scene'
6import type { Scene } from './scene'
7
8export type CardFacts = { name: string; color: string; outfit?: Outfit | undefined; scene?: Scene | undefined; days: number; turns: number; pets: number; helpers: number; greens: number }
9
10const escape = (s: string) => s.replace(/[<>&"]/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c]!)
11const FONT = `font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, system-ui, sans-serif"`
12
13export function petCard(f: CardFacts): string {
14  const px = 26
15  const grid = draw('happy', { color: f.color, outfit: f.outfit })
16  const pixels = grid.flatMap((row, y) => row.map((c, x) => (c === null ? '' : `<rect x="${x * px}" y="${y * px}" width="${px}" height="${px}" fill="${hex(c)}"/>`))).join('')
17  const accent = hex(paletteFor(f.color).body)
18  const stats: [number, string][] = [
19    [f.days, f.days === 1 ? 'day together' : 'days together'],
20    [f.turns, f.turns === 1 ? 'turn' : 'turns'],
21    [f.pets, f.pets === 1 ? 'pet' : 'pets'],
22    f.greens > 0 ? [f.greens, f.greens === 1 ? 'green test run' : 'green test runs'] : [f.helpers, f.helpers === 1 ? 'helper hatched' : 'helpers hatched'],
23  ]
24  const tiles = stats.map(([n, label], i) => {
25    const x = 470 + (i % 2) * 330
26    const y = 360 + Math.floor(i / 2) * 105
27    return `<text x="${x}" y="${y}" font-size="52" font-weight="800" fill="#f4f4f6">${String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}</text><text x="${x}" y="${y + 34}" font-size="22" fill="#9a9db0">${label}</text>`
28  }).join('')
29  const nameSize = f.name.length > 14 ? 52 : 76
30  return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" ${FONT}>`
31    + `<defs><radialGradient id="glow" cx="0.25" cy="0.45" r="0.6"><stop offset="0" stop-color="${accent}" stop-opacity="0.28"/><stop offset="1" stop-color="${accent}" stop-opacity="0"/></radialGradient></defs>`
32    + (f.scene
33      // Its world behind it, darkened under the words so they read on any scene.
34      ? `<g shape-rendering="crispEdges">${sceneSvgLayers(f.scene, 120, 63, 10, false, 120)}</g>`
35        + `<defs><linearGradient id="shade" x1="0" x2="1"><stop offset="0.24" stop-color="#0b0d12" stop-opacity="0"/><stop offset="0.36" stop-color="#0b0d12" stop-opacity="0.82"/></linearGradient></defs><rect width="1200" height="630" fill="url(#shade)"/>`
36      : `<rect width="1200" height="630" fill="#11131a"/><rect width="1200" height="630" fill="url(#glow)"/>`)
37    + `<rect x="0" y="0" width="1200" height="8" fill="${accent}"/>`
38    + `<g transform="translate(${(430 - WIDTH * px) / 2 + 20} ${f.scene ? Math.round(groundOf(f.scene) * 630 - HEIGHT * px) : (630 - HEIGHT * px) / 2 - 10})" shape-rendering="crispEdges">${pixels}</g>`
39    + `<text x="470" y="200" font-size="${nameSize}" font-weight="800" fill="${accent}" letter-spacing="-1">${escape(f.name)}</text>`
40    + `<text x="472" y="250" font-size="26" fill="#c9cbd6">my pixel pet in Claude Code</text>`
41    + tiles
42    + `<text x="1140" y="600" text-anchor="end" font-size="20" fill="#8a8ea3">pixel-pet · github.com/lakmadev/pixel-pet</text></svg>`
43}
44
hooks/meter.ts 185 lines
1// The context meter on the band's second line: how full the context window is, what the session
2// cost, and the 5-hour limit. A gradient runs mint → amber → red along the bar, so the colour at
3// the tip says how worried to be.
4
5export type Limit = { kind: string; percent: number; resetsAt?: string }
6// Where the numbers come from: a Claude plan meters usage in 5-hour and weekly windows and bills
7// nothing per token; the API and the cloud providers bill per token and have no windows.
8export type Source = 'plan' | 'api' | 'bedrock' | 'vertex' | 'foundry' | 'gateway'
9export type Meter = { percent?: number; tokens?: number; window?: number; usd?: number; limits?: Limit[]; source?: Source }
10export type Segment = { text: string; color?: string; dim?: boolean; bold?: boolean }
11export type Run = { text: string; fg: string; bold?: boolean }
12
13const STOPS: [at: number, color: number][] = [[0, 0x34d399], [0.6, 0xfbbf24], [1, 0xf87171]]
14const TRACK = 0x3a3f4b
15
16const mix = (a: number, b: number, t: number) => {
17  const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - t) + ((b >> s) & 255) * t)
18  return (ch(16) << 16) | (ch(8) << 8) | ch(0)
19}
20export const hex = (color: number) => `#${color.toString(16).padStart(6, '0')}`
21
22export function gradientAt(t: number): number {
23  const x = Math.max(0, Math.min(1, t))
24  for (let i = 1; i < STOPS.length; i++) {
25    const [a, ca] = STOPS[i - 1]!
26    const [b, cb] = STOPS[i]!
27    if (x <= b) return mix(ca, cb, (x - a) / (b - a))
28  }
29  return STOPS[STOPS.length - 1]![1]
30}
31
32const kilo = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n))
33
34const LIMIT_LABELS: Record<string, string> = { five_hour: '5h', seven_day: 'week', seven_day_opus: 'week·opus', spend_limit: 'spend' }
35export const SOURCE_LABELS: Record<Source, string> = { plan: 'Claude plan', api: 'API', bedrock: 'Bedrock', vertex: 'Vertex AI', foundry: 'Foundry', gateway: 'gateway' }
36
37// "1h52m", "38m", "3d4h": how long until a window resets.
38export function resetIn(resetsAt: string | undefined, now: number): string | undefined {
39  if (!resetsAt) return undefined
40  const ms = Date.parse(resetsAt) - now
41  if (!(ms > 0)) return undefined
42  const m = Math.round(ms / 60_000)
43  if (m < 60) return `${m}m`
44  if (m < 24 * 60) return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
45  const h = Math.round(m / 60)
46  return `${Math.floor(h / 24)}d${h % 24 ? `${h % 24}h` : ''}`
47}
48
49export const miniGauge = (percent: number, width = 5) => {
50  const filled = Math.max(percent > 0 ? 1 : 0, Math.min(width, Math.round((percent / 100) * width)))
51  return '▰'.repeat(filled) + '▱'.repeat(width - filled)
52}
53
54// A window's reset only earns a place on the line once it's getting tight; the card always has it.
55export const RESET_SHOWN_FROM = 70
56
57// The terminal's line after the context bar: tokens (when there are no windows to show), each
58// usage window as a gauge and a percent, and the bill on the API or a cloud provider. On a plan
59// the $ is only what the session would cost at API prices, so it stays in the card.
60export function segments(m: Meter, now: number): Segment[] {
61  const out: Segment[] = []
62  const sep = () => out.length && out.push({ text: '  ' })
63  if (m.tokens !== undefined && m.window && !m.limits?.length) out.push({ text: `${kilo(m.tokens)}/${kilo(m.window)}`, dim: true })
64  for (const limit of m.limits ?? []) {
65    sep()
66    const color = hex(gradientAt(limit.percent / 100))
67    out.push({ text: `${LIMIT_LABELS[limit.kind] ?? limit.kind} `, dim: true }, { text: miniGauge(limit.percent), color }, { text: ` ${Math.round(limit.percent)}%`, color, bold: true })
68    const reset = limit.percent >= RESET_SHOWN_FROM ? resetIn(limit.resetsAt, now) : undefined
69    if (reset) out.push({ text: ` resets ${reset}`, dim: true })
70  }
71  if (m.source && m.source !== 'plan' && m.usd !== undefined) {
72    sep()
73    out.push({ text: `$${m.usd.toFixed(2)}`, bold: true })
74  }
75  return out
76}
77
78const LIMIT_NAMES: Record<string, string> = { five_hour: '5-hour limit', seven_day: 'Weekly limit', seven_day_opus: 'Weekly Opus limit', spend_limit: 'Spend limit' }
79
80// The hover card: everything the line leaves out, in plain words.
81export function cardLines(m: Meter, now: number): string[] {
82  const lines: string[] = []
83  if (m.percent !== undefined) lines.push(`Context ${m.percent}% full${m.tokens !== undefined && m.window ? ` · ${kilo(m.tokens)} of ${kilo(m.window)} tokens` : ''}`)
84  for (const limit of m.limits ?? []) {
85    const reset = resetIn(limit.resetsAt, now)
86    lines.push(`${LIMIT_NAMES[limit.kind] ?? limit.kind} ${Math.round(limit.percent)}% used${reset ? ` · resets in ${reset}` : ''}`)
87  }
88  const usd = m.usd !== undefined ? `$${m.usd.toFixed(2)}` : undefined
89  if (m.source === 'plan') lines.push(`Billing: Claude plan, usage limits instead of per-token charges${usd ? ` (≈${usd} at API rates)` : ''}`)
90  else if (m.source) lines.push(`Billing: ${SOURCE_LABELS[m.source]}${usd ? `, ${usd} billed this session` : ''}`)
91  return lines
92}
93
94export type Tones = { label: string }
95export const TONES: Record<'dark' | 'light', Tones> = { dark: { label: '#9a9aa2' }, light: { label: '#6b7280' } }
96
97// Desktop: the usage windows as one SVG, so labels, pills and percents line up exactly
98// (the app's proportional font draws ▰ and ▱ at different widths).
99// The windows' pieces in their own 16px-tall coordinates; limitsSvg wraps them.
100export function limitsParts(limits: readonly Limit[], tones: Tones): { body: string; width: number } {
101  const CHAR = 7.4
102  const PILL = 30
103  let x = 0
104  let end = 0
105  const parts = limits.map(limit => {
106    const label = LIMIT_LABELS[limit.kind] ?? limit.kind
107    const color = hex(gradientAt(limit.percent / 100))
108    const pct = `${Math.round(limit.percent)}%`
109    const fill = Math.max(limit.percent > 0 ? 4 : 0, (Math.min(100, limit.percent) / 100) * PILL)
110    const lx = x
111    const px = lx + label.length * CHAR + 6
112    const tx = px + PILL + 6
113    end = tx + pct.length * 8.4 // bold digits run wider than labels
114    x = end + 16
115    return `<text x="${lx}" y="12" fill="${tones.label}">${label}</text>`
116      + `<rect x="${px}" y="5" width="${PILL}" height="5" rx="2.5" fill="#8b93a7" fill-opacity="0.25"/>`
117      + `<rect x="${px}" y="5" width="${fill.toFixed(1)}" height="5" rx="2.5" fill="${color}"/>`
118      + `<text x="${tx}" y="12" fill="${color}" font-weight="700">${pct}</text>`
119  })
120  return { body: parts.join(''), width: Math.ceil(Math.max(1, end + 2)) }
121}
122
123export const FONT = `font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, system-ui, sans-serif" font-size="12.5"`
124
125export function limitsSvg(limits: readonly Limit[], tones: Tones): { svg: string; width: number } {
126  const { body, width } = limitsParts(limits, tones)
127  return { width, svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="16" viewBox="0 0 ${width} 16" ${FONT}>${body}</svg>` }
128}
129
130export const segmentsText = (parts: readonly Segment[]) => parts.map(p => p.text).join('')
131
132// The terminal bar: heavy line cells in the gradient, a half cell for precision, a dim track after.
133// `shine` is the cell a highlight sweeps across while Claude works.
134export function barRuns(percent: number, width: number, shine?: number): Run[] {
135  const exact = (Math.max(0, Math.min(100, percent)) / 100) * width
136  const full = Math.floor(exact)
137  const half = exact - full >= 0.5
138  const runs: Run[] = []
139  const push = (text: string, color: number) => {
140    const fg = hex(color)
141    const last = runs[runs.length - 1]
142    if (last && last.fg === fg) last.text += text
143    else runs.push({ text, fg })
144  }
145  for (let i = 0; i < width; i++) {
146    const glow = shine === undefined ? 0 : Math.max(0, 1 - Math.abs(i - shine) / 2)
147    const color = mix(gradientAt(i / Math.max(1, width - 1)), 0xffffff, glow * 0.6)
148    if (i < full) push('━', color)
149    else if (i === full && half) push('╸', color)
150    else push('─', TRACK)
151  }
152  return runs
153}
154
155// Desktop: a rounded pill whose fill glides from the last reading to this one, with a soft
156// highlight sweeping across while Claude works and a glow at the tip.
157// The bar's pieces in its own 12px-tall coordinates: what meterSvg wraps, and what the band's
158// second line places among the helpers. Ids are local to whichever SVG holds them.
159export function meterParts(percent: number, from: number, isWorking: boolean, width = 110): { defs: string; body: string } {
160  const w = (p: number) => Math.max(0, Math.min(1, p / 100)) * width
161  const to = w(percent)
162  const start = w(from)
163  const tip = hex(gradientAt(percent / 100))
164  const glide = Math.abs(to - start) > 0.5
165    ? (attr: string) => `<animate attributeName="${attr}" from="${start.toFixed(1)}" to="${to.toFixed(1)}" dur="0.8s" calcMode="spline" keyTimes="0;1" keySplines="0.2 0.8 0.2 1" fill="freeze"/>`
166    : () => ''
167  const shimmer = isWorking
168    ? `<rect y="3" width="30" height="6" fill="url(#s)" clip-path="url(#c)"><animate attributeName="x" values="-30;${width}" dur="1.6s" repeatCount="indefinite"/></rect>`
169    : ''
170  return {
171    defs: `<linearGradient id="g" x1="0" x2="${width}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#34d399"/><stop offset="0.6" stop-color="#fbbf24"/><stop offset="1" stop-color="#f87171"/></linearGradient>`
172      + `<linearGradient id="s" x1="0" x2="1"><stop offset="0" stop-color="#fff" stop-opacity="0"/><stop offset="0.5" stop-color="#fff" stop-opacity="0.55"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>`
173      + `<clipPath id="c"><rect y="3" width="${to.toFixed(1)}" height="6" rx="3">${glide('width')}</rect></clipPath>`,
174    body: `<rect y="3" width="${width}" height="6" rx="3" fill="#8b93a7" fill-opacity="0.22"/>`
175      + `<rect y="3" width="${to.toFixed(1)}" height="6" rx="3" fill="url(#g)">${glide('width')}</rect>`
176      + shimmer
177      + `<circle cx="${to.toFixed(1)}" cy="6" r="4.5" fill="${tip}" fill-opacity="0.35">${glide('cx')}</circle>`,
178  }
179}
180
181export function meterSvg(percent: number, from: number, isWorking: boolean, width = 110): string {
182  const { defs, body } = meterParts(percent, from, isWorking, width)
183  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width + 6}" height="12" viewBox="-3 0 ${width + 6} 12"><defs>${defs}</defs>${body}</svg>`
184}
185
hooks/meter-view.tsx 47 lines
1// The terminal's context meter, on the surface's own clock: the bar and the number glide to each
2// new reading with an ease-out, and a highlight sweeps along the fill while Claude works.
3import type { ClientModule } from 'claude-code'
4
5import { barRuns, gradientAt, hex } from './meter'
6import type { Segment } from './meter'
7
8export type MeterViewProps = { percent?: number; segments: Segment[]; isWorking: boolean; width: number }
9
10type Ref = { shown: number; target: number; phase: number; isWorking: boolean }
11type State = { ref: Ref }
12
13const FRAME_MS = 60
14
15const MeterView: ClientModule<MeterViewProps, State> = (props, surface) => {
16  const { Box, Text } = surface.elements
17  // The first reading shows as it is; later ones glide.
18  const ref = surface.state?.ref ?? { shown: props.percent ?? 0, target: props.percent ?? 0, phase: 0, isWorking: props.isWorking }
19  ref.target = props.percent ?? 0
20  ref.isWorking = props.isWorking
21  if (surface.state === undefined) {
22    surface.setState({ ref })
23    surface.every(FRAME_MS, () => {
24      const isGliding = Math.abs(ref.target - ref.shown) > 0.05
25      if (isGliding) ref.shown += (ref.target - ref.shown) * 0.18
26      else ref.shown = ref.target
27      if (ref.isWorking) ref.phase += 1
28      if (isGliding || ref.isWorking) surface.setState({ ref })
29    })
30  }
31
32  if (props.percent === undefined) return <Text dimColor>context · updates on the next reply</Text>
33
34  const filled = Math.max(1, Math.round((ref.shown / 100) * props.width))
35  const shine = ref.isWorking ? (ref.phase % (filled + 8)) - 4 : undefined
36  return (
37    <Box>
38      {barRuns(ref.shown, props.width, shine).map(run => <Text color={run.fg}>{run.text}</Text>)}
39      <Text bold color={hex(gradientAt(ref.shown / 100))}> {Math.round(ref.shown)}%</Text>
40      {props.segments.length > 0 && <Text> </Text>}
41      {props.segments.map(seg => <Text color={seg.color} dimColor={seg.dim} bold={seg.bold}>{seg.text}</Text>)}
42    </Box>
43  )
44}
45
46export default MeterView
47
hooks/pet-view.tsx 83 lines
1// The pet itself, drawn on the surface's own frame clock: it bobs and blinks between the band's
2// redraws, a change of mood or colour crossfades instead of popping, and a click pets it. With a
3// scene it stands in its little world, 16 columns wide, which scrolls past while Claude works.
4import type { ClientModule } from 'claude-code'
5
6import type { Mood } from '../types'
7import { DEFAULT_COLOR, WIDTH, blend, sprite, toRunsOf } from './sprite'
8import { sceneGrid } from './scene'
9import type { Scene } from './scene'
10import type { Outfit, Style } from './sprite'
11
12// `outfit` is 'none' without a hat: a Client's props can't hold undefined.
13export type PetViewProps = { mood: Mood; look: number; color: string; outfit: Outfit | 'none'; tired: number; calm: boolean; scene: Scene | 'none'; isMoving: boolean }
14
15// Its world in the terminal: 14 columns by 5 rows (10 pixels), the pet standing at the bottom.
16export const HABITAT_COLUMNS = 14
17export const HABITAT_ROWS = 5
18const PET_AT = 2
19const SCROLL_PER_FRAME = 0.9 // the nearest layer's pixels per frame; farther ones move less
20
21type Ref = { t: number; mood: Mood; color: string; from?: { mood: Mood; color: string; at: number }; offset: number; isMoving: boolean }
22type State = { ref: Ref }
23
24const FRAME_MS = 100
25const FADE_MS = 350
26
27const PetView: ClientModule<PetViewProps, State> = (props, surface) => {
28  const { Box, Text } = surface.elements
29  const ref = surface.state?.ref ?? { t: 0, mood: props.mood, color: props.color, offset: 0, isMoving: props.isMoving }
30  ref.isMoving = props.isMoving
31  if (props.mood !== ref.mood || props.color !== ref.color) {
32    ref.from = { mood: ref.mood, color: ref.color, at: ref.t }
33    ref.mood = props.mood
34    ref.color = props.color
35  }
36  if (surface.state === undefined) {
37    surface.setState({ ref })
38    // Some clicks arrive as a down, some only as an up: either pets, once per click.
39    let lastPet = -Infinity
40    surface.onPointer(event => {
41      if ((event.type !== 'down' && event.type !== 'up') || ref.t - lastPet < 300) return
42      lastPet = ref.t
43      surface.post({ pet: true })
44    })
45    surface.every(FRAME_MS, () => {
46      // Asleep it barely moves, so a quarter of the frames will do.
47      ref.t += FRAME_MS
48      if (ref.isMoving) ref.offset += SCROLL_PER_FRAME
49      if (ref.isMoving || ref.mood !== 'sleepy' || ref.t % (FRAME_MS * 4) === 0) surface.setState({ ref })
50    })
51  }
52
53  const style: Style = { outfit: props.outfit === 'none' ? undefined : props.outfit, tired: props.tired, calm: props.calm }
54  let grid = sprite(ref.mood, ref.t, props.look, ref.color ?? DEFAULT_COLOR, style)
55  if (ref.from) {
56    const k = (ref.t - ref.from.at) / FADE_MS
57    if (k >= 1) ref.from = undefined
58    else grid = blend(sprite(ref.from.mood, ref.t, 0, ref.from.color, style), grid, k * k * (3 - 2 * k)) // smoothstep
59  }
60
61  // In its world: the scene behind, the pet's see-through pixels showing it.
62  let width = WIDTH
63  if (props.scene !== 'none') {
64    const world = sceneGrid(props.scene, HABITAT_COLUMNS, HABITAT_ROWS * 2, ref.offset, 32)
65    const top = HABITAT_ROWS * 2 - grid.length
66    grid.forEach((row, y) => row.forEach((c, x) => c !== null && (world[y + top]![x + PET_AT] = c)))
67    grid = world
68    width = HABITAT_COLUMNS
69  }
70
71  return (
72    <Box flexDirection="column">
73      {toRunsOf(grid, width).map(runs => (
74        <Text>
75          {runs.map(run => (run.fg ? <Text color={run.fg} backgroundColor={run.bg}>{run.text}</Text> : <Text>{run.text}</Text>))}
76        </Text>
77      ))}
78    </Box>
79  )
80}
81
82export default PetView
83
hooks/sprite.ts 332 lines
1import type { Mood } from '../types'
2
3// A 10x8 pixel canvas, two pixels per terminal row: 10 columns by 4 rows. null is see-through.
4export type Grid = (number | null)[][]
5export const WIDTH = 10
6export const HEIGHT = 8
7
8// Colours a person can pick with /pet color: the common names, plus a few moods. Each is a body
9// and a darker outline; the order is what a typed prefix matches first.
10export const COLORS: Record<string, { body: number; edge: number }> = {
11  teal: { body: 0x4fd1c5, edge: 0x1f7a73 },
12  red: { body: 0xef4444, edge: 0x7f1d1d },
13  orange: { body: 0xfb923c, edge: 0x9a3412 },
14  yellow: { body: 0xfacc15, edge: 0x854d0e },
15  green: { body: 0x4ade80, edge: 0x166534 },
16  blue: { body: 0x60a5fa, edge: 0x1e40af },
17  purple: { body: 0x8b7cf6, edge: 0x4b3cb0 },
18  pink: { body: 0xf9a8d4, edge: 0xbe185d },
19  white: { body: 0xf3f4f6, edge: 0x9ca3af },
20  gray: { body: 0x9ca3af, edge: 0x4b5563 },
21  black: { body: 0x374151, edge: 0x111827 },
22  brown: { body: 0xb08968, edge: 0x5c3d2e },
23  cyan: { body: 0x22d3ee, edge: 0x155e75 },
24  mint: { body: 0x86efac, edge: 0x15803d },
25  lime: { body: 0xa3e635, edge: 0x3f6212 },
26  sky: { body: 0x7dd3fc, edge: 0x0369a1 },
27  navy: { body: 0x4f63d2, edge: 0x1e2a78 },
28  indigo: { body: 0x818cf8, edge: 0x3730a3 },
29  violet: { body: 0xa78bfa, edge: 0x5b21b6 },
30  lavender: { body: 0xc4b5fd, edge: 0x6d28d9 },
31  magenta: { body: 0xe879f9, edge: 0x86198f },
32  rose: { body: 0xfb7185, edge: 0x9f1239 },
33  peach: { body: 0xfdba74, edge: 0xc2410c },
34  coral: { body: 0xff8a65, edge: 0xb2462a },
35  gold: { body: 0xf6c945, edge: 0x9c7a12 },
36  lava: { body: 0xf87171, edge: 0x991b1b },
37  ghost: { body: 0xe5e7eb, edge: 0x6b7280 },
38  midnight: { body: 0x64748b, edge: 0x1e293b },
39}
40export const COLOR_NAMES = Object.keys(COLORS)
41export const DEFAULT_COLOR = 'teal'
42const ALIASES: Record<string, string> = { grey: 'gray', auto: DEFAULT_COLOR }
43
44export const colorName = (name: string | undefined) => {
45  const n = (name ?? '').toLowerCase()
46  return COLORS[n] ? n : ALIASES[n] ?? undefined
47}
48export const paletteFor = (color = DEFAULT_COLOR) => COLORS[colorName(color) ?? DEFAULT_COLOR]!
49
50const INK = 0x1a1a2e
51const WHITE = 0xffffff
52const BLUSH = 0xff8fb1
53const TONGUE = 0xff5c6c
54const SPARK = 0xffe066
55const HEART = 0xff5c8a
56const SWEAT = 0x7fdbff
57const ZZZ = 0xcfd8ff
58const ALERT = 0xfbbf24
59
60// Hats for the season, painted over the top two rows of the body (the crown and the row below
61// it), so they ride along with every bob and blink. '.' keeps the body.
62export type Outfit = 'pumpkin' | 'santa' | 'party'
63export const OUTFITS: readonly Outfit[] = ['pumpkin', 'santa', 'party']
64const HATS: Record<Outfit, { rows: [string, string]; paint: Record<string, number> }> = {
65  pumpkin: { rows: ['..PPGP..', '.PDPPDP.'], paint: { P: 0xff8c1a, D: 0xd9480f, G: 0x3fa34d } },
66  santa: { rows: ['..RRRRW.', '.WWWWWW.'], paint: { R: 0xe03131, W: 0xffffff } },
67  party: { rows: ['...MY...', '..YMYM..'], paint: { M: 0xe879f9, Y: 0xfacc15 } },
68}
69
70// The wall clock where the person is: `now` shifted by their UTC offset, read with the UTC getters,
71// so it's right whatever time zone the mod's own sandbox runs in.
72export const localDate = (now: number, offsetMin: number) => new Date(now + offsetMin * 60_000)
73
74// Dressed for the day: a pumpkin the week before Halloween, a Santa hat over Christmas, a party
75// hat for New Year and on the pet's birthday (the day it hatched, from its first year on).
76export function outfitFor(now: number, born: number, offsetMin = 0): Outfit | undefined {
77  const d = localDate(now, offsetMin)
78  const month = d.getUTCMonth() + 1
79  const day = d.getUTCDate()
80  const b = localDate(born, offsetMin)
81  if (born > 0 && d.getUTCFullYear() > b.getUTCFullYear() && month === b.getUTCMonth() + 1 && day === b.getUTCDate()) return 'party'
82  if (month === 10 && day >= 25) return 'pumpkin'
83  if (month === 12 && day >= 18 && day <= 26) return 'santa'
84  if ((month === 12 && day === 31) || (month === 1 && day === 1)) return 'party'
85  return undefined
86}
87
88// How it's drawn beyond mood and colour: a hat, how worn out a full context makes it (0..1:
89// slower, heavier bobbing), and calm, for people who'd rather it barely moved.
90export type Style = { outfit?: Outfit | undefined; tired?: number; calm?: boolean }
91
92const BODY = [
93  '..oooo..',
94  '.obbbbo.',
95  'obbbbbbo',
96  'obbbbbbo',
97  'opbbbbpo',
98  '.obbbbo.',
99  '.oo..oo.',
100]
101
102type Eyes = 'open' | 'glance' | 'closed' | 'happy' | 'dizzy' | 'wide'
103type Mouth = 'smile' | 'open' | 'flat' | 'o' | 'gasp'
104
105// Eyes are 1x2 at body columns 2 and 5, rows 2-3: [top, bottom].
106const EYES: Record<Eyes, [string, string]> = {
107  open: ['w', 'k'],
108  glance: ['k', 'k'],
109  closed: ['b', 'k'],
110  happy: ['k', 'b'],
111  dizzy: ['k', 'w'],
112  wide: ['k', 'k'],
113}
114const MOUTHS: Record<Mouth, [x: number, y: number, c: 'k' | 'r'][]> = {
115  smile: [[3, 5, 'k'], [4, 5, 'k']],
116  open: [[3, 4, 'k'], [4, 4, 'k'], [3, 5, 'r'], [4, 5, 'r']],
117  flat: [[2, 5, 'k'], [3, 5, 'k'], [4, 5, 'k'], [5, 5, 'k']],
118  o: [],
119  gasp: [[3, 4, 'k'], [4, 4, 'k'], [3, 5, 'k'], [4, 5, 'k']],
120}
121
122// Rhythm per mood: how fast it bobs (ms per cycle) and whether it shakes instead.
123const RHYTHM: Record<Mood, { period: number; shake?: boolean; still?: boolean }> = {
124  reading: { period: 1400 },
125  wince: { period: 200, shake: true },
126  shocked: { period: 300 },
127  idle: { period: 2400 },
128  working: { period: 640 },
129  happy: { period: 480 },
130  oops: { period: 260, shake: true },
131  calling: { period: 520 },
132  sleepy: { period: 3600, still: true },
133  dozing: { period: 3000, still: true },
134  waking: { period: 520 },
135  loved: { period: 900 },
136}
137
138const wave = (t: number, period: number) => 0.5 - 0.5 * Math.cos((2 * Math.PI * (t % period)) / period)
139
140// Blink for 140ms every few seconds, at a beat that doesn't look mechanical.
141export const isBlinking = (t: number) => (t % 3700) < 140 || ((t + 1300) % 6100) < 120
142
143// look: where the eyes point, -1 left, 0 ahead, 1 right (reading along as you type).
144// t: the clock, for extras that drift (a sleeper's z's).
145type Pose = { lift?: number; dx?: number; blink?: boolean; odd?: boolean; look?: number; color?: string; t?: number; withBody?: boolean; withExtras?: boolean; outfit?: Outfit | undefined }
146
147// One still frame. The terminal animates by drawing many of these; the desktop SVG layers a few.
148export function draw(mood: Mood, { lift = 0, dx = 0, blink = false, odd = false, look = 0, color = DEFAULT_COLOR, t = 0, withBody = true, withExtras = true, outfit }: Pose = {}): Grid {
149  const { body, edge } = paletteFor(color)
150  const eyes: Eyes =
151    mood === 'happy' || mood === 'loved' ? 'happy'
152    : mood === 'sleepy' ? 'closed'
153    : mood === 'dozing' ? (blink ? 'open' : 'closed') // heavy lids: only now and then do they open
154    : mood === 'waking' ? (blink ? 'closed' : 'open') // quick bleary blinks
155    : mood === 'oops' ? 'dizzy'
156    : mood === 'wince' ? 'closed'
157    : mood === 'shocked' ? 'wide'
158    : blink ? 'closed'
159    : mood === 'working' && odd ? 'glance'
160    : 'open'
161  const mouth: Mouth = mood === 'happy' || mood === 'calling' ? 'open' : mood === 'oops' || mood === 'wince' ? 'flat' : mood === 'sleepy' ? 'o' : mood === 'shocked' || mood === 'dozing' || mood === 'waking' ? 'gasp' : 'smile'
162
163  const grid: Grid = Array.from({ length: HEIGHT }, () => Array<number | null>(WIDTH).fill(null))
164  const ox = 1 + dx
165  const oy = 1 - lift
166  const put = (x: number, y: number, c: number) => {
167    if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) grid[y]![x] = c
168  }
169  const paint = { o: edge, b: body, p: BLUSH, k: INK, w: WHITE, r: TONGUE } as const
170
171  if (withBody) {
172    BODY.forEach((row, y) => [...row].forEach((c, x) => c !== '.' && put(ox + x, oy + y, paint[c as keyof typeof paint])))
173    const shift = mood === 'reading' ? Math.max(-1, Math.min(1, Math.round(look))) : 0
174    for (const col of [2 + shift, 5 + shift]) EYES[eyes].forEach((c, i) => put(ox + col, oy + 2 + i, paint[c as keyof typeof paint]))
175    for (const [x, y, c] of MOUTHS[mouth]) put(ox + x, oy + y, paint[c])
176    if (outfit) {
177      const hat = HATS[outfit]
178      hat.rows.forEach((row, y) => [...row].forEach((c, x) => c !== '.' && put(ox + x, oy + y, hat.paint[c]!)))
179    }
180  }
181  if (withExtras) {
182    if (mood === 'happy') for (const [x, y] of odd ? [[0, 1], [9, 3]] : [[9, 0], [0, 4]]) put(x!, y!, SPARK)
183    if (mood === 'oops') put(9, 2 + (odd ? 1 : 0), SWEAT)
184    if (mood === 'sleepy') {
185      // Two z's drifting up and away, half a cycle apart, and a snore bubble on the breath.
186      const path = [[7, 4], [8, 3], [8, 2], [9, 1], [9, 0]]
187      for (const offset of [0, 2]) {
188        const [x, y] = path[(Math.floor(t / 420) + offset) % path.length]!
189        put(x!, y!, ZZZ)
190      }
191      if (Math.floor(t / 1800) % 2 === 0) put(9, 4, SWEAT) // the snore bubble, beside the cheek
192    }
193    if (mood === 'loved') for (const [x, y] of odd ? [[8, 0], [9, 1]] : [[0, 0], [1, 1]]) put(x!, y!, HEART)
194    if (mood === 'shocked') for (const y of [0, 1, 3]) put(9, y, odd ? SPARK : 0xff6b6b) // a blinking "!"
195    if (mood === 'wince') put(odd ? 9 : 8, 2, SWEAT)
196    if (mood === 'calling') {
197      // A "!" beside it and an arm waving: over here!
198      for (const y of [0, 1, 3]) put(0, y, ALERT)
199      put(9, odd ? 2 : 3, paletteFor(color).edge)
200    }
201  }
202  return grid
203}
204
205// The frame at time t: bob or shake on the mood's rhythm, blink now and then, twinkle the extras.
206export function sprite(mood: Mood, t: number, look = 0, color = DEFAULT_COLOR, style: Style = {}): Grid {
207  const rhythm = RHYTHM[mood]
208  const phase = wave(t, periodOf(mood, style.tired))
209  const isStill = rhythm.still || style.calm
210  const lids = mood === 'dozing' ? (t % 1800) < 420 : mood === 'waking' ? (t % 520) < 140 : isBlinking(t)
211  return draw(mood, {
212    lift: isStill || rhythm.shake ? 0 : phase > 0.5 ? 1 : 0,
213    dx: rhythm.shake && !isStill ? (phase > 0.5 ? 1 : -1) : 0,
214    blink: lids,
215    odd: Math.floor(t / 350) % 2 === 1,
216    look,
217    color,
218    t,
219    outfit: style.outfit,
220  })
221}
222
223// A full context slows its everyday moods down: at the brim it bobs at about half speed.
224const SLOWS: readonly Mood[] = ['idle', 'working', 'reading']
225export const periodOf = (mood: Mood, tired = 0) => Math.round(RHYTHM[mood].period * (SLOWS.includes(mood) ? 1 + Math.min(1, Math.max(0, tired)) : 1))
226
227export function mix(a: number, b: number, t: number): number {
228  const ch = (shift: number) => Math.round(((a >> shift) & 255) * (1 - t) + ((b >> shift) & 255) * t)
229  return (ch(16) << 16) | (ch(8) << 8) | ch(0)
230}
231
232// A crossfade between two poses: colors blend, and a pixel that appears or vanishes swaps halfway.
233export function blend(from: Grid, to: Grid, t: number): Grid {
234  return to.map((row, y) => row.map((c, x) => {
235    const a = from[y]?.[x] ?? null
236    if (a === null || c === null) return t < 0.5 ? a : c
237    return mix(a, c, t)
238  }))
239}
240
241export type Run = { text: string; fg?: string; bg?: string }
242export const hex = (color: number) => `#${color.toString(16).padStart(6, '0')}`
243
244// Two pixels per cell with half blocks; empty pixels draw nothing, so the surface shows through.
245export const toRuns = (grid: Grid) => toRunsOf(grid, WIDTH)
246
247export function toRunsOf(grid: Grid, width: number): Run[][] {
248  const rows: Run[][] = []
249  for (let y = 0; y < grid.length; y += 2) {
250    const runs: Run[] = []
251    for (let x = 0; x < width; x++) {
252      const top = grid[y]![x] ?? null
253      const bottom = grid[y + 1]?.[x] ?? null
254      const cell: Run =
255        top === null && bottom === null ? { text: ' ' }
256        : top === null ? { text: '▄', fg: hex(bottom!) }
257        : bottom === null ? { text: '▀', fg: hex(top) }
258        : top === bottom ? { text: '█', fg: hex(top) }
259        : { text: '▀', fg: hex(top), bg: hex(bottom) }
260      const last = runs[runs.length - 1]
261      if (last && last.fg === cell.fg && last.bg === cell.bg) last.text += cell.text
262      else runs.push(cell)
263    }
264    rows.push(runs)
265  }
266  return rows
267}
268
269// Desktop: one SVG with the motion built in, so it animates without redraws. The body glides on
270// an eased curve (smoother than whole pixels), blinks and twinkles switch layers, and a mood change
271// fades the previous pose out. Every animated layer rests where a still image should be, so a
272// surface that ignores SMIL still shows a clean pet.
273export function petSvg(mood: Mood, from?: { mood: Mood; color: string }, look = 0, color = DEFAULT_COLOR, px = 5, style: Style = {}): string {
274  const { outfit, calm = false } = style
275  // Pixels as rects, a row's same-coloured neighbours merged; with `over`, only the pixels that differ from it.
276  const rects = (grid: Grid, over?: Grid) =>
277    grid.map((row, y) => {
278      const cells = row.map((c, x) => (over && (over[y]![x] ?? null) === c ? null : c))
279      let out = ''
280      for (let x = 0; x < WIDTH; ) {
281        let end = x + 1
282        while (end < WIDTH && cells[end] === cells[x]) end++
283        if (cells[x] !== null) out += `<rect x="${x * px}" y="${y * px}" width="${(end - x) * px}" height="${px}" fill="${hex(cells[x]!)}"/>`
284        x = end
285      }
286      return out
287    }).join('')
288  const ease = 'calcMode="spline" keyTimes="0;0.5;1" keySplines="0.45 0 0.55 1;0.45 0 0.55 1"'
289  const once = (ms: number, spline = '0.2 0.8 0.2 1') => `dur="${ms}ms" calcMode="spline" keyTimes="0;1" keySplines="${spline}" fill="freeze"`
290  const rhythm = RHYTHM[mood]
291  // How the body moves: a bob or a shake on the mood's rhythm; asleep, a slow breath that swells it
292  // a touch; dozing off, a slow sink; waking, a rise from that sink with a little overshoot.
293  const period = periodOf(mood, style.tired)
294  const motion =
295    calm ? ''
296    : mood === 'sleepy' ? `<animateTransform attributeName="transform" type="translate" values="0 0;0 ${-px * 0.35};0 0" dur="3600ms" ${ease} repeatCount="indefinite"/>`
297    : mood === 'dozing' ? `<animateTransform attributeName="transform" type="translate" from="0 0" to="0 ${px * 0.6}" ${once(2600, '0.4 0 0.6 1')}/>`
298    : mood === 'waking' ? `<animateTransform attributeName="transform" type="translate" values="0 ${px * 0.6};0 ${-px * 0.5};0 0" keyTimes="0;0.6;1" dur="1100ms" calcMode="spline" keySplines="0.2 0.8 0.3 1;0.4 0 0.6 1" fill="freeze"/>`
299    : rhythm.shake ? `<animateTransform attributeName="transform" type="translate" values="${-px * 0.6} 0;${px * 0.6} 0;${-px * 0.6} 0" dur="${period}ms" ${ease} repeatCount="indefinite"/>`
300    : `<animateTransform attributeName="transform" type="translate" values="0 0;0 ${-px * (mood === 'idle' || mood === 'reading' ? 0.6 : 1)};0 0" dur="${period}ms" ${ease} repeatCount="indefinite"/>`
301  const toggle = (dur: number, on: string) => `<animate attributeName="opacity" values="0;1" keyTimes="0;${on}" calcMode="discrete" dur="${dur}ms" repeatCount="indefinite"/>`
302
303  const base = draw(mood, { withExtras: false, look, color, outfit })
304  // Lids: a blink now and then; dozing, heavy lids that open less and less; waking, quick bleary blinks.
305  const lids =
306    mood === 'idle' || mood === 'working' || mood === 'reading' ? `<g opacity="0">${rects(draw(mood, { blink: true, withExtras: false, look, color, outfit }), base)}${toggle(3700, '0.962')}</g>`
307    : mood === 'dozing' ? `<g opacity="0">${rects(draw(mood, { blink: true, withExtras: false, color, outfit }), base)}<animate attributeName="opacity" values="0;1;0;1;0" keyTimes="0;0.1;0.35;0.45;1" calcMode="discrete" dur="2600ms" fill="freeze"/></g>`
308    : mood === 'waking' ? `<g opacity="0">${rects(draw(mood, { blink: true, withExtras: false, color, outfit }), base)}<animate attributeName="opacity" values="1;0;1;0" keyTimes="0;0.25;0.4;0.6" calcMode="discrete" dur="1100ms" fill="freeze"/></g>`
309    : ''
310  const glance = mood === 'working' ? `<g opacity="0">${rects(draw(mood, { odd: true, withExtras: false, color, outfit }), base)}${toggle(700, '0.5')}</g>` : ''
311
312  // Asleep: z's that drift up and fade, one after another, and a snore bubble that swells and pops.
313  // Calm, they fade in and out where they are.
314  const z = (begin: number) =>
315    `<g opacity="0"><rect x="${px * (calm ? 7.6 + begin / 1300 : 7.6)}" y="${px * (calm ? 3 - begin / 700 : 3.6)}" width="${px * 0.9}" height="${px * 0.9}" fill="#cfd8ff"/>`
316    + (calm ? '' : `<animateTransform attributeName="transform" type="translate" values="0 0;${px * 1.2} ${-px * 3.4}" dur="2400ms" begin="${begin}ms" repeatCount="indefinite"/>`)
317    + `<animate attributeName="opacity" values="0;0.95;0" keyTimes="0;0.25;1" dur="2400ms" begin="${begin}ms" repeatCount="indefinite"/></g>`
318  const snore = mood === 'sleepy'
319    ? z(0) + z(800) + z(1600)
320      + `<circle shape-rendering="geometricPrecision" cx="${px * 6.9}" cy="${px * 6.2}" r="0" fill="#7fdbff" fill-opacity="0.55" stroke="#bfefff" stroke-opacity="0.8" stroke-width="0.6"><animate attributeName="r" values="0;${px * 0.9};${px * 1.25};0;0" keyTimes="0;0.55;0.7;0.72;1" dur="3600ms" repeatCount="indefinite"/></circle>`
321    : ''
322  const extrasA = mood === 'sleepy' ? '' : rects(draw(mood, { withBody: false, color }))
323  const extrasB = mood === 'sleepy' ? '' : rects(draw(mood, { withBody: false, odd: true, color }))
324  const twinkle = extrasA || extrasB
325    ? `<g>${extrasA}<animate attributeName="opacity" values="1;0" keyTimes="0;0.5" calcMode="discrete" dur="700ms" repeatCount="indefinite"/></g><g opacity="0">${extrasB}${toggle(700, '0.5')}</g>`
326    : ''
327  const fade = from && (from.mood !== mood || from.color !== color)
328    ? `<g opacity="0">${rects(draw(from.mood, { color: from.color, outfit }))}<animate attributeName="opacity" values="1;0" dur="350ms" fill="freeze"/></g>`
329    : ''
330  return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH * px}" height="${HEIGHT * px}" viewBox="0 0 ${WIDTH * px} ${HEIGHT * px}" shape-rendering="crispEdges"><g>${rects(base)}${lids}${glance}${motion}</g>${twinkle}${snore}${fade}</svg>`
331}
332
hooks/status.ts 122 lines
1// What the pet says while Claude works, one line per kind of action, and the desktop's slide
2// between one line and the next.
3
4const base = (path: unknown) => (typeof path === 'string' ? path.split('/').filter(Boolean).pop() ?? path : 'a file')
5const clip = (text: unknown, max = 28) => {
6  const s = String(text ?? '').replace(/\s+/g, ' ').trim()
7  return s.length > max ? `${s.slice(0, max - 1)}…` : s
8}
9
10const SHELL: [RegExp, string][] = [
11  [/\b(jest|vitest|pytest|mocha|rspec|phpunit|go test|cargo test|(npm|pnpm|yarn|bun) (run )?test)\b/, 'is running the tests 🧪'],
12  [/\bgit commit\b/, 'is committing the work ✍️'],
13  [/\bgit push\b/, 'is pushing to the remote 🚀'],
14  [/\bgit (pull|fetch|clone)\b/, 'is pulling from git…'],
15  [/\bgit (diff|status|log|show|blame)\b/, 'is checking the git history…'],
16  [/\bgit\b/, 'is talking to git…'],
17  [/\b((npm|pnpm|yarn|bun) (i|install|add)|pip3? install|poetry add|cargo add|brew install|go get|gem install)\b/, 'is installing packages 📦'],
18  [/\b(tsc|webpack|vite build|next build|make|cargo build|go build|gradle|mvn|(npm|pnpm|yarn|bun) run build)\b/, 'is building the project 🔨'],
19  [/\b(eslint|prettier|ruff|black|flake8|rubocop|biome|(npm|pnpm|yarn|bun) run lint)\b/, 'is tidying the code style…'],
20  [/\b(docker|kubectl|helm|terraform)\b/, 'is poking the infrastructure 🐳'],
21  [/\b(curl|wget|http)\b/, 'is fetching something from the web…'],
22  [/^\s*(ls|cat|head|tail|find|tree|pwd|wc)\b/, 'is looking around the repo 👀'],
23  [/\b(rm|mv|cp|mkdir)\b/, 'is moving files around…'],
24]
25
26// What kind of work a call is, so a run of the same kind (five reads in a row) is told once.
27export function actionKind(tool: string, args: Record<string, unknown>): string | undefined {
28  if (tool === 'Read' || tool === 'NotebookRead') return 'read'
29  if (tool === 'Edit' || tool === 'MultiEdit' || tool === 'Write' || tool === 'NotebookEdit') return 'edit'
30  if (tool === 'Grep' || tool === 'Glob' || tool === 'LS') return 'search'
31  if (tool === 'WebSearch' || tool === 'WebFetch') return 'web'
32  if (tool === 'Bash') {
33    const cmd = String(args.command ?? '')
34    const at = SHELL.findIndex(([re]) => re.test(cmd))
35    return at < 0 ? 'shell' : `shell:${at}`
36  }
37  const mcp = /^mcp__([^_]+(?:_[^_]+)*)__/.exec(tool)?.[1]
38  if (mcp) return `mcp:${mcp}`
39  return actionLine(tool, args) === undefined ? undefined : tool
40}
41
42const shellRe = (line: string) => SHELL.find(([, l]) => l.startsWith(line))![0]
43const TESTS = shellRe('is running the tests')
44const BUILD = shellRe('is building')
45const count = (text: string, re: RegExp) => Number(re.exec(text)?.[1] ?? 0)
46
47// What came of a call worth reacting to: tests passing or failing, a push landing or bouncing,
48// a build breaking. Undefined for everything else, which the pet lets pass without comment.
49export function outcomeOf(tool: string, args: Record<string, unknown>, isError: boolean, text = ''): { tone: 'good' | 'bad'; line: string } | undefined {
50  if (tool !== 'Bash') return undefined
51  const cmd = String(args.command ?? '')
52  if (TESTS.test(cmd)) {
53    const failed = count(text, /(\d+)\s+(?:tests?\s+)?(?:failed|failing|failures?)\b/i)
54    const passed = count(text, /(\d+)\s+(?:tests?\s+)?(?:passed|passing)\b/i)
55    if (isError || failed > 0) return { tone: 'bad', line: failed > 0 ? `saw ${failed} test${failed === 1 ? '' : 's'} fail ❌` : 'saw the tests fail ❌' }
56    return { tone: 'good', line: passed > 0 ? `cheers: all ${passed} tests pass ✅` : 'cheers: the tests pass ✅' }
57  }
58  if (/\bgit push\b/.test(cmd)) return isError ? { tone: 'bad', line: 'saw the push bounce 😬' } : { tone: 'good', line: 'watched it ship 🚀' }
59  if (isError && BUILD.test(cmd)) return { tone: 'bad', line: 'saw the build break 🔨' }
60  return undefined
61}
62
63// Once a turn runs long, one quiet summary instead of a line per step.
64export const focusLine = (steps: number, files: number) => `is deep in it · ${steps} steps${files ? ` · ${files} file${files === 1 ? '' : 's'} changed` : ''}`
65
66// The line for a tool call that's starting, or undefined for a tool not worth a line.
67export function actionLine(tool: string, args: Record<string, unknown>): string | undefined {
68  const t = tool
69  if (t === 'Read' || t === 'NotebookRead') return `is reading ${base(args.file_path ?? args.notebook_path)}…`
70  if (t === 'Edit' || t === 'MultiEdit') return `is editing ${base(args.file_path)} ✏️`
71  if (t === 'Write') return `is writing ${base(args.file_path)} ✏️`
72  if (t === 'NotebookEdit') return 'is editing a notebook 📓'
73  if (t === 'Bash') {
74    const cmd = String(args.command ?? '')
75    return SHELL.find(([re]) => re.test(cmd))?.[1] ?? `is running \`${clip(cmd.split(/\s+/)[0], 16)}\`…`
76  }
77  if (t === 'Grep') return `is searching for "${clip(args.pattern, 22)}" 🔍`
78  if (t === 'Glob' || t === 'LS') return `is looking for ${clip(args.pattern ?? args.path, 22)}…`
79  if (t === 'WebSearch') return `is searching the web for "${clip(args.query, 22)}" 🌐`
80  if (t === 'WebFetch') {
81    const host = /^https?:\/\/([^/]+)/.exec(String(args.url ?? ''))?.[1]
82    return `is reading ${host ?? 'a web page'} 🌐`
83  }
84  if (t === 'TodoWrite' || t === 'TaskCreate' || t === 'TaskUpdate') return 'is planning the next steps 📝'
85  if (t === 'EnterPlanMode' || t === 'ExitPlanMode') return 'is drafting a plan 🗺️'
86  if (t === 'AskUserQuestion') return 'has a question for you ❓'
87  if (t === 'Skill') return `is using the ${clip(args.skill ?? args.name, 20)} skill 🧰`
88  if (t === 'Agent' || t === 'Task') return `is sending a helper off ${args.subagent_type ? `(${clip(args.subagent_type, 16)}) ` : ''}🧭`
89  const mcp = /^mcp__([^_]+(?:_[^_]+)*)__/.exec(t)?.[1]
90  if (mcp) return `is asking ${clip(mcp.replace(/[-_]/g, ' '), 20)}…`
91  return undefined
92}
93
94export type LineColors = { name: string; text: string; good: string; bad: string; ask: string }
95export const LINE_COLORS: Record<'dark' | 'light', LineColors> = {
96  dark: { name: '#d97757', text: '#e6e6e6', good: '#4ade80', bad: '#f87171', ask: '#fbbf24' },
97  light: { name: '#c4613f', text: '#1f2328', good: '#15803d', bad: '#b91c1c', ask: '#b45309' },
98}
99export const toneColor = (colors: LineColors, tone: 'plain' | 'good' | 'bad' | 'ask' = 'plain') => (tone === 'plain' ? colors.text : colors[tone])
100
101const escape = (s: string) => s.replace(/[<>&"]/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c]!)
102
103// Desktop: the line as SVG text. The name stays put; only what follows it moves: the new words
104// rise from below while the old ones drift up and fade (calm: they just cross-fade). Each status
105// carries the name invisibly in front of it, so it starts exactly where the name ends in any font.
106// Each layer rests where a still image should be, so without SMIL only the new line shows.
107export const lineWidth = (name: string, line: string, previous?: string) => Math.min(640, Math.ceil((name.length + 1 + Math.max(line.length, previous?.length ?? 0)) * 7.9) + 24)
108
109export function lineSvg(name: string, line: string, previous: string | undefined, colors: LineColors, { tone = 'plain', calm = false }: { tone?: 'plain' | 'good' | 'bad' | 'ask'; calm?: boolean } = {}): string {
110  const width = lineWidth(name, line, previous)
111  const status = (l: string, fill: string) => `<tspan font-weight="700" fill-opacity="0">${escape(name)}</tspan><tspan fill="${fill}"> ${escape(l)}</tspan>`
112  const ease = 'dur="0.38s" calcMode="spline" keyTimes="0;1" keySplines="0.2 0.8 0.2 1" fill="freeze"'
113  const isChange = previous !== undefined && previous !== line
114  const old = isChange
115    ? `<text x="0" y="${calm ? 15 : -4}" opacity="0">${status(previous, colors.text)}${calm ? '' : `<animate attributeName="y" values="15;-4" ${ease}/>`}<animate attributeName="opacity" values="1;0" ${ease}/></text>`
116    : ''
117  const rise = isChange ? `${calm ? '' : `<animate attributeName="y" values="32;15" ${ease}/>`}<animate attributeName="opacity" values="0;1" ${ease}/>` : ''
118  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="20" viewBox="0 0 ${width} 20" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, system-ui, sans-serif" font-size="14">`
119    + `${old}<text x="0" y="15">${status(line, toneColor(colors, tone))}${rise}</text>`
120    + `<text x="0" y="15" fill="${colors.name}" font-weight="700">${escape(name)}</text></svg>`
121}
122
hooks/mini.ts 89 lines
1// The pet's little helpers, one per running subagent: half its size (5x4 body, plus a column for a
2// waving arm), in the agent's own colour. They pop in, bob while their agent works, and when it's
3// done they wave bye, float up and fade away.
4import type { Grid } from './sprite'
5import { COLOR_NAMES, hex, paletteFor } from './sprite'
6
7export const MINI_W = 6
8export const MINI_H = 4
9export const ARRIVE_MS = 600
10export const WAVE_MS = 1300
11export const LEAVE_MS = 2200
12
13const INK = 0x1a1a2e
14const BODY = ['.ooo.', 'okbko', 'obbbo', '.o.o.']
15
16// A stable colour for an agent with none of its own, never the parent's.
17export function miniColor(id: string, avoid: string): string {
18  const names = COLOR_NAMES.filter(name => name !== avoid && name !== 'black' && name !== 'white')
19  let h = 0
20  for (const ch of id) h = (h * 31 + ch.charCodeAt(0)) >>> 0
21  return names[h % names.length]!
22}
23
24// The Claude Code agent colours as a definition file names them, onto the pet's palette.
25const AGENT_COLORS: Record<string, string> = { red: 'red', blue: 'blue', green: 'green', yellow: 'yellow', purple: 'purple', orange: 'orange', pink: 'pink', cyan: 'cyan' }
26export const colorFromDefinition = (markdown: string) => {
27  const front = /^---\n([\s\S]*?)\n---/.exec(markdown)?.[1] ?? ''
28  const named = /^color:\s*["']?([a-z]+)/im.exec(front)?.[1]?.toLowerCase()
29  return named ? AGENT_COLORS[named] ?? (COLOR_NAMES.includes(named) ? named : undefined) : undefined
30}
31
32export function miniDraw(color: string, { blink = false, armUp = false, arm = false } = {}): Grid {
33  const { body, edge } = paletteFor(color)
34  const paint: Record<string, number> = { o: edge, b: body, k: blink ? body : INK }
35  const grid: Grid = BODY.map(row => [...row].map(c => (c === '.' ? null : paint[c]!)))
36  for (const row of grid) row.push(null)
37  if (arm) grid[armUp ? 0 : 1]![5] = edge
38  return grid
39}
40
41// Terminal frames, by how long the mini has been in its state.
42export function miniFrame(color: string, state: 'here' | 'bye', age: number, seed: number): Grid | null {
43  if (state === 'here' && age < ARRIVE_MS) {
44    // A sparkle, then the body: a pop in two beats.
45    if (age < 200) return Array.from({ length: MINI_H }, (_, y) => Array.from({ length: MINI_W }, (_, x) => (x === 2 && y === 1 ? 0xffe066 : null)))
46    return miniDraw(color)
47  }
48  if (state === 'bye') {
49    if (age < WAVE_MS) return miniDraw(color, { arm: true, armUp: Math.floor(age / 220) % 2 === 0 })
50    if (age < WAVE_MS + 300) return miniDraw(color, { blink: true })
51    if (age < WAVE_MS + 550) return Array.from({ length: MINI_H }, (_, y) => Array.from({ length: MINI_W }, (_, x) => (x === 2 && y === 1 ? 0xcfd8ff : null)))
52    return null
53  }
54  return miniDraw(color, { blink: (age + seed * 377) % 3100 < 130 })
55}
56
57export const seedOf = (id: string) => [...id].reduce((h, ch) => (h * 31 + ch.charCodeAt(0)) >>> 0, 7) % 997
58
59// Desktop: one helper drawn at its slot's origin, its story told by its age: once its slot has
60// opened (SLOT_MS) it pops in with a little spring, then bobs and blinks at its own pace; leaving,
61// it waves, floats up and fades. Laid out by the band's second line (line2.ts).
62export const SLOT_MS = 380
63
64export function miniBody(mini: { id: string; color: string; state: 'here' | 'bye'; age: number }, px = 5, calm = false): string {
65  const w = MINI_W * px
66  const h = MINI_H * px
67  const rects = (grid: Grid) => grid.map((row, y) => row.map((c, x) => (c === null ? '' : `<rect x="${x * px}" y="${y * px}" width="${px}" height="${px}" fill="${hex(c)}"/>`)).join('')).join('')
68  const seed = seedOf(mini.id)
69  if (mini.state === 'bye') {
70    const wave = (up: boolean) => `<g opacity="${up ? 1 : 0}">${rects(miniDraw(mini.color, { arm: true, armUp: up }))}<animate attributeName="opacity" values="${up ? '1;0' : '0;1'}" keyTimes="0;0.5" calcMode="discrete" dur="440ms" repeatCount="${Math.ceil(WAVE_MS / 440)}" fill="freeze"/></g>`
71    const fadeAt = Math.max(0, WAVE_MS - mini.age)
72    return `<g>${wave(true)}${wave(false)}`
73      + `<animateTransform attributeName="transform" type="translate" values="0 0;0 ${-px * 1.6}" dur="800ms" begin="${fadeAt}ms" calcMode="spline" keyTimes="0;1" keySplines="0.3 0 0.7 1" fill="freeze"/>`
74      + `<animate attributeName="opacity" values="1;0" dur="800ms" begin="${fadeAt}ms" fill="freeze"/></g>`
75  }
76  const spline = 'calcMode="spline" keySplines="0.45 0 0.55 1;0.45 0 0.55 1"'
77  const bob = `<animateTransform attributeName="transform" type="translate" values="0 0;0 ${-px * 0.7};0 0" keyTimes="0;0.5;1" dur="${560 + (seed % 240)}ms" ${spline} repeatCount="indefinite"/>`
78  const blink = `<g opacity="0">${rects(miniDraw(mini.color, { blink: true }))}<animate attributeName="opacity" values="0;1" keyTimes="0;0.96" calcMode="discrete" dur="${2900 + (seed % 900)}ms" begin="${-(seed % 2900)}ms" repeatCount="indefinite"/></g>`
79  const body = `<g>${rects(miniDraw(mini.color))}${blink}${calm ? '' : bob}</g>`
80  if (mini.age >= SLOT_MS + ARRIVE_MS) return body
81  // Not yet popped: hold at nothing while the slot opens, then spring out from the middle.
82  const wait = Math.max(0, SLOT_MS - mini.age)
83  const cx = (w - px) / 2
84  const cy = h / 2
85  return `<g transform="translate(${cx} ${cy})"><g transform="scale(${wait > 0 ? 0 : 1})">`
86    + `<animateTransform attributeName="transform" type="scale" values="0;1.2;1" keyTimes="0;0.65;1" dur="${ARRIVE_MS}ms" begin="${wait}ms" calcMode="spline" keySplines="0.2 0.8 0.3 1;0.4 0 0.6 1" fill="freeze"/>`
87    + `<g transform="translate(${-cx} ${-cy})">${body}</g></g></g>`
88}
89
hooks/line2.ts 92 lines
1// Desktop: the band's second line as one SVG: the helpers on the left, newest first, then the
2// context bar, its percent, the usage windows, the bill and the ⓘ. Each element starts where the
3// previous draw left it and glides to its new place, so a helper's slot opening pushes the line
4// right and one closing pulls it back.
5import { FONT, gradientAt, hex, limitsParts, meterParts } from './meter'
6import type { Limit, Tones } from './meter'
7import { MINI_W, miniBody } from './mini'
8
9export type Layout = Map<string, number>
10export type LineTwo = {
11  minis: { id: string; color: string; state: 'here' | 'bye'; age: number }[]
12  percent?: number
13  from: number
14  isWorking: boolean
15  limits: Limit[]
16  resets?: string
17  bill?: string
18  hasInfo: boolean
19  tones: Tones & { text: string }
20  // Calm: the helpers stand still instead of bobbing.
21  calm?: boolean
22}
23
24const PX = 5
25const SLOT = MINI_W * PX + 4
26const HEIGHT = 26
27const PILL = 110
28const GLIDE = 'dur="420ms" calcMode="spline" keyTimes="0;1" keySplines="0.25 0.8 0.25 1" fill="freeze"'
29
30export function lineTwoSvg(line: LineTwo, previous: Layout | undefined): { svg: string; width: number; layout: Layout } {
31  const layout: Layout = new Map()
32  const minis = line.minis.filter(m => m.age >= 0)
33  minis.forEach((m, i) => layout.set(m.id, i * SLOT))
34  const contentX = minis.length ? minis.length * SLOT + 4 : 0
35  layout.set('content', contentX)
36
37  // Where an element was on the last draw, to glide from; a new helper has no past and pops in.
38  const place = (key: string, y: number) => {
39    const x = layout.get(key)!
40    const was = previous?.get(key)
41    const move = was !== undefined && Math.abs(was - x) > 0.5
42      ? `<animateTransform attributeName="transform" type="translate" values="${was} ${y};${x} ${y}" ${GLIDE}/>`
43      : ''
44    return { open: `<g transform="translate(${x} ${y})">${move}`, close: '</g>' }
45  }
46
47  let defs = ''
48  let content = ''
49  let x = 0
50  if (line.percent === undefined) {
51    content = `<text x="0" y="17.5" fill="${line.tones.label}">context · updates on the next reply</text>`
52    x = 230
53  } else {
54    const meter = meterParts(line.percent, line.from, line.isWorking, PILL)
55    defs = meter.defs
56    const pct = `${line.percent}%`
57    content = `<g transform="translate(3 7)">${meter.body}</g>`
58      + `<text x="${PILL + 12}" y="17.5" fill="${hex(gradientAt(line.percent / 100))}" font-weight="700">${pct}</text>`
59    x = PILL + 12 + pct.length * 8.4 + 12
60    if (line.limits.length) {
61      const limits = limitsParts(line.limits, line.tones)
62      content += `<g transform="translate(${x.toFixed(1)} 5)">${limits.body}</g>`
63      x += limits.width + 10
64    }
65    if (line.resets) {
66      content += `<text x="${x.toFixed(1)}" y="17.5" fill="${line.tones.label}">${line.resets}</text>`
67      x += line.resets.length * 7.1 + 10
68    }
69    if (line.bill) {
70      content += `<text x="${x.toFixed(1)}" y="17.5" fill="${line.tones.text}" font-weight="700">${line.bill}</text>`
71      x += line.bill.length * 8.4 + 10
72    }
73  }
74  if (line.hasInfo) {
75    content += `<text x="${x.toFixed(1)}" y="17.5" fill="${line.tones.label}">ⓘ</text>`
76    x += 14
77  }
78
79  const helpers = minis.map(m => {
80    const at = place(m.id, 5)
81    return `${at.open}${miniBody(m, PX, line.calm)}${at.close}`
82  })
83  const body = place('content', 0)
84  const width = Math.ceil(Math.max(contentX + x, (previous?.get('content') ?? 0) + x))
85  return {
86    layout,
87    width,
88    svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${HEIGHT}" viewBox="0 0 ${width} ${HEIGHT}" ${FONT}><defs>${defs}</defs>`
89      + `<g shape-rendering="crispEdges">${helpers.join('')}</g>${body.open}${content}${body.close}</svg>`,
90  }
91}
92
hooks/scene.ts 330 lines
1// The pet's little world: layered pixel scenery drawn in code (sky, far ridges or towers, trees,
2// hills, ground), each layer seamless over its period so it can scroll for parallax while Claude
3// works. Sizes are fractions of the scene's height, so the same scene draws 8 pixels tall in the
4// terminal, 20 on desktop and full size on the share card.
5import type { Grid } from './sprite'
6
7export const SCENES = ['meadow', 'desert', 'jungle', 'city', 'skyline', 'snow', 'moon', 'savanna', 'lava', 'mountains'] as const
8export type Scene = (typeof SCENES)[number]
9
10type Layer =
11  | { kind: 'sky'; stops: number[] }
12  | { kind: 'dots'; color: number; from: number; to: number; every: number }
13  | { kind: 'clouds'; color: number; at: number; every: number; speed: number }
14  | { kind: 'ridge'; color: number; base: number; amp: number; jag?: boolean; speed: number }
15  | { kind: 'bumps'; color: number; base: number; amp: number; every: number; speed: number }
16  | { kind: 'trees'; color: number; base: number; size: number; every: number; shape: 'round' | 'pine' | 'palm'; speed: number }
17  | { kind: 'towers'; colors: [number, number]; base: number; tall: number; speed: number }
18  | { kind: 'band'; color: number; from: number; to: number; speed: number }
19  | { kind: 'craters'; color: number; at: number; every: number; speed: number }
20
21// Where the pet's feet go (a fraction of the height), and the layers back to front.
22const SCENE: Record<Scene, { ground: number; layers: Layer[] }> = {
23  meadow: { ground: 0.9, layers: [
24    { kind: 'sky', stops: [0x1d7fe0, 0x3fa0ee, 0x7cc4f6] },
25    { kind: 'clouds', color: 0xd9efff, at: 0.14, every: 26, speed: 0.08 },
26    { kind: 'ridge', color: 0x7d8496, base: 0.42, amp: 0.08, jag: true, speed: 0.15 },
27    { kind: 'trees', color: 0x2f6b3a, base: 0.56, size: 0.12, every: 3, shape: 'pine', speed: 0.3 },
28    { kind: 'band', color: 0x86c94a, from: 0.56, to: 1, speed: 0.5 },
29    { kind: 'bumps', color: 0x9ed858, base: 0.82, amp: 0.2, every: 22, speed: 0.7 },
30    { kind: 'bumps', color: 0xb2e26a, base: 0.95, amp: 0.16, every: 30, speed: 1 },
31  ] },
32  desert: { ground: 0.9, layers: [
33    { kind: 'sky', stops: [0x1f86e8, 0x56aef2] },
34    { kind: 'clouds', color: 0xdcefff, at: 0.16, every: 30, speed: 0.08 },
35    { kind: 'ridge', color: 0x5b616b, base: 0.42, amp: 0.05, jag: true, speed: 0.15 },
36    { kind: 'bumps', color: 0xc8aa7c, base: 0.55, amp: 0.12, every: 18, speed: 0.4 },
37    { kind: 'band', color: 0xddbf92, from: 0.6, to: 1, speed: 0.7 },
38    { kind: 'bumps', color: 0xe6cc9f, base: 0.78, amp: 0.08, every: 34, speed: 1 },
39  ] },
40  jungle: { ground: 0.88, layers: [
41    { kind: 'sky', stops: [0x3a9e9a, 0x6cc3b6] },
42    { kind: 'trees', color: 0x4b8f93, base: 0.62, size: 0.42, every: 9, shape: 'palm', speed: 0.2 },
43    { kind: 'trees', color: 0x4f8a2a, base: 0.66, size: 0.5, every: 14, shape: 'palm', speed: 0.5 },
44    { kind: 'bumps', color: 0xa9a85a, base: 0.72, amp: 0.1, every: 20, speed: 0.7 },
45    { kind: 'band', color: 0xc9c27a, from: 0.72, to: 1, speed: 1 },
46    { kind: 'band', color: 0xeee6a8, from: 0.9, to: 1, speed: 1 },
47  ] },
48  city: { ground: 0.95, layers: [
49    { kind: 'sky', stops: [0x5d7f8a, 0x9fb8b8] },
50    { kind: 'towers', colors: [0xc6c9c0, 0x9da3a0], base: 0.62, tall: 0.55, speed: 0.15 },
51    { kind: 'towers', colors: [0x7a3b3b, 0xd9c08a], base: 0.95, tall: 0.6, speed: 0.5 },
52    { kind: 'band', color: 0x3a3a3e, from: 0.95, to: 1, speed: 1 },
53  ] },
54  // The city at night: lit windows under the stars.
55  skyline: { ground: 0.95, layers: [
56    { kind: 'sky', stops: [0x0a1030, 0x1a2252, 0x2c3266] },
57    { kind: 'dots', color: 0xdfe6ff, from: 0, to: 0.35, every: 8 },
58    { kind: 'towers', colors: [0x2a3156, 0x8f8a52], base: 0.62, tall: 0.55, speed: 0.15 },
59    { kind: 'towers', colors: [0x1b1e2e, 0xf2cf62], base: 0.95, tall: 0.6, speed: 0.5 },
60    { kind: 'band', color: 0x101218, from: 0.95, to: 1, speed: 1 },
61  ] },
62  snow: { ground: 0.92, layers: [
63    { kind: 'sky', stops: [0x8f9ed1, 0xc4cbe6, 0xf0e2c8] },
64    { kind: 'ridge', color: 0xa3afd6, base: 0.5, amp: 0.07, jag: true, speed: 0.15 },
65    { kind: 'band', color: 0xe9effc, from: 0.6, to: 1, speed: 0.5 },
66    { kind: 'bumps', color: 0xffffff, base: 0.78, amp: 0.14, every: 20, speed: 0.7 },
67    { kind: 'dots', color: 0x9fb2dd, from: 0.8, to: 0.95, every: 7 },
68  ] },
69  moon: { ground: 0.92, layers: [
70    { kind: 'sky', stops: [0x0b1426, 0x101c33] },
71    { kind: 'dots', color: 0xe8ecff, from: 0, to: 0.4, every: 9 },
72    { kind: 'ridge', color: 0x9a9a9e, base: 0.45, amp: 0.05, jag: true, speed: 0.15 },
73    { kind: 'band', color: 0xd4d4d8, from: 0.52, to: 1, speed: 0.5 },
74    { kind: 'craters', color: 0xa9a9ae, at: 0.66, every: 22, speed: 0.6 },
75    { kind: 'band', color: 0xe9e9ec, from: 0.85, to: 1, speed: 1 },
76  ] },
77  savanna: { ground: 0.9, layers: [
78    { kind: 'sky', stops: [0x9a4418, 0xd97a26, 0xf2b84b] },
79    { kind: 'trees', color: 0x3d3a1c, base: 0.6, size: 0.2, every: 11, shape: 'round', speed: 0.3 },
80    { kind: 'band', color: 0x1f1c10, from: 0.6, to: 0.7, speed: 0.4 },
81    { kind: 'band', color: 0xb8a65e, from: 0.7, to: 1, speed: 0.8 },
82    { kind: 'band', color: 0xe8ddb0, from: 0.88, to: 1, speed: 1 },
83  ] },
84  lava: { ground: 0.86, layers: [
85    { kind: 'sky', stops: [0x140806, 0x3a120a, 0x6a1e0c] },
86    { kind: 'ridge', color: 0x2a0f08, base: 0.4, amp: 0.08, jag: true, speed: 0.15 },
87    { kind: 'band', color: 0xff7a12, from: 0.6, to: 0.7, speed: 0.4 },
88    { kind: 'dots', color: 0xffd040, from: 0.6, to: 0.66, every: 5 },
89    { kind: 'band', color: 0x3a1a10, from: 0.7, to: 1, speed: 1 },
90    { kind: 'dots', color: 0xa8401a, from: 0.78, to: 1, every: 11 },
91  ] },
92  mountains: { ground: 0.92, layers: [
93    { kind: 'sky', stops: [0xdfe3ea, 0xcdd5e0] },
94    { kind: 'ridge', color: 0x7180a4, base: 0.32, amp: 0.1, jag: true, speed: 0.1 },
95    { kind: 'ridge', color: 0xcbbfb2, base: 0.46, amp: 0.05, speed: 0.2 },
96    { kind: 'ridge', color: 0x4c7a3a, base: 0.58, amp: 0.1, speed: 0.45 },
97    { kind: 'band', color: 0x3f6b2e, from: 0.8, to: 1, speed: 1 },
98  ] },
99}
100
101export const isScene = (name: string | undefined): name is Scene => SCENES.includes(name as Scene)
102
103// Where the pet is, said naturally: "on the moon", "in the city at night".
104const WHERE: Record<Scene, string> = { meadow: 'in a meadow', desert: 'in the desert', jungle: 'in the jungle', city: 'in the city', skyline: 'in the city at night', snow: 'in the snow', moon: 'on the moon', savanna: 'on the savanna', lava: 'by the lava', mountains: 'in the mountains' }
105export const whereIn = (scene: Scene) => WHERE[scene]
106export const groundOf = (scene: Scene) => SCENE[scene].ground
107
108// A steady random from a seed, so a scene looks the same every time.
109const rand = (seed: number) => () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32)
110
111const mix = (a: number, b: number, t: number) => {
112  const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - t) + ((b >> s) & 255) * t)
113  return (ch(16) << 16) | (ch(8) << 8) | ch(0)
114}
115
116// One layer over its period: `period` columns, `height` rows, null where it's see-through.
117function drawLayer(layer: Layer, period: number, height: number, seed: number): Grid {
118  const grid: Grid = Array.from({ length: height }, () => Array<number | null>(period).fill(null))
119  const put = (x: number, y: number, c: number) => {
120    const yy = Math.round(y)
121    if (yy >= 0 && yy < height) grid[yy]![((Math.round(x) % period) + period) % period] = c
122  }
123  const fill = (x: number, from: number, c: number) => {
124    for (let y = Math.max(0, Math.round(from)); y < height; y++) put(x, y, c)
125  }
126  const r = rand(seed)
127  const scale = height / 20
128  const every = (n: number) => Math.max(2, Math.round(n * Math.max(scale, 0.4)))
129  // Strokes (stars, fronds, cloud puffs) grow with the scene, so a big one isn't hairlines.
130  const brush = Math.max(1, Math.round(scale))
131  const dab = (x: number, y: number, c: number) => {
132    for (let dx = 0; dx < brush; dx++) for (let dy = 0; dy < brush; dy++) put(x + dx, y + dy, c)
133  }
134  switch (layer.kind) {
135    case 'sky':
136      for (let y = 0; y < height; y++) {
137        const t = (y / Math.max(1, height - 1)) * (layer.stops.length - 1)
138        const i = Math.min(layer.stops.length - 2, Math.floor(t))
139        const c = layer.stops.length === 1 ? layer.stops[0]! : mix(layer.stops[i]!, layer.stops[i + 1]!, t - i)
140        for (let x = 0; x < period; x++) put(x, y, c)
141      }
142      break
143    case 'dots':
144      for (let x = 0; x < period; x += every(layer.every)) dab(x + Math.floor(r() * 3), (layer.from + r() * (layer.to - layer.from)) * height, layer.color)
145      break
146    case 'clouds':
147      for (let x = 0; x < period; x += every(layer.every)) {
148        const cx = x + r() * 4
149        const y = layer.at * height
150        const w = Math.max(2, Math.round(5 * scale))
151        for (let i = 0; i < w; i++) dab(cx + i, y, layer.color)
152        for (let i = Math.round(w * 0.2); i < w * 0.8; i++) dab(cx + i, y - brush, layer.color)
153      }
154      break
155    case 'ridge': {
156      // Whole sine waves over the period, so the ridge joins up seamlessly.
157      const waves = (layer.jag ? [1, 3, 7, 13] : [1, 2, 4]).map(k => ({ k, phase: r() * Math.PI * 2, weight: 1 / k ** 0.6 }))
158      const total = waves.reduce((sum, w) => sum + w.weight, 0)
159      for (let x = 0; x < period; x++) {
160        const v = waves.reduce((sum, w) => sum + w.weight * Math.sin((2 * Math.PI * w.k * x) / period + w.phase), 0) / total
161        fill(x, (layer.base - layer.amp * v) * height, layer.color)
162      }
163      break
164    }
165    case 'bumps':
166      for (let x = 0; x < period; x++) {
167        const k = Math.max(1, Math.round(period / every(layer.every)))
168        const v = Math.abs(Math.sin((Math.PI * k * x) / period))
169        fill(x, (layer.base - layer.amp * v) * height, layer.color)
170      }
171      break
172    case 'band':
173      for (let x = 0; x < period; x++) for (let y = Math.round(layer.from * height); y < Math.round(layer.to * height); y++) put(x, y, layer.color)
174      break
175    case 'craters':
176      for (let x = 0; x < period; x += every(layer.every)) {
177        const cx = x + r() * 6
178        const w = Math.max(2, Math.round((3 + r() * 3) * scale))
179        const y = layer.at * height + r() * 2 * scale
180        for (let i = -w; i <= w; i++) dab(cx + i, y + (Math.abs(i) < w * 0.7 ? brush : 0), layer.color)
181      }
182      break
183    case 'trees':
184      for (let x = 0; x < period; x += every(layer.every)) {
185        const cx = x + r() * 2
186        const s = Math.max(1, layer.size * height * (0.75 + r() * 0.5))
187        const base = layer.base * height
188        if (layer.shape === 'pine') {
189          for (let y = 0; y < s; y++) for (let i = -Math.floor((y * 0.5)); i <= Math.floor(y * 0.5); i++) put(cx + i, base - s + y, layer.color)
190        } else if (layer.shape === 'round') {
191          // An acacia: a trunk and a flat-topped crown.
192          for (let y = 0; y < s * 0.6; y++) dab(cx, base - y, layer.color)
193          for (let i = -s; i <= s; i++) for (let y = 0; y < Math.max(1, s * 0.35); y++) put(cx + i, base - s * 0.6 - y - (Math.abs(i) < s * 0.6 ? 1 : 0), layer.color)
194        } else {
195          // A palm: a leaning trunk and fronds falling either side.
196          for (let y = 0; y < s; y++) dab(cx + (y / s) * s * 0.25, base - y, layer.color)
197          const top = { x: cx + s * 0.25, y: base - s }
198          for (let i = 0; i < s * 0.6; i++) {
199            dab(top.x + i, top.y + i * 0.45, layer.color)
200            dab(top.x - i, top.y + i * 0.45, layer.color)
201            dab(top.x + i * 0.7, top.y - i * 0.25, layer.color)
202            dab(top.x - i * 0.7, top.y - i * 0.25, layer.color)
203          }
204        }
205      }
206      break
207    case 'towers': {
208      let x = 0
209      while (x < period) {
210        const w = Math.max(2, Math.round((3 + r() * 5) * scale))
211        const top = (layer.base - layer.tall * (0.45 + r() * 0.55)) * height
212        for (let i = 0; i < w && x + i < period; i++) {
213          for (let y = Math.round(top); y < layer.base * height; y++) {
214            const isWindow = scale >= 0.8 && i % 2 === 1 && i < w - 1 && Math.round(y - top) % 2 === 1
215            put(x + i, y, isWindow ? layer.colors[1] : layer.colors[0])
216          }
217        }
218        x += w + (r() < 0.5 ? 1 : 0)
219      }
220      break
221    }
222  }
223  return grid
224}
225
226const cache = new Map<string, { grids: Grid[]; speeds: number[] }>()
227
228// The scene's layers at this size, each over `period` columns, with how fast each scrolls.
229export function sceneLayers(scene: Scene, period: number, height: number): { grids: Grid[]; speeds: number[] } {
230  const key = `${scene}:${period}:${height}`
231  let layers = cache.get(key)
232  if (!layers) {
233    const spec = SCENE[scene].layers
234    layers = { grids: spec.map((layer, i) => drawLayer(layer, period, height, 7 + i * 101 + scene.length * 13)), speeds: spec.map(layer => ('speed' in layer ? layer.speed : 0)) }
235    cache.set(key, layers)
236  }
237  return layers
238}
239
240// A window onto the scene, `width` wide, the layers scrolled by `offset` (the nearest layer's,
241// in pixels; farther ones move less).
242export function sceneGrid(scene: Scene, width: number, height: number, offset: number, period = 64): Grid {
243  const { grids, speeds } = sceneLayers(scene, period, height)
244  const out: Grid = Array.from({ length: height }, () => Array<number | null>(width).fill(null))
245  grids.forEach((grid, l) => {
246    const shift = Math.floor(offset * speeds[l]!)
247    for (let y = 0; y < height; y++) {
248      for (let x = 0; x < width; x++) {
249        const c = grid[y]![(((x + shift) % period) + period) % period]
250        if (c !== null && c !== undefined) out[y]![x] = c
251      }
252    }
253  })
254  return out
255}
256
257const hex = (c: number) => `#${c.toString(16).padStart(6, '0')}`
258
259// One layer's pixels as rects, `copies` periods side by side: runs merged along rows or along
260// columns, whichever is shorter (a sky is a few rows; a ridge is many columns), since a drawing
261// has a size limit.
262function layerRects(grid: Grid, px: number, copies: number): string {
263  const period = grid[0]!.length
264  const height = grid.length
265  const rect = (x: number, y: number, w: number, h: number, c: number) => `<rect x="${x * px}" y="${y * px}" width="${w * px}" height="${h * px}" fill="${hex(c)}"/>`
266  let byRows = ''
267  for (let y = 0; y < height; y++) {
268    const at = (x: number) => grid[y]![x % period] ?? null
269    for (let x = 0; x < period * copies; ) {
270      const c = at(x)
271      let end = x + 1
272      while (end < period * copies && at(end) === c) end++
273      if (c !== null) byRows += rect(x, y, end - x, 1, c)
274      x = end
275    }
276  }
277  let byColumns = ''
278  for (let x = 0; x < period * copies; x++) {
279    for (let y = 0; y < height; ) {
280      const c = grid[y]![x % period] ?? null
281      let end = y + 1
282      while (end < height && (grid[end]![x % period] ?? null) === c) end++
283      if (c !== null) byColumns += rect(x, y, 1, end - y, c)
284      y = end
285    }
286  }
287  return byRows.length <= byColumns.length ? byRows : byColumns
288}
289
290// Desktop and the card: the scene as SVG layers. Moving, each layer slides left by its period
291// forever at its own speed (parallax); still, it stands. `scrolledMs` is how long the scenery has
292// been moving in all: each layer starts from where that leaves it, so a redraw (a new status
293// line) or a stop carries on from the same spot instead of jumping back to the start.
294export function sceneSvgLayers(scene: Scene, width: number, height: number, px: number, isMoving: boolean, period = 64, pxPerSecond = 14, scrolledMs = 0): string {
295  const { grids, speeds } = sceneLayers(scene, period, height)
296  const copies = Math.ceil(width / period) + 1
297  return grids.map((grid, l) => {
298    const speed = speeds[l]!
299    const rects = layerRects(grid, px, speed > 0 ? copies : Math.ceil(width / period))
300    if (speed <= 0) return `<g>${rects}</g>`
301    const dur = Math.round((period / (pxPerSecond * speed)) * 1000)
302    const phase = scrolledMs % dur
303    if (!isMoving) return phase ? `<g transform="translate(${((-phase / dur) * period * px).toFixed(2)} 0)">${rects}</g>` : `<g>${rects}</g>`
304    return `<g><animateTransform attributeName="transform" type="translate" from="0 0" to="${-period * px} 0" dur="${dur}ms" begin="${-Math.round(phase)}ms" repeatCount="indefinite"/>${rects}</g>`
305  }).join('')
306}
307
308// `auto` follows the time of day: a meadow in the morning (5–12), the desert in the afternoon
309// (12–17), a savanna sunset in the evening (17–20), the city skyline at night (20–24) and the
310// moon after midnight (0–5); and a lava cave for a moment while it groans over failing tests.
311export const TIMES_OF_DAY: [from: number, name: string, scene: Scene][] = [[0, 'midnight', 'moon'], [5, 'morning', 'meadow'], [12, 'afternoon', 'desert'], [17, 'evening', 'savanna'], [20, 'night', 'skyline']]
312export function sceneFor(hour: number, isGroaning: boolean): Scene {
313  if (isGroaning) return 'lava'
314  return TIMES_OF_DAY.findLast(([from]) => hour >= from)![2]
315}
316
317// Desktop: the pet in its little world, a rounded window with sky above it and a little ground
318// either side, the pet standing at the bottom. While Claude works the scenery scrolls past in
319// layers, so the pet seems to run through it.
320export const HABITAT_WIDTH = 76
321export const HABITAT_HEIGHT = 52
322// The pixels stay crisp, but the window's rounded corners are drawn smooth (a crisp-edged clip
323// would come out stepped, barely rounded).
324export function habitatSvg(scene: Scene, isMoving: boolean, pet: string, scrolledMs = 0): string {
325  const inner = pet.replace('<svg ', `<svg x="${(HABITAT_WIDTH - 50) / 2}" y="${HABITAT_HEIGHT - 40}" `)
326  return `<svg xmlns="http://www.w3.org/2000/svg" width="${HABITAT_WIDTH}" height="${HABITAT_HEIGHT}" viewBox="0 0 ${HABITAT_WIDTH} ${HABITAT_HEIGHT}">`
327    + `<defs><clipPath id="habitat"><rect width="${HABITAT_WIDTH}" height="${HABITAT_HEIGHT}" rx="12" shape-rendering="geometricPrecision"/></clipPath></defs>`
328    + `<g clip-path="url(#habitat)"><g shape-rendering="crispEdges">${sceneSvgLayers(scene, HABITAT_WIDTH / 2, HABITAT_HEIGHT / 2, 2, isMoving, 64, 14, scrolledMs)}</g></g>${inner}</svg>`
329}
330
hooks/minis-view.tsx 75 lines
1// The terminal's helpers, left of the context bar, newest first, on the surface's own clock. A new
2// one first widens its slot a column at a time, pushing the bar along, then sparkles in; a leaving
3// one waves, shrinks to a speck, and its slot narrows back.
4import type { ClientModule } from 'claude-code'
5
6import { LEAVE_MS, MINI_W, SLOT_MS, miniFrame, seedOf } from './mini'
7import { toRunsOf } from './sprite'
8
9export type MinisViewProps = { minis: { id: string; color: string; state: 'here' | 'bye'; age: number }[]; stamp: number }
10
11type Ref = { t: number; stamp: number }
12type State = { ref: Ref }
13
14const FRAME_MS = 40
15const SLOT = MINI_W + 1
16const CLOSE_MS = 300
17
18// How wide a helper's slot is at this age: opening, full, then closing as it leaves.
19export function slotWidth(state: 'here' | 'bye', age: number): number {
20  if (age < 0) return 0
21  if (state === 'here') return Math.min(SLOT, Math.round((age / SLOT_MS) * SLOT))
22  const closing = age - (LEAVE_MS - CLOSE_MS)
23  return closing <= 0 ? SLOT : Math.max(0, Math.round(SLOT * (1 - closing / CLOSE_MS)))
24}
25
26const MinisView: ClientModule<MinisViewProps, State> = (props, surface) => {
27  const { Box, Text } = surface.elements
28  const ref = surface.state?.ref ?? { t: 0, stamp: props.stamp }
29  if (props.stamp !== ref.stamp) {
30    // Fresh ages from the band; count on from them.
31    ref.stamp = props.stamp
32    ref.t = 0
33  }
34  if (surface.state === undefined) {
35    surface.setState({ ref })
36    surface.every(FRAME_MS, () => {
37      ref.t += FRAME_MS
38      surface.setState({ ref })
39    })
40  }
41
42  const slots = props.minis.map(m => {
43    const age = m.age + ref.t
44    const width = slotWidth(m.state, age)
45    // The helper itself waits for its slot to open; its own story starts then.
46    const grid = width === SLOT || m.state === 'bye' ? miniFrame(m.color, m.state, m.state === 'here' ? age - SLOT_MS : age, seedOf(m.id)) : null
47    const rows = grid ? toRunsOf(grid, MINI_W) : [[{ text: ' '.repeat(MINI_W) }], [{ text: ' '.repeat(MINI_W) }]]
48    return { width, rows }
49  })
50  return (
51    <Box flexDirection="column">
52      {[0, 1].map(row => (
53        <Text>
54          {slots.flatMap(slot => {
55            if (slot.width === 0) return []
56            // A slot narrower than the helper shows its left part: the room it has so far.
57            let room = slot.width
58            const out = []
59            for (const run of slot.rows[row]!) {
60              if (room <= 0) break
61              const text = run.text.slice(0, room)
62              room -= text.length
63              out.push(run.fg ? <Text color={run.fg} backgroundColor={run.bg}>{text}</Text> : <Text>{text}</Text>)
64            }
65            if (room > 0) out.push(<Text>{' '.repeat(room)}</Text>)
66            return out
67          })}
68        </Text>
69      ))}
70    </Box>
71  )
72}
73
74export default MinisView
75
hooks/status-view.tsx 45 lines
1// The terminal's status line. The name stays put; text there moves in whole rows only, so the
2// words after it can't glide: they roll instead, the old ones fading out, then the new ones
3// fading in, in about a quarter second (calm: they simply change). Good news, bad news and
4// "needs you" lines take a colour.
5import type { ClientModule } from 'claude-code'
6
7// `color` is left out for plain narration (a Client's props can't hold undefined).
8export type StatusViewProps = { name: string; line: string; color?: string; calm: boolean }
9
10type Ref = { t: number; line: string; previous?: string; changedAt: number }
11type State = { ref: Ref }
12
13const FRAME_MS = 50
14const OUT_MS = 110
15const GAP_MS = 40
16const IN_MS = 130
17
18const StatusView: ClientModule<StatusViewProps, State> = (props, surface) => {
19  const { Text } = surface.elements
20  const ref = surface.state?.ref ?? { t: 0, line: props.line, changedAt: -Infinity }
21  if (props.line !== ref.line) {
22    ref.previous = ref.line
23    ref.line = props.line
24    ref.changedAt = ref.t
25  }
26  if (surface.state === undefined) {
27    surface.setState({ ref })
28    surface.every(FRAME_MS, () => {
29      ref.t += FRAME_MS
30      if (ref.t - ref.changedAt <= OUT_MS + GAP_MS + IN_MS + FRAME_MS) surface.setState({ ref })
31    })
32  }
33
34  const since = props.calm ? Infinity : ref.t - ref.changedAt
35  const name = <Text bold color="claude">{props.name}</Text>
36  if (ref.previous !== undefined && since < OUT_MS) {
37    return <Text wrap="truncate">{name}<Text dimColor> {ref.previous}</Text></Text>
38  }
39  if (ref.previous !== undefined && since < OUT_MS + GAP_MS) return <Text wrap="truncate">{name}</Text>
40  const isFadingIn = ref.previous !== undefined && since < OUT_MS + GAP_MS + IN_MS
41  return <Text wrap="truncate">{name}<Text color={props.color} dimColor={isFadingIn}> {ref.line}</Text></Text>
42}
43
44export default StatusView
45