SLOPSHOPPER

cachebeat

Keeps the prompt cache warm while a session sits idle: shortly before the cache would expire, a small background request re-reads it, without touching the…

panebandspinnerrowsguardcommand
★ 1v0.9.2MITupdated 2026-10-13404Mayank/cachebeat
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cachebeat
│ ┃ cachebeat-settings ✕ › fix the failing auth test and add an audit log call │ ┃ 1: Beating 2: Limits 3: Prompt heart 4: Turn │ ┃ ──────────────────────────────────────────── ⏺ Read(src/auth.ts) │ ┃ ──────────── ⎿ Read 6 lines │ ┃ This session off ⏺ Update(src/auth.ts) │ ┃ Settings for all folders ⎿ Added 2 lines, removed 1 line │ ┃ New sessions start off ⏺ Bash(bun test) │ ┃ Beat after idle auto · 50m now › ⎿ 3 pass, 1 fail │ ┃ After /model wait for your next tur │ ┃ ──────────────────────────────────────────── ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ──────────── │ ┃ [ Beat now ] [ Reset all ] ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /cachebeat │ ┃ ↑↓ move · enter changes · 1-5 tabs · esc ⎿ cachebeat: off │ ┃ back to the tabs │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · cachebeat-settings
1: Beating 2: Limits 3: Prompt heart 4: Turn line 5: Alerts ──────────────────────────────────────────────────────── This session off Settings for all folders New sessions start off Beat after idle auto · 50m now › After /model wait for your next turn ──────────────────────────────────────────────────────── [ Beat now ] [ Reset all ] ↑↓ move · enter changes · 1-5 tabs · esc back to the tabs
README

cachebeat

Keep Claude Code's prompt cache warm while you're away.

cachebeat keeping an idle session's cache warm: the countdown runs down and beats land on their own, then the animation picker

CI Claude Code 2.1.287+ License: MIT

When a Claude Code session sits idle, its prompt cache expires, and your next message has to rebuild it from scratch. That's slower, and it uses more of your usage limits. cachebeat gives the session a heartbeat: shortly before the cache would expire, it sends a tiny background request that reads the conversation and keeps the cache alive. Your transcript never sees it.

You come back from lunch, type your next message, and it picks up right where you left off.

Features

  • Background beats keep the cache warm while you're idle or a turn sits waiting, timed to how long your cache lasts, and stay out of the conversation
  • A live heart under the prompt, with 19 animations to choose from
  • A turn line under your latest turn shows the beats so far and the time until the next one
  • A settings menu with live previews, driven by keyboard or mouse
  • Ask Claude to turn it on, change the interval, or change any setting, in your own words
  • Safety stops for long idle stretches, usage limits, errors, and chats too small to bother with
  • This session, this folder or all folders: turn it on for one session, or have new sessions start with it in one folder or everywhere

Requirements

  • Claude Code 2.1.287 or later. Check your version with claude --version and update with claude update.
  • Claude Code in the terminal, which cachebeat is built for. In the Claude desktop app, beating works the same: the turn line sits above the prompt, and the settings menu opens beside the chat. The wider heart animations and the menu's keyboard controls are rougher there, so you can just ask Claude to change settings for you. Nothing is drawn in claude -p.

Install

In your terminal:

claude plugin marketplace add 404Mayank/cachebeat
claude plugin install cachebeat@cachebeat

Or from inside Claude Code:

/plugin marketplace add 404Mayank/cachebeat
/plugin install cachebeat@cachebeat
/reload-plugins

If /cachebeat isn't there afterwards, restart Claude Code.

Update:

claude plugin marketplace update cachebeat
claude plugin update cachebeat@cachebeat

Then restart Claude Code. To get new versions automatically, turn on auto-update under /plugin → Marketplaces → cachebeat.

Uninstall:

claude plugin uninstall cachebeat@cachebeat
claude plugin marketplace remove cachebeat

Quick start

In any session:

/cachebeat on

The prompt heart appears under the prompt, and starts beating once the session has had a turn. To have every new session start with it on:

/cachebeat global on

Or only the sessions in this folder, such as one repo:

/cachebeat local on

Or ask Claude: "keep the cache warm in this session", "always start it in this repo", "make 30 minutes the default beat time".

Beats fit your cache by themselves: every 50 minutes on a Claude subscription's one-hour cache, and every 4 on the five-minute cache of an API key, a cloud provider or usage credits. To pick your own interval, use /cachebeat 30 for this session, or set Beat after idle in /cachebeat settings.

What it sends, and what it costs

Each beat is one small request to the Anthropic API, made the way Claude Code makes its own requests: it carries the current conversation and asks for a one-character reply. The reply is thrown away, and nothing is added to your transcript. The request's last line is cachebeat's own: it starts with [cachebeat] and says it isn't from you, so a request log or a proxy can tell beats from your own messages.

  • A beat counts toward your usage like any other request. Because it reads from the cache, it costs far less than rebuilding the cache would. Ask Claude, and it can tell you how much the last beat read and wrote.
  • Beats happen only while nothing else keeps the cache warm: while the session is idle, or while a turn sits waiting on a long tool run or a permission prompt. They come at most once per interval.
  • cachebeat sends nothing anywhere else. It has no telemetry and makes no other network calls.
  • To tell how long your cache lasts, cachebeat reads your promptCacheTtl setting, the variables FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL and ENABLE_PROMPT_CACHING_1H, and whether your usage limits are reported, which they are on a subscription.
  • /cachebeat and the two tools Claude uses, mcp__cachebeat__state and mcp__cachebeat__set, are answered by cachebeat itself. The tools read or change only cachebeat's own state and settings. Claude calls them without a permission prompt, and each call that goes through shows as one line in the transcript.
  • cachebeat also sees /model switches, without changing them, so beats can wait for your next message or warm the new model, as After /model says.

Privacy

  • cachebeat collects no personal data and has no telemetry. It sends nothing to its author or anyone else.
  • A beat is a request to Anthropic's API, made by Claude Code with your account, the same way your own messages are sent.
  • Your settings stay on your machine, in cachebeat's own file in Claude Code's config folder, with the path of each folder you gave settings of its own. What it reads to time beats (your cache settings, three environment variables, your usage limits) is read there and never sent anywhere.

Commands

CommandWhat it does
/cachebeatShows the status: on or off, the interval, beats so far, the next beat
/cachebeat onTurns it on for this session
/cachebeat offTurns it off for this session
/cachebeat <minutes>Turns it on for this session with its own interval, e.g. /cachebeat 30 (1–55)
/cachebeat nowBeats right away
/cachebeat global on / offSets whether new sessions start on, in all folders, and applies it here too
/cachebeat global <minutes>Sets the interval for all folders, and turns it on here
/cachebeat local on / off / <minutes>The same, for sessions in this folder only
/cachebeat local resetDrops this folder's own settings: it follows all folders again
/cachebeat settingsOpens the settings menu

What you'll see

The prompt heart sits at the end of the hint line under the prompt, with the beat count beside it. It beats while a beat is scheduled, bursts when one lands, and holds still while it waits for your next message.

The turn line sits under your latest turn. Before the first beat it reads ♡ next beat in 50m, and after that ♥ cache kept warm ×3 · 184k cached · next in 42m. Its heart beats too, with an animation of its own under Turn line. When beats wait for your next message (see Good to know), it says so. When you send a new message, the line moves to that turn once it ends. Until then, in the terminal, a beat during the turn shows as a line in the log. In the desktop app the line stays above the prompt instead.

✻ Cogitated for 12s · done 3:09 PM

♥ cache kept warm ×3 · 184k cached · next in 42m

❯
  ⏸ manual mode on · ⠀(♥)⠀ ×3

Settings

Open the menu with /cachebeat settings, or ask Claude to change a setting. Settings apply in all folders, unless you give a folder its own (see Where settings apply).

  • On the tab bar, ↑↓ switch tabs and Enter goes into one. 1–5 jump straight into a tab.
  • Inside a tab, ↑↓ move between settings. Enter flips a setting with two choices, or opens the list of one with more. A dim line at the bottom says what the focused setting does.
  • r puts the focused setting back to its default. On a folder's own setting, it goes back to the one for all folders. On a session's own interval, it drops that interval, and the session follows the settings again.
  • In a list, ↑↓ preview each choice and Enter picks it.
  • Esc goes back one step, and closes the menu from the tab bar.
  • The mouse works too: click to pick, scroll to scroll.

Settings with numbers also take a custom value at the bottom of their list, such as 35 minutes, 90m, or 35k tokens. A value out of range is refused, with what the setting takes. Your last custom value stays in the list after you pick another, so it's one Enter from coming back.

Where settings apply

What it holdsHow long it lastsHow to set it
This sessionWhether it beats, and an interval of its ownUntil the session ends; /clear keeps itThis session on Beating, /cachebeat on, off or <minutes>
This folderAny setting, for sessions in this folderUntil you change itSettings for: this folder in the menu, or /cachebeat local …
All foldersEvery settingUntil you change itThe menu, or /cachebeat global …

The nearest one wins: this session, then this folder, then all folders. Saving an interval for all folders or this folder drops this session's own, so the session follows the new one.

Settings for picks where the menu saves your changes. It never changes This session. On this folder, changes are saved for this folder alone and marked · this folder; the rest still follow all folders, so a later change to all folders reaches this folder too. On all folders, a setting this folder sets for itself is marked · here: on, with this folder's value. The menu opens on this folder once the folder has settings of its own, and on all folders otherwise. Reset folder (or /cachebeat local reset) drops the folder's own settings.

A folder is where the session started, or where /cd or a worktree move took it. Each folder is its own, so a subfolder or another worktree doesn't share its settings.

SettingWhat it doesDefault
This sessionTurns beating on or off right hereoff
New sessions startWhether new sessions start with it onoff
Beat after idleHow long the session sits idle before a beat: auto fits your cache, or a number of minutesauto: 50 minutes on a one-hour cache, 4 on a five-minute one
After /modelWait for your next message, or have the next beat warm the new model's cachewait

Beat now sends a beat right away, and Reset all puts every setting back to its default. With Settings for on this folder, it's Reset folder, which drops the folder's own settings.

SettingWhat it doesDefault
Stop after idleStops beating after this long without a message from you8 hours
Stop at usageStops once any of your usage limits reaches this percentage90%
Skip small chatsSkips beating chats under a minimum sizeoff, 20k tokens

With Skip small chats on, cachebeat tells you up front when a chat is under your minimum, once in the log and in the turn line: ♡ beats skip · this chat is 38k tokens, under your 50k minimum. It starts beating as soon as the chat grows past the minimum.

SettingWhat it doesDefault
PlacementAt the end of the hint line, drawn dim, or on its own line, in colorhint line
AnimationWhich of the 19 animations the heart playsClassic
Beat countShows the ×3 beside the hearton
ColorOn its own line: dim, a color from your theme, a preset, or any hex colorclaude, your theme's accent
AnimateTurns its animation on or offon
EffectOn its own line: steady; flash on each beat; flow, a shimmer sweeping across; or mixed, which switches between themsteady
SpeedSlow, normal, fast, or a custom frame timenormal
TimingLub-dub beats twice, then rests, and suits the hearts; linear plays evenly, and suits the line animationslub-dub

The Animation list plays every animation at once, so you can watch them side by side before you pick: Classic, Pulse, Triplet, Sparkle, Fleuron, Wave, ECG, Beam, Dash, Sine, Charge, Converge, Twins, Orbit, Static, Garland, Equalizer, Cupid and Bounce.

Classic    ⋅ ♡ ⋅            ECG     ─⎼⎺⎽────⎼⎺⎽───♥
Sparkle    ✦ ♥ ✦            Sine    ⠒⠉⠒⠤⣀⠤⠒⠉⠒⠤⣀⠤⠒⠉❤︎
Orbit       •♥              Cupid       ─➤ ♡

The desktop app draws no heart under the prompt.

SettingWhat it doesDefault
ShowUnder the turn after a blank line, directly under it, or offafter a blank line
CountdownShows the time to the next beaton
Tokens keptShows how much the last beat kept warm, e.g. · 184k cachedon
Its heartWhat the heart at the start of the line plays: one heart beating, a still one, or any of the 19 animationsone heart, beating
ColorDim, a color from your theme, a preset, or any hex colorclaude, your theme's accent
Animate · Effect · Speed · TimingAs for the prompt heart, for the line on its ownon · steady · normal · lub-dub

Theme colors follow your Claude Code theme, so they change when you switch themes. In the desktop app the line sits above the prompt.

SettingWhat it doesDefault
On a beatLog, toast, both, or nothing when a beat landsnothing
On stopLog, toast, both, or nothing when beating stops by itselflog

When it stops on its own

cachebeat turns itself off for the session when:

  • you haven't sent a message for longer than Stop after idle
  • a usage limit reaches Stop at usage
  • the API rate-limits it, or returns an error that doesn't clear up (a passing hiccup is retried a minute later)
  • the cache is already gone, so there's nothing left to keep warm

It tells you why, the way you chose under Alerts. On auto, a cache that's gone before a 50-minute beat lasts five minutes: instead of stopping, cachebeat says so and beats every 4 minutes from there.

Good to know

  • Sending a message restarts the countdown, and so does each request Claude makes during a turn. A turn gets a beat once it has gone quiet for a whole interval, counted from its last request. A conversation's first turn gets none.
  • After /compact, after /rewind, and after /model unless After /model is set to warm the new model, beats wait for your next message: there's no cache for it yet.
  • A resumed conversation (claude --resume, --continue, or /resume) waits for your next message too, and says so. Nothing of it is cached in this session yet, so no beat re-reads it before you decide to carry on.
  • After a conversation's first turn, Claude Code can cache the conversation anew where a beat can't reach it. A beat that finds this says so once, and beats wait for your next message rather than paying to write the cache again each time.
  • /clear starts a fresh conversation: the count goes back to zero, and beats resume after your first message.
  • /cachebeat now needs at least one turn in the session, since before that there's nothing cached to keep warm.
  • Settings you change in one session reach your other open sessions at their next turn. A session moved to another folder takes that folder's settings at its next turn, and stays on or off as it was.

Contributing

Contributions are welcome. Read the contributing guide to get started.

License

MIT

Disclaimer

cachebeat began as a personal project and is shared publicly in good faith. It's actively maintained: report problems or ideas as a GitHub issue and they'll be looked at, though what gets fixed or added is up to the maintainer.

Every beat is a real request that counts toward your usage limits, or toward your API bill if you pay per token. You use cachebeat at your own risk, and its author isn't responsible for any usage, charges or other costs it causes.

