A fluffy black cat above the prompt, in memory of Mango.

<img src="assets/banner.svg" alt="Mango, a fluffy black cat with tufted ears, golden eyes, a white bib and white paws, sits tall on a blue knitted cushion in front of a glowing orange moon." width="100%">
<b>A fluffy black cat who lives above your Claude Code prompt.</b><br> <i>In loving memory of my Mango, the most amazing cat who ever lived.</i> ❤️
<img src="assets/icons/stripe.svg" width="100%" height="8" alt="">
Mango sits in the little band above the prompt and keeps you company while you work. She blinks, flicks her tail and kneads while Claude thinks. She naps when you go quiet, flattens her ears at a failed command, purrs at a green test run and gets a little worried when your context window fills up.
<img src="assets/bands.svg" alt="Mango in the band above the prompt, twice. In the desktop Code tab she is a little drawing of a black cat with a sparkle, saying: Mango purrs at the green run. In the terminal she is an ASCII cat with flattened ears, saying: Mango knocks the error off the table." width="100%">
She is small, she is soft, and she is always there.
<img src="assets/moods.svg" alt="Six mood cards, each with her terminal face and her desktop drawing. Awake: just being here. Working: kneads while Claude works. Proud: purrs at green test runs. Sleeping: naps when you go quiet. Ruffled: after a failed command. Worried: when context passes 20 percent." width="100%">
Every mood comes with something to say, like "Mango knocks the error off the table." or "Mango dreams of warm laptops." Pet her and she leans into your hand.
She keeps up with Claude, too. She sniffs at the files it reads, watches it edit, peers out when it goes to the web and waits with you through a long build. She pounces on a commit and chases a push out the door.
<img src="assets/activities.svg" alt="Six activity cards, each with her terminal face and her desktop drawing. Sniffing: at files Claude reads. Watching: as Claude edits a file. Peering: out at the web. Waiting: while a command runs. Pouncing: on a fresh commit. Chasing: a push out the door." width="100%">
Now and then she says what she sees, like "Mango sniffs at cat.ts." or "Mango pounces on the commit."
You need Claude Code 2.1.287 or newer. Type this at the prompt in a terminal session:
/plugin install mango --marketplace malinfossum/mango-buddy
Say y to add the marketplace, then pick user scope so she follows you into every project.
| Command | What happens |
|---|---|
/mango or /mango pet | You pet her. She purrs. |
/mango card | Your story together: sessions, pets, errors survived, context |
/mango mute / unmute | She stays, but keeps her thoughts to herself |
/mango still | She sits still without moving (calmer for screen readers) |
/mango move | She always moves, even when your system asks for reduced motion |
/mango auto | She follows your system's reduced-motion setting (the default) |
/mango off / on | She hides, or comes back. She remembers this between sessions. |
/mango mute keeps her quiet./mango move.She is a Claude Code mod (function hooks) written in TypeScript.
claude plugin validate .
claude plugin test .
The .claude-plugin/types/ folder that tsconfig.json extends is laid by the engine after the first claude plugin validate . or load, so run that before tsc.
Contributions are welcome and come in under this repo's MIT licence.
<img src="assets/icons/stripe.svg" width="100%" height="8" alt="">
Mango was my cat. A fluffy black cat, the most amazing cat who ever lived, and I miss her every single day. I built this so a small part of her can sit with me while I code, and maybe keep you company too.
hooks/register.tsx 499 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3import type { Activity, Mood, Motion } from '../types'
4import { ACTIVITY_TICKS, activityFor, callLine, gitStepOf, KEEP_WATCH_TICKS, LINE_GAP_TICKS, lineFor, showing, topicOf } from './activity'
5import type { Topic } from './activity'
6import { ART_WIDTH, BUDGET_PERCENT, faceFor, frameFor, GAP, isTestCommand, PROUD_TICKS, remarkFor, resolveMood, RUFFLED_TICKS, TICK_MS, toneFor } from './cat'
7import { altFor, DRAWING_HEIGHT, DRAWING_WIDTH } from './drawing'
8import { pictureFor } from './stage'
9
10type EngineType = EngineInterface
11
12export const tick = atom({ plugin: 'mango', key: 'tick' } as const, 0)
13export const mood = atom({ plugin: 'mango', key: 'mood' } as const, 'awake' as Mood)
14export const moodUntil = atom({ plugin: 'mango', key: 'moodUntil' } as const, 0)
15export const lastActivityTick = atom({ plugin: 'mango', key: 'lastActivityTick' } as const, 0)
16export const contextPercent = atom({ plugin: 'mango', key: 'contextPercent' } as const, 0)
17export const remark = atom({ plugin: 'mango', key: 'remark' } as const, null as string | null)
18export const isSessionCounted = atom({ plugin: 'mango', key: 'isSessionCounted' } as const, false)
19export const wasOverBudget = atom({ plugin: 'mango', key: 'wasOverBudget' } as const, false)
20export const isOff = atom({ plugin: 'mango', key: 'isOff' } as const, false)
21export const isMuted = atom({ plugin: 'mango', key: 'isMuted' } as const, false)
22// How she moves, stored. Read once in session.start, written on change.
23export const motion = atom({ plugin: 'mango', key: 'motion' } as const, 'auto' as Motion)
24// What the desktop picture shows over her mood. Written at most once per clock period,
25// so a burst of tool calls is one write and one redraw.
26export const activity = atom({ plugin: 'mango', key: 'activity' } as const, null as Activity | null)
27// The mood the picture surfaces draw. They never read the tick, which the clock writes
28// every period: each redraw rebuilds the picture's frame, and that shows as a blink.
29export const shownMood = atom({ plugin: 'mango', key: 'shownMood' } as const, 'awake' as Mood)
30
31const FACE_WIDTH = 5
32
33const flag = (x: unknown): boolean => x === true
34
35const motionOf = (x: unknown): Motion | undefined => (x === 'auto' || x === 'always' || x === 'never' ? x : undefined)
36
37// The clock's own count. In still mode the tick atom is only written on a mood
38// change, so time is kept here and the atom follows it.
39let clockTick = 0
40
41// The running clock, kept so a repeated session.start stops it before starting another.
42let clock: Timer | undefined
43
44// The last line the timed-mood and sleep logic wrote to `remark`, kept so expiry and
45// waking clear only that line and never a later purr, yawn or worried remark.
46let timedRemark: string | null = null
47let sleepRemark: string | null = null
48
49// The mood the clock saw on its previous period, to spot the move into sleeping.
50let lastMood: Mood = 'awake'
51
52// The activity the picture shows (the last one written) and the one the next clock period
53// writes. Tool calls set only the pending one, so a burst of them costs one redraw.
54let shownActivity: Activity | null = null
55let pendingActivity: Activity | null = null
56
57// The clock tick the activity ends on, unless a Bash or Agent call still runs.
58let activityUntil = 0
59let runningWaits = 0
60
61// The activity line showing, kept so the end of an activity clears only that line.
62let activityRemark: string | null = null
63// The tick of the last activity line; one per LINE_GAP_TICKS at most.
64let lastLineTick = -LINE_GAP_TICKS
65// What she has named this turn: one line each for reading, editing and the web.
66const namedThisTurn = new Set<Topic>()
67
68// Sets what she does next and restarts its timer. The clock writes it. The same activity
69// writes nothing, so a burst of Reads, or a second commit that returns within one clock
70// period, draws nothing new and never restarts her motion.
71const setActivity = (a: Activity) => {
72 pendingActivity = a
73 activityUntil = clockTick + ACTIVITY_TICKS
74}
75
76// Bookkeeping around a tool call never blocks it: a failed read or write is dropped.
77const quietly = async (work: () => Promise<unknown>): Promise<void> => {
78 try {
79 await work()
80 } catch {
81 // the call goes on
82 }
83}
84
85// Writes the pending activity once, and only when it differs from the one showing. A
86// failed write is tried again on the next period.
87const writeActivity = async ($: EngineType) => {
88 const a = pendingActivity
89 if (a === shownActivity) return
90 await update($, activity, () => a)
91 shownActivity = a
92}
93
94// Shows an activity line: one per LINE_GAP_TICKS at most, and only over an empty remark,
95// the sleep remark or an older activity line, never over a purr, yawn, worried or
96// timed-mood line. The slot is claimed before the first await, so two parallel calls
97// cannot both speak; a line that may not show gives it back.
98const say = async ($: EngineType, line: string) => {
99 const t = clockTick
100 if (t - lastLineTick < LINE_GAP_TICKS) return
101 const before = lastLineTick
102 lastLineTick = t
103 const current = await read($, remark)
104 if (current !== null && current !== sleepRemark && current !== activityRemark) {
105 lastLineTick = before
106 return
107 }
108 activityRemark = line
109 await update($, remark, () => line)
110}
111
112// Clears the activity line if it is still the one showing. The end of an activity calls this.
113const clearActivityRemark = async ($: EngineType) => {
114 if (activityRemark === null) return
115 const line = activityRemark
116 activityRemark = null
117 if ((await read($, remark)) === line) await update($, remark, () => null)
118}
119
120const snapshot = async ($: EngineType, t: number) => ({
121 mood: await read($, mood),
122 moodUntil: await read($, moodUntil),
123 tick: t,
124 lastActivityTick: await read($, lastActivityTick),
125 contextPercent: await read($, contextPercent),
126})
127
128// Clears the sleeping remark if it is still the one showing. Waking calls this.
129const clearSleepRemark = async ($: EngineType) => {
130 if (sleepRemark === null) return
131 const line = sleepRemark
132 sleepRemark = null
133 if ((await read($, remark)) === line) await update($, remark, () => null)
134}
135
136// Writes the mood only when it changes, so the picture is redrawn only then.
137const showMood = async ($: EngineType, m: Mood) => {
138 if ((await read($, shownMood)) !== m) await update($, shownMood, () => m)
139}
140
141// Resolves the mood now. Every write outside the clock that can change it calls this.
142const syncShownMood = async ($: EngineType) => showMood($, resolveMood(await snapshot($, clockTick)))
143
144export const markActivity = async ($: EngineType) => {
145 const t = clockTick
146 await update($, lastActivityTick, () => t)
147 await clearSleepRemark($)
148 await syncShownMood($)
149}
150
151// Runs a Bash or Agent call while she waits for it. The count keeps the activity from
152// ending while any such call runs, and each return restarts the timer. The count is
153// raised and lowered around nothing but the call, so it always comes back down.
154const whileWaiting = async <T,>($: EngineType, run: () => Promise<T>): Promise<T> => {
155 runningWaits += 1
156 try {
157 setActivity('waiting')
158 return await run()
159 } finally {
160 runningWaits -= 1
161 activityUntil = clockTick + ACTIVITY_TICKS
162 // A long run must not leave her asleep the moment it ends.
163 await quietly(() => markActivity($))
164 }
165}
166
167// Reads the count, adds one and writes it back at the moment of change.
168const bump = async ($: EngineType, key: string): Promise<number> => {
169 const value = (Number(await $.store.get(key)) || 0) + 1
170 await $.store.set(key, value)
171 return value
172}
173
174const HELP = 'Mango knows: pet, mute, unmute, still, move, auto, off, on, card.'
175
176// Stores how she moves and redraws her with it.
177const setMotion = async ($: EngineType, value: Motion): Promise<void> => {
178 await $.store.set('motion', value)
179 await update($, motion, () => value)
180}
181
182export const runCommand = async ($: EngineType, args: string): Promise<string> => {
183 const word = args.trim().toLowerCase().split(/\s+/)[0] ?? ''
184 switch (word) {
185 case '':
186 case 'pet':
187 await bump($, 'pets')
188 await update($, remark, () => remarkFor('purr', clockTick))
189 return 'Mango purrs.'
190 case 'mute':
191 await $.store.set('isMuted', true)
192 await update($, isMuted, () => true)
193 return 'Mango is quiet now.'
194 case 'unmute':
195 await $.store.set('isMuted', false)
196 await update($, isMuted, () => false)
197 return 'Mango may speak again.'
198 case 'still':
199 await setMotion($, 'never')
200 return 'Mango sits still.'
201 case 'move':
202 await setMotion($, 'always')
203 return 'Mango always moves.'
204 case 'auto':
205 await setMotion($, 'auto')
206 return 'Mango follows your system.'
207 case 'off':
208 await $.store.set('isOff', true)
209 await update($, isOff, () => true)
210 return 'Mango is away.'
211 case 'on':
212 await $.store.set('isOff', false)
213 await update($, isOff, () => false)
214 return 'Mango is back.'
215 case 'card': {
216 const n = async (k: string) => Number(await $.store.get(k)) || 0
217 return `Mango · sessions ${await n('sessions')} · pets ${await n('pets')} · errors survived ${await n('errorsSurvived')} · context ${await read($, contextPercent)} %`
218 }
219 default:
220 return HELP
221 }
222}
223
224const setTimedMood = async ($: EngineType, m: 'ruffled' | 'proud', ticks: number) => {
225 const t = clockTick
226 await update($, mood, () => m)
227 await update($, moodUntil, () => t + ticks)
228 const line = remarkFor(m, t)
229 timedRemark = line
230 await update($, remark, () => line)
231 await syncShownMood($)
232}
233
234// One period of the clock. Normal mode writes the tick every period. Still mode writes
235// it only when the resolved mood differs from the one the stored tick would draw.
236const advanceClock = async ($: EngineType) => {
237 clockTick += 1
238 const t = clockTick
239 let s = await snapshot($, t)
240 // While a Bash or Agent call runs she is busy waiting, so she does not fall asleep.
241 if (runningWaits > 0) s = { ...s, lastActivityTick: t }
242 if ((s.mood === 'ruffled' || s.mood === 'proud') && t >= s.moodUntil) {
243 // The timed mood is over: fall back to awake and drop its remark, once.
244 await update($, mood, () => 'awake')
245 if (timedRemark !== null && (await read($, remark)) === timedRemark) await update($, remark, () => null)
246 timedRemark = null
247 s = { ...s, mood: 'awake' }
248 }
249 const now = resolveMood(s)
250 await showMood($, now)
251 if ((await read($, motion)) === 'never') {
252 const stored = await read($, tick)
253 if (now !== resolveMood({ ...s, tick: stored })) await update($, tick, () => t)
254 } else {
255 await update($, tick, () => t)
256 }
257 if (now === 'sleeping') {
258 if (lastMood !== 'sleeping') {
259 const line = remarkFor('sleeping', t)
260 sleepRemark = line
261 await update($, remark, () => line)
262 }
263 } else {
264 await clearSleepRemark($)
265 }
266 lastMood = now
267 if (runningWaits === 0 && t >= activityUntil && pendingActivity !== null) {
268 pendingActivity = null
269 await clearActivityRemark($)
270 }
271 await writeActivity($)
272}
273
274// Reads the context figure the way turn.complete does. Undefined when usage has no figure.
275const readContextPercent = async ($: EngineType): Promise<number | undefined> => {
276 const { context } = await $.session.usage()
277 const percent =
278 context.percent ??
279 (context.window > 0 && context.tokens !== undefined ? (context.tokens / context.window) * 100 : undefined)
280 return percent === undefined ? undefined : Math.round(percent)
281}
282
283export const register: Register = on => {
284 on('session.start', async ($, e, next) => {
285 // The clock and the command come first: a failing store read must not leave Mango
286 // frozen or /mango unregistered. The clock goes first of all, so a failed
287 // registration still leaves her moving.
288 clockTick = await read($, tick)
289 clock?.cancel()
290 clock = $.clock.every(TICK_MS, async () => {
291 try {
292 await advanceClock($)
293 } catch {
294 // The engine asks the next period either way and never awaits this promise, so
295 // the catch only keeps a failed read or write from becoming an unhandled rejection.
296 }
297 })
298 await $.command.register({
299 name: 'mango',
300 description: 'Pet Mango, or tell her to be still, quiet or away.',
301 argumentHint: 'pet | mute | unmute | still | move | auto | off | on | card',
302 })
303 // A repeated session.start picks up the activity the picture already shows.
304 await quietly(async () => {
305 shownActivity = await read($, activity)
306 pendingActivity = shownActivity
307 })
308
309 const storedOff = flag(await $.store.get('isOff'))
310 const storedMuted = flag(await $.store.get('isMuted'))
311 // An old still flag becomes motion: never, written once; isStill is not read after that.
312 let storedMotion = motionOf(await $.store.get('motion'))
313 if (storedMotion === undefined && flag(await $.store.get('isStill'))) {
314 storedMotion = 'never'
315 await $.store.set('motion', storedMotion)
316 }
317 const moves = storedMotion ?? 'auto'
318 await update($, isOff, () => storedOff)
319 await update($, isMuted, () => storedMuted)
320 await update($, motion, () => moves)
321
322 if (!(await read($, isSessionCounted))) {
323 await bump($, 'sessions')
324 await update($, isSessionCounted, () => true)
325 }
326 try {
327 // A resumed session may already be well into its context: show the real figure, no toast.
328 const rounded = await readContextPercent($)
329 if (rounded !== undefined) await update($, contextPercent, () => rounded)
330 await syncShownMood($)
331 } catch {
332 // usage unavailable: keep the default
333 }
334 return next(e)
335 }).catch(($, e, next) => next(e))
336
337 on('command.run', { command: 'mango' }, async ($, e) => ({ text: await runCommand($, e.args) }))
338 .catch(() => ({ text: 'Mango could not do that.' }))
339
340 // Reading, editing and the web: she sniffs, watches or peers.
341 on('tool.call', { tool: ['Read', 'Grep', 'Glob', 'Edit', 'Write', 'WebFetch', 'WebSearch'] }, async ($, e, next) => {
342 const a = activityFor(e.tool)
343 if (a !== null) setActivity(a)
344 // The first-of-turn flag is spent before the first await, so two parallel calls
345 // cannot both claim it. A call with nothing to name spends it too.
346 let line: string | null = null
347 const topic = topicOf(e.tool)
348 if (topic !== null && !namedThisTurn.has(topic)) {
349 namedThisTurn.add(topic)
350 line = callLine(e, clockTick)
351 }
352 await quietly(() => markActivity($))
353 if (line !== null) {
354 const said = line
355 await quietly(() => say($, said))
356 }
357 return next(e)
358 }).catch(($, e, next) => next(e))
359
360 on('tool.call', { tool: 'Agent' }, async ($, e, next) =>
361 whileWaiting($, async () => {
362 await quietly(() => markActivity($))
363 return next(e)
364 }),
365 ).catch(($, e, next) => next(e))
366
367 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
368 const started = clockTick
369 const isTest = isTestCommand(e.command)
370 const step = gitStepOf(e.command)
371 const ran = await whileWaiting($, async () => {
372 await quietly(() => markActivity($))
373 return next(e)
374 })
375 if (ran.deny !== undefined) return ran
376 if (ran.isError === true) {
377 await setTimedMood($, 'ruffled', RUFFLED_TICKS)
378 await bump($, 'errorsSurvived')
379 return ran
380 }
381 if (isTest) await setTimedMood($, 'proud', PROUD_TICKS)
382 // A commit or push that went through: she pounces on it, or chases it out.
383 if (step !== null) {
384 setActivity(step === 'push' ? 'chasing' : 'pouncing')
385 await quietly(() => say($, lineFor(step, clockTick)))
386 }
387 // Measured in clock ticks between the call and its result, so tests can drive it.
388 const ticks = clockTick - started
389 if (ticks > KEEP_WATCH_TICKS) {
390 const seconds = String(Math.round((ticks * TICK_MS) / 1000))
391 await quietly(() => say($, lineFor('watch', clockTick, seconds)))
392 }
393 return ran
394 }).catch(($, e, next) => next(e))
395
396 on('turn.complete', async ($, e, next) => {
397 await markActivity($)
398 try {
399 const rounded = await readContextPercent($)
400 if (rounded !== undefined) {
401 await update($, contextPercent, () => rounded)
402 const over = rounded >= BUDGET_PERCENT
403 const was = await read($, wasOverBudget)
404 if (over && !was) {
405 // Fire and forget: a failed toast fails in its own dispatch, never here.
406 $.ui.toast(`Mango: context passed ${BUDGET_PERCENT} %`)
407 await update($, remark, () => remarkFor('worried', clockTick))
408 }
409 if (!over && was) await update($, remark, () => null)
410 await update($, wasOverBudget, () => over)
411 await syncShownMood($)
412 }
413 } catch {
414 // usage unavailable: keep the previous figure
415 }
416 if (!e.isAborted && e.durationMs > 120000) {
417 await update($, remark, () => remarkFor('yawn', clockTick))
418 }
419 return next(e)
420 }).catch(($, e, next) => next(e))
421
422 on('prompt.submit', async ($, e, next) => {
423 namedThisTurn.clear()
424 await markActivity($)
425 await update($, remark, () => null)
426 return next(e)
427 }).catch(($, e, next) => next(e))
428
429 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
430 if (e.props.hasSurvey || (await read($, isOff))) return next(e)
431 const { Box, Text } = $.ui.resolve(e)
432 const isTerminal = e.surface === 'terminal'
433 // Only the terminal reads the tick: its frames change with it. The picture surfaces
434 // read the shown mood, so an idle clock period never redraws them.
435 const t = isTerminal ? await read($, tick) : 0
436 const shown = isTerminal ? resolveMood(await snapshot($, t)) : await read($, shownMood)
437 const drawnActivity = await read($, activity)
438 const moves = await read($, motion)
439 const still = moves === 'never'
440 // Still, the tick can sit on a blink frame (0 % 8), which would draw an awake cat with
441 // closed eyes. Nudge by two so the tail and the z keep their parity.
442 const drawTick = still && t % 8 === 0 ? t + 2 : t
443 const said = await read($, remark)
444 const muted = await read($, isMuted)
445 // Priority, highest first: a timed mood, an activity, working, the resting mood.
446 const now = showing(shown, drawnActivity, e.props.isWorking)
447 const look = now.activity ?? now.pose
448 const isShort = e.props.maxRows < 3
449 // The face is 5 columns wide, the two-row art ART_WIDTH. A band narrower than
450 // the art draws the art with an empty line, never a negative slice.
451 const room = Math.max(0, e.props.bodyColumns - (isShort ? FACE_WIDTH : ART_WIDTH) - GAP)
452 const text = (said ?? `context ${await read($, contextPercent)} %`).slice(0, room)
453 // A remark takes the look's theme colour; the context figure stays dim.
454 const tone = said === null ? {} : { color: toneFor(look) }
455 const speech = muted ? null : (
456 <>
457 <Text>{' '.repeat(GAP)}</Text>
458 {/* Text has no `key` prop, so the key lives on the Box around it. */}
459 <Box key="line"><Text dimColor={said === null} {...tone}>{text}</Text></Box>
460 </>
461 )
462 if (!isTerminal) {
463 // Surfaces that draw an Svg get the picture; a short band gets it at half size. The
464 // markup follows the activity, pose and motion, never the tick, so her animations
465 // run on between periods. Always an image: a frame reloads, and blinks, on every new
466 // source. An image gets no :hover, so she has no hover heart for now.
467 const { Svg } = $.ui.resolve(e)
468 const scale = isShort ? 0.5 : 1
469 const source = pictureFor({ pose: now.pose, activity: now.activity, motion: moves })
470 return (
471 <Box alignItems="center">
472 <Box key="cat">
473 <Svg source={source} alt={altFor(now.pose, now.activity)} width={DRAWING_WIDTH * scale} height={DRAWING_HEIGHT * scale} isInteractive={false} />
474 </Box>
475 {speech}
476 </Box>
477 )
478 }
479 if (isShort) {
480 return (
481 <Box>
482 <Box key="face"><Text>{faceFor(look, drawTick)}</Text></Box>
483 {speech}
484 </Box>
485 )
486 }
487 const [row1, row2] = frameFor(look, drawTick)
488 return (
489 <Box flexDirection="column">
490 <Box key="row1"><Text>{row1}</Text></Box>
491 <Box>
492 <Box key="row2"><Text>{row2}</Text></Box>
493 {speech}
494 </Box>
495 </Box>
496 )
497 }).catch(($, e, next) => next(e))
498}
499hooks/activity.ts 156 lines1import type { Activity, Mood } from '../types'
2import type { Pose } from './cat'
3
4// What Mango does while Claude works. Pure: the hooks in register.tsx keep the timers and
5// write the atoms.
6
7export const ACTIVITIES = ['sniffing', 'watching', 'peering', 'waiting', 'pouncing', 'chasing'] as const satisfies readonly Activity[]
8
9// An activity lasts this many clock ticks after the call that set it (4.5 s).
10export const ACTIVITY_TICKS = 6
11
12// What each tool sets her doing. A git commit or push is read from a Bash command once
13// it has succeeded (gitStepOf), so Bash itself only waits.
14export const activityFor = (tool: string): Activity | null => {
15 switch (tool) {
16 case 'Read':
17 case 'Grep':
18 case 'Glob':
19 return 'sniffing'
20 case 'Edit':
21 case 'Write':
22 return 'watching'
23 case 'WebFetch':
24 case 'WebSearch':
25 return 'peering'
26 case 'Bash':
27 case 'Agent':
28 return 'waiting'
29 default:
30 return null
31 }
32}
33
34// What the band shows. Priority, highest first: a timed mood, an activity, working, the
35// resting mood. Under a timed mood no activity shows.
36export const showing = (mood: Mood, activity: Activity | null, isWorking: boolean): { pose: Pose; activity: Activity | null } => {
37 if (mood === 'ruffled' || mood === 'proud') return { pose: mood, activity: null }
38 return { pose: isWorking ? 'working' : mood, activity }
39}
40
41// At most one activity line per this many ticks (about 10 s).
42export const LINE_GAP_TICKS = 14
43// A Bash call longer than this many ticks (30 s) that succeeds gets a keep-watch line.
44export const KEEP_WATCH_TICKS = 40
45
46export const NAME_MAX = 32
47
48// What a name may show as: printable ASCII only, at most NAME_MAX characters.
49export const cleanName = (s: string): string => {
50 const ascii = Array.from(s, ch => (ch >= ' ' && ch <= '~' ? ch : '?')).join('')
51 return ascii.length > NAME_MAX ? `${ascii.slice(0, NAME_MAX - 3)}...` : ascii
52}
53
54// A file's own name: everything after the last / or \, so no folder shows, and no user
55// name inside one. A path with no file name gives none.
56export const baseName = (path: string): string | null => {
57 const name = cleanName(path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1))
58 return name.trim() === '' ? null : name
59}
60
61// A web address's host only: never the user, password, port, path or query. A URL that
62// does not parse, or has no host (file:, mailto:), gives none.
63export const hostOf = (url: string): string | null => {
64 try {
65 const host = new URL(url).hostname
66 return host === '' ? null : cleanName(host)
67 } catch {
68 return null
69 }
70}
71
72// Each topic has its own first-of-turn line: reading, editing and the web.
73export type Topic = 'read' | 'edit' | 'web'
74
75export const topicOf = (tool: string): Topic | null => {
76 switch (tool) {
77 case 'Read':
78 case 'Grep':
79 case 'Glob':
80 return 'read'
81 case 'Edit':
82 case 'Write':
83 return 'edit'
84 case 'WebFetch':
85 case 'WebSearch':
86 return 'web'
87 default:
88 return null
89 }
90}
91
92export const MOMENTS = ['read', 'search', 'edit', 'fetch', 'websearch', 'commit', 'push', 'watch'] as const
93export type Moment = (typeof MOMENTS)[number]
94
95// Two or three lines per moment, picked by tick as remarkFor picks. `name` is a basename,
96// a host or a number of seconds, already cleaned.
97const LINES: Record<Moment, readonly ((name: string) => string)[]> = {
98 read: [n => `Mango sniffs at ${n}.`, n => `Mango noses through ${n}.`, n => `Mango gives ${n} a good sniff.`],
99 search: [() => 'Mango sniffs around the files.', () => 'Mango follows a scent through the files.', () => 'Mango noses along the folders.'],
100 edit: [n => `Mango watches you edit ${n}.`, n => `Mango keeps an eye on ${n}.`, n => `Mango watches ${n} change.`],
101 fetch: [n => `Mango peers out at ${n}.`, n => `Mango spots ${n} through the window.`],
102 websearch: [() => 'Mango peers out the window.', () => 'Mango watches the web go by.'],
103 commit: [() => 'Mango pounces on the commit.', () => 'Mango catches the commit in her paws.'],
104 push: [() => 'Mango chases the push out the door.', () => 'Mango runs after the push.'],
105 watch: [n => `Mango kept watch for ${n} s.`, n => `Mango sat with you for all ${n} s.`],
106}
107
108export const lineFor = (moment: Moment, tick: number, name = ''): string => {
109 const lines = LINES[moment]
110 const pick = lines[Math.abs(tick) % lines.length]
111 return pick === undefined ? '' : pick(name)
112}
113
114// The first-of-turn line a looking call may say. Only a Read, Edit or Write file name and
115// a WebFetch host are named; Grep and Glob patterns and search queries never are.
116export const callLine = (e: { tool: string; file_path?: string; url?: string }, tick: number): string | null => {
117 switch (e.tool) {
118 case 'Read': {
119 const name = baseName(e.file_path ?? '')
120 return name === null ? null : lineFor('read', tick, name)
121 }
122 case 'Grep':
123 case 'Glob':
124 return lineFor('search', tick)
125 case 'Edit':
126 case 'Write': {
127 const name = baseName(e.file_path ?? '')
128 return name === null ? null : lineFor('edit', tick, name)
129 }
130 case 'WebFetch': {
131 const host = hostOf(e.url ?? '')
132 return host === null ? null : lineFor('fetch', tick, host)
133 }
134 case 'WebSearch':
135 return lineFor('websearch', tick)
136 default:
137 return null
138 }
139}
140
141// A git step counts only at command position, as isTestCommand reads it: the start of a
142// line, or after &&, ;, |, ( or a backtick, with optional VAR=value prefixes. git's own
143// options may come first (git -C repo commit). So `echo git commit` and `git commit-tree`
144// do not count. Each option reads one way only (an -c or -C value never starts with a
145// dash, and a word char follows the dashes), so a long run of options cannot make the
146// match backtrack exponentially and stall the Bash call.
147const GIT_COMMIT = /(^|&&|;|\||\n|\(|`)\s*(\w+=\S*\s+)*git\s+((-[cC]\s+[^\s-]\S*|-{1,2}\w[\w-]*(=\S*)?)\s+)*commit(?![\w-])/
148const GIT_PUSH = /(^|&&|;|\||\n|\(|`)\s*(\w+=\S*\s+)*git\s+((-[cC]\s+[^\s-]\S*|-{1,2}\w[\w-]*(=\S*)?)\s+)*push(?![\w-])/
149
150// A command that commits and then pushes counts as the push, its last step.
151export const gitStepOf = (command: string): 'commit' | 'push' | null => {
152 const c = command.trim()
153 if (GIT_PUSH.test(c)) return 'push'
154 return GIT_COMMIT.test(c) ? 'commit' : null
155}
156hooks/cat.ts 166 lines1import type { Activity, Mood } from '../types'
2
3export type Pose = Mood | 'working'
4// What the band draws: a pose, or an activity over it.
5export type Look = Pose | Activity
6
7export const TICK_MS = 750
8export const SLEEP_AFTER_TICKS = 160
9export const RUFFLED_TICKS = 8
10export const PROUD_TICKS = 12
11export const BUDGET_PERCENT = 20
12export const ART_WIDTH = 10
13export const GAP = 2
14
15const EARS = ' /\\_/\\'
16
17const pad = (s: string): string => (s + ' ').slice(0, ART_WIDTH)
18
19export const frameFor = (look: Look, tick: number): [string, string] => {
20 switch (look) {
21 case 'awake': {
22 const eyes = tick % 8 === 0 ? '( -.- )' : '( o.o )'
23 const tail = tick % 2 === 1 ? ' ~' : ' '
24 return [pad(EARS), pad(eyes + tail)]
25 }
26 case 'sleeping':
27 return [pad(EARS), pad('( -.- )' + (tick % 2 === 0 ? ' z' : 'zz'))]
28 case 'ruffled':
29 return [pad(' \\/_\\/'), pad('( >.< ) !')]
30 case 'proud':
31 return [pad(EARS), pad('( ^.^ ) *')]
32 case 'worried':
33 return [pad(EARS), pad('( O.O )')]
34 case 'working':
35 return [pad(EARS), pad(tick % 2 === 0 ? '( o.o )nn' : '( o.o ) nn')]
36 case 'sniffing':
37 return [pad(EARS), pad(tick % 2 === 0 ? '( o.o )..' : '( o.o ).')]
38 case 'watching':
39 // Her eyes follow the edit from side to side, two ticks each way.
40 return [pad(EARS), pad(tick % 4 < 2 ? '(o.o )' : '( o.o)')]
41 case 'peering':
42 return [pad(EARS), pad('( O.O ) >')]
43 case 'waiting':
44 return [pad(EARS), pad(tick % 2 === 0 ? '( -.- ) ~' : '( -.- ) .')]
45 case 'pouncing':
46 return [pad(EARS), pad('( ^o^ ) /')]
47 case 'chasing':
48 return [pad(EARS), pad('( >o< )==')]
49 }
50}
51
52export const faceFor = (look: Look, tick: number): string => {
53 switch (look) {
54 case 'awake':
55 return tick % 8 === 0 ? '(-.-)' : '(o.o)'
56 case 'sleeping':
57 return '(-.-)'
58 case 'ruffled':
59 return '(>.<)'
60 case 'proud':
61 return '(^.^)'
62 case 'worried':
63 return '(O.O)'
64 case 'working':
65 return '(o.o)'
66 case 'sniffing':
67 case 'watching':
68 return '(o.o)'
69 case 'peering':
70 return '(O.O)'
71 case 'waiting':
72 return '(-.-)'
73 case 'pouncing':
74 return '(^o^)'
75 case 'chasing':
76 return '(>o<)'
77 }
78}
79
80// The theme colour a remark is drawn in, by the look Mango shows. Theme keys follow the
81// person's theme, so these stay readable in light and dark.
82export const toneFor = (look: Look): string => {
83 switch (look) {
84 case 'proud':
85 case 'pouncing':
86 case 'chasing':
87 return 'success'
88 case 'ruffled':
89 return 'error'
90 case 'worried':
91 return 'warning'
92 case 'sleeping':
93 return 'suggestion'
94 case 'awake':
95 case 'working':
96 case 'sniffing':
97 case 'watching':
98 case 'peering':
99 case 'waiting':
100 return 'claude'
101 }
102}
103
104// Awake has no lines: an awake cat shows the context figure instead.
105type Voice = Exclude<Mood, 'awake'> | 'purr' | 'yawn'
106
107const REMARKS: Record<Voice, readonly string[]> = {
108 sleeping: [
109 'Mango is asleep. Type gently.', 'Mango dreams of warm laptops.', 'Mango curls up on the prompt.', 'Mango is off duty.',
110 'Mango snores, very softly.', 'Mango tucks her white paws under.', 'Mango twitches. She is chasing a bug in her dreams.',
111 'Mango is a loaf now.', 'Mango keeps one ear on the keyboard.', 'Mango sleeps on the warm side of the screen.',
112 ],
113 ruffled: [
114 'Mango did not like that one.', 'Mango flattens her ears.', 'Mango knocks the error off the table.', 'Mango stares at the stack trace.', 'Mango will allow one retry.',
115 'Mango fluffs up her ruff.', 'Mango hisses at the exit code.', 'Mango swats at the red text.',
116 'Mango turns her back on the terminal.', 'Mango says read it again, slowly.', 'Mango blames the semicolon.',
117 ],
118 proud: [
119 'Mango purrs at the green run.', 'Mango knew you would get it.', 'Mango stretches. Tests pass.', 'Mango sits taller now.', 'Mango is pleased.',
120 'Mango slow-blinks at you.', 'Mango kneads in celebration.', 'Mango brings you a green tick.',
121 'Mango flicks her tail. Well done.', 'Mango approves this commit.', 'Mango puffs out her white ruff.',
122 ],
123 worried: [
124 'Mango eyes the context meter.', 'Mango thinks this is a lot of context.', 'Mango suggests saving and clearing soon.', 'Mango paces. The window is filling.',
125 'Mango counts the tokens twice.', 'Mango says write it down before you forget.', 'Mango wants a fresh session soon.',
126 'Mango sits on the memory file to keep it safe.', 'Mango taps the save key with one paw.', 'Mango thinks a recap would fit nicely here.',
127 ],
128 purr: [
129 'Mango purrs.', 'Mango leans into your hand.', 'Mango closes her eyes and rumbles.', 'Mango headbutts the cursor.',
130 'Mango rolls over. The belly is a trap.', 'Mango kneads your sleeve.', 'Mango slow-blinks. That means love.',
131 'Mango tucks her head under your chin.', 'Mango purrs louder than the fans.', 'Mango lets you stroke her ruff.',
132 ],
133 yawn: [
134 'Mango yawns. That was a long one.', 'Mango checks the clock. Still here.', 'Mango stretches after the long turn.', 'Mango wonders if you need a break too.',
135 'Mango yawns and shows every tooth.', 'Mango stretched twice while that ran.', 'Mango thinks water and a stretch would help.',
136 'Mango opens one eye. Is it done?', 'Mango groomed both paws while she waited.', 'Mango has counted every star on the ceiling.',
137 ],
138}
139
140export const remarkFor = (mood: Voice, tick: number): string => {
141 const lines = REMARKS[mood]
142 return lines[Math.abs(tick) % lines.length] ?? ''
143}
144
145// A runner counts only at command position: the start of a line, or after &&, ;, |, ( or a
146// backtick, with optional VAR=value prefixes. So `npm install -D vitest` and
147// `cat jest.config.js` do not.
148const TEST_COMMAND =
149 /(^|&&|;|\||\n|\(|`)\s*(\w+=\S*\s+)*((npm|pnpm|yarn|bun)\s+(run\s+)?test|((npx|bunx|bun|npm\s+exec(\s+--)?|pnpm(\s+(exec|dlx))?|yarn(\s+(exec|dlx))?)\s+)?(vitest|jest)|dotnet\s+test)\b/
150
151export const isTestCommand = (command: string): boolean => TEST_COMMAND.test(command.trim())
152
153export const resolveMood = (s: {
154 mood: Mood
155 moodUntil: number
156 tick: number
157 lastActivityTick: number
158 contextPercent: number
159}): Mood => {
160 const isTimed = s.mood === 'ruffled' || s.mood === 'proud'
161 if (isTimed && s.tick < s.moodUntil) return s.mood
162 if (s.contextPercent >= BUDGET_PERCENT) return 'worried'
163 if (s.tick - s.lastActivityTick >= SLEEP_AFTER_TICKS) return 'sleeping'
164 return 'awake'
165}
166hooks/drawing.ts 448 lines1import type { Activity } from '../types'
2import type { Look, Pose } from './cat'
3
4// Mango as a picture for the surfaces that draw an Svg (desktop, editor, mobile). The
5// terminal keeps the ASCII frames. Drawn on a 120 x 96 grid and shown at half that, so
6// strokes stay crisp. She is drawn from photos of the real Mango: a long black coat with
7// a brown sheen, a white bib and mittens, long white whiskers and golden eyes.
8//
9// She moves by CSS inside the SVG, so the browser animates her smoothly and the markup
10// changes only when her pose does. A frame that is redrawn restarts every animation, so
11// nothing here may depend on the clock tick. Still mode and reduced motion draw her
12// without motion.
13
14export const DRAWING_WIDTH = 60
15export const DRAWING_HEIGHT = 48
16
17export const COAT = '#1a1210'
18export const RIM = '#433632'
19export const WHITE = '#f4efe6'
20export const EYE = '#f0c040'
21export const PUPIL = '#0d0a10'
22const EAR = '#3a2219'
23const TUFT = '#e0d6ca'
24const LEG = '#150f0e'
25const NOSE = '#0a0708'
26const CLOSED = '#8a6f60'
27const HEART = '#e5484d'
28
29// Accent marks share the README mood card colours.
30const SLEEP_MARK = '#b9a6ff'
31const PROUD_MARK = '#ffc24d'
32const RUFFLED_MARK = '#ff8a80'
33const WORRIED_MARK = '#8ac7ff'
34
35export const DEFS = `<defs><radialGradient id="coat" cx="0.32" cy="0.28" r="0.85"><stop offset="0" stop-color="#33231b"/><stop offset="0.45" stop-color="#141011"/><stop offset="1" stop-color="#09080a"/></radialGradient><radialGradient id="iris" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#fde98e"/><stop offset="0.6" stop-color="${EYE}"/><stop offset="1" stop-color="#c0841c"/></radialGradient></defs>`
36
37type Point = [number, number]
38
39// Coordinates are rounded to one decimal, so a path is short and the same every time.
40const r1 = (n: number): number => Math.round(n * 10) / 10
41const P = (x: number, y: number): string => `${r1(x)} ${r1(y)}`
42
43// Mirrors every point in a path around her centre line at x 52.
44const flipPath = (d: string): string => d.replace(/(-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)/g, (_, x: string, y: string) => `${r1(104 - Number(x))} ${y}`)
45
46// A fur outline around an ellipse: tufts with pointed tips. depth(a) is the tuft length
47// at angle a (degrees, 0 = right, 90 = down).
48const fluff = (cx: number, cy: number, rx: number, ry: number, n: number, depth: number | ((a: number) => number), lean = 0.15): string => {
49 const pt = (a: number, k: number): Point => {
50 const t = (a * Math.PI) / 180
51 return [cx + Math.cos(t) * (rx + k), cy + Math.sin(t) * (ry + k)]
52 }
53 const step = 360 / n
54 let d = `M ${P(...pt(0, 0))}`
55 for (let i = 0; i < n; i++) {
56 const a = i * step
57 const k = typeof depth === 'function' ? depth(a + step / 2) : depth
58 d += ` Q ${P(...pt(a + step * 0.3, k * 0.1))} ${P(...pt(a + step * (0.5 + lean), k))}`
59 d += ` Q ${P(...pt(a + step * 0.8, k * 0.25))} ${P(...pt(a + step, 0))}`
60 }
61 return `${d} Z`
62}
63
64// A bushy plume along a cubic Bezier: w wide at its fullest, n tufts down each edge.
65const plume = (p0: Point, p1: Point, p2: Point, p3: Point, w: number, n: number, tuft: number): string => {
66 const at = (t: number) => {
67 const u = 1 - t
68 const x = u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0]
69 const y = u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1]
70 const dx = 3 * u * u * (p1[0] - p0[0]) + 6 * u * t * (p2[0] - p1[0]) + 3 * t * t * (p3[0] - p2[0])
71 const dy = 3 * u * u * (p1[1] - p0[1]) + 6 * u * t * (p2[1] - p1[1]) + 3 * t * t * (p3[1] - p2[1])
72 const l = Math.hypot(dx, dy) || 1
73 return { x, y, nx: -dy / l, ny: dx / l, tx: dx / l, ty: dy / l }
74 }
75 const width = (t: number) => w * (0.42 + 0.78 * Math.sin(Math.PI * Math.min(1, t * 0.92 + 0.04)))
76 const side = (s: number): Point[] => {
77 const pts: Point[] = []
78 for (let i = 0; i <= n * 2; i++) {
79 const t = i / (n * 2)
80 const c = at(t)
81 const isTip = i % 2 === 1
82 const half = width(t) / 2 + (isTip ? tuft : 0)
83 // Tips lean back toward the base, like fur.
84 const back = isTip ? -1.6 : 0
85 pts.push([c.x + c.nx * half * s + c.tx * back, c.y + c.ny * half * s + c.ty * back])
86 }
87 return pts
88 }
89 const left = side(1)
90 const right = side(-1).reverse()
91 const end = at(1)
92 const tip: Point = [end.x + end.tx * (width(1) / 2 + 3), end.y + end.ty * (width(1) / 2 + 3)]
93 // Each tuft bulges out to its tip, then sweeps back in to the next valley. lead is how
94 // the edge is reached: a move for the first, a curve round the tip for the second.
95 const trace = (lead: string, pts: Point[]): string => {
96 let d = ''
97 let prev: Point | null = null
98 for (const [i, [bx, by]] of pts.entries()) {
99 if (prev === null) d += `${lead} ${P(bx, by)}`
100 else {
101 const [ax, ay] = prev
102 d += i % 2 === 1 ? ` Q ${P(ax + (bx - ax) * 0.25, ay + (by - ay) * 0.75)} ${P(bx, by)}` : ` Q ${P(ax + (bx - ax) * 0.75, ay + (by - ay) * 0.25)} ${P(bx, by)}`
103 }
104 prev = [bx, by]
105 }
106 return d
107 }
108 return `${trace('M', left)}${trace(` Q ${P(...tip)}`, right)} Z`
109}
110
111// The low plume starts under her body and curls up along the floor; the raised one stands
112// up behind her for a proud cat or one on a chase. Each is fixed at its root half: a Bend
113// moves only the last two control points, so the tail bends and never slides off her.
114type Bend = [Point, Point]
115const lowPlume = ([p2, p3]: Bend): string => plume([60, 88], [88, 89], p2, p3, 10, 6, 2.2)
116const upPlume = ([p2, p3]: Bend): string => plume([74, 86], [100, 84], p2, p3, 11, 7, 2.6)
117const LOW_REST: Bend = [[108, 86], [106, 68]]
118const UP_REST: Bend = [[112, 60], [102, 40]]
119
120const isRaised = (look: Look): boolean => look === 'proud' || look === 'chasing'
121
122const tail = (raised: boolean): string =>
123 `<path class="${raised ? 'tail tail-up' : 'tail'}" d="${raised ? upPlume(UP_REST) : lowPlume(LOW_REST)}" fill="url(#coat)" stroke="${RIM}" stroke-width="1"/>`
124
125// A tail motion is a list of keyframe stops, each with the bend the tail takes there.
126// Every plume has the same points in the same order, so the browser can blend between
127// them; a browser without CSS d just shows the resting tail.
128type Stops = [string, Bend][]
129const LOW_SWAY: Stops = [['0%,100%', [[107, 87], [100, 69]]], ['50%', [[109, 87], [110, 73]]]]
130const UP_SWAY: Stops = [['0%,100%', [[110, 60], [96, 40]]], ['50%', [[112, 62], [106, 43]]]]
131// A flick whips the tip up toward her, then throws it out low.
132const FLICK: Stops = [['0%,100%', LOW_REST], ['25%', [[108, 83], [101, 60]]], ['55%', [[109, 86], [112, 77]]]]
133const SHIVER: Stops = [['0%,100%', [[108, 86], [105, 68]]], ['50%', [[108, 86], [107, 68.5]]]]
134// Only the tip taps: it lifts, drops back and settles.
135const TAP: Stops = [['0%,55%,100%', LOW_REST], ['70%', [[108, 85], [104, 63]]], ['85%', [[108, 86], [107, 70]]]]
136const LASH: Stops = [['0%,100%', [[108, 60], [92, 41]]], ['50%', [[112, 63], [109, 46]]]]
137
138const tailKeyframes = (name: string, raised: boolean, stops: Stops): string =>
139 `@keyframes ${name}{${stops.map(([at, bend]) => `${at}{d:path("${raised ? upPlume(bend) : lowPlume(bend)}")}`).join('')}}`
140
141// A chase lashes the raised tail before it sways on.
142export const LASH_KEYFRAMES = tailKeyframes('lash', true, LASH)
143
144// Sitting tall: a fluffy body, smooth along the floor, with her front legs before it.
145const LEGS = `<path d="M 38.5 70 L 38.5 90 L 48.5 90 L 48.5 72 Z M 65.5 70 L 65.5 90 L 55.5 90 L 55.5 72 Z" fill="${LEG}" stroke="${RIM}" stroke-width="0.8" stroke-linejoin="round"/>`
146const BODY = `<g class="body"><path d="${fluff(52, 79, 26, 16, 16, a => (Math.sin((a * Math.PI) / 180) > 0.6 ? 0.4 : 2.8))}" fill="url(#coat)" stroke="${RIM}" stroke-width="1"/>${LEGS}</g>`
147
148// White mittens over the toes.
149const mitten = (cx: number, cy: number): string =>
150 `<ellipse cx="${cx}" cy="${cy}" rx="5.6" ry="3.4" fill="${WHITE}"/><path d="M ${cx - 1.8} ${cy - 1} L ${cx - 1.8} ${cy + 2.6} M ${cx + 1.8} ${cy - 1} L ${cx + 1.8} ${cy + 2.6}" stroke="#cfc6ba" stroke-width="0.6"/>`
151const PAWS = `<g class="paw-l">${mitten(43.5, 91)}</g><g class="paw-r">${mitten(60.5, 91)}</g>`
152
153type Ears = 'up' | 'flat' | 'forward'
154
155// The left ear of each kind; the right one is its mirror image.
156const EAR_SHAPES: Record<Ears, { outer: string; inner: string; tufts: string[] }> = {
157 up: { outer: 'M 29 33 L 31 6 L 48 22 Z', inner: 'M 33 28 L 34 13 L 43 22 Z', tufts: ['M 35 27 Q 34 21 35 15', 'M 37 27 Q 37 21 38 17', 'M 39 26 Q 40 22 41 19'] },
158 flat: { outer: 'M 30 32 L 17 18 L 43 21 Z', inner: 'M 30 27 L 23 20.5 L 38 22 Z', tufts: ['M 31 26 Q 27 23.5 24.5 21.5', 'M 33 25 Q 30 23 27.5 21.8'] },
159 // Pricked forward for a cat that peers: taller, narrower, turned in.
160 forward: { outer: 'M 30 32 L 35 3 L 49 21 Z', inner: 'M 34 27 L 36 10 L 44 22 Z', tufts: ['M 36 26 Q 36 19 37 13', 'M 38 26 Q 39 20 40 16', 'M 40 25 Q 41 22 42 19'] },
161}
162
163const earShape = (outer: string, inner: string, tufts: string[]): string =>
164 `<path d="${outer}" fill="${COAT}" stroke="${RIM}" stroke-width="1" stroke-linejoin="round"/><path d="${inner}" fill="${EAR}"/><g stroke="${TUFT}" stroke-width="0.6" stroke-linecap="round" opacity="0.85">${tufts.map(t => `<path d="${t}"/>`).join('')}</g>`
165
166const EARS = Object.fromEntries(
167 (Object.keys(EAR_SHAPES) as Ears[]).map(kind => {
168 const { outer, inner, tufts } = EAR_SHAPES[kind]
169 const side = (s: string, shape: string) => `<g class="perk-${s}"><g class="ear-${s}">${shape}</g></g>`
170 return [kind, side('l', earShape(outer, inner, tufts)) + side('r', earShape(flipPath(outer), flipPath(inner), tufts.map(flipPath)))]
171 }),
172) as Record<Ears, string>
173
174const ears = (kind: Ears): string => EARS[kind]
175
176const earsFor = (look: Look): Ears => (look === 'ruffled' ? 'flat' : look === 'peering' ? 'forward' : 'up')
177
178// Long fur: the ruff stands out widest at the cheeks, and the crown stays short.
179const HEAD = `<path d="${fluff(
180 52,
181 40,
182 20,
183 17.5,
184 18,
185 a => {
186 const c = Math.abs(Math.cos((a * Math.PI) / 180))
187 const s = Math.sin((a * Math.PI) / 180)
188 return s < -0.4 ? 1.2 : 2 + 6 * c * c * (s > -0.1 ? 1 : 0.5) + 2 * Math.max(0, s)
189 },
190 0.3,
191)}" fill="url(#coat)" stroke="${RIM}" stroke-width="0.8"/>`
192
193// A big white bib from under her chin to a point on her chest. Each tuft down the left
194// edge is the valley it starts from and its tip; it bulges out to the tip and snaps back
195// in a straight line to the next valley, like a lock of fur. The last valley is the point.
196const BIB_TUFTS: [Point, Point][] = [[[38, 57], [30, 62]], [[34, 64], [30, 70]], [[36, 70], [34, 76]], [[41, 75], [42, 81]], [[46, 80], [49, 85]]]
197
198const BIB = (() => {
199 let down = ''
200 let up = ''
201 let next: Point = [52, 84]
202 for (const [[vx, vy], [tx, ty]] of [...BIB_TUFTS].reverse()) {
203 const [nx, ny] = next
204 down = ` Q ${P(vx + (tx - vx) * 0.2, vy + (ty - vy) * 0.8)} ${P(tx, ty)} L ${P(nx, ny)}${down}`
205 // The right edge mirrors it on the way back up: tip first, then the valley.
206 const [mtx, mvx] = [104 - tx, 104 - vx]
207 up += ` L ${P(mtx, ty)} Q ${P(mvx + (mtx - mvx) * 0.2, vy + (ty - vy) * 0.8)} ${P(mvx, vy)}`
208 next = [vx, vy]
209 }
210 const outline = `M ${P(38, 57)}${down}${up} Q 64 53.5 60 56.5 Q 56 53.5 52 56 Q 48 53.5 44 56.5 Q 40 53.5 38 57 Z`
211 // Black fur behind the bib: its own outline in the coat, widened around the head axis,
212 // so the white tufts never reach past her and some black shows on both sides.
213 return (
214 `<path d="${outline}" fill="url(#coat)" stroke="${RIM}" stroke-width="0.7" transform="translate(52 0) scale(1.18 1) translate(-52 0)"/>` +
215 `<path d="${outline}" fill="${WHITE}"/>` +
216 `<g stroke="#cfc5b8" stroke-width="0.6" fill="none" stroke-linecap="round" opacity="0.9"><path d="M 44 61 Q 45 67 47 72"/><path d="M 60 61 Q 59 67 57 72"/><path d="M 52 62 L 52 80"/><path d="M 37 61 Q 38 65 40 68"/><path d="M 67 61 Q 66 65 64 68"/><path d="M 49 74 Q 50 78 51 81"/><path d="M 55 74 Q 54 78 53 81"/></g>`
217 )
218})()
219
220// A black nose, the mouth, three long whiskers a cheek and two brow whiskers above each eye.
221const FACE =
222 `<path d="M 49 47.6 Q 52 46.8 55 47.6 Q 54 50.2 52 51.2 Q 50 50.2 49 47.6 Z" fill="${NOSE}" stroke="#4a3a34" stroke-width="0.6"/><ellipse cx="51" cy="48.2" rx="1" ry="0.45" fill="#7a6a64" opacity="0.7"/>` +
223 `<path d="M 52 51.2 L 52 52.6 Q 50 54.6 47.8 53.8 M 52 52.6 Q 54 54.6 56.2 53.8" stroke="#5a4842" stroke-width="0.8" fill="none" stroke-linecap="round"/>` +
224 `<g stroke="${WHITE}" stroke-width="0.75" fill="none" stroke-linecap="round" opacity="0.9">` +
225 `<path d="M 46 50.5 Q 32 45.8 19.5 44.2"/><path d="M 46 52 Q 32 50.8 17.5 52"/><path d="M 46 53.5 Q 32 55.6 20.5 59"/>` +
226 `<path d="M 58 50.5 Q 72 45.8 84.5 44.2"/><path d="M 58 52 Q 72 50.8 86.5 52"/><path d="M 58 53.5 Q 72 55.6 83.5 59"/>` +
227 `<path d="M 38.5 32.8 Q 34 30.8 30 30"/><path d="M 40.5 32.2 Q 36.5 30 33 29.2"/><path d="M 65.5 32.8 Q 70 30.8 74 30"/><path d="M 63.5 32.2 Q 67.5 30 71 29.2"/></g>`
228
229type Eyes = 'open' | 'closed' | 'happy' | 'squint' | 'wide'
230
231const eyeShapes = (kind: Eyes): string => {
232 const pair = (draw: (cx: number) => string) => draw(42) + draw(62)
233 switch (kind) {
234 case 'open':
235 return pair(cx => `<circle cx="${cx}" cy="40" r="6.6" fill="url(#iris)" stroke="#5a3a10" stroke-width="0.8"/><g class="pupil"><ellipse cx="${cx}" cy="40" rx="2.3" ry="4.9" fill="${PUPIL}"/><circle cx="${cx + 2.3}" cy="37.6" r="1.4" fill="${WHITE}"/></g>`)
236 case 'wide':
237 return pair(cx => `<circle cx="${cx}" cy="40" r="7.2" fill="url(#iris)" stroke="#5a3a10" stroke-width="0.8"/><g class="pupil"><circle cx="${cx}" cy="40" r="3.1" fill="${PUPIL}"/><circle cx="${cx + 2.5}" cy="37.4" r="1.5" fill="${WHITE}"/></g>`)
238 case 'closed':
239 return pair(cx => `<path d="M ${cx - 5.5} 40 Q ${cx} 44.5 ${cx + 5.5} 40" stroke="${CLOSED}" stroke-width="2" fill="none" stroke-linecap="round"/>`)
240 case 'happy':
241 return pair(cx => `<path d="M ${cx - 5.5} 42.5 Q ${cx} 34.5 ${cx + 5.5} 42.5" stroke="${EYE}" stroke-width="2.4" fill="none" stroke-linecap="round"/>`)
242 case 'squint':
243 return `<g stroke="${EYE}" stroke-width="2.4" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M 37 36 L 47 40 L 37 44"/><path d="M 67 36 L 57 40 L 67 44"/></g>`
244 }
245}
246
247// Two groups: the outer one widens on hover, the inner one blinks.
248const eyes = (kind: Eyes): string => `<g class="look"><g class="eyes">${eyeShapes(kind)}</g></g>`
249
250const zMark = (x: number, y: number, s: number, cls = ''): string =>
251 `<path${cls === '' ? '' : ` class="${cls}"`} d="M ${x} ${y} h ${s} l ${-s} ${s * 1.1} h ${s}" stroke="${SLEEP_MARK}" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>`
252
253const mark = (look: Look, isAnimated: boolean): string => {
254 switch (look) {
255 case 'sleeping':
256 // Moving, three small z drift up from the same spot in turn; still, two sit apart.
257 return isAnimated ? zMark(84, 24, 6, 'z z1') + zMark(84, 24, 6, 'z z2') + zMark(84, 24, 6, 'z z3') : zMark(84, 26, 6) + zMark(98, 10, 8)
258 case 'proud':
259 return `<path class="mark" d="M 100 14 l 3 8 l 8 3 l -8 3 l -3 8 l -3 -8 l -8 -3 l 8 -3 Z" fill="${PROUD_MARK}"/>`
260 case 'ruffled':
261 return `<g class="mark"><path d="M 102 8 L 102 24" stroke="${RUFFLED_MARK}" stroke-width="3.4" stroke-linecap="round"/><circle cx="102" cy="31" r="2" fill="${RUFFLED_MARK}"/></g>`
262 case 'worried':
263 return `<path class="mark" d="M 82 18 Q 78 25 82 28 Q 86 25 82 18 Z" fill="${WORRIED_MARK}"/>`
264 default:
265 return ''
266 }
267}
268
269// Shown only while a pointer rests on her. Hidden by its own attribute, so a picture
270// without the style sheet never shows it.
271const heart = `<path class="heart" opacity="0" d="M 96 14 C 96 10 91 9 90 13 C 89 9 84 10 84 14 C 84 18 90 21 90 23 C 90 21 96 18 96 14 Z" fill="${HEART}"/>`
272
273const eyesFor = (look: Look): Eyes => {
274 switch (look) {
275 case 'awake':
276 case 'working':
277 case 'sniffing':
278 case 'watching':
279 return 'open'
280 case 'sleeping':
281 case 'waiting':
282 return 'closed'
283 case 'ruffled':
284 return 'squint'
285 case 'proud':
286 case 'pouncing':
287 return 'happy'
288 case 'worried':
289 case 'peering':
290 case 'chasing':
291 return 'wide'
292 }
293}
294
295// Keyframes every pose may use. Transform origins are in the 120 x 96 grid.
296const KEYFRAMES = [
297 '@keyframes breathe{0%,100%{transform:scaleY(1)}50%{transform:scaleY(1.035)}}',
298 '@keyframes deep{0%,100%{transform:scaleY(1)}50%{transform:scaleY(1.06)}}',
299 '@keyframes bob{0%,100%{transform:translateY(0)}50%{transform:translateY(-0.8px)}}',
300 '@keyframes sink{0%,100%{transform:translateY(0)}50%{transform:translateY(1.2px)}}',
301 '@keyframes blink{0%,44%,48%,86%,89%,92%,100%{transform:scaleY(1)}46%,87.5%,90.5%{transform:scaleY(0.1)}}',
302 '@keyframes twitch-l{0%,58%,66%,100%{transform:rotate(0)}61%{transform:rotate(-14deg)}}',
303 '@keyframes twitch-r{0%,22%,30%,100%{transform:rotate(0)}25%{transform:rotate(14deg)}}',
304 '@keyframes knead{0%,100%{transform:translateY(0)}50%{transform:translateY(-4px)}}',
305 '@keyframes drift{0%{opacity:0;transform:translate(0,3px)}25%{opacity:1}100%{opacity:0;transform:translate(14px,-18px)}}',
306 '@keyframes twinkle{0%,100%{opacity:0.6;transform:scale(0.75) rotate(0)}50%{opacity:1;transform:scale(1.15) rotate(25deg)}}',
307 '@keyframes pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.25)}}',
308 '@keyframes drip{0%{opacity:0;transform:translateY(-2px)}20%{opacity:1}100%{opacity:0;transform:translateY(7px)}}',
309 '@keyframes glance{0%,20%,90%,100%{transform:translateX(0)}30%,50%{transform:translateX(-2px)}60%,80%{transform:translateX(2px)}}',
310 '@keyframes love{0%{opacity:0;transform:translateY(4px) scale(0.6)}25%{opacity:1;transform:translateY(0) scale(1)}100%{opacity:0;transform:translateY(-8px) scale(1)}}',
311].join('')
312
313// Keyframes only the activity looks use. Kept apart so the single drawing stays as it is.
314const LOOK_KEYFRAMES = [
315 '@keyframes sniff{0%,100%{transform:translateY(0)}50%{transform:translateY(1.5px)}}',
316 '@keyframes follow{0%,100%{transform:translateX(-2.5px)}50%{transform:translateX(2.5px)}}',
317].join('')
318
319const ORIGINS = [
320 '.body{transform-origin:52px 94px}',
321 '.eyes,.look{transform-origin:52px 40px}',
322 '.ear-l,.perk-l{transform-origin:38px 30px}',
323 '.ear-r,.perk-r{transform-origin:66px 30px}',
324 '.mark{transform-origin:103px 22px}',
325 '.heart{transform-origin:90px 16px}',
326 '.perk-l,.perk-r,.look{transition:transform 0.25s ease-out}',
327].join('')
328
329// A pointer on her perks her ears, widens her eyes and floats a heart.
330const HOVER = 'svg:hover .perk-l{transform:rotate(6deg) translateY(-1px)}svg:hover .perk-r{transform:rotate(-6deg) translateY(-1px)}svg:hover .look{transform:scale(1.08)}svg:hover .heart{animation:love 1.8s ease-out infinite}'
331
332// Without motion the three z would sit on one spot, so they spread out as a still picture.
333export const REDUCED = '@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}.z2{transform:translate(7px,-8px)}.z3{transform:translate(14px,-16px)}}'
334
335const motionFor = (look: Look): string => {
336 const breath = (name: string, seconds: number) => `.body{animation:${name} ${seconds}s ease-in-out infinite}.head{animation:${name === 'deep' ? 'sink' : 'bob'} ${seconds}s ease-in-out infinite}`
337 const raised = isRaised(look)
338 const tailMoves = (name: string, stops: Stops, seconds: number) => `${tailKeyframes(name, raised, stops)}.tail{animation:${name} ${seconds}s ease-in-out infinite}`
339 const sway = raised ? UP_SWAY : LOW_SWAY
340 const blink = '.eyes{animation:blink 6.8s linear infinite}'
341 const earTwitch = '.ear-l{animation:twitch-l 9s ease-in-out infinite}.ear-r{animation:twitch-r 11s ease-in-out infinite}'
342 switch (look) {
343 case 'awake':
344 return breath('breathe', 3.2) + tailMoves('sway', sway, 4.4) + blink + earTwitch
345 case 'working':
346 return (
347 breath('breathe', 3.2) + tailMoves('sway', sway, 2.6) + blink + earTwitch +
348 '.paw-l{animation:knead 0.9s ease-in-out infinite}.paw-r{animation:knead 0.9s ease-in-out -0.45s infinite}'
349 )
350 case 'sleeping':
351 // Asleep she keeps one ear on the keyboard.
352 return (
353 breath('deep', 5) + '.ear-r{animation:twitch-r 13s ease-in-out infinite}' +
354 '.z{animation:drift 3.6s ease-out infinite}.z2{animation-delay:-1.2s}.z3{animation-delay:-2.4s}'
355 )
356 case 'proud':
357 return breath('breathe', 3.2) + tailMoves('sway', sway, 3.6) + '.mark{animation:twinkle 1.6s ease-in-out infinite}'
358 case 'ruffled':
359 return breath('breathe', 1.6) + tailMoves('flick', FLICK, 0.9) + '.mark{animation:pulse 0.6s ease-in-out infinite}'
360 case 'worried':
361 return (
362 breath('breathe', 2.2) + tailMoves('shiver', SHIVER, 1.2) + blink +
363 '.pupil{animation:glance 4s ease-in-out infinite}.mark{animation:drip 2.4s ease-in infinite}'
364 )
365 case 'sniffing':
366 // Head low, nose working: the head dips in quick small sniffs.
367 return '.body{animation:breathe 3.2s ease-in-out infinite}.head{animation:sniff 0.6s ease-in-out infinite}' + tailMoves('sway', sway, 4.4)
368 case 'watching':
369 return breath('breathe', 3.2) + tailMoves('sway', sway, 4.4) + blink + '.pupil{animation:follow 2.4s ease-in-out infinite}'
370 case 'peering':
371 return breath('breathe', 2.6) + tailMoves('sway', sway, 3) + '.ear-l{animation:twitch-l 3s ease-in-out infinite}.ear-r{animation:twitch-r 3.4s ease-in-out infinite}'
372 case 'waiting':
373 // She sits with her eyes closed; only the tail tip taps.
374 return breath('breathe', 4) + tailMoves('tap', TAP, 1.4)
375 case 'pouncing':
376 return breath('breathe', 1.6) + tailMoves('flick', FLICK, 0.9)
377 case 'chasing':
378 return breath('breathe', 1.2) + tailMoves('sway', sway, 1)
379 }
380}
381
382// A look's style for the picture: no hover rules, which a picture drawn as an image never
383// gets, and no reduced-motion query, which the picture adds or leaves out by the motion
384// setting. The heart's keyframes and origin ride along unused: drawingFor shares them.
385export const frontStyle = (look: Look): string => `${KEYFRAMES}${LOOK_KEYFRAMES}${ORIGINS}${motionFor(look)}`
386
387// The front view's markup on the 120 x 96 grid, without the <svg> around it, a style or
388// the heart (the picture has no hover).
389// Sniffing lowers her head over her chest and leaves the bib where it is; everything else
390// about a look is in its eyes, ears and motion.
391export const frontView = (look: Look, isAnimated: boolean): string => {
392 const face = `${eyes(eyesFor(look))}${FACE}`
393 const earPair = ears(earsFor(look))
394 return (
395 tail(isRaised(look)) +
396 BODY +
397 PAWS +
398 (look === 'sniffing'
399 ? `${BIB}<g transform="translate(0 11)"><g class="head">${earPair}${HEAD}${face}</g></g>`
400 : `<g class="head">${earPair}${HEAD}${BIB}${face}</g>`) +
401 mark(look, isAnimated)
402 )
403}
404
405// What a reader that cannot see the picture is told: the activity when one shows, else
406// the same mood the ASCII shows.
407export const altFor = (pose: Pose, activity: Activity | null = null): string => {
408 switch (activity) {
409 case 'sniffing':
410 return 'Mango, a black cat, sniffs around.'
411 case 'watching':
412 return 'Mango, a black cat, watches the code change.'
413 case 'peering':
414 return 'Mango, a black cat, peers out at the web.'
415 case 'waiting':
416 return 'Mango, a black cat, sits and waits.'
417 case 'pouncing':
418 return 'Mango, a black cat, pounces on the commit.'
419 case 'chasing':
420 return 'Mango, a black cat, chases the push.'
421 case null:
422 break
423 }
424 switch (pose) {
425 case 'awake':
426 return 'Mango, a black cat, is awake.'
427 case 'sleeping':
428 return 'Mango, a black cat, is asleep.'
429 case 'ruffled':
430 return 'Mango, a black cat, is ruffled.'
431 case 'proud':
432 return 'Mango, a black cat, is proud.'
433 case 'worried':
434 return 'Mango, a black cat, is worried.'
435 case 'working':
436 return 'Mango, a black cat, kneads while Claude works.'
437 }
438}
439
440// The single drawing, as the README art and v1 drew it, heart and hover included.
441export const drawingFor = (pose: Pose, isAnimated: boolean): string =>
442 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 96" width="120" height="96">` +
443 DEFS +
444 (isAnimated ? `<style>${KEYFRAMES}${ORIGINS}${motionFor(pose)}${HOVER}${REDUCED}</style>` : '') +
445 frontView(pose, isAnimated) +
446 heart +
447 `</svg>`
448hooks/stage.ts 38 lines1import type { Activity, Motion } from '../types'
2import type { Look, Pose } from './cat'
3import { DEFS, frontStyle, frontView, LASH_KEYFRAMES, REDUCED } from './drawing'
4
5// Mango's picture on the desktop: the front view on its 120 x 96 grid, drawn at 60 x 48
6// where the single drawing sits. She stays in place; a pounce hops and a chase bounces
7// there, once per picture. Pure: the same inputs give the same string.
8
9export type PictureInput = { pose: Pose; activity: Activity | null; motion: Motion }
10
11const ACT_KEYFRAMES = [
12 '@keyframes pounce{0%,100%{transform:translateY(0) scaleY(1)}25%{transform:translateY(0) scaleY(0.9)}55%{transform:translateY(-4px) scaleY(1)}80%{transform:translateY(0) scaleY(0.96)}}',
13 // Three quick hops on the spot.
14 '@keyframes bounce{0%,30%,60%,100%{transform:translateY(0)}15%,45%,75%{transform:translateY(-3px)}}',
15 // A crouch squashes her down onto the floor under her paws.
16 '.act{transform-origin:52px 94px}',
17].join('')
18
19// Only a pounce or a chase moves her whole body. A chase is four lashes of the tail long
20// (4 x 0.3 s = 1.2 s); after it the tail sways on as the chasing look has it.
21const actStyle = (activity: Activity | null): string => {
22 switch (activity) {
23 case 'pouncing':
24 return `${ACT_KEYFRAMES}.act{animation:pounce 0.8s ease-out both}`
25 case 'chasing':
26 return `${ACT_KEYFRAMES}${LASH_KEYFRAMES}.act{animation:bounce 1.2s ease-in-out both}.tail{animation:lash 0.3s ease-in-out 4,sway 1s ease-in-out 1.2s infinite}`
27 default:
28 return ''
29 }
30}
31
32export const pictureFor = (p: PictureInput): string => {
33 const look: Look = p.activity ?? p.pose
34 const isAnimated = p.motion !== 'never'
35 const style = isAnimated ? `<style>${frontStyle(look)}${actStyle(p.activity)}${p.motion === 'auto' ? REDUCED : ''}</style>` : ''
36 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 96" width="120" height="96">${DEFS}${style}<g class="act">${frontView(look, isAnimated)}</g></svg>`
37}
38types/index.d.ts 28 lines1export type Mood = 'awake' | 'sleeping' | 'ruffled' | 'proud' | 'worried'
2
3// What Mango does while Claude works, layered over her mood.
4export type Activity = 'sniffing' | 'watching' | 'peering' | 'waiting' | 'pouncing' | 'chasing'
5// auto follows the system's reduced-motion setting; always ignores it; never is a still image.
6export type Motion = 'auto' | 'always' | 'never'
7
8declare module 'claude-code' {
9 interface PluginState {
10 mango: {
11 tick: number
12 mood: Mood
13 moodUntil: number
14 lastActivityTick: number
15 contextPercent: number
16 remark: string | null
17 isSessionCounted: boolean
18 wasOverBudget: boolean
19 isOff: boolean
20 isMuted: boolean
21 shownMood: Mood
22 // What the desktop picture shows over her mood. One atom, so a change is one write and one redraw.
23 activity: Activity | null
24 motion: Motion
25 }
26 }
27}
28