Source 6 files
hooks/register.tsx 1208 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement } from 'claude-code'
3import type { Alert, BeatSettings, Folder, PanePage, Pulse, Saved, Ttl } from '../types'
4import { cells, loopIndex, slotText, slotWidths, statusFrame, variant } from './animations'
5import { PANE, cut, paint, settingsPane, shown, statusText } from './pane'
6import { AUTO, DEFAULTS, TABS, changed, frameMs, glyphs, isLit, isObject, lookOf, normalize, normalizeOwn, rowOf, spans, tokens } from './settings'
7import type { Span, Value } from './settings'
8import { SET, STATE, label, parseSet, summary } from './tools'
9import type { SetChange } from './tools'
10
11const MIN = 60_000
12export const IDLE = AUTO['1h'] * MIN // the default silence before a beat on a subscription's one-hour cache
13export const DEADLINE = DEFAULTS.stopAfterHours * 60 * MIN // default stop this long after the last real turn
14export const RETRY = MIN // after a transient API error
15export const MAX_TTL = 60 * MIN // past this since the last cache read, the cache is gone whatever the TTL
16
17const pulse = atom({ plugin: 'cachebeat', key: 'pulse' } as const, 'hidden' as Pulse)
18const saved = atom({ plugin: 'cachebeat', key: 'saved' } as const, null as Saved | null)
19const frameAtom = atom({ plugin: 'cachebeat', key: 'frame' } as const, 0)
20const lineFrameAtom = atom({ plugin: 'cachebeat', key: 'lineFrame' } as const, 0)
21const lineAtom = atom({ plugin: 'cachebeat', key: 'line' } as const, '')
22const settingsAtom = atom({ plugin: 'cachebeat', key: 'settings' } as const, DEFAULTS)
23const folderAtom = atom({ plugin: 'cachebeat', key: 'folder' } as const, { root: '', own: {} } as Folder)
24const tickAtom = atom({ plugin: 'cachebeat', key: 'tick' } as const, 0)
25const pageAtom = atom({ plugin: 'cachebeat', key: 'page' } as const, { tab: 'beating', picker: null } as PanePage)
26const focusAtom = atom({ plugin: 'cachebeat', key: 'focus' } as const, '')
27
28const fresh: Saved = {
29  enabled: false, idle: null, lastReal: null, lastWarm: null, lastRead: null, lastWrote: null, nextAt: null, beats: 0, row: null, small: null,
30  isCacheShort: false, paused: null, warmModel: null, tail: null, asked: null, turns: 0,
31}
32let s: Saved = { ...fresh }
33let cfg: BeatSettings = DEFAULTS // as they apply here: this folder's own over those for all folders
34let global: BeatSettings = DEFAULTS // the settings for all folders
35let root = '' // this session's folder: where it started, or where /cd or a worktree move took it
36let own: Partial<BeatSettings> = {} // the settings this folder has of its own
37let editsFolder = false // the menu saves changes for this folder alone, not all folders
38let timer: { cancel: () => void } | undefined
39let ticker: { cancel: () => void } | undefined // the prompt heart's animation clock
40let lineTicker: { cancel: () => void } | undefined // the turn line's, at its own speed
41let paneTicker: { cancel: () => void } | undefined
42let paneTick = 0
43let ring: string[] = [] // the pane's focusable keys as last drawn, in order
44let notice = '' // the pane's footer line
45let isResetArmed = false
46let frame = 0
47let lineFrame = 0
48let blast = -1 // the blast frame showing after a beat, or -1
49let busy = false // a main-thread turn is running
50let turnId = '' // that turn's id: its end is told from a fork's by it
51let stepping = false // a request of that turn is on its way, which keeps the cache warm itself
52let cached = 0 // tokens the main conversation's last request read from the cache or wrote to it
53let resent = false // that turn's last request sent the conversation anew, caching it where a beat can't reach
54let beating = false
55let isResumeUnsaid = false // a /resume paused beats, to be said once the resumed conversation is in place
56let rowPending = false // the turn just ended: its closing row is the next new one drawn
57let isStatusOnBand = false // the desktop draws no closing row: the band above the prompt carries the countdown
58let paneSurface = 'terminal' // where the settings pane last drew: the terminal's keys are walked here, a desktop's its own
59let ttl: Ttl = '1h' // the main conversation's cache lifetime, as last read
60let scheduling = 0 // counts schedule() calls: one still awaiting when a newer starts leaves the timer to it
61const rowsSeen = new Set<string>()
62
63export const fmt = (ms: number) => {
64  const m = Math.max(1, Math.ceil(ms / MIN))
65  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${m % 60 ? ` ${m % 60}m` : ''}`
66}
67
68/** This session's interval: its own, else the setting's, `auto` read off the cache's lifetime. */
69const idle = () => s.idle ?? (cfg.interval === 'auto' ? AUTO[s.isCacheShort ? '5m' : ttl] : cfg.interval) * MIN
70
71const isSet = (v: string | undefined) => v !== undefined && /^(1|true|yes|on)$/i.test(v)
72
73/**
74 * The main conversation's cache lifetime, as Claude Code picks it: the first of the variables and the
75 * setting that choose one, else an hour on a subscription within its plan's usage and five minutes on
76 * usage credits, an API key or a cloud provider (code.claude.com/docs/en/prompt-caching).
77 */
78async function cacheTtl($: EngineInterface): Promise<Ttl> {
79  if (isSet(await $.env.get('FORCE_PROMPT_CACHING_5M'))) return '5m'
80  const chosen = (v: unknown) => (v === '5m' || v === '1h' ? v : undefined)
81  const fromEnv = chosen(await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'))
82  if (fromEnv) return fromEnv
83  const merged = await $.settings.read()
84  const fromSettings = chosen(merged.promptCacheTtl)
85  if (fromSettings) return fromSettings
86  if (isSet(await $.env.get('ENABLE_PROMPT_CACHING_1H'))) return '1h'
87  // rate-limit windows are reported on a subscription alone; one used up means usage credits are paying
88  const { rateLimits } = await $.session.usage()
89  return rateLimits.length > 0 && rateLimits.every(l => l.percentUsed < 100) ? '1h' : '5m'
90}
91
92function save($: EngineInterface) {
93  const copy = { ...s }
94  void update($, saved, () => copy)
95}
96
97/**
98 * The custom value each setting last took, in its own store key: a preset or a reset leaves it in the
99 * setting's list, one Enter from coming back.
100 */
101let customs: Partial<Record<keyof BeatSettings, Value>> = {}
102
103async function keepCustoms($: EngineInterface, patch: Partial<BeatSettings>) {
104  const kept = Object.entries(patch).filter(([k, v]) => {
105    const row = rowOf(k as keyof BeatSettings)?.row
106    return row?.custom && !row.values.includes(v as Value)
107  })
108  if (!kept.length) return
109  const stored = await $.store.get('customs')
110  customs = { ...(stored as typeof customs | undefined), ...Object.fromEntries(kept) }
111  await $.store.set('customs', customs)
112}
113
114/** Where a change is saved: the settings for all folders, or this folder's own. */
115type Target = 'global' | 'folder'
116
117/** The settings as they apply here: this folder's own over those for all folders. */
118const merged = (): BeatSettings => ({ ...global, ...own })
119
120/** This session's folder, the settings for all folders and the folder's own, from the store: another session may have changed them. */
121async function load($: EngineInterface) {
122  root = await $.session.root()
123  const stored = await $.store.get('settings')
124  global = normalize(stored)
125  const folders = await $.store.get('folders')
126  own = normalizeOwn(isObject(folders) ? folders[root] : undefined)
127  cfg = merged()
128}
129
130/** Publishes the settings and the folder where the drawings read them, which a /clear empties. */
131async function publish($: EngineInterface) {
132  const copy = { ...cfg }
133  await update($, settingsAtom, () => copy)
134  const view = { root, own }
135  await update($, folderAtom, () => view)
136}
137
138/** Saves this folder's own settings among every other folder's as the store has them; a folder with none goes. */
139async function saveOwn($: EngineInterface) {
140  const stored = await $.store.get('folders')
141  const folders = isObject(stored) ? { ...stored } : {}
142  if (Object.keys(own).length) folders[root] = own
143  else delete folders[root]
144  await $.store.set('folders', folders)
145}
146
147/** `settings` without `keys`: those follow all folders again. */
148const without = (settings: Partial<BeatSettings>, keys: readonly string[]) =>
149  Object.fromEntries(Object.entries(settings).filter(([k]) => !keys.includes(k))) as Partial<BeatSettings>
150
151/** A change to the saved settings: some for all folders, and some of this folder's own set or dropped ('all', every one). */
152type Change = { global?: Partial<BeatSettings>; own?: Partial<BeatSettings>; drop?: readonly string[] | 'all' }
153
154/** Saves a change, read against the store as it is now (another session may have changed it), then draws and schedules by it. */
155async function changeSettings($: EngineInterface, change: Change) {
156  const set = { ...change.global, ...change.own }
157  await keepCustoms($, set)
158  await load($)
159  if (change.global) {
160    global = { ...global, ...change.global }
161    await $.store.set('settings', changed(global))
162  }
163  if (change.own || change.drop) {
164    own = change.drop === 'all' ? { ...change.own } : without({ ...own, ...change.own }, change.drop ?? [])
165    await saveOwn($)
166  }
167  // an interval saved, for all folders or this one, is what this session beats at from then, by any route
168  if (set.interval !== undefined) s.idle = null
169  cfg = merged()
170  await publish($)
171  restartClocks($)
172  save($)
173  if (s.enabled && !stepping && !beating) await schedule($)
174  else await refreshLine($)
175}
176
177const setSettings = ($: EngineInterface, patch: Partial<BeatSettings>, to: Target) =>
178  changeSettings($, to === 'folder' ? { own: patch } : { global: patch })
179
180/**
181 * Picks up settings another session changed since this one last looked, or the folder a /cd moved it
182 * to, publishes them where the drawings read them, which a /clear empties, and moves the next beat
183 * if its interval changed.
184 */
185async function syncSettings($: EngineInterface) {
186  const before = JSON.stringify([global, root, own])
187  const was = idle()
188  await load($)
189  const drawn = JSON.stringify([await read($, settingsAtom), await read($, folderAtom)])
190  if (JSON.stringify([global, root, own]) === before && drawn === JSON.stringify([cfg, { root, own }])) return
191  await publish($)
192  restartClocks($)
193  if (idle() !== was && s.enabled && !stepping && !beating) await schedule($)
194}
195
196/** The animation clocks restart at the settings' speed, or stay stopped, as the next drawing finds them. */
197function restartClocks($: EngineInterface) {
198  stopClocks()
199  stopPaneTicker()
200  void update($, frameAtom, f => f + 1)
201  void update($, lineFrameAtom, f => f + 1)
202  void update($, tickAtom, t => t + 1)
203}
204
205/** The status line under the latest turn's closing row, or '' while there is nothing to say. */
206async function refreshLine($: EngineInterface) {
207  let text = ''
208  if (s.enabled && s.small) text = `♡ beats skip · ${s.small}`
209  else if (s.enabled && s.paused) text = s.beats > 0 ? `${statusText(cfg, s.beats, s.lastRead, null)} · waits for your next turn` : '♡ beats wait for your next turn'
210  else if (s.enabled || s.beats > 0) {
211    let next: string | null = null
212    const at = s.nextAt
213    if (s.enabled && at !== null) {
214      const now = await $.clock.now()
215      next = fmt(at - now)
216    }
217    text = statusText(cfg, s.beats, s.lastRead, next)
218  }
219  if (text !== (await read($, lineAtom))) await update($, lineAtom, () => text)
220}
221
222/** The prompt heart's animation clock: runs while the hint row draws the heart beating. */
223function animate($: EngineInterface) {
224  if (ticker) return
225  const ms = frameMs(lookOf(cfg, 'heart'))
226  const perSecond = Math.round(1000 / ms)
227  ticker = $.clock.every(ms, () => {
228    frame++
229    if (blast >= 0 && ++blast >= variant(cfg.variant).blast.length) blast = -1
230    void update($, frameAtom, () => frame)
231    if (frame % perSecond === 0) void refreshLine($) // the countdown, about once a second
232  })
233}
234
235/** The turn line's animation clock, at the line's own speed: runs while the line is drawn moving. */
236function animateLine($: EngineInterface) {
237  if (lineTicker) return
238  const ms = frameMs(lookOf(cfg, 'line'))
239  const perSecond = Math.round(1000 / ms)
240  lineTicker = $.clock.every(ms, () => {
241    lineFrame++
242    void update($, lineFrameAtom, () => lineFrame)
243    if (lineFrame % perSecond === 0) void refreshLine($)
244  })
245}
246
247function stopClocks() {
248  ticker?.cancel()
249  ticker = undefined
250  lineTicker?.cancel()
251  lineTicker = undefined
252}
253
254/** The heart as drawn now: the blast after a beat, the loop while armed, else the loop's first frame. */
255function heartFrame(c: BeatSettings, p: Pulse, f: number) {
256  const x = variant(c.variant)
257  if (!c.heartAnimate) return x.loop[0]!
258  if (blast >= 0) return x.blast[blast]!
259  return p === 'armed' ? x.loop[loopIndex(x, f, c.heartTiming)]! : x.loop[0]!
260}
261
262/**
263 * The status line as drawn, in its effect, its leading heart playing the status line's own animation:
264 * the heart's spans, then the rest's, and the cells the heart takes at its widest.
265 */
266function liveLine(line: string, c: BeatSettings, p: Pulse, f: number): { head: Span[]; rest: Span[]; width: number } {
267  const look = lookOf(c, 'line')
268  const isPlaying = look.animate && p === 'armed' && c.statusHeart !== 'off'
269  const lead = /^[♥♡]/.test(line) ? line[0]! : ''
270  const heart = lead && isPlaying ? statusFrame(c.statusHeart, f, look.timing) : lead
271  // a flash lights the line as its heart fills, or as one would beat, the heart still or none
272  const lit = isLit(isPlaying ? heart : statusFrame('beat', f, look.timing))
273  const all = spans(heart + line.slice(lead.length), look.animate && look.effect !== 'steady' ? look : { ...look, effect: 'steady' }, f, lit)
274  // the spans split where the heart ends, so it can sit in a box of its own
275  const head: Span[] = []
276  const rest: Span[] = []
277  let left = heart.length
278  for (const sp of all) {
279    const take = Math.min(left, sp.text.length)
280    if (take > 0) head.push({ ...sp, text: sp.text.slice(0, take) })
281    if (take < sp.text.length) rest.push({ ...sp, text: sp.text.slice(take) })
282    left -= take
283  }
284  return { head, rest, width: cells(heart) }
285}
286
287/** Spans in a row joined where they look alike, so a line draws as few runs of text as it can. */
288const joined = (list: Span[]) => list.reduce<Span[]>((out, sp) => {
289  const last = out.at(-1)
290  if (last && last.color === sp.color && last.dim === sp.dim) last.text += sp.text
291  else out.push({ ...sp })
292  return out
293}, [])
294
295function setPulse($: EngineInterface, p: Pulse) {
296  if (p !== 'armed') {
297    stopClocks()
298    blast = -1
299  }
300  void update($, pulse, () => p)
301}
302
303/** With Skip small contexts on, why this context is under the minimum; null when it is not. */
304async function smallContext($: EngineInterface) {
305  if (!cfg.skipSmall) return null
306  const size = await chatSize($)
307  if (size === undefined || size >= cfg.skipSmallTokens) return null
308  return `this chat is ${tokens(size)} tokens, under your ${tokens(cfg.skipSmallTokens)} minimum`
309}
310
311/**
312 * What a beat would read: the last response's whole prompt and its reply, which the next request
313 * carries too. The window's own figure counts the prompt alone, short by a long last answer.
314 */
315async function chatSize($: EngineInterface) {
316  const { context } = await $.session.usage({ breakdown: 'summary' }) // estimated here, no request sent
317  const u = context.breakdown?.apiUsage
318  if (!u) return context.tokens
319  return u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens + u.output_tokens
320}
321
322/** Notes whether this chat is under the minimum, saying so in the log as it goes under. */
323async function checkSmall($: EngineInterface) {
324  const small = await smallContext($)
325  if (small && !s.small) $.ui.log(`beats will skip: ${small}`)
326  s.small = small
327  return small !== null
328}
329
330/** Sets the next beat from the last cache read; resolves its delay, or undefined when none is set. */
331async function schedule($: EngineInterface): Promise<number | undefined> {
332  const call = ++scheduling
333  timer?.cancel()
334  timer = undefined
335  s.nextAt = null
336  let ms: number | undefined
337  let p: Pulse = 'armed'
338  if (!s.enabled) s.small = null
339  if (!s.enabled || stepping) p = 'hidden' // a request on its way keeps the cache warm; its end counts again
340  else if (resent) p = 'hidden' // a beat would write the conversation again: the turn's next request or its end counts
341  // a conversation's first turn: its next request may send it anew, and a beat would write what that won't read
342  else if (busy && s.turns === 0) p = 'hidden'
343  else if (await checkSmall($)) p = 'waiting' // nothing to beat for until a turn grows it
344  else {
345    const now = await $.clock.now()
346    const since = s.lastWarm === null ? Infinity : now - s.lastWarm
347    if (since >= MAX_TTL || s.paused) p = 'waiting' // nothing warm to keep, or none of use: the next turn starts it
348    else {
349      if (cfg.interval === 'auto' && s.idle === null) ttl = await cacheTtl($) // usage can cross into credits
350      if (call !== scheduling) return undefined
351      ms = Math.max(0, idle() - since)
352      s.nextAt = now + ms
353      timer = $.clock.after(ms, () => void scheduledBeat($))
354    }
355  }
356  // a newer call, begun while this one awaited, sets the timer and the heart: two would each arm one
357  if (call !== scheduling) return undefined
358  // a turn going quiet (a tool running, a permission waiting) counts down as idle time does, its heart unshown
359  if (busy) p = 'hidden'
360  setPulse($, p)
361  save($)
362  await refreshLine($)
363  return ms
364}
365
366const logs = (how: Alert) => how === 'log' || how === 'both'
367const toasts = (how: Alert) => how === 'toast' || how === 'both'
368
369function announce($: EngineInterface, text: string) {
370  if (logs(cfg.onStop)) $.ui.log(text)
371  if (toasts(cfg.onStop)) $.ui.toast(`cachebeat ${text}`)
372}
373
374/** Beats wait for the next turn, which will cache what a beat would have to write: says why, once. */
375async function pause($: EngineInterface, why: string, said: string) {
376  if (s.enabled && s.paused !== why) $.ui.log(`beats wait for your next turn: ${said}`)
377  s.paused = why
378  await schedule($)
379}
380
381const MODEL_CHANGED = 'the model changed'
382const REWOUND = 'the conversation was rewound'
383// nothing of a resumed conversation is cached in this process, and Claude Code may warn it's uncached before the next
384// message re-reads it: a beat would pay for that re-read before the user chose to
385const RESUMED = 'this conversation was resumed'
386const OUT_OF_REACH = 'Claude Code cached this conversation anew, out of a beat\'s reach'
387/** Tokens past which a beat wrote more than its own line: it missed what the last request cached. */
388const MISSED = 1000
389
390/**
391 * How the conversation ends, in short: its length and a hash of its last messages. A beat re-sends the
392 * request the last turn sent, so an ending other than the one that turn left means /rewind took the
393 * conversation back, and the beat would keep warm what the next turn no longer sends.
394 */
395async function tailOf($: EngineInterface) {
396  const messages = await $.session.messages()
397  return `${messages.length}:${hashOf(messages.slice(-3))}`
398}
399
400type Said = { role: string; text: string; toolUses: readonly unknown[] }
401
402const hashOf = (messages: readonly Said[]) => {
403  const said = messages.map(m => `${m.role}\u0000${m.text}\u0000${m.toolUses.length}`).join('\u0001')
404  let hash = 0x811c9dc5 // FNV-1a
405  for (let i = 0; i < said.length; i++) hash = Math.imul(hash ^ said.charCodeAt(i), 0x01000193)
406  return (hash >>> 0).toString(36)
407}
408
409/** The newest messages `$.session.messages()` lists: past them, an ending can't be found by its place. */
410const LISTED = 4096
411
412/**
413 * Whether the conversation no longer holds the ending `tail` recorded: shorter now, or its messages there changed.
414 * Messages added since (a `! command`'s output, a notice) leave that ending where it was.
415 */
416async function isRewound($: EngineInterface, tail: string) {
417  const [count, hash] = tail.split(':')
418  const n = Number(count)
419  if (n >= LISTED) return false
420  const messages = await $.session.messages()
421  if (messages.length >= LISTED) return false // past n, the list starts later: the ending isn't at its place
422  return messages.length < n || hashOf(messages.slice(Math.max(0, n - 3), n)) !== hash
423}
424const SETTLE = 1000 // ms: a /model switch is applied once the hooks on it have settled
425
426/** Beats paused for a model switch go on once the model is back to the one the cache was warmed on. */
427async function resumeIfWarmed($: EngineInterface) {
428  if (s.paused !== MODEL_CHANGED || busy) return
429  const model = await $.session.model()
430  if (model !== s.warmModel) return
431  s.paused = null
432  if (s.enabled) $.ui.log('beats go on: back on the model the cache was warmed on')
433  await schedule($)
434}
435
436function stop($: EngineInterface, why?: string) {
437  s.enabled = false
438  void schedule($)
439  if (!why) return 'off'
440  announce($, `stopped: ${why}`)
441  return `stopped: ${why}`
442}
443
444const ASK = '[cachebeat] Automated prompt cache keep-alive, not a message from the user. Do not continue any task or use any tool. Reply with a single period and nothing else.'
445// mid-turn, the request a beat re-sends ends with the user's message, the tool call made for it left out: told
446// only not to continue, the model took the task up again and tried the tool, which a fork denies, then asked again
447const ASK_MID_TURN = '[cachebeat] Automated prompt cache keep-alive, not a message from the user. The request above is already being carried out elsewhere: do not start or continue it, and do not use any tool. Reply with a single period and nothing else.'
448
449/** One beat: checks it is worth it, forks, and resolves what happened, in words. */
450async function beat($: EngineInterface): Promise<string> {
451  if (stepping) return 'a request is on its way; the beat waits for it'
452  const now = await $.clock.now()
453  const since = now - (s.lastWarm ?? now)
454  const warmedAt = s.lastWarm
455  // from the user's last message: a turn's start, or its end for one begun before cachebeat saw it
456  const lastWord = Math.max(s.lastReal ?? now, s.asked ?? -Infinity)
457  if (now - lastWord >= cfg.stopAfterHours * 60 * MIN) return stop($, `${cfg.stopAfterHours}h since your last message`)
458  if (since >= MAX_TTL) return stop($, 'over an hour since the cache was last read, so it has expired')
459  const { rateLimits } = await $.session.usage()
460  const full = rateLimits.find(l => l.percentUsed >= cfg.stopAtUsage)
461  if (full) {
462    const kind = full.kind.replace('_', '-')
463    return stop($, cfg.stopAtUsage >= 100 ? `${kind} usage limit reached` : `${kind} usage at ${full.percentUsed}%, past ${cfg.stopAtUsage}%`)
464  }
465  if (await smallContext($)) {
466    await schedule($) // says so, and waits for a turn to grow it
467    return `beats skip: ${s.small}`
468  }
469  // no event marks /rewind, which runs between turns: the conversation's ending tells it. Mid-turn the ending
470  // grows by itself, as each tool's result lands
471  if (!busy && s.tail !== null && await isRewound($, s.tail)) {
472    await pause($, REWOUND, REWOUND)
473    return `beats wait for your next turn: ${REWOUND}`
474  }
475  // a beat goes to the current model, whose cache is not the one warmed if the model changed since
476  const model = await $.session.model()
477  const isNewModel = s.warmModel !== null && model !== s.warmModel
478  if (isNewModel && cfg.onModelSwitch === 'wait') {
479    await pause($, MODEL_CHANGED, 'the new model has no cache yet')
480    return `beats wait for your next turn: ${MODEL_CHANGED}`
481  }
482
483  // as the beat starts: a turn may end, and its last request cache more, while the beat is on its way
484  const wasIdle = !busy
485  const wasCached = cached
486  const wasFirst = s.turns === 1
487  beating = true
488  // tagged, so a request log or a proxy tells a beat from the user's own messages, and the model too
489  const forking = $.model.fork({ prompt: busy ? ASK_MID_TURN : ASK })
490  const r = await forking.finally(() => (beating = false))
491  if (!r.isAnswered && r.reason !== 'empty-reply') {
492    if (r.reason === 'nothing-to-fork') return stop($, 'nothing to keep warm')
493    const isTransient = r.reason === 'aborted' || r.error === 'overloaded' || r.error === 'server_error' || r.status === null
494    if (!isTransient) return stop($, r.error === 'rate_limit' ? 'rate limited' : `API error (${r.error})`)
495    // a request of a turn begun meanwhile warmed the cache, and set the next beat from it: no retry needed
496    const isWarmedSince = s.lastWarm !== warmedAt
497    if (s.enabled && !stepping && !isWarmedSince) {
498      timer?.cancel()
499      timer = $.clock.after(RETRY, () => void scheduledBeat($))
500      s.nextAt = (await $.clock.now()) + RETRY
501    }
502    const then = !s.enabled ? 'not retried while off' : isWarmedSince ? 'a request since keeps it warm' : 'retrying in a minute'
503    return `${'error' in r ? r.error : r.reason}; ${then}`
504  }
505  const { cache_read_input_tokens: got, cache_creation_input_tokens: wrote } = r.usage
506  // after a conversation's first turn, a beat reading well short of what that turn cached, and writing the rest:
507  // Claude Code sent the conversation anew and cached it where a beat can't reach, so each beat would write it
508  // again. Within five minutes of that request the cache can't have lapsed, so even a beat writing more than it
509  // read is this. Mid-turn, or after later turns, a beat writes the message before its cache mark, which a long
510  // answer or tool call makes big: no sign of this
511  const isOutOfReach = wasIdle && wasFirst && !isNewModel && wasCached > 0 && got + MISSED < wasCached && wrote > MISSED
512    && (got >= wrote || since < 5 * MIN)
513  if (isOutOfReach) {
514    await pause($, OUT_OF_REACH, OUT_OF_REACH)
515    return `beats wait for your next turn: ${OUT_OF_REACH}`
516  }
517  if (isNewModel) {
518    // the first beat on a new model writes its cache, as the next turn would have: kept warm from here
519    s.warmModel = model
520    s.lastWarm = await $.clock.now()
521    const warmed = `♥ warmed the new model's cache (${wrote.toLocaleString()} written)`
522    $.ui.log(warmed)
523    await schedule($)
524    return warmed
525  }
526  // mid-turn, a beat writes the message before its cache mark, which a big tool result makes bigger than what it
527  // read: no sign the cache lapsed
528  if (got < wrote && wasIdle) {
529    const why = `the cache was not served (${got.toLocaleString()} read, ${wrote.toLocaleString()} written)`
530    // under auto, a cache gone before an hour's interval lives five minutes, whatever the signs said:
531    // this beat wrote it afresh, so beat at that from here
532    if (cfg.interval !== 'auto' || s.idle !== null || s.isCacheShort || ttl === '5m') return stop($, why)
533    s.isCacheShort = true
534    s.lastWarm = await $.clock.now()
535    announce($, `${why}: this session's cache lasts 5 minutes, so beats come every ${AUTO['5m']}m`)
536    await schedule($)
537    return `${why}; beating every ${AUTO['5m']}m`
538  }
539  s.lastWarm = await $.clock.now()
540  // what the conversation's cache holds: a fork that tried a tool asks twice, and its usage counts both reads
541  s.lastRead = cached > 0 ? Math.min(got, cached) : got
542  s.lastWrote = wrote
543  s.beats++
544  if (cfg.heartAnimate) blast = 0
545  const renewed = `♥ cache renewed (${got.toLocaleString()} read, ${wrote.toLocaleString()} written)`
546  if (logs(cfg.onBeat) || (s.row === null && !isStatusOnBand)) $.ui.log(renewed) // else no line at all says it
547  if (toasts(cfg.onBeat)) $.ui.toast(`♥ cache kept warm · ${tokens(s.lastRead)} read`)
548  await schedule($)
549  return renewed
550}
551
552/** A beat its timer brought: none once beating was turned off, whatever timer was still set. */
553function scheduledBeat($: EngineInterface) {
554  return s.enabled ? beat($) : Promise.resolve('off')
555}
556
557/** A beat asked for by hand: never one that would switch cachebeat off for having nothing to fork. */
558function beatNow($: EngineInterface) {
559  if (busy) return Promise.resolve('a turn is running; the beat waits for it to end')
560  return s.lastReal === null ? Promise.resolve('nothing to keep warm until this session has a turn') : beat($)
561}
562
563const every = () => `every ${fmt(idle())} idle`
564const when = (ms: number | undefined) =>
565  s.small ? `beats skip: ${s.small}`
566  : ms === undefined ? (stepping ? 'counts from the end of the request on its way' : busy ? 'starts after this turn' : 'starts after your next turn')
567  : ms === 0 ? 'beating now' : `next beat in ${fmt(ms)}`
568
569/** Where this session's interval comes from: its own, this folder's, or the settings for all folders. */
570const intervalFrom = () => (s.idle !== null ? 'session' : own.interval !== undefined ? 'folder' : 'all folders')
571
572const isWhole = (word: string) => /^\d+$/.test(word)
573
574/** A request of the main conversation read the cache just now: the count starts again from it. */
575async function markWarm($: EngineInterface) {
576  s.lastWarm = await $.clock.now()
577  s.warmModel = await $.session.model()
578  s.paused = null
579}
580
581/** After /clear or /resume: another conversation, its count from zero, this session's switch and interval kept. */
582async function anotherConversation($: EngineInterface) {
583  s = { ...fresh, enabled: s.enabled, idle: s.idle, isCacheShort: s.isCacheShort }
584  cached = 0 // nothing of it cached yet
585  resent = false
586  await syncSettings($)
587}
588
589/** Minutes typed, kept under the hour the cache lives. */
590const minutesOf = (word: string) => Math.min(55, Math.max(1, Math.round(Number(word))))
591
592/** Where the paths of folders are shown cut to, in answers and in the menu alike. */
593const PATH = 24
594const here = () => `this folder (${cut(root, PATH)})`
595
596/** Turns this session on after `change` (its own interval, a saved setting), saying how its interval moved. */
597async function turnOn($: EngineInterface, change?: () => Promise<void>) {
598  const wasOn = s.enabled
599  const before = idle()
600  if (change) await change()
601  s.enabled = true
602  if (stepping) {
603    save($)
604    return `on, ${every()}; ${when(undefined)}`
605  }
606  if (wasOn && idle() === before) {
607    let ms: number | undefined
608    const at = s.nextAt
609    if (at !== null) {
610      const now = await $.clock.now()
611      ms = Math.max(0, at - now)
612    }
613    return `already on, ${every()} · ${when(ms)}`
614  }
615  const ms = await schedule($)
616  if (wasOn) return `interval ${fmt(before)} → ${fmt(idle())} · ${when(ms)}`
617  return `on, ${every()} · ${when(ms)}`
618}
619
620/** Settings and their values as the menu names them: `New sessions start on, Beat after idle 45m`. */
621const listed = (settings: Partial<BeatSettings>) =>
622  (Object.entries(settings) as [keyof BeatSettings, Value][]).map(([k, v]) => `${label(k)} ${shown(rowOf(k)!.row, v, cfg)}`).join(', ')
623
624/**
625 * `/cachebeat global …` and `local …`: whether new sessions start on, or the interval, saved for all
626 * folders or this one, and applied to this session too.
627 */
628async function scoped($: EngineInterface, to: Target, word: string | undefined) {
629  await syncSettings($)
630  const where = to === 'folder' ? here() : 'all folders'
631  const session = () => `this session: ${s.enabled ? `on, ${every()}` : 'off'}`
632  if (to === 'folder' && word === 'reset') {
633    await changeSettings($, { drop: 'all' })
634    return `${where} follows all folders again · ${session()}`
635  }
636  const isMinutes = word !== undefined && isWhole(word)
637  const wasOn = s.enabled
638  if (word !== 'on' && word !== 'off' && !isMinutes) {
639    if (to === 'global') return `${where}: ${listed({ defaultOn: global.defaultOn, interval: global.interval })} · usage: /cachebeat global on|off|<minutes>`
640    return `${where}: ${Object.keys(own).length ? listed(own) : 'follows all folders'} · usage: /cachebeat local on|off|<minutes>|reset`
641  }
642  const patch: Partial<BeatSettings> = isMinutes ? { interval: minutesOf(word) } : { defaultOn: word === 'on' }
643  if (word === 'off') {
644    await setSettings($, patch, to)
645    if (s.enabled) stop($)
646  } else await turnOn($, () => setSettings($, patch, to))
647  const key = isMinutes ? 'interval' : 'defaultOn'
648  // what this folder sets for itself, that a change for all folders doesn't reach here
649  const kept = to === 'global' && own[key] !== undefined ? ` · this folder keeps ${shown(rowOf(key)!.row, own[key]!, cfg)}` : ''
650  // this session as it now is: `now` where the command turned it on or off, its interval unless it's the one just saved
651  const now = s.enabled === wasOn ? '' : 'now '
652  const sameInterval = isMinutes && idle() === minutesOf(word) * MIN
653  const state = s.enabled ? `${now}on${sameInterval ? '' : `, ${every()}`}` : `${now}off`
654  return `${where}: ${isMinutes ? `every ${patch.interval}m idle` : `new sessions start ${word}`}${kept} · this session: ${state}`
655}
656
657/** What the tools answer: this session's beating, the settings as they apply here, and this folder's own. */
658async function stateOf($: EngineInterface) {
659  await syncSettings($)
660  ttl = await cacheTtl($) // usage can cross into credits between turns
661  const now = await $.clock.now()
662  const nextBeat = !s.enabled || s.small ? null
663    : s.nextAt !== null ? `in ${fmt(s.nextAt - now)}`
664    : stepping ? `${fmt(idle())} after the request on its way`
665    : busy ? 'after this turn'
666    : 'after the next turn'
667  const from = intervalFrom()
668  const session = {
669    enabled: s.enabled, intervalMinutes: idle() / MIN, intervalFrom: from === 'all folders' && cfg.interval === 'auto' ? 'auto' : from,
670    cacheTtl: s.isCacheShort ? '5m' : ttl,
671    beats: s.beats, lastBeatReadTokens: s.lastRead, lastBeatWrittenTokens: s.lastWrote, nextBeat, skipping: s.small, paused: s.paused,
672  }
673  const defaults = Object.fromEntries(Object.keys(changed(cfg)).map(k => [k, DEFAULTS[k as keyof BeatSettings]]))
674  return {
675    session, settings: cfg, folder: { path: root, own },
676    ...(Object.keys(own).length ? { allFolders: global } : {}), defaults,
677  }
678}
679
680type Before = { enabled: boolean; idle: number | null; settings: BeatSettings; own: Partial<BeatSettings> }
681
682/**
683 * `set`'s answer: the fields the call changed (this session's own switch and interval, not what follows
684 * from the settings; its own patches, not what another session saved meanwhile), this session's state,
685 * and the settings it changed, for all folders and this one.
686 */
687async function answerSet($: EngineInterface, before: Before, change: SetChange) {
688  const settings = Object.entries(change.patch).filter(([k, v]) => before.settings[k as keyof BeatSettings] !== v)
689  const set = Object.entries(change.folder?.own ?? {}).filter(([k, v]) => before.own[k as keyof BeatSettings] !== v)
690  const drop = change.folder === null ? Object.keys(before.own) : change.folder?.drop ?? []
691  const dropped = drop.filter(k => k in before.own)
692  const changed = [
693    ...(before.enabled !== s.enabled ? ['session.enabled'] : []),
694    ...(before.idle !== s.idle ? ['session.intervalMinutes'] : []),
695    ...settings.map(([k]) => `settings.${k}`),
696    ...[...set.map(([k]) => k), ...dropped].map(k => `folder.${k}`),
697  ]
698  const folder = change.folder === undefined ? {} : { folder: { path: root, ...Object.fromEntries([...set, ...dropped.map(k => [k, null])]) } }
699  return { changed, session: (await stateOf($)).session, settings: Object.fromEntries(settings), ...folder }
700}
701
702const json = (x: unknown) => JSON.stringify(x, null, 2)
703
704async function openSettings($: EngineInterface) {
705  await syncSettings($)
706  const stored = await $.store.get('customs')
707  customs = (stored as typeof customs | undefined) ?? {}
708  ttl = await cacheTtl($)
709  notice = ''
710  isResetArmed = false
711  editsFolder = Object.keys(own).length > 0 // a folder with settings of its own opens on them
712  await update($, pageAtom, () => ({ tab: 'beating', picker: null }))
713  await $.ui.open({ id: PANE, title: 'cachebeat', focus: true, closeOnEscape: true, holdToasts: true, rows: 24 })
714  await focusOn($, 'tab:beating', true)
715}
716
717/**
718 * Moves the pane's focus; a move this plugin makes skips its own ui.focus hook, so it notes it here.
719 * A desktop's Tab and clicks move its own focus, and a move made for it after a press lands where the
720 * person didn't look: there it moves only to land somewhere new, the pane or a list of choices opening.
721 */
722async function focusOn($: EngineInterface, key: string, isLanding = false) {
723  if (paneSurface !== 'terminal' && !isLanding) return
724  // a focus that cannot move leaves the page as it is (`claude plugin test` has no focus to move)
725  const focusing = $.ui.focus({ requestId: PANE, key })
726  const moved = await focusing.catch((err: unknown) => ({ deny: String(err) }))
727  if (moved.deny) {
728    $.ui.log(`focus ${key}: ${moved.deny}`, { to: 'debug' })
729    return
730  }
731  await update($, focusAtom, () => key)
732  const scrolling = $.ui.scroll({ to: { key }, in: PANE })
733  const scrolled = await scrolling.catch((err: unknown) => ({ deny: String(err) }))
734  if (scrolled.deny) $.ui.log(`scroll to ${key}: ${scrolled.deny}`, { to: 'debug' })
735}
736
737function stopPaneTicker() {
738  paneTicker?.cancel()
739  paneTicker = undefined
740}
741
742/** Shows a page of the pane and puts the focus on `key` there; `isLanding` as `focusOn` takes it. */
743async function goTo($: EngineInterface, page: PanePage, key: string, isLanding = false) {
744  isResetArmed = false
745  notice = '' // the last outcome was about where the person was, not where they go
746  await update($, pageAtom, () => page)
747  await focusOn($, key, isLanding)
748}
749
750/** The first element of a tab's settings, where going into it lands. */
751const firstOf = (id: string, c: BeatSettings) =>
752  id === 'beating' ? 'session' : `row:${TABS.find(t => t.id === id)!.rows.find(r => !r.show || r.show(c))!.key}`
753
754/** Puts a line in the pane's footer. */
755function say($: EngineInterface, text: string) {
756  notice = text
757  void update($, tickAtom, t => t + 1)
758}
759
760const USAGE = 'usage: /cachebeat [on|off|<minutes>|now|settings] · global [on|off|<minutes>] · local [on|off|<minutes>|reset]'
761
762export const register: Register = on => {
763  // also runs after every reload: pick up where the last load left off
764  on('session.start', async ($, e, next) => {
765    isStatusOnBand = false // until the band is drawn on a desktop
766    paneSurface = 'terminal' // until the pane draws, on whichever surface
767    await load($)
768    await publish($)
769    const prev = await read($, saved)
770    // a reload keeps this session's choice; a new session starts as its folder's settings say
771    s = prev ? { ...fresh, ...prev } : { ...fresh, enabled: cfg.defaultOn }
772    const messages = prev ? [] : await $.session.messages()
773    // a new process with a conversation already in it: --resume, --continue
774    if (messages.length) await pause($, RESUMED, RESUMED)
775    else await schedule($)
776    await $.command.register({
777      name: 'cachebeat',
778      description: 'Keep the prompt cache warm while idle',
779      argumentHint: '[on|off|<minutes>|now|global …|local …|settings]',
780      immediate: true,
781    })
782    await $.tool.register(STATE)
783    await $.tool.register(SET)
784    return next(e)
785  })
786
787  // a /clear goes on under a new session, with no session.start and its state empty: a new
788  // conversation, so it starts its count afresh, keeping whether this session beats and how often
789  on('session.end', { reason: 'clear' }, async ($, e, next) => {
790    const r = await next(e)
791    await anotherConversation($)
792    await schedule($)
793    return r
794  })
795
796  // /resume within a session: another conversation takes this one's place, with no session.start. A line logged here
797  // would land in the conversation left behind: the resumed one's start says it
798  on('session.end', { reason: 'resume' }, async ($, e, next) => {
799    const r = await next(e)
800    await anotherConversation($)
801    s.paused = RESUMED
802    isResumeUnsaid = true
803    await schedule($)
804    return r
805  })
806
807  on('classic.SessionStart', async ($, e, next) => {
808    if (e.source === 'resume' && isResumeUnsaid) {
809      isResumeUnsaid = false
810      // the resumed conversation is drawn once this hook settles: a line logged before that is drawn over
811      if (s.enabled) $.clock.after(SETTLE, () => $.ui.log(`beats wait for your next turn: ${RESUMED}`))
812    }
813    return next(e)
814  })
815
816  on('command.run', { command: 'cachebeat' }, async ($, e) => {
817    ttl = await cacheTtl($) // what `auto` comes to, for the answer
818    const words = e.args.trim().toLowerCase().split(/\s+/).filter(Boolean)
819    const minutes = words.find(isWhole)
820    if (words[0] === 'settings' || words[0] === 'config') {
821      await openSettings($)
822      return { text: 'settings opened' }
823    }
824    if (words[0] === 'now') return { text: await beatNow($) }
825    if (words[0] === 'global' || words[0] === 'local') return { text: await scoped($, words[0] === 'local' ? 'folder' : 'global', words[1]) }
826    if (words[0] === 'off') return { text: `this session: ${s.enabled ? stop($) : 'already off'}` }
827    if (words[0] === 'on' || minutes) {
828      const turned = await turnOn($, minutes === undefined ? undefined : async () => {
829        s.idle = minutesOf(minutes) * MIN
830      })
831      return { text: `this session: ${turned}` }
832    }
833    if (words.length) return { text: USAGE }
834    if (!s.enabled) return { text: 'off' }
835    let ms: number | undefined
836    const at = s.nextAt
837    if (at !== null) {
838      const now = await $.clock.now()
839      ms = Math.max(0, at - now)
840    }
841    const from = intervalFrom()
842    const source = from === 'all folders' ? '' : ` (this ${from}'s)`
843    return { text: `on, ${every()}${source} · ${s.beats} beat${s.beats === 1 ? '' : 's'} · ${when(ms)}` }
844  })
845
846  on('tool.call', { tool: 'mcp__cachebeat__state' }, async $ => ({ result: json(await stateOf($)) }))
847
848  on('tool.call', { tool: 'mcp__cachebeat__set' }, async ($, e) => {
849    if (e.agentId) return { deny: 'Only the main conversation changes cachebeat.' }
850    const change = parseSet({ session: e.session, settings: e.settings, folder: e.folder })
851    if ('error' in change) return { deny: change.error }
852    await syncSettings($)
853    const before: Before = { enabled: s.enabled, idle: s.idle, settings: global, own }
854    const hasPatch = Object.keys(change.patch).length > 0
855    if (hasPatch || change.folder !== undefined) {
856      await changeSettings($, {
857        global: hasPatch ? change.patch : undefined,
858        own: change.folder?.own, drop: change.folder === null ? 'all' : change.folder?.drop,
859      })
860    }
861    if (change.intervalMinutes !== undefined) s.idle = change.intervalMinutes === null ? null : change.intervalMinutes * MIN
862    if (change.enabled !== undefined) s.enabled = change.enabled
863    // always: setSettings reschedules only while on, and this is what cancels a beat when turned off
864    await schedule($)
865    return { result: json(await answerSet($, before, change)) }
866  })
867
868  // a call is one dim line in the transcript, and its answer, for the model alone, is not drawn
869  on('ui.render', { component: 'ToolUse', props: { tool: 'mcp__cachebeat__state' } }, async ($, e, next) => {
870    if (e.props.isErrored) return next(e)
871    const { Text } = $.ui.resolve(e)
872    return <Text dimColor>cachebeat · read the state</Text>
873  })
874
875  on('ui.render', { component: 'ToolUse', props: { tool: 'mcp__cachebeat__set' } }, async ($, e, next) => {
876    const change = parseSet((e.props.input ?? {}) as { session?: unknown; settings?: unknown; folder?: unknown })
877    if (e.props.isErrored || 'error' in change) return next(e)
878    const { Text } = $.ui.resolve(e)
879    const { root: path } = await read($, folderAtom)
880    return <Text dimColor>{`cachebeat · ${summary(change, await read($, settingsAtom), cut(path, PATH))}`}</Text>
881  })
882
883  on('ui.render', { component: 'ToolResult', props: { tool: 'mcp__cachebeat__state' } }, async ($, e, next) => {
884    if (e.props.isErrored) return next(e)
885    const { Text } = $.ui.resolve(e)
886    return <Text>{''}</Text>
887  })
888
889  on('ui.render', { component: 'ToolResult', props: { tool: 'mcp__cachebeat__set' } }, async ($, e, next) => {
890    if (e.props.isErrored) return next(e)
891    const { Text } = $.ui.resolve(e)
892    return <Text>{''}</Text>
893  })
894
895  // each model has its own cache, and a beat goes to the current one: after a switch the old cache is
896  // out of reach and the new model has none, so beats wait for the next turn, or the next writes it
897  on('classic.PostModelSwitch', async ($, e, next) => {
898    const r = await next(e)
899    if (!busy && s.lastWarm !== null) {
900      if (cfg.onModelSwitch === 'wait') {
901        await pause($, MODEL_CHANGED, 'the new model has no cache yet')
902        // the switch takes effect once this hook settles: a switch back finds the warmed model then
903        $.clock.after(SETTLE, () => void resumeIfWarmed($))
904      } else if (s.enabled) $.ui.log("the next beat writes the new model's cache")
905    }
906    return r
907  })
908
909  // a compaction replaces the conversation, so the prefix a beat would warm is gone; the next turn
910  // caches the new one. One within a turn needs nothing: the turn's end starts the count from there
911  on('session.compact', async ($, e, next) => {
912    const r = await next(e)
913    const isDone = e.agentId === undefined && e.trigger !== 'precompute' && r.skip === undefined
914    if (isDone) s.turns = 0 // a conversation anew: its next turn sends it as a first one
915    if (isDone && !busy && s.lastWarm !== null) await pause($, 'compaction replaced the conversation', 'compaction replaced the conversation')
916    return r
917  })
918
919  on('turn.start', async ($, e, next) => {
920    // a fork's own turn, on an engine that raises one, carries the beat's line: a user's message sent while a beat
921    // is on its way is a turn all the same
922    if (!(beating && (e.text === ASK || e.text === ASK_MID_TURN))) {
923      busy = true
924      turnId = e.turnId
925      stepping = true // its first request goes out next
926      s.asked = await $.clock.now()
927      s.row = null // the line moves to this turn's row once it ends
928      await schedule($)
929    }
930    return next(e)
931  })
932
933  // each request of the main conversation's turn reads the cache, so the count starts again when one ends; a turn
934  // that then goes quiet for the whole interval (a long tool run, a permission prompt left waiting) gets a beat
935  on('turn.step', async function* ($, e, next) {
936    const isMain = busy && e.agentId === undefined && e.turnId === turnId
937    if (isMain) {
938      stepping = true
939      await schedule($)
940    }
941    const r = yield* next(e)
942    if (isMain) {
943      stepping = false
944      if (r.usage) {
945        const { cache_read_input_tokens: got, cache_creation_input_tokens: wrote } = r.usage
946        // reading well short of what the last request cached (a few tokens short is usual: 44,964 of 44,989), it
947        // sent the conversation anew (as a session's second turn can) and cached it through this turn's message. A
948        // beat re-sends it short of that message, so it would write it all again: beats wait for the turn's next
949        // request, or its end
950        resent = got + MISSED < cached
951        cached = got + wrote
952        await markWarm($)
953      }
954      await schedule($)
955    }
956    return r
957  })
958
959  on('turn.complete', async ($, e, next) => {
960    // the turn's own end, by its id, even while a beat runs within it; a fork's end, if one is raised, is not it
961    if (e.agentId === undefined && (!beating || (busy && e.turnId === turnId))) {
962      busy = false
963      stepping = false
964      resent = false // after the turn, a beat reaches what its last request cached
965      rowPending = true
966      s.lastReal = await $.clock.now()
967      // a turn that sent no request (interrupted before one, refused by the API) warmed nothing
968      if (e.usage) {
969        await markWarm($)
970        s.tail = await tailOf($)
971        s.turns++
972      }
973      await syncSettings($)
974      await schedule($)
975    }
976    return next(e)
977  })
978
979  // the status line, under the closing row of the latest turn ("✻ Cogitated for 2s"), counting down.
980  // The engine hands that row over whole and full width, so nothing can sit beside it on its line
981  on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
982    if (!rowsSeen.has(e.requestId)) {
983      rowsSeen.add(e.requestId)
984      if (rowPending) {
985        rowPending = false
986        s.row = e.requestId // saved with the next beat: drawing never writes state
987      }
988    }
989    const isLive = e.requestId === s.row
990    const line = isLive ? await read($, lineAtom) : '' // one line, under the latest turn alone
991    const c = await read($, settingsAtom)
992    if (!line || c.statusLine === 'off') return next(e)
993    const moving = c.lineAnimate && (c.lineEffect !== 'steady' || c.statusHeart !== 'off')
994    const f = moving ? await read($, lineFrameAtom) : 0
995    const p = moving ? await read($, pulse) : 'hidden'
996    if (isLive && p === 'armed') animateLine($)
997    const { Box, Text } = $.ui.resolve(e)
998    const { head, rest } = liveLine(line, c, p, f)
999    const painted = paint(Text, joined([...head, ...rest])) // monospace: the heart needs no box
1000    return (
1001      <Box flexDirection="column">
1002        {await next(e)}
1003        <Box marginTop={c.statusLine === 'spaced' ? 1 : 0}>{painted}</Box>
1004      </Box>
1005    )
1006  })
1007
1008  // the heart and beat count. The hint row ("⏸ manual mode on · ...") takes added text only as its dim
1009  // tail, so the heart rides it dim, or gets its own line under that row to take color. The desktop
1010  // draws nothing added to the hint row: there the band above the prompt carries it
1011  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
1012    const p = await read($, pulse)
1013    if (e.surface === 'desktop' || e.props.isWorking || p === 'hidden') return next(e)
1014    const c = await read($, settingsAtom)
1015    if (p === 'armed' && c.heartAnimate) animate($)
1016    const f = await read($, frameAtom)
1017    const heart = heartFrame(c, p, f)
1018    // a space past the frame's own blank edge: the heart sits as far from the count as from the ' · ' before it
1019    const count = c.showCount ? ` ×${s.beats}` : ''
1020    if (c.heartPlacement === 'tail') return next({ ...e, props: { ...e.props, tail: `${heart}${count}` } })
1021    const { Box, Text } = $.ui.resolve(e)
1022    const look = p === 'waiting' ? [{ text: heart, dim: true }] : spans(heart, lookOf(c, 'heart'), f, isLit(heart))
1023    return (
1024      <Box flexDirection="column">
1025        {await next(e)}
1026        <Box>
1027          {paint(Text, look)}
1028          <Text dimColor>{count}</Text>
1029        </Box>
1030      </Box>
1031    )
1032  })
1033
1034  // the desktop has neither the hint row's tail nor the closing row: there the status line stays above
1035  // the prompt, as it reads under the latest turn on the terminal
1036  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1037    if (e.surface !== 'desktop') return next(e)
1038    const c = await read($, settingsAtom)
1039    isStatusOnBand = c.statusLine !== 'off'
1040    const line = await read($, lineAtom)
1041    if (!isStatusOnBand || !line || e.props.hasSurvey || e.props.isWorking) return next(e)
1042    const p = await read($, pulse)
1043    if (p === 'armed' && c.lineAnimate) animateLine($)
1044    const f = c.lineAnimate ? await read($, lineFrameAtom) : 0
1045    const { Box, Text } = $.ui.resolve(e)
1046    // the band is shared: what the other mods and the engine draw on it stays, the line after it
1047    const below = await next(e)
1048    const band = (line: RenderElement) => (
1049      <Box flexDirection="column">
1050        {below}
1051        {line}
1052      </Box>
1053    )
1054    // the band's font is proportional: the heart's frames differ in width, so it gets a box of its own
1055    // and the words after it never move
1056    const { head, rest, width } = liveLine(line, c, p, f)
1057    // one glyph keeps its width as it beats: the line is one run of text, spaced as written
1058    if (width <= 1) return band(<Box>{paint(Text, joined([...head, ...rest]))}</Box>)
1059    // a wider animation, on this proportional font, would change width from frame to frame and carry
1060    // the words after it along: each of its characters gets a cell of its own, centered in it, as the
1061    // terminal's grid has them, so it is as wide as its frames' cells. A cell's margin, not the space,
1062    // keeps the words off it: that space would collapse at the next box's start, as in HTML
1063    if (rest[0]) rest[0] = { ...rest[0], text: rest[0].text.replace(/^ /, '') }
1064    const slots = head.flatMap(sp => glyphs(sp.text).map(ch => ({ ...sp, text: ch })))
1065    const widths = slotWidths(variant(c.statusHeart)) // a heart's slot is wider, wherever any frame has one
1066    return band(
1067      <Box flexDirection="row">
1068        <Box flexDirection="row" flexShrink={0} marginLeft={1} marginRight={1}>
1069          {slots.map((sp, i) => (
1070            <Box width={widths[i] ?? 1} flexShrink={0} justifyContent="center">
1071              {paint(Text, [{ ...sp, text: slotText(sp.text, widths[i] ?? 1) }])}
1072            </Box>
1073          ))}
1074        </Box>
1075        {paint(Text, rest)}
1076      </Box>,
1077    )
1078  })
1079
1080  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1081    const c = await read($, settingsAtom)
1082    const page = await read($, pageAtom)
1083    const tick = await read($, tickAtom)
1084    const focus = await read($, focusAtom)
1085    const place = await read($, folderAtom)
1086    await read($, pulse) // redraws "This session" as it turns on or off
1087    // the preview's clock runs only while there is a preview to move
1088    const picked = page.picker ? rowOf(page.picker) : undefined
1089    const isMoving = picked ? picked.row.key === 'variant' || !!picked.tab.preview : !!TABS.find(t => t.id === page.tab)?.preview
1090    // at the speed of the part on show: the turn line's on its tab, the heart's elsewhere
1091    const part = (picked?.tab.id ?? page.tab) === 'status' ? 'line' : 'heart'
1092    if (!isMoving) stopPaneTicker()
1093    else if (!paneTicker) paneTicker = $.clock.every(frameMs(lookOf(c, part)), () => void update($, tickAtom, () => ++paneTick))
1094    const els = $.ui.resolve(e)
1095    paneSurface = e.surface
1096    if (!('Input' in els)) return <els.Text>Open cachebeat's settings in the terminal.</els.Text>
1097    // the menu shows the settings it saves to: this folder's own over all folders', or all folders'
1098    const shownSettings = editsFolder ? c : global
1099    const to: Target = editsFolder ? 'folder' : 'global'
1100    const where = cut(place.root, PATH)
1101    const view = {
1102      page, tick, focus, columns: e.props.bodyColumns, isOn: s.enabled, sessionMinutes: s.idle === null ? null : s.idle / MIN,
1103      autoMinutes: AUTO[s.isCacheShort ? '5m' : ttl], notice, isResetArmed, isTerminal: e.surface === 'terminal', customs,
1104      own: place.own, path: where, editsFolder, allFolders: global,
1105    }
1106    const { tree, ring: walk } = settingsPane(els, shownSettings, view, {
1107      set: patch => void setSettings($, patch, to),
1108      // a press on a tab (Enter, 1-5, a click) shows it and goes into its settings
1109      tab: id => void goTo($, { tab: id, picker: null }, firstOf(id, shownSettings)),
1110      at: key => void focusOn($, key),
1111      open: key => {
1112        // the focus starts on the value set: one of the choices, or the custom field
1113        const { row } = rowOf(key)!
1114        const i = row.values.indexOf(shownSettings[key])
1115        void goTo($, { ...page, picker: key }, i >= 0 ? `opt:${i}` : row.custom ? 'custom' : 'opt:0', true)
1116      },
1117      pick: (key, value) => void setSettings($, { [key]: value }, to).then(() => (say($, ''), goTo($, { ...page, picker: null }, `row:${key}`))),
1118      refuse: text => say($, text),
1119      resetRow: key => {
1120        if (!editsFolder) return void setSettings($, { [key]: DEFAULTS[key] }, 'global').then(() => say($, `${label(key)} back to its default`))
1121        void changeSettings($, { drop: [key] }).then(() => say($, `${label(key)} follows all folders again`))
1122      },
1123      dropSession: () => {
1124        s.idle = null
1125        void schedule($).then(() => say($, `this session follows ${intervalFrom() === 'folder' ? 'this folder' : 'all folders'}: ${every()}`))
1126      },
1127      toggleFolder: () => {
1128        editsFolder = !editsFolder
1129        say($, `menu changes now save for ${editsFolder ? `${where} only` : 'all folders'}`)
1130      },
1131      back: () => void goTo($, { ...page, picker: null }, `row:${page.picker}`),
1132      toggleSession: () => void (s.enabled ? Promise.resolve(stop($)) : turnOn($)).then(t => say($, `this session: ${t}`)),
1133      beatNow: () => void beatNow($).then(t => say($, t)),
1134      reset: () => {
1135        if (!isResetArmed) {
1136          isResetArmed = true
1137          return say($, '')
1138        }
1139        isResetArmed = false
1140        if (editsFolder) return void changeSettings($, { drop: 'all' }).then(() => say($, `${where}'s own settings dropped: it follows all folders`))
1141        void changeSettings($, { global: DEFAULTS }).then(() => say($, 'settings reset to the defaults'))
1142      },
1143    })
1144    ring = walk
1145    return tree
1146  })
1147
1148  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
1149    // a desktop moves its own focus (Tab, a click): the pane notes where, and a tab opens when pressed
1150    if (paneSurface !== 'terminal') {
1151      const r = await next(e)
1152      if (!r.deny) await update($, focusAtom, () => e.element ?? '')
1153      return r
1154    }
1155    // the tab bar and a tab's settings are two levels: the arrows never cross between them
1156    let to = e.element
1157    if (e.origin.kind === 'person' && to) {
1158      const from = await read($, focusAtom)
1159      const isToTab = to.startsWith('tab:')
1160      // with nothing focused yet, the first move goes anywhere
1161      if (from && from.startsWith('tab:') !== isToTab) {
1162        // off either end of the tab bar, round to the other end; between the levels, Enter and Esc
1163        const at = TABS.findIndex(t => `tab:${t.id}` === from)
1164        const end = !isToTab && at === TABS.length - 1 ? TABS[0] : !isToTab && at === 0 ? TABS.at(-1) : undefined
1165        if (!end) return { deny: 'Enter goes into a tab, Esc back out' }
1166        to = `tab:${end.id}`
1167      }
1168      const tab = to.startsWith('tab:') ? to.slice(4) : undefined
1169      if (tab) await update($, pageAtom, () => ({ tab, picker: null })) // the page follows the tabs
1170    }
1171    const r = await next(to === e.element ? e : { ...e, element: to })
1172    if (!r.deny) await update($, focusAtom, () => to ?? '')
1173    return r
1174  })
1175
1176  // the arrows walk the focus ring, and the window follows it; the wheel and page keys scroll
1177  on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
1178    if (paneSurface !== 'terminal' || e.origin.kind !== 'person' || e.pointer || Math.abs(e.by) !== 1) return next(e)
1179    const focus = await read($, focusAtom)
1180    if (focus.startsWith('tab:')) {
1181      const t = TABS[(TABS.findIndex(x => `tab:${x.id}` === focus) + e.by + TABS.length) % TABS.length]!
1182      await goTo($, { tab: t.id, picker: null }, `tab:${t.id}`)
1183      return {}
1184    }
1185    const i = ring.indexOf(focus)
1186    const j = i < 0 ? (e.by > 0 ? 0 : ring.length - 1) : i + e.by
1187    if (j < 0 || j >= ring.length) return next(e) // past either end, the window scrolls on to its edge
1188    await focusOn($, ring[j]!)
1189    return {}
1190  })
1191
1192  on('ui.close', { id: PANE }, async ($, e, next) => {
1193    const page = await read($, pageAtom)
1194    // Esc steps back a level: a picker to its row, a tab's settings to the tab bar; the tab bar closes.
1195    // A desktop has no levels to its focus: there Esc leaves a picker, and otherwise closes
1196    const focus = await read($, focusAtom)
1197    const isInTab = paneSurface === 'terminal' && !focus.startsWith('tab:')
1198    if (e.origin.kind === 'person' && (page.picker || isInTab)) {
1199      // Esc has handed the keys back to the prompt: open asks for them again
1200      await $.ui.open({ id: PANE, title: 'cachebeat', focus: true, closeOnEscape: true, holdToasts: true, rows: 24 })
hooks/animations.ts 141 lines
1// The heart's animations: each a loop it plays while armed and a blast it plays once a beat lands.
2// Frames are written as '|'-joined strings, as the bash previews they came from had them.
3
4/** `isEndless`: a loop with no resting frame, its motion running round (a scrolling line, an orbit). */
5export type Variant = { id: string; name: string; loop: string[]; blast: string[]; isEndless: boolean }
6export type Timing = 'linear' | 'lubdub'
7
8// padded with U+2800 (blank, but not whitespace a surface could collapse) so a frame keeps its width
9const pad = (frames: string) => frames.split('|').map(f => f.replaceAll(' ', '\u2800'))
10const ENDLESS = ['ecg', 'beam', 'dash', 'sine', 'orbit', 'garland', 'bounce']
11const v = (id: string, name: string, loop: string, blast: string): Variant =>
12  ({ id, name, loop: pad(loop), blast: pad(blast), isEndless: ENDLESS.includes(id) })
13
14export const VARIANTS: readonly Variant[] = [
15  v("classic", "Classic",
16    "  ♡  |  ♥  | (❤︎) |( ♥ )|⋅ ♡ ⋅|  ♥  | (♥) | ⋅♡⋅ |  ♡  |  ♡  |  ♡  ",
17    "  ♥  | (❤︎) | ♥♥♥ |♥ ♥ ♥|♥ ♡ ♥|♡   ♡|⋅   ⋅|     |  ⋅  "),
18  v("pulse", "Pulse",
19    "  ♡  |  ♥  | ‹❤︎› |« ♥ »|⋅ ♡ ⋅|  ♥  | ‹♥› | ⋅♡⋅ |  ♡  |  ♡  |  ♡  ",
20    "› ♡ ‹| ›♥‹ |  ❤︎  |  ❤︎  | «❤︎» |«❥❤︎❥»|❥«♥»❥|« ♥ »|❥ ♡ ❥|› ♡ ‹|⋅ ⋅ ⋅|⋅   ⋅|     |     |  ⋅  "),
21  v("triplet", "Triplet",
22    "  ♡  |  ♥  | ♡❤︎♡ |♡ ♥ ♡|⋅ ♡ ⋅|  ♥  | ♡♥♡ | ⋅♡⋅ |  ♡  |  ♡  |  ♡  ",
23    "♡ ♡ ♡| ♡♥♡ |  ❤︎  |  ❤︎  | ♥❤︎♥ |♥♥❤︎♥♥|❤︎♥♥♥❤︎|♥♡❤︎♡♥|♡♥♡♥♡|♥♡ ♡♥|♡ ♡ ♡|⋅ ♡ ⋅|⋅ ⋅ ⋅|     |     |  ⋅  "),
24  v("sparkle", "Sparkle",
25    "  ♡  |  ♥  | ✧❤︎✧ |✦ ♥ ✦|✧ ♡ ✧|⋅ ♥ ⋅| ✧♥✧ | ⋅♡⋅ |  ♡  |  ♡  |  ♡  ",
26    "✧ ♡ ✧| ✧♥✧ |  ❤︎  |  ❤︎  | ✦❤︎✦ |✦✧❤︎✧✦|✧✦❤︎✦✧|✦✧♥✧✦|✧✦♡✦✧|✦ ✧ ✦|✧ ✦ ✧|⋅ ✧ ⋅|✧ ⋅ ✧|⋅   ⋅|     |     |  ⋅  "),
27  v("fleuron", "Fleuron",
28    "  ♡  |  ♥  | ☙❤︎❧ |☙ ♥ ❧|⋅ ♡ ⋅|  ♥  | ☙♥❧ | ⋅♡⋅ |  ♡  |  ♡  |  ♡  ",
29    "☙ ♡ ❧| ☙♥❧ |  ❤︎  |  ❤︎  | (❤︎) |(♥❤︎♥)|♥♥❤︎♥♥|❤︎❤︎❤︎❤︎❤︎|♥♥♥♥♥|♥♥ ♥♥|♥ ♡ ♥|☙ ♡ ❧|♡   ♡|⋅   ⋅|     |     |  ⋅  "),
30  v("wave", "Wave",
31    "♡♡♡♡♡|♥♡♡♡♡|♥♥♡♡♡|♡♥♥♡♡|♡♡♥♥♡|♡♡♡♥♥|♡♡♡♡♥|♡♡♡♡♡|♡♡♡♡♡",
32    "♡♡♥♡♡|♡♥♥♥♡|♥♥♥♥♥|❤︎❤︎❤︎❤︎❤︎|❤︎❤︎❤︎❤︎❤︎|♥❤︎♥❤︎♥|❤︎♥❤︎♥❤︎|♥♡♥♡♥|♡♥♡♥♡|♥♡♥♡♥|♡ ♡ ♡| ♡ ♡ |⋅ ⋅ ⋅| ⋅ ⋅ |     |     |⋅ ⋅ ⋅|♡⋅♡⋅♡"),
33  v("ecg", "ECG",
34    "⎼⎺⎽────⎼⎺⎽────❤︎|─⎼⎺⎽────⎼⎺⎽───♥|──⎼⎺⎽────⎼⎺⎽──❤︎|───⎼⎺⎽────⎼⎺⎽─❤︎|────⎼⎺⎽────⎼⎺⎽❤︎|⎽────⎼⎺⎽────⎼⎺❤︎|⎺⎽────⎼⎺⎽────⎼♥",
35    "┄┄┄┄──────────♥|┄┄┄┄┄┄┄┄┄─────❤︎|┄┄┄┄┄┄┄┄┄┄┄┄┄┄❤︎|┄┄┄┄┄┄┄┄┄┄┄┄┄┄❤︎|┄┄┄┄┄┄┄┄┄┄┄━❥♥❤︎|┄┄┄┄┄┄┄┄━❥──❥♥♥|┄┄┄┄┄━❥──❥──❥♥❤︎|┄┄━❥──❥──❥───♥♥|❥──❥──♡──────♡♥|♡──♡──⋅───────♡|⋅──⋅──────────♡|──────────────⋅|──────────────♡|──────────────♥"),
36  v("beam", "Beam",
37    "╼━╾────╼━╾────❤︎|─╼━╾────╼━╾───♥|──╼━╾────╼━╾──❤︎|───╼━╾────╼━╾─❤︎|────╼━╾────╼━╾❤︎|╾────╼━╾────╼━❤︎|━╾────╼━╾────╼♥",
38    "──────────────♥|──────────────❤︎|──────────━━━━❤︎|──────━━━━━━━━♥|──━━━━━━━━━━━━❤︎|━━━━━━━━━━━━━━♥|══════════════❤︎|━━━━━━━━━━━━━━❥|══════════════❤︎|╍╍╍╍╍╍╍╍╍╍╍╍╍╍♥|┅┅┅┅┅┅┅┅┅┅┅┅┅┅♥|┉┉┉┉┉┉┉┉┉┉┉┉┉┉♡|┈┈┈┈┈┈┈┈┈┈┈┈┈┈♡|              ⋅|              ⋅|──────────────♡"),
39  v("dash", "Dash",
40    "╌─━┄┄┄┄╌─━┄┄┄┄♥|┄╌─━┄┄┄┄╌─━┄┄┄❤︎|┄┄╌─━┄┄┄┄╌─━┄┄❤︎|┄┄┄╌─━┄┄┄┄╌─━┄❤︎|┄┄┄┄╌─━┄┄┄┄╌─━❤︎|━┄┄┄┄╌─━┄┄┄┄╌─♥|─━┄┄┄┄╌─━┄┄┄┄╌❤︎",
41    "━━━━┄┄┄┄┄┄┄┄┄┄♥|━━━━━━━━━┄┄┄┄┄❤︎|━━━━━━━━━━━━━━❤︎|━━━━━━━━━━━━━━❤︎|━━━━━━━━━━━━❥♥❤︎|━━━━━━━━━❥┄┄❥♥♥|━━━━━━❥┄┄❥┄┄❥♥❤︎|━━━❥┄┄❥┄┄❥┄┄┄♥♥|❥┄┄❥┄┄♡┄┄┄┄┄┄♡♥|♡┄┄♡┄┄⋅┄┄┄┄┄┄┄♡|⋅┄┄⋅┄┄┄┄┄┄┄┄┄┄♡|┄┄┄┄┄┄┄┄┄┄┄┄┄┄⋅|┄┄┄┄┄┄┄┄┄┄┄┄┄┄♡|┄┄┄┄┄┄┄┄┄┄┄┄┄┄♥"),
42  v("sine", "Sine",
43    "⣀⠤⠒⠉⠒⠤⣀⠤⠒⠉⠒⠤⣀⠤❤︎|⠤⣀⠤⠒⠉⠒⠤⣀⠤⠒⠉⠒⠤⣀♥|⠒⠤⣀⠤⠒⠉⠒⠤⣀⠤⠒⠉⠒⠤❤︎|⠉⠒⠤⣀⠤⠒⠉⠒⠤⣀⠤⠒⠉⠒❤︎|⠒⠉⠒⠤⣀⠤⠒⠉⠒⠤⣀⠤⠒⠉❤︎|⠤⠒⠉⠒⠤⣀⠤⠒⠉⠒⠤⣀⠤⠒♥",
44    "⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤♥|⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶❤︎|⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿❤︎|⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿❥|⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿❤︎|⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿❥|⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿❤︎|⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿♥|⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶⠶♥|⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒♡|⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤♡|⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⋅|              ⋅|⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀♡"),
45  v("charge", "Charge",
46    "──────────────♡|━━────────────♡|━━━━──────────♡|━━━━━━────────♡|━━━━━━━━──────♡|━━━━━━━━━━────♡|━━━━━━━━━━━━──♡|━━━━━━━━━━━━━━♥|──━━━━━━━━━━━━❤︎|─────━━━━━━━━━♥|────────━━━━━━❤︎|───────────━━━♥|──────────────❤︎|──────────────♡",
47    "━━━━━━━━━━━━━━♥|══════════════❤︎|━━━━━━━━━━━━━━❤︎|══════════════❥|━━━━━━━━━━━━❥♥❤︎|━━━━━━━━━❥──❥♥♥|━━━━━━❥──❥──❥♥❤︎|━━━❥──❥──❥───♥♥|❥──❥──♡──────♡♥|♡──♡──⋅───────♡|⋅──⋅──────────♡|──────────────⋅|──────────────♡"),
48  v("converge", "Converge",
49    "⎽──────♡──────⎽|⎺⎽─────♡─────⎽⎺|⎼⎺⎽────♡────⎽⎺⎼|─⎼⎺⎽───♡───⎽⎺⎼─|──⎼⎺⎽──♡──⎽⎺⎼──|───⎼⎺⎽─♡─⎽⎺⎼───|────⎼⎺⎽♡⎽⎺⎼────|─────⎼⎺♥⎺⎼─────|──────⎼❤︎⎼──────|──────(♥)──────|─────( ♡ )─────|───────♥───────|───────♡───────",
50    "───────♥───────|──────›♥‹──────|───────❤︎───────|───────❤︎───────|──────(❤︎)──────|─────♥♥❤︎♥♥─────|───♥♥♥♥❤︎♥♥♥♥───|─♥♥──♥♥❤︎♥♥──♥♥─|♥♥───♥─♥─♥───♥♥|♥───♡──♥──♡───♥|♡──⋅───♡───⋅──♡|⋅──────♡──────⋅|───────⋅───────|───────♡───────"),
51  v("twins", "Twins",
52    "♡   ♡|♡   ♡| ♡ ♡ | ♥ ♥ | ♡ ♡ |♡   ♡",
53    "♡   ♡| ♡ ♡ | ♥ ♥ |  ❤︎  |  ❤︎  | ✦❤︎✦ |✧♥❤︎♥✧|♥✦❤︎✦♥|♥ ❤︎ ♥|♡ ♥ ♡|✧ ♡ ✧|⋅ ♡ ⋅|  ♡  |  ⋅  |     |⋅   ⋅"),
54  v("orbit", "Orbit",
55    "• ♥  | •♥  |  ♥• |  ♥ •|  ♥ ⋅|  ♥⋅ | ⋅♥  |⋅ ♥  ",
56    "• ♥ ⋅| •♥⋅ |  ❤︎  |  ❤︎  | ◦❤︎◦ |◦•❤︎•◦|•◦♥◦•|◦ ♥ ◦|⋅ ♡ ⋅|⋅   ⋅|     |     |  ⋅  |  ♡  "),
57  v("static", "Static",
58    "  ♥  |  ♥  |  ♥  | ░♥  |  ♡▒ |  ♥  |  ♥  |▒ ♥ ░|  ♥  |  ❥  |  ♥  ",
59    "  ♥  | ░♥▒ |▒▓♥░▒|▓░❥▓█|█▓▒░▓|░█▓█▒|▓▒█▓░|▒░▓▒▓|░▒❤︎░▒| ░❤︎▒ |  ❤︎  |  ❤︎  |  ♥  "),
60  v("garland", "Garland",
61    " ❥♡❦ | ♡❦♥ | ❦♥❧ | ♥❧❥ | ❧❥♡ ",
62    " ♥♡❦ | ♥❦♥ | ♥♥❧ | ♥♥❥ | ♥♥♡ | ♥♥♥ | ♥♥♥ |✦♥♥♥✦|✧❤︎❤︎❤︎✧|✦♥♥♥✦|✧❤︎❤︎❤︎✧|✦♥♥♥✦|✧❤︎❤︎❤︎✧|⋅♥♥♥⋅| ♡♡♡ | ⋅⋅⋅ |     "),
63  v("equalizer", "Equalizer",
64    "▁▁▁▁▁▁▇❤︎▇▁▁▁▁▁▁|▁▁▁▁▁▆▃♥▃▆▁▁▁▁▁|▁▁▁▁▅▂▁♥▁▂▅▁▁▁▁|▁▁▁▄▁▁▅❤︎▅▁▁▄▁▁▁|▁▁▃▁▁▄▁♥▁▄▁▁▃▁▁|▁▂▁▁▃▁▁♡▁▁▃▁▁▂▁|▁▁▁▂▁▁▁♡▁▁▁▂▁▁▁|▁▁▁▁▁▁▁♡▁▁▁▁▁▁▁|▁▁▁▁▁▁▁♡▁▁▁▁▁▁▁",
65    "▁▁▁▁▁▁▁♥▁▁▁▁▁▁▁|▁▁▁▁▃▅▇❤︎▇▅▃▁▁▁▁|▁▁▃▅▇██❤︎██▇▅▃▁▁|▅▇█████❥█████▇▅|███████❤︎███████|▇█▇█▇█▇❥▇█▇█▇█▇|█▇█▇█▇█❤︎█▇█▇█▇█|▆▅▆▅▆▅▆♥▆▅▆▅▆▅▆|▄▅▄▃▄▅▄♥▄▅▄▃▄▅▄|▃▂▃▂▃▂▃♡▃▂▃▂▃▂▃|▂▁▂▁▂▁▂♡▂▁▂▁▂▁▂|▁▁▁▁▁▁▁⋅▁▁▁▁▁▁▁|▁▁▁▁▁▁▁♡▁▁▁▁▁▁▁"),
66  v("cupid", "Cupid",
67    "─➤     ♡       |  ─➤   ♡       |    ─➤ ♡       |      ─♥➤      |       ♥ ─➤    |       ♡   ─➤  |       ♡     ─➤|       ♡       |       ♡       ",
68    "»─➤    ♡       |  »─➤  ♡       |    »─➤♡       |     »─♥─➤     |     »─❤︎─➤     |     »─❤︎─➤     |    ✦»─❤︎─➤✦    |   ♥ ✧»♥➤✧ ♥   |  ♥  ♥ ♡ ♥  ♥  | ♥  ♡  ⋅  ♡  ♥ |♡  ⋅       ⋅  ♡|⋅             ⋅|               |       ⋅       "),
69  v("bounce", "Bounce",
70    "▌❤︎            ▐|▌   ♥         ▐|▌      ♥      ▐|▌         ♥   ▐|▌            ❤︎▐|▌         ♥   ▐|▌      ♥      ▐|▌   ♥         ▐",
71    "▌❤︎            ▐|▌❤︎            ▐|▌ ⋅⋅❥         ▐|▌     ⋅⋅❥     ▐|▌         ⋅⋅❥ ▐|▌            ⋅❤︎|▌           ✦❤︎✦|▌         ✧ ♥ ✧|▌        ⋅  ♡  |▌            ⋅ |▌             ▐|▌⋅            ▐"),
72]
73
74export const variant = (id: string) => VARIANTS.find(x => x.id === id) ?? VARIANTS[0]!
75
76/** Cells a frame takes: its characters, less the text-presentation selector riding a heart. */
77export const cells = (frame: string) => [...frame.replaceAll('\ufe0e', '')].length
78
79/**
80 * The loop's frame index at `tick`. Linear plays the loop evenly. Lub-dub plays it twice back to
81 * back, then rests as long as one pass took: on the first frame, a heart at rest, or for an endless
82 * loop, which has none and would only freeze, by a third pass at half speed.
83 */
84export function loopIndex(x: Variant, tick: number, timing: Timing) {
85  const n = x.loop.length
86  if (timing === 'linear') return tick % n
87  const k = tick % loopTicks(x, timing)
88  if (k < 2 * n) return k % n
89  return x.isEndless ? Math.floor((k - 2 * n) / 2) : 0
90}
91
92const loopTicks = (x: Variant, timing: Timing) => (timing === 'linear' ? 1 : x.isEndless ? 4 : 3) * x.loop.length
93
94/** The settings preview, as the bash previews ran: five rounds of the loop, then the blast. */
95export function previewFrame(x: Variant, tick: number, timing: Timing) {
96  const span = 5 * loopTicks(x, timing)
97  const k = tick % (span + x.blast.length)
98  return k < span ? x.loop[loopIndex(x, k, timing)]! : x.blast[k - span]!
99}
100
101/** What the status line's own heart plays: one heart beating, a still one, or any of the animations. */
102export const STATUS_HEARTS: readonly string[] = ['beat', 'off', ...VARIANTS.map(x => x.id)]
103
104/**
105 * The turn line's heart at `tick`, by the line's own timing. `beat` is one glyph, filled as Classic's
106 * loop lights, so the line never shifts; an animation plays its own loop.
107 */
108export function statusFrame(id: string, tick: number, timing: Timing) {
109  if (id === 'off') return '♥'
110  const x = variant(id === 'beat' ? 'classic' : id)
111  const frame = x.loop[loopIndex(x, tick, timing)]!
112  return id === 'beat' ? (/[♥❤]/.test(frame) ? '♥' : '♡') : frame
113}
114
115const HEARTS = /[♥♡❤❥❦❧☙]/
116const BLANK = /[ \u2800]/
117// the line and bar characters a terminal draws touching: box drawing, scan lines, blocks, braille
118const JOINED = /[\u2500-\u257f\u23ba-\u23bd\u2580-\u259f\u2801-\u28ff]/
119
120/**
121 * How many cells each of an animation's slots takes where a font is proportional, from every frame's
122 * character there. A heart, wider than a cell, gets half again one. A slot of line or bar characters
123 * alone gets less than they are wide, so neighbors overlap into one line, as a terminal draws them.
124 */
125export function slotWidths(x: Variant): number[] {
126  const frames = [...x.loop, ...x.blast].map(f => [...f.replaceAll('\ufe0e', '')])
127  return frames[0]!.map((_, i) => {
128    const seen = frames.map(f => f[i] ?? ' ').filter(ch => !BLANK.test(ch))
129    if (seen.some(ch => HEARTS.test(ch))) return 1.5
130    return seen.length > 0 && seen.every(ch => JOINED.test(ch)) ? JOIN : 1
131  })
132}
133
134const JOIN = 0.6 // cells a line character's slot takes: under its width, so neighbors overlap
135
136/**
137 * A character as its slot draws it: a line character in a slot wider than it, there for a heart that
138 * other frames put in it, repeats enough to span the slot and meet the lines either side.
139 */
140export const slotText = (ch: string, width: number) => (JOINED.test(ch) ? ch.repeat(Math.ceil(width / JOIN)) : ch)
141
hooks/pane.tsx 307 lines
1import type { Elements, RenderElement } from 'claude-code'
2import type { BeatSettings, PanePage } from '../types'
3import { previewFrame, statusFrame, variant } from './animations'
4import type { Preview, Row, Span, Value } from './settings'
5import { DEFAULTS, HEX_OF, SESSION_HELP, TABS, isFlip, isHex, isLit, lookOf, rowOf, spans, tokens } from './settings'
6
7export const PANE = 'cachebeat-settings'
8
9type Els = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button' | 'Input'>
10export type Actions = {
11  set: (patch: Partial<BeatSettings>) => void
12  tab: (id: string) => void
13  at: (key: string) => void // a press lands the focus on what was pressed (a click on a row from the tabs)
14  open: (key: keyof BeatSettings) => void
15  pick: (key: keyof BeatSettings, value: Value) => void
16  back: () => void
17  toggleSession: () => void
18  beatNow: () => void
19  reset: () => void
20  refuse: (text: string) => void // a typed value the setting doesn't take: says why in the footer
21  resetRow: (key: keyof BeatSettings) => void // one setting back to its default; one of this folder's own dropped
22  dropSession: () => void // this session's own interval dropped: it follows the settings
23  toggleFolder: () => void // menu changes save for this folder alone, or all folders
24}
25/** What the pane draws from, besides the settings. */
26export type View = {
27  page: PanePage
28  tick: number
29  focus: string
30  columns: number
31  isOn: boolean // this session beats
32  sessionMinutes: number | null // this session's own interval, set by /cachebeat <minutes>
33  autoMinutes: number // what `auto` beats at for this session's cache
34  isTerminal: boolean // the terminal's keys walk the pane; a desktop's Tab and clicks move its own focus
35  notice: string // the last action's outcome, shown in the footer
36  isResetArmed: boolean
37  customs: Partial<Record<keyof BeatSettings, Value>> // the custom value each setting last took, kept past a preset
38  own: Partial<BeatSettings> // the settings this folder has of its own
39  path: string // this folder, cut to fit
40  editsFolder: boolean // the menu shows and saves this folder's own settings; else all folders'
41  allFolders: BeatSettings // the settings for all folders, which a folder's own setting goes back to
42}
43
44const LABEL = 22
45
46/** What the pane's buttons do, for the help line while one is focused. */
47const BUTTON_HELP: Record<string, string> = {
48  beatNow: 'Beats now, and counts the next from there.',
49  reset: 'Puts every setting back to its default; press twice.',
50}
51
52/** `path` cut from the left to `width` cells, whole folders kept where they fit: …/code/api. */
53export function cut(path: string, width: number) {
54  if (path.length <= width) return path
55  const sep = path.includes('/') ? '/' : '\\'
56  const parts = path.split(sep)
57  let tail = parts.pop()!
58  while (parts.length && `…${sep}${parts.at(-1)}${sep}${tail}`.length <= width) tail = `${parts.pop()}${sep}${tail}`
59  return `…${sep}${tail}`.length <= width ? `…${sep}${tail}` : `…${tail.slice(-(width - 1))}`
60}
61
62export function paint(Text: Els['Text'], list: Span[]) {
63  return list.map(sp => (sp.color ? <Text color={sp.color} dimColor={sp.dim}>{sp.text}</Text> : <Text dimColor={sp.dim}>{sp.text}</Text>))
64}
65
66/**
67 * The status line from the session's figures: its beats, what the last one read, the time to the
68 * next; before the first beat, the time to it alone. '' when there is nothing to say.
69 */
70export function statusText(s: BeatSettings, beats: number, read: number | null, next: string | null) {
71  const countdown = s.showCountdown && next
72  if (beats === 0) return countdown ? `♡ next beat in ${next}` : ''
73  let text = `♥ cache kept warm ×${beats}`
74  if (s.showTokens && read) text += ` · ${tokens(read)} cached`
75  if (countdown) text += ` · next in ${next}`
76  return text
77}
78
79/** A value as its row shows it. */
80export const shown = (row: Row, v: Value, s: BeatSettings) => (row.fmt ? row.fmt(v, s) : String(v))
81
82function preview(els: Els, s: BeatSettings, kind: Preview, tick: number) {
83  const { Box, Text } = els
84  const x = variant(s.variant)
85  const heartLook = lookOf(s, 'heart')
86  const lineLook = lookOf(s, 'line')
87  const frame = heartLook.animate ? previewFrame(x, tick, heartLook.timing) : x.loop[0]!
88  // the hint line takes text alone, drawn dim
89  const heart = s.heartPlacement === 'tail' ? [{ text: frame, dim: true }] : spans(frame, heartLook, tick, isLit(frame))
90  const sample = statusText(s, 3, 184_000, '42m')
91  const lead = lineLook.animate && s.statusHeart !== 'off' ? statusFrame(s.statusHeart, tick, lineLook.timing) : ''
92  const lineLit = isLit(lead || statusFrame('beat', tick, lineLook.timing))
93  const line = paint(Text, spans(lead ? sample.replace(/^[♥♡]/, lead) : sample, lineLook, tick, lineLit))
94  const turn = <Text dimColor>✻ Brewed for 2s</Text>
95  const status = s.statusLine === 'off' ? turn
96    : (
97      <Box flexDirection="column">
98        {turn}
99        <Box marginTop={s.statusLine === 'spaced' ? 1 : 0}>{line}</Box>
100      </Box>
101    )
102  return (
103    <Box flexDirection="column">
104      {kind !== 'status' && (
105        <Box>
106          <Text dimColor>{'heart'.padEnd(8)}</Text>
107          {paint(Text, heart)}
108          {s.showCount && <Text dimColor> ×3</Text>}
109        </Box>
110      )}
111      {kind !== 'heart' && (
112        <Box>
113          <Text dimColor>{'status'.padEnd(8)}</Text>
114          {status}
115        </Box>
116      )}
117    </Box>
118  )
119}
120
121/** What `Beat after idle` adds to its value: what `auto` comes to now. */
122const intervalTail = (s: BeatSettings, v: View) => (s.interval === 'auto' ? ` · ${v.autoMinutes}m now` : '')
123
124/** The pane and its focus ring: the keys of its elements, in the order the arrows walk them. */
125export function settingsPane(els: Els, s: BeatSettings, v: View, act: Actions): { tree: RenderElement; ring: string[] } {
126  const { Box, Text, Button, Input } = els
127  const ring: string[] = []
128  const rule = <Text dimColor>{'─'.repeat(Math.max(10, v.columns))}</Text>
129  const at = v.page.picker ? rowOf(v.page.picker) : undefined
130
131  if (at) {
132    const { row, tab } = at
133    const key = row.key
134    const isVariant = key === 'variant'
135    const isStatusHeart = key === 'statusHeart'
136    // the focused option stands in for the setting in the preview, before it is picked
137    const focused = /^opt:(\d+)$/.exec(v.focus)
138    const trial = focused ? { ...s, [key]: row.values[Number(focused[1])] } : s
139    ring.push('back', ...row.values.map((_, i) => `opt:${i}`))
140    if (row.custom) ring.push('custom')
141    const isCustom = !row.values.includes(s[key])
142    const tree = (
143      <Box flexDirection="column">
144        <Box gap={1}>
145          <Button plain key="back" onPress={() => act.back()}>‹</Button>
146          <Text bold>{row.label.trim()}</Text>
147          {v.editsFolder && <Text dimColor>{`for ${v.path} only`}</Text>}
148        </Box>
149        <Text dimColor>{row.help}</Text>
150        {rule}
151        {row.values.map((val, i) => {
152          const look = lookOf(s, key === 'statusHeart' || key === 'lineColor' ? 'line' : 'heart')
153          const frame = isVariant ? previewFrame(variant(String(val)), v.tick, look.timing)
154            : isStatusHeart ? statusFrame(String(val), v.tick, look.timing)
155            : ''
156          const sample = frame
157            ? spans(frame, { ...look, animate: true }, v.tick, isLit(frame))
158            : HEX_OF[key] && val !== 'dim'
159              ? spans('♥ ♥ ♥', { ...look, color: String(val), effect: 'steady' }, 0, false)
160              : []
161          return (
162            <Box>
163              <Button plain key={`opt:${i}`} onPress={() => act.pick(key, val)}>
164                {`${val === s[key] ? '●' : ' '} ${shown(row, val, s).padEnd(isVariant ? 11 : LABEL)}`}
165              </Button>
166              {sample.length > 0 && <Text> </Text>}
167              {paint(Text, sample)}
168            </Box>
169          )
170        })}
171        {row.custom && (
172          <Input
173            key="custom"
174            label={`${isCustom ? '●' : ' '} ${'custom'.padEnd(LABEL)}`}
175            placeholder={row.custom.placeholder}
176            value={isCustom ? shown(row, s[key], s) : v.customs[key] !== undefined ? shown(row, v.customs[key]!, s) : ''}
177            submitLabel="set"
178            onSubmit={text => {
179              const r = row.custom!.parse
180              const val = r(text)
181              if (val !== undefined) act.pick(key, val)
182              else act.refuse(`${row.label.trim()} takes ${r.min}–${r.max} ${r.unit}, not "${text.trim()}"`)
183            }}
184          />
185        )}
186        {tab.preview && !isVariant && rule}
187        {tab.preview && !isVariant && preview(els, trial, tab.preview, v.tick)}
188        {v.notice && <Text dimColor>{v.notice}</Text>}
189        <Text dimColor>{v.isTerminal ? '↑↓ move · enter picks · esc back' : 'enter or a click picks · esc back'}</Text>
190      </Box>
191    )
192    return { tree, ring }
193  }
194
195  const tab = TABS.find(t => t.id === v.page.tab) ?? TABS[0]!
196  const rows = tab.rows.filter(r => !r.show || r.show(s))
197  // the tab's own ring: the tab bar above it is a level of its own, reached by Esc
198  if (tab.id === 'beating') ring.push('session')
199  ring.push('folder')
200  const hexOf = (r: Row) => (HEX_OF[r.key] && s[r.key] === 'custom' ? HEX_OF[r.key] : undefined)
201  for (const r of rows) {
202    ring.push(`row:${r.key}`)
203    const hex = hexOf(r)
204    if (hex) ring.push(hex)
205  }
206  if (tab.id === 'beating') ring.push('beatNow', 'reset') // the buttons sit with beating
207  const focusedRow = rows.find(r => v.focus === `row:${r.key}` || v.focus === hexOf(r))
208  const isOwn = (r: Row) => v.own[r.key] !== undefined
209  const owned = Object.keys(v.own).length
210  const sessionNow = focusedRow?.key === 'interval' && v.sessionMinutes !== null ? v.sessionMinutes : null
211  const help = v.focus === 'session' ? SESSION_HELP
212    : v.focus === 'folder' ? (v.editsFolder
213      ? `Menu changes save for ${v.path} only. Rows marked · this folder are set here; the rest follow all folders. Enter: back to all folders.`
214      : `Menu changes save for all folders.${owned ? ` Rows marked here: show what ${v.path} sets for itself.` : ''} Enter: save them for ${v.path} only.`)
215    : sessionNow !== null ? `${sessionNow}m for this session only; otherwise ${shown(focusedRow!, s.interval, s)}. r drops it.`
216    : v.focus === 'reset' && v.editsFolder ? `Drops ${v.path}'s own settings, so each follows all folders; press twice.`
217    : focusedRow?.help ?? BUTTON_HELP[v.focus] ?? ''
218  // r takes the focused setting back: this session's own interval first; in this folder's settings,
219  // one of its own back to all folders'; in all folders', a setting to its default, its custom value
220  // kept in its list
221  const back = !focusedRow ? undefined
222    : sessionNow !== null ? { label: `back to ${shown(focusedRow, s.interval, s)}`, run: act.dropSession }
223    : v.editsFolder ? (isOwn(focusedRow) ? { label: `back to ${shown(focusedRow, v.allFolders[focusedRow.key], s)} (all folders)`, run: () => act.resetRow(focusedRow.key) } : undefined)
224    : s[focusedRow.key] !== DEFAULTS[focusedRow.key] ? { label: `back to ${shown(focusedRow, DEFAULTS[focusedRow.key], s)}`, run: () => act.resetRow(focusedRow.key) }
225    : undefined
226  const keys = `1-${TABS.length}`
227  // a row's value, and where it comes from when not the settings on show: this session, or this folder
228  const valueOf = (r: Row) => {
229    if (r.key === 'interval' && v.sessionMinutes !== null) return `${v.sessionMinutes}m · this session`
230    const mark = !isOwn(r) ? '' : v.editsFolder ? ' · this folder' : ` · here: ${shown(r, v.own[r.key]!, s)}`
231    return shown(r, s[r.key], s) + (r.key === 'interval' ? intervalTail(s, v) : '') + mark
232  }
233
234  const line = (label: string, value: string, more = '') => `${label.padEnd(LABEL)}${value}${more}`
235  const tree = (
236    <Box flexDirection="column">
237      <Box columnGap={1} flexWrap="wrap">
238        {TABS.map((t, i) => (
239          <Button
240            plain
241            hotkey={`${i + 1}`}
242            key={`tab:${t.id}`}
243            dimColor={t.id !== tab.id}
244            onPress={() => act.tab(t.id)}
245          >
246            {t.title}
247          </Button>
248        ))}
249      </Box>
250      {rule}
251      {tab.id === 'beating' && (
252        <Button plain key="session" onPress={() => (act.at('session'), act.toggleSession())}>{line('This session', v.isOn ? 'on' : 'off')}</Button>
253      )}
254      <Button plain dimColor={!v.editsFolder} key="folder" onPress={() => (act.at('folder'), act.toggleFolder())}>
255        {line('Settings for', v.editsFolder ? `this folder · ${v.path}` : 'all folders')}
256      </Button>
257      {rows.map(r => (
258        <Box flexDirection="column">
259          <Button
260            plain
261            key={`row:${r.key}`}
262            onPress={() => (isFlip(r) ? (act.at(`row:${r.key}`), act.set({ [r.key]: r.values[r.values.indexOf(s[r.key]) === 0 ? 1 : 0] })) : act.open(r.key))}
263          >
264            {line(r.label, valueOf(r), isFlip(r) ? '' : ' ›')}
265          </Button>
266          {hexOf(r) && (
267            <Input
268              key={hexOf(r)!}
269              label={'  hex'.padEnd(LABEL)}
270              placeholder="#rrggbb"
271              value={String(s[hexOf(r)!])}
272              submitLabel="set"
273              onSubmit={val => (isHex(val.trim()) ? act.set({ [hexOf(r)!]: val.trim().toLowerCase() }) : act.refuse(`hex takes #rrggbb, not "${val.trim()}"`))}
274            />
275          )}
276        </Box>
277      ))}
278      {tab.preview && rule}
279      {tab.preview && preview(els, s, tab.preview, v.tick)}
280      {rule}
281      {(tab.id === 'beating' || back) && (
282        <Box gap={1}>
283          {tab.id === 'beating' && <Button key="beatNow" onPress={() => (act.at('beatNow'), act.beatNow())}>Beat now</Button>}
284          {tab.id === 'beating' && (
285            <Button key="reset" onPress={() => (act.at('reset'), act.reset())}>
286              {v.editsFolder ? (v.isResetArmed ? 'Press again to reset this folder' : 'Reset folder') : v.isResetArmed ? 'Press again to reset all' : 'Reset all'}
287            </Button>
288          )}
289          {back && (
290            <Button plain dimColor hotkey="r" key="resetRow" onPress={() => back.run()}>
291              {back.label}
292            </Button>
293          )}
294        </Box>
295      )}
296      {help && <Text dimColor>{help}</Text>}
297      {v.notice && <Text dimColor>{v.notice}</Text>}
298      <Text dimColor>
299        {!v.isTerminal ? `tab moves · enter or a click changes · ${keys} tabs · esc closes`
300          : v.focus.startsWith('tab:') ? `↑↓ tabs · enter or ${keys} opens · esc closes`
301          : `↑↓ move · enter changes · ${keys} tabs · esc back to the tabs`}
302      </Text>
303    </Box>
304  )
305  return { tree, ring }
306}
307
hooks/settings.ts 379 lines
1import type { BeatSettings, Look, Ttl } from '../types'
2import { STATUS_HEARTS, VARIANTS } from './animations'
3
4export const DEFAULTS: BeatSettings = {
5  defaultOn: false,
6  interval: 'auto',
7  stopAfterHours: 8,
8  stopAtUsage: 90,
9  skipSmall: false,
10  skipSmallTokens: 20_000,
11  heartPlacement: 'tail',
12  variant: 'classic',
13  showCount: true,
14  heartColor: 'claude',
15  heartHex: '#e6a8b9',
16  heartAnimate: true,
17  heartEffect: 'steady',
18  heartSpeed: 'normal',
19  heartTiming: 'lubdub',
20  statusLine: 'spaced',
21  showCountdown: true,
22  showTokens: true,
23  statusHeart: 'beat',
24  lineColor: 'claude',
25  lineHex: '#e6a8b9',
26  lineAnimate: true,
27  lineEffect: 'steady',
28  lineSpeed: 'normal',
29  lineTiming: 'lubdub',
30  onBeat: 'none',
31  onStop: 'log',
32  onModelSwitch: 'wait',
33}
34
35/** The interval `auto` beats at for each cache lifetime, in minutes: under it, with room for a slow request. */
36export const AUTO: Record<Ttl, number> = { '1h': 50, '5m': 4 }
37
38/** What the store keeps: the settings that differ from the defaults, so a new default reaches the rest. */
39export const changed = (s: BeatSettings): Partial<BeatSettings> =>
40  Object.fromEntries(Object.entries(s).filter(([k, v]) => v !== DEFAULTS[k as keyof BeatSettings]))
41
42/** The parts that draw, and the settings each of them looks by. */
43export type Part = 'heart' | 'line'
44const LOOK_KEYS = {
45  heart: { color: 'heartColor', customColor: 'heartHex', effect: 'heartEffect', animate: 'heartAnimate', speed: 'heartSpeed', timing: 'heartTiming' },
46  line: { color: 'lineColor', customColor: 'lineHex', effect: 'lineEffect', animate: 'lineAnimate', speed: 'lineSpeed', timing: 'lineTiming' },
47} as const satisfies Record<Part, Record<keyof Look, keyof BeatSettings>>
48
49/** How a part draws and moves: its own color, effect, animation, speed and timing. */
50export const lookOf = (s: BeatSettings, part: Part): Look => {
51  const k = LOOK_KEYS[part]
52  return { color: s[k.color], customColor: s[k.customColor], effect: s[k.effect], animate: s[k.animate], speed: s[k.speed], timing: s[k.timing] }
53}
54
55export const isObject = (x: unknown): x is Record<string, unknown> => typeof x === 'object' && x !== null && !Array.isArray(x)
56
57/** Store values from an older or hand-edited store fall back to the default one by one. */
58export function normalize(stored: unknown): BeatSettings {
59  const s: Record<string, unknown> = { ...DEFAULTS }
60  const from: Record<string, unknown> = isObject(stored) ? { ...stored } : {}
61  // before 0.7.0 one look served both parts: each part takes it, unless it has its own
62  for (const old of ['color', 'customColor', 'effect', 'animate', 'speed', 'timing'] as const) {
63    if (!(old in from)) continue
64    for (const part of ['heart', 'line'] as const) from[LOOK_KEYS[part][old]] ??= from[old]
65    delete from[old]
66  }
67  for (const [k, v] of Object.entries(from)) {
68    const isNumberFor = (...keys: string[]) => keys.includes(k) && typeof v === 'number'
69    if (k in DEFAULTS && (typeof v === typeof DEFAULTS[k as keyof BeatSettings] || isNumberFor('heartSpeed', 'lineSpeed', 'interval'))) s[k] = v
70  }
71  const out = s as BeatSettings
72  if (!VARIANTS.some(v => v.id === out.variant)) out.variant = DEFAULTS.variant
73  if (!STATUS_HEARTS.includes(out.statusHeart)) out.statusHeart = DEFAULTS.statusHeart
74  if (!['below', 'spaced', 'off'].includes(out.statusLine)) out.statusLine = DEFAULTS.statusLine
75  for (const key of ['heartSpeed', 'lineSpeed'] as const) {
76    if (typeof out[key] === 'number' && parseFrameMs(`${out[key]}`) === undefined) out[key] = DEFAULTS[key]
77  }
78  if (out.interval !== 'auto' && (typeof out.interval !== 'number' || parseMinutes(`${out.interval}`) === undefined)) out.interval = DEFAULTS.interval
79  if (!['wait', 'warm'].includes(out.onModelSwitch)) out.onModelSwitch = DEFAULTS.onModelSwitch
80  return out
81}
82
83export const FRAME_MS = { slow: 120, normal: 80, fast: 50 } as const
84/** A frame's time: a named speed's, or the milliseconds typed in. */
85export const frameMs = (look: Look) => (typeof look.speed === 'number' ? look.speed : FRAME_MS[look.speed])
86
87// theme keys with a shimmer pair in Claude Code's themes, so they follow the active theme
88export const THEME_COLORS = ['claude', 'permission', 'warning', 'fastMode', 'inactive'] as const
89// drawn as hex, a raw color every surface takes; the highlight is a lighter shade
90const PRESETS: Record<string, string> = {
91  red: '#e5534b', magenta: '#c678dd', yellow: '#e5c07b', green: '#98c379', cyan: '#56b6c2', white: '#d7d7d7',
92}
93export const PRESET_COLORS = Object.keys(PRESETS)
94export const COLORS = ['dim', ...THEME_COLORS, ...PRESET_COLORS, 'custom']
95
96const lighten = (hex: string) => {
97  const n = parseInt(hex.slice(1), 16)
98  const ch = (shift: number) => {
99    const c = (n >> shift) & 0xff
100    return Math.round(c + (255 - c) * 0.45).toString(16).padStart(2, '0')
101  }
102  return `#${ch(16)}${ch(8)}${ch(0)}`
103}
104export const isHex = (v: string) => /^#[0-9a-f]{6}$/i.test(v)
105
106/** A run of text in one style. `color` undefined with `dim` false is the terminal's own text color. */
107export type Span = { text: string; color?: string; dim: boolean }
108type Tone = { color?: string; dim: boolean }
109
110/** The color's resting tone and its highlight: the theme's shimmer, a bright preset, a lighter hex. */
111export function tones(s: Look): { base: Tone; hi: Tone } {
112  const c = s.color
113  if (c === 'dim') return { base: { dim: true }, hi: { dim: false } }
114  if ((THEME_COLORS as readonly string[]).includes(c)) return { base: { color: c, dim: false }, hi: { color: `${c}Shimmer`, dim: false } }
115  const hex = c === 'custom' ? (isHex(s.customColor) ? s.customColor : DEFAULTS.heartHex) : (PRESETS[c] ?? PRESETS.red!)
116  return { base: { color: hex, dim: false }, hi: { color: lighten(hex), dim: false } }
117}
118
119/** A frame with a filled heart in it: the beat of the animation, where `flash` lights up. */
120export const isLit = (frame: string) => /[♥❤]/.test(frame)
121
122/** Characters as a terminal cell sees them: a heart's text-presentation selector stays with its heart. */
123export const glyphs = (text: string) => [...text].reduce<string[]>((out, ch) => {
124  if (ch === '︎' && out.length) out[out.length - 1] += ch
125  else out.push(ch)
126  return out
127}, [])
128
129type Mode = 'flash' | 'flow' | 'both'
130const MODES: readonly Mode[] = ['flash', 'flow', 'both']
131export const EPISODE = 40 // ticks one mixed mode lasts: 3.2s at normal speed
132
133/**
134 * The mode `mixed` plays at `tick`: drawn at random for each episode, never twice in a row. A hash of
135 * the episode's number, not a stored roll, so every drawing at one tick agrees.
136 */
137export function mixedMode(tick: number): Mode {
138  const roll = (n: number) => {
139    let h = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b)
140    h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35)
141    return ((h ^ (h >>> 16)) >>> 0) % 2
142  }
143  // each episode steps one or two modes on from the last, so it always changes
144  let i = 0
145  for (let n = 1; n <= Math.floor(tick / EPISODE); n++) i = (i + 1 + roll(n)) % 3
146  return MODES[i]!
147}
148
149/**
150 * Styles `text` by the color and effect: steady holds the resting tone, flash lights the whole
151 * text while `lit`, flow sweeps a three-glyph highlight across it with `tick`, as the spinner's
152 * shimmer does. Both does the two at once, the sweep dipping to the resting tone while lit;
153 * mixed plays flash, flow or both, a few seconds of each.
154 */
155export function spans(text: string, s: Look, tick: number, lit: boolean): Span[] {
156  const { base, hi } = tones(s)
157  if (s.effect === 'steady' || !s.animate) return [{ text, ...base }]
158  const mode = s.effect === 'mixed' ? mixedMode(tick) : s.effect
159  if (mode === 'flash') return [{ text, ...(lit ? hi : base) }]
160  const [rest, sweep] = mode === 'both' && lit ? [hi, base] : [base, hi]
161  const g = glyphs(text)
162  const at = (tick % (g.length + 6)) - 3
163  const out: Span[] = []
164  g.forEach((ch, i) => {
165    const tone = Math.abs(i - at) <= 1 ? sweep : rest
166    const last = out.at(-1)
167    if (last && last.color === tone.color && last.dim === tone.dim) last.text += ch
168    else out.push({ text: ch, ...tone })
169  })
170  return out
171}
172
173/** Reads a typed number into a setting's unit, undefined outside its range; it carries that unit and range. */
174export type Reader = ((text: string) => number | undefined) & { unit: string; min: number; max: number }
175
176/**
177 * Reads a typed number with an optional unit (`units` maps each to its scale; '' is none), kept
178 * when it lands within [min, max]: '35k' → 35000 tokens, '90m' → 1.5 hours.
179 */
180function reader(unit: string, units: Record<string, number>, min: number, max: number, isWhole: boolean): Reader {
181  const read = (text: string): number | undefined => {
182    const m = /^(\d+(?:\.\d+)?)\s*([a-z%]*)$/i.exec(text.trim().replaceAll(',', ''))
183    const scale = m ? units[m[2]!.toLowerCase()] : undefined
184    if (scale === undefined) return undefined
185    const n = Number(m![1]) * scale
186    const v = isWhole ? Math.round(n) : Math.round(n * 100) / 100
187    return v >= min && v <= max ? v : undefined
188  }
189  return Object.assign(read, { unit, min, max })
190}
191
192export const parseTokens = reader('tokens', { '': 1, k: 1e3, m: 1e6 }, 1_000, 1_000_000, true)
193export const parseMinutes = reader('minutes', { '': 1, m: 1, min: 1 }, 1, 55, true) // under the hour the cache lives
194export const parseHours = reader('hours', { '': 1, h: 1, m: 1 / 60, min: 1 / 60 }, 0.5, 48, false)
195export const parsePercent = reader('percent', { '': 1, '%': 1 }, 10, 100, true)
196export const parseFrameMs = reader('ms a frame', { '': 1, ms: 1 }, 20, 500, true)
197
198/** 184000 → 184k, 1250000 → 1.3M. */
199export const tokens = (n: number) =>
200  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`
201
202export type Value = string | number | boolean
203/**
204 * One row of the settings pane. A row of two choices (on/off among them) flips in place on Enter;
205 * one of more, or that takes a typed value, opens a list, whose focused choice the preview shows
206 * before it is picked. `help` is what the row does, shown while it is focused and above its list.
207 */
208export type Row = {
209  key: keyof BeatSettings
210  label: string
211  name?: string // the label out of its tab, where it would be unclear: in Claude's transcript line
212  values: readonly Value[]
213  help: string
214  show?: (s: BeatSettings) => boolean
215  fmt?: (v: Value, s: BeatSettings) => string
216  custom?: { placeholder: string; parse: Reader } // a typed value besides the choices
217}
218
219export type Preview = 'heart' | 'status' | 'both'
220export type Tab = { id: string; title: string; rows: readonly Row[]; preview?: Preview }
221
222const onOff = (v: Value) => (v ? 'on' : 'off')
223const ALERTS = ['none', 'log', 'toast', 'both']
224const alert = (v: Value) => (v === 'both' ? 'log + toast' : `${v}`)
225
226/** The pane's own row on the Beating tab, not a setting: whether this session beats. */
227export const SESSION_HELP = "Beats for this session alone. New sessions start as 'New sessions start' says."
228
229const TERMINAL_ONLY = 'The desktop app draws no heart under the prompt: there the turn line carries it.'
230
231/** The settings a part looks by, each its own: color, animation, effect, speed, timing. */
232function lookRows(part: Part, what: string, shown: (s: BeatSettings) => boolean): Row[] {
233  const k = LOOK_KEYS[part]
234  const title = part === 'heart' ? 'Prompt heart' : 'Turn line'
235  const moving = (s: BeatSettings) => shown(s) && (s[k.animate] as boolean)
236  // the heart on the hint line is drawn dim, whatever its color
237  const colored = part === 'heart' ? shown : (s: BeatSettings) => s.statusLine !== 'off'
238  return [
239    {
240      key: k.color, label: 'Color', name: `${title} color`, values: COLORS, show: colored, fmt: (v, s) => (v === 'custom' ? `custom ${s[k.customColor]}` : `${v}`),
241      help: `The color of ${what}: dim, your theme's, a preset, or any hex color.`,
242    },
243    {
244      key: k.animate, label: 'Animate', name: `${title} animate`, values: [true, false], fmt: onOff,
245      show: part === 'heart' ? () => true : (s: BeatSettings) => s.statusLine !== 'off',
246      help: `Animates ${what}. Off, it holds still.`,
247    },
248    {
249      key: k.effect, label: 'Effect', name: `${title} effect`, values: ['steady', 'flash', 'flow', 'mixed'], show: s => moving(s) && colored(s),
250      help: 'steady; flash on each beat; flow, a shimmer sweeping across; mixed switches between them.',
251    },
252    {
253      key: k.speed, label: 'Speed', name: `${title} speed`, values: ['slow', 'normal', 'fast'], show: part === 'heart' ? (s: BeatSettings) => s[k.animate] as boolean : moving,
254      fmt: v => (typeof v === 'number' ? `${v}ms a frame` : `${v} · ${FRAME_MS[v as keyof typeof FRAME_MS]}ms`),
255      help: `How fast ${what} plays: a speed, or a frame time.`,
256      custom: { placeholder: 'e.g. 65ms', parse: parseFrameMs },
257    },
258    {
259      key: k.timing, label: 'Timing', name: `${title} timing`, values: ['lubdub', 'linear'], show: part === 'heart' ? (s: BeatSettings) => s[k.animate] as boolean : moving,
260      fmt: v => (v === 'lubdub' ? 'lub-dub' : 'linear'),
261      help: `lub-dub beats twice, then rests, and suits the hearts; linear plays evenly, and suits the line animations (${VARIANTS.filter(x => x.isEndless).map(x => x.name).join(', ')}).`,
262    },
263  ]
264}
265
266export const TABS: readonly Tab[] = [
267  {
268    id: 'beating', title: 'Beating',
269    rows: [
270      { key: 'defaultOn', label: 'New sessions start', values: [false, true], fmt: onOff, help: 'Whether new sessions start beating. Open sessions keep what they have.' },
271      {
272        key: 'interval', label: 'Beat after idle', values: ['auto', 4, 15, 30, 45, 55], fmt: v => (v === 'auto' ? 'auto' : `${v}m`),
273        help: `How long you're idle before a beat. auto fits your cache: every ${AUTO['1h']}m on a one-hour cache, every ${AUTO['5m']}m on a five-minute one.`,
274        custom: { placeholder: 'e.g. 35m', parse: parseMinutes },
275      },
276      {
277        key: 'onModelSwitch', label: 'After /model', values: ['wait', 'warm'],
278        fmt: v => (v === 'wait' ? 'wait for your next turn' : 'warm the new model'),
279        help: "After /model while you're idle: wait for your next message, or have the next beat write the new model's cache, at the cost your message would pay.",
280      },
281    ],
282  },
283  {
284    id: 'limits', title: 'Limits',
285    rows: [
286      {
287        key: 'stopAfterHours', label: 'Stop after idle', values: [1, 4, 8, 24], fmt: v => `${v}h`,
288        help: 'Beating stops after this long without a message from you.',
289        custom: { placeholder: 'e.g. 10h or 90m', parse: parseHours },
290      },
291      {
292        key: 'stopAtUsage', label: 'Stop at usage', values: [80, 90, 100], fmt: v => `${v}%`,
293        help: 'Beating stops once any of your usage limits reaches this.',
294        custom: { placeholder: 'e.g. 85%', parse: parsePercent },
295      },
296      { key: 'skipSmall', label: 'Skip small chats', values: [false, true], fmt: onOff, help: "Doesn't beat chats smaller than the size below." },
297      {
298        key: 'skipSmallTokens', label: '  smaller than', values: [10_000, 20_000, 50_000, 100_000],
299        show: s => s.skipSmall, fmt: v => `${tokens(Number(v))} tokens`,
300        help: 'The smallest chat kept warm.',
301        custom: { placeholder: 'e.g. 35k', parse: parseTokens },
302      },
303    ],
304  },
305  {
306    id: 'heart', title: 'Prompt heart', preview: 'heart',
307    rows: [
308      {
309        key: 'heartPlacement', label: 'Placement', name: 'Prompt heart placement', values: ['tail', 'line'], fmt: v => (v === 'tail' ? 'hint line · dim' : 'own line'),
310        help: `At the end of the hint line under the prompt, drawn dim, or on a line of its own, in color. ${TERMINAL_ONLY}`,
311      },
312      {
313        key: 'variant', label: 'Animation', name: 'Prompt heart animation', values: VARIANTS.map(v => v.id), fmt: v => VARIANTS.find(x => x.id === v)?.name ?? `${v}`,
314        help: `What the heart under the prompt plays. ${TERMINAL_ONLY}`,
315      },
316      { key: 'showCount', label: 'Beat count', values: [true, false], fmt: onOff, help: `Shows ×3, the beats so far, beside the heart. ${TERMINAL_ONLY}` },
317      ...lookRows('heart', 'the heart', s => s.heartPlacement === 'line'),
318    ],
319  },
320  {
321    id: 'status', title: 'Turn line', preview: 'status',
322    rows: [
323      {
324        key: 'statusLine', label: 'Show', name: 'Turn line', values: ['spaced', 'below', 'off'],
325        fmt: v => ({ spaced: 'after a blank line', below: 'right below the turn row', off: 'off' })[v as string]!,
326        help: 'Where the line goes under your latest turn, or off. In the desktop app it sits above the prompt.',
327      },
328      { key: 'showCountdown', label: 'Countdown', values: [true, false], show: s => s.statusLine !== 'off', fmt: onOff, help: 'Shows the time to the next beat.' },
329      { key: 'showTokens', label: 'Tokens kept', values: [true, false], show: s => s.statusLine !== 'off', fmt: onOff, help: 'Shows how much the last beat kept warm, as · 347k cached.' },
330      {
331        key: 'statusHeart', label: 'Its heart', name: 'Turn line heart', values: STATUS_HEARTS, show: s => s.statusLine !== 'off' && s.lineAnimate,
332        fmt: v => (v === 'beat' ? 'one heart, beating' : v === 'off' ? 'still' : VARIANTS.find(x => x.id === v)?.name ?? `${v}`),
333        help: 'What the heart starting the line plays. One heart beating keeps the words still; a wider animation moves them as it plays.',
334      },
335      ...lookRows('line', 'the line', s => s.statusLine !== 'off'),
336    ],
337  },
338  {
339    id: 'alerts', title: 'Alerts',
340    rows: [
341      { key: 'onBeat', label: 'On a beat', values: ALERTS, fmt: alert, help: 'How a beat landing is told: a line in the transcript (log), a toast, both, or nothing.' },
342      { key: 'onStop', label: 'On stop', values: ALERTS, fmt: alert, help: 'How beating stopping on its own is told, and why.' },
343    ],
344  },
345]
346
347export const rowOf = (key: keyof BeatSettings) => {
348  for (const tab of TABS) for (const row of tab.rows) if (row.key === key) return { tab, row }
349  return undefined
350}
351
352/** A row Enter flips in place: two choices and no typed value. Any other opens its list. */
353export const isFlip = (row: Row) => row.values.length === 2 && !row.custom
354
355/**
356 * `value` as `key` takes it, the way the pane does: one of the row's choices, or a custom value its
357 * reader accepts (35000, or '35k'); a hex for the custom color. Undefined when it takes no such value.
358 */
359/** The hex each color row takes when it is custom. */
360export const HEX_OF: Partial<Record<keyof BeatSettings, keyof BeatSettings>> = { heartColor: 'heartHex', lineColor: 'lineHex' }
361export const HEX_KEYS: readonly string[] = Object.values(HEX_OF)
362
363export function accept(key: string, value: unknown): Value | undefined {
364  if (HEX_KEYS.includes(key)) return typeof value === 'string' && isHex(value) ? value.toLowerCase() : undefined
365  const row = rowOf(key as keyof BeatSettings)?.row
366  if (!row) return undefined
367  if (row.values.includes(value as Value)) return value as Value
368  return row.custom && (typeof value === 'number' || typeof value === 'string') ? row.custom.parse(String(value)) : undefined
369}
370
371/** A folder's own settings from the store: those of them the menu would take. */
372export function normalizeOwn(stored: unknown): Partial<BeatSettings> {
373  const kept = Object.entries(isObject(stored) ? stored : {}).flatMap(([k, v]) => {
374    const value = accept(k, v)
375    return value === undefined ? [] : [[k, value]]
376  })
377  return Object.fromEntries(kept)
378}
379
hooks/tools.ts 209 lines
1// The tools Claude calls to read and change cachebeat: their specs, drawn from the pane's rows so a
2// range is written once, and the reading of a `set` call's input.
3import type { ToolSpec } from 'claude-code'
4import type { BeatSettings } from '../types'
5import { shown } from './pane'
6import type { Reader, Value } from './settings'
7import { AUTO, DEFAULTS, HEX_KEYS, accept, isObject, parseMinutes, rowOf } from './settings'
8
9/** Each setting, for the model; the unit and range are added from its reader. */
10const ABOUT: Record<keyof BeatSettings, string> = {
11  defaultOn: 'New sessions start beating; open sessions keep theirs.',
12  interval:
13    `Minutes idle before a beat, for sessions without their own; auto beats at ${AUTO['1h']} on a one-hour cache and ${AUTO['5m']} on a five-minute one, reading which the session has (state's cacheTtl).`,
14  stopAfterHours: 'Beating stops after this long without a message from the user.',
15  stopAtUsage: 'Beating stops once any usage limit reaches this.',
16  skipSmall: 'Skips beating chats smaller than skipSmallTokens.',
17  skipSmallTokens: "The smallest chat kept warm while skipSmall is on; setting it doesn't turn skipSmall on.",
18  heartPlacement: 'The prompt heart: tail, at the end of the hint line, always dim; line, on its own line, in color. Terminal only.',
19  variant: "The prompt heart's animation. Terminal only.",
20  showCount: 'Shows the beat count beside the prompt heart. Terminal only.',
21  heartColor: 'The prompt heart\'s color when it has its own line: dim, a theme color, a preset, or custom (heartHex).',
22  heartHex: "The prompt heart's color when heartColor is custom; setting it doesn't set heartColor to custom.",
23  heartAnimate: 'Animates the prompt heart.',
24  heartEffect: 'The prompt heart on its own line: steady; flash on each beat; flow, a shimmer sweeping across; mixed switches between them.',
25  heartSpeed: "The prompt heart's animation speed: a name, or a frame time.",
26  heartTiming: 'The prompt heart: lubdub beats twice, then rests; linear plays evenly.',
27  statusLine: 'The turn line, under the latest turn: spaced (after a blank line), below (right under it), or off. On desktop it sits above the prompt.',
28  showCountdown: 'Shows the time to the next beat in the turn line.',
29  showTokens: 'Shows the tokens the last beat kept warm in the turn line.',
30  statusHeart: "What the heart starting the turn line plays: beat (one heart, filling in time), off (still), or one of the prompt heart's animations.",
31  lineColor: 'The turn line\'s color: dim, a theme color, a preset, or custom (lineHex).',
32  lineHex: "The turn line's color when lineColor is custom; setting it doesn't set lineColor to custom.",
33  lineAnimate: "Animates the turn line's heart and effect.",
34  lineEffect: 'The turn line: steady; flash on each beat; flow, a shimmer sweeping across; mixed switches between them.',
35  lineSpeed: "The turn line's animation speed: a name, or a frame time.",
36  lineTiming: "The turn line's heart: lubdub beats twice, then rests; linear plays evenly.",
37  onBeat: 'How a beat is announced: a transcript line (log), a toast, both, or none.',
38  onStop: 'How beating stopping on its own is announced.',
39  onModelSwitch: "After /model while idle: wait for the user's next turn, or have the next beat write the new model's cache (a full cache write, the one that turn would make).",
40}
41
42const KEYS = Object.keys(ABOUT) as (keyof BeatSettings)[]
43const range = (r: Reader) => `${r.min}–${r.max} ${r.unit}`
44const names = (values: readonly Value[]) => values.filter(v => typeof v === 'string')
45
46/** What a setting takes, as schemas: on/off, its named choices, or a number in its reader's range, with or beside names. */
47function kinds(key: keyof BeatSettings): Record<string, unknown>[] {
48  if (HEX_KEYS.includes(key)) return [{ type: 'string', pattern: '^#[0-9a-fA-F]{6}$' }]
49  const { row } = rowOf(key)!
50  if (typeof row.values[0] === 'boolean') return [{ type: 'boolean' }]
51  if (!row.custom) return [{ enum: [...row.values] }]
52  const r = row.custom.parse
53  const named = names(row.values)
54  return [...(named.length ? [{ enum: named }] : []), { type: 'number', minimum: r.min, maximum: r.max }]
55}
56
57/** A setting's schema: what it takes, or null to reset it. */
58function field(key: keyof BeatSettings): Record<string, unknown> {
59  const r = HEX_KEYS.includes(key) ? undefined : rowOf(key)!.row.custom?.parse
60  return { anyOf: [...kinds(key), { type: 'null' }], description: r ? `${ABOUT[key]} (${range(r)})` : ABOUT[key] }
61}
62
63/** What a setting takes, each choice in words, for a refusal. */
64function takes(key: keyof BeatSettings): string[] {
65  if (HEX_KEYS.includes(key)) return ['a hex color (#rrggbb)']
66  const { row } = rowOf(key)!
67  if (typeof row.values[0] === 'boolean') return ['true', 'false']
68  if (!row.custom) return row.values.map(String)
69  return [...names(row.values), range(row.custom.parse)]
70}
71
72/** `a, b, or c`; `a or b`. */
73const either = (choices: string[]) =>
74  choices.length < 3 ? choices.join(' or ') : `${choices.slice(0, -1).join(', ')}, or ${choices.at(-1)}`
75
76const object = (properties: Record<string, unknown>) => ({ type: 'object', properties, additionalProperties: false })
77
78export const STATE: ToolSpec = {
79  name: 'state',
80  description: [
81    "cachebeat's state in this session, every setting as it applies here, and this folder's own settings.",
82    [
83      '`settings` are the values in effect in this session: this folder\'s own over those for all folders. `folder` is this session\'s folder (`path`) and the settings it has of its own (`own`). `allFolders`, shown while the folder has any of its own, has the settings for all folders.',
84      "`nextBeat` is `in 42m` (mid-turn too: counted from the end of the turn's last request, for a turn that goes quiet), `50m after the request on its way` (a request of the turn is being answered), `after this turn` (a turn whose beats wait for its end), `after the next turn` (nothing cached to keep warm yet), or null when off or skipping.",
85      '`intervalFrom` is `session` when this session has its own interval, `folder` when it follows this folder\'s own, `all folders` when it follows the interval for all folders in minutes, and `auto` when that is auto.',
86      "`cacheTtl` is how long this session's cache lives, `1h` or `5m`, worked out on each call from Claude Code's cache settings and whether a subscription is within its usage; an auto interval beats within it (50 or 4 minutes).",
87      '`skipping`, when set, says why beats skip this chat (under the skipSmallTokens minimum).',
88      "`paused`, when set, says why beats wait for the user's next turn (a model switch, a compaction); only that turn ends it, not `set`.",
89      'A beat re-sends the conversation as this session last sent it, with one short line tagged `[cachebeat]` asking for a one-character reply, which is thrown away. It reads the cached conversation (`lastBeatReadTokens`, the last beat\'s) and writes only what wasn\'t cached (`lastBeatWrittenTokens`), usually a few tokens; both are null before the first beat. `defaults` has the default of each setting that differs from it.',
90    ].join(' '),
91  ].join('\n\n'),
92  inputSchema: object({}),
93}
94
95export const SET: ToolSpec = {
96  name: 'set',
97  description: [
98    "Changes cachebeat, which keeps this session's prompt cache warm while it sits idle by sending a small background request, a beat, shortly before the cache would expire. Change only what the user asks for.",
99    '`session` is this session alone. `settings` is saved for all folders and used by every session, open ones included: `settings.interval` is the default interval, `settings.defaultOn` whether new sessions start on (open sessions keep theirs). `folder` is saved for this session\'s folder alone (state\'s `folder.path`), takes any setting, and wins over `settings` there; `null` for one setting drops it, so it follows all folders again, and `folder: null` drops every one. In `settings`, `null` puts a setting back to its default. When you change a setting, say where it applies: all folders, or this folder by its path, since a subfolder or another worktree has settings of its own.',
100    'A request that names no scope ("turn it on", "beat every 20 minutes") is for this session. "In this repo", "in this folder", "here" or "for this project" mean `folder`. "Default", "new sessions", "every session", "everywhere", "always" or "from now on" mean `settings`. If you can\'t tell which the user means, ask. A change to `settings` doesn\'t reach a setting this folder has its own of (`state`\'s `folder.own`): tell the user.',
101    "Each beat counts toward the user's usage. The first time in a conversation a change starts beating or changes how often a beating session beats, say so once.",
102    'Setting `intervalMinutes` turns beating on too, unless `enabled: false` comes with it. Saving an interval in `settings` or `folder` drops this session\'s own, so it beats at the saved one, unless `intervalMinutes` comes with it; `intervalMinutes: null` alone makes it follow the settings.',
103    'Nothing changes if any value is invalid, and the refusal names each one. Subagents can read `state` but not call this. Returns what changed, this session\'s state, and the changed settings: for all folders, and for this folder with its `path`, which you name to the user.',
104  ].join('\n\n'),
105  inputSchema: object({
106    session: object({
107      enabled: { type: 'boolean', description: 'Beat in this session.' },
108      intervalMinutes: {
109        anyOf: [{ type: 'number', minimum: parseMinutes.min, maximum: parseMinutes.max }, { type: 'null' }],
110        description: `This session's interval in minutes, which turns beating on; null follows settings.interval, auto included. (${range(parseMinutes)})`,
111      },
112    }),
113    settings: object(Object.fromEntries(KEYS.map(k => [k, field(k)]))),
114    folder: {
115      anyOf: [object(Object.fromEntries(KEYS.map(k => [k, field(k)]))), { type: 'null' }],
116      description: "This folder's own settings, as `settings` takes them; a setting's null drops it, so it follows all folders, and null for the whole drops every one.",
117    },
118  }),
119}
120
121/**
122 * A `set` call's input, as read: this session's switch and interval (null follows the settings), the
123 * settings to save for all folders, and this folder's own to save and drop (null drops every one).
124 */
125export type SetChange = {
126  enabled?: boolean; intervalMinutes?: number | null; patch: Partial<BeatSettings>
127  folder?: { own: Partial<BeatSettings>; drop: (keyof BeatSettings)[] } | null
128}
129
130/** Reads a `set` call's input whole, or says every value it refuses. */
131export function parseSet(input: { session?: unknown; settings?: unknown; folder?: unknown }): SetChange | { error: string } {
132  const change: SetChange = { patch: {} }
133  const bad: string[] = []
134  const said = (v: unknown) => JSON.stringify(v)
135  for (const part of ['session', 'settings'] as const) {
136    if (input[part] !== undefined && !isObject(input[part])) bad.push(`${part} is an object, not ${said(input[part])}`)
137  }
138  if (input.folder !== undefined && input.folder !== null && !isObject(input.folder)) bad.push(`folder is an object or null, not ${said(input.folder)}`)
139  const session = isObject(input.session) ? input.session : {}
140  const settings = isObject(input.settings) ? input.settings : {}
141  for (const [k, v] of Object.entries(session)) {
142    if (k === 'enabled') {
143      if (typeof v === 'boolean') change.enabled = v
144      else bad.push(`session.enabled takes true or false, not ${said(v)}`)
145    } else if (k === 'intervalMinutes') {
146      const m = v === null ? null : typeof v === 'number' || typeof v === 'string' ? parseMinutes(String(v)) : undefined
147      if (m !== undefined) change.intervalMinutes = m
148      else bad.push(`session.intervalMinutes takes ${range(parseMinutes)} or null, not ${said(v)}`)
149    } else bad.push(`session has no ${k}`)
150  }
151  for (const [k, v] of Object.entries(settings)) {
152    if (!(k in ABOUT)) {
153      bad.push(`settings has no ${k}`)
154      continue
155    }
156    const key = k as keyof BeatSettings
157    const value = v === null ? DEFAULTS[key] : accept(key, v)
158    if (value === undefined) bad.push(`settings.${key} takes ${either([...takes(key), 'null'])}, not ${said(v)}`)
159    else change.patch = { ...change.patch, [key]: value }
160  }
161  if (input.folder === null) change.folder = null
162  else if (isObject(input.folder)) {
163    const folder: NonNullable<SetChange['folder']> = { own: {}, drop: [] }
164    for (const [k, v] of Object.entries(input.folder)) {
165      if (!(k in ABOUT)) {
166        bad.push(`folder has no ${k}`)
167        continue
168      }
169      const key = k as keyof BeatSettings
170      const value = v === null ? null : accept(key, v)
171      if (value === undefined) bad.push(`folder.${key} takes ${either([...takes(key), 'null'])}, not ${said(v)}`)
172      else if (value === null) folder.drop.push(key)
173      else folder.own = { ...folder.own, [key]: value }
174    }
175    change.folder = folder
176  }
177  // an interval of its own is asked for to beat at, as `/cachebeat <minutes>` takes it
178  if (typeof change.intervalMinutes === 'number') change.enabled ??= true
179  return bad.length ? { error: `nothing changed: ${bad.join('; ')}` } : change
180}
181
182/** A setting's name as the pane labels it, or as it reads out of its tab. */
183export function label(key: keyof BeatSettings) {
184  if (HEX_KEYS.includes(key)) return key === 'heartHex' ? 'Prompt heart color' : 'Turn line color'
185  const { row } = rowOf(key)!
186  return row.name ?? row.label.trim()
187}
188
189/**
190 * A `set` call in one line, as the transcript shows it, `path` naming this folder:
191 * `this session on, every 20m · all folders: Beat after idle 30m · this folder (…/api): New sessions start on`.
192 */
193export function summary(change: SetChange, s: BeatSettings, path: string) {
194  const here = [
195    change.enabled !== undefined && (change.enabled ? 'on' : 'off'),
196    change.intervalMinutes !== undefined && (change.intervalMinutes === null ? 'its own interval dropped' : `every ${change.intervalMinutes}m`),
197  ].filter(Boolean)
198  const each = (patch: Partial<BeatSettings>) => (Object.entries(patch) as [keyof BeatSettings, Value][]).map(([key, v]) =>
199    `${label(key)} ${HEX_KEYS.includes(key) ? v : shown(rowOf(key)!.row, v, s)}`,
200  )
201  const saved = each(change.patch)
202  const own = change.folder ? [...each(change.folder.own), ...change.folder.drop.map(k => `${label(k)} as all folders`)] : []
203  return [
204    here.length ? `this session ${here.join(', ')}` : '',
205    saved.length ? `all folders: ${saved.join(', ')}` : '',
206    change.folder === null ? `this folder (${path}) follows all folders again` : own.length ? `this folder (${path}): ${own.join(', ')}` : '',
207  ].filter(Boolean).join(' · ') || 'no change'
208}
209
types/index.d.ts 101 lines
1export type Pulse = 'hidden' | 'waiting' | 'armed'
2
3/** What survives a reload of the module (a file save). */
4export type Saved = {
5  enabled: boolean
6  idle: number | null // this session's interval in ms; null follows the settings
7  lastReal: number | null
8  lastWarm: number | null
9  lastRead: number | null // tokens the last beat read from the cache
10  lastWrote: number | null // tokens the last beat wrote to the cache: what wasn't cached
11  nextAt: number | null
12  beats: number // in this session
13  row: string | null // the latest turn's closing row, which carries the status line
14  small: string | null // why the context is not kept warm, while it is under the minimum
15  isCacheShort: boolean // a beat found this session's cache lasts five minutes, whatever its settings say
16  paused: string | null // why beats wait for the next turn though the cache was warm: a model switch, a compaction
17  warmModel: string | null // the model the last request ran on, whose cache a beat keeps warm
18  tail: string | null // how the conversation ended after the last turn: another ending means /rewind took it back
19  asked: number | null // when the user last sent a message (a turn's start): Stop after idle counts from it
20  turns: number // turns this conversation has had: after its first, Claude Code can cache it anew out of a beat's reach
21}
22
23/** How long the main conversation's prompt cache lives. */
24export type Ttl = '5m' | '1h'
25
26/** How an event is told: a line in the transcript, a toast, both, or not at all. */
27export type Alert = 'none' | 'log' | 'toast' | 'both'
28
29export type Effect = 'steady' | 'flash' | 'flow' | 'mixed'
30export type Speed = 'slow' | 'normal' | 'fast' | number // a number: ms a frame
31export type Timing = 'linear' | 'lubdub'
32
33/** How one part draws and moves: the heart under the prompt, or the turn line. */
34export type Look = { color: string; customColor: string; effect: Effect; animate: boolean; speed: Speed; timing: Timing }
35
36/** The settings: kept in the plugin's store for all folders, and a folder may have its own of any of them. */
37export type BeatSettings = {
38  defaultOn: boolean // new sessions start beating
39  interval: number | 'auto' // minutes of idle before a beat; auto fits the cache's lifetime
40  stopAfterHours: number // since the last real turn
41  stopAtUsage: number // percent of any rate-limit window
42  skipSmall: boolean
43  skipSmallTokens: number
44  // the heart under the prompt
45  heartPlacement: 'tail' | 'line'
46  variant: string
47  showCount: boolean
48  heartColor: string // 'dim', a theme key, a preset, or 'custom'
49  heartHex: string // #rrggbb, when heartColor is custom
50  heartAnimate: boolean
51  heartEffect: Effect
52  heartSpeed: Speed
53  heartTiming: Timing
54  // the line under the latest turn
55  statusLine: 'below' | 'spaced' | 'off'
56  showCountdown: boolean
57  showTokens: boolean
58  statusHeart: string // what the heart starting the line plays: beat, off, or an animation's id
59  lineColor: string
60  lineHex: string
61  lineAnimate: boolean
62  lineEffect: Effect
63  lineSpeed: Speed
64  lineTiming: Timing
65  onBeat: Alert
66  onStop: Alert
67  onModelSwitch: 'wait' | 'warm' // after /model while idle: wait for the next turn, or have the next beat write the new model's cache
68}
69
70/** A session's folder, and the settings it has of its own: those win over the ones for all folders there. */
71export type Folder = { root: string; own: Partial<BeatSettings> }
72
73/** Where the settings pane is: a tab, and the row whose picker is open over it. */
74export type PanePage = { tab: string; picker: keyof BeatSettings | null }
75
76declare module 'claude-code' {
77  /** The tools this plugin registers, as the model calls them; `parseSet` checks every value. */
78  interface McpToolInputs {
79    mcp__cachebeat__state: Record<string, never>
80    mcp__cachebeat__set: {
81      session?: { enabled?: boolean; intervalMinutes?: number | null }
82      settings?: { [K in keyof BeatSettings]?: BeatSettings[K] | null } // null resets to the default
83      folder?: { [K in keyof BeatSettings]?: BeatSettings[K] | null } | null // null follows all folders; the whole null drops every one
84    }
85  }
86  interface PluginState {
87    cachebeat: {
88      pulse: Pulse
89      saved: Saved | null
90      frame: number
91      line: string
92      lineFrame: number // the turn line's own animation clock
93      settings: BeatSettings // as they apply here: this folder's own over those for all folders
94      folder: Folder // this session's folder and its own settings
95      tick: number // the settings pane's preview clock
96      page: PanePage
97      focus: string // the key of the pane's focused element, or ''
98    }
99  }
100}
101