SLOPSHOPPER

cache-timer

Prompt cache hit rate for the last request, and whether the cache is still warm with a countdown, above the prompt

bandcommandtimer
v0.2.2no licenseupdated 2026-10-15katipally/modz/mods/ui/cache-timer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-timer
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /cache-ttl ⎿ cache-timer: Cache ttl is 1h. Use /cache-ttl 5m or /cache-ttl 1h. cache – · – ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
cache – · – ⟨Claude Code's own drawing⟩
README

cache-timer

Prompt cache hit rate for the main agent's last request, and how long until the cache goes cold.

cache 98% · 54m

Install

/plugin install cache-timer --marketplace katipally/modz

Update, then restart your sessions (more in the main README):

claude plugin marketplace update modz
claude plugin update cache-timer@modz
  • The time is green while the cache is warm and counts down from the last request; it turns red (2m ago) once the cache has gone cold.
  • The percentage turns yellow under 90% and red under 70%.
  • Claude Code does not report the cache lifetime: set it with /cache-ttl 5m or /cache-ttl 1h (default 1h, remembered).
  • Subagent requests are ignored.
  • Until the first request of a new session the tile reads cache – · –: Claude Code has no cache figures before a request is made. When you resume a session the countdown starts at once from the time since the last response, and the hit rate too if Claude Code has that response's token counts, otherwise it shows – until the next request.
Source 2 files
hooks/register.tsx 176 lines
1import { atom, read, update } from 'claude-code'
2import type { Register, BoxProps, ElementConstructor, EngineInterface, RenderElement, RenderNode, Timer, ModelUsage } from 'claude-code'
3
4import type { Request } from '../types'
5
6// Claude Code's prompt cache lives 5 minutes or 1 hour depending on the account; the engine does not say which.
7const TTL_CHOICES: Record<string, number> = { '5m': 5, '1h': 60 }
8const TINT = 'suggestion'
9const TICK_MS = 5000
10
11const last = atom({ plugin: 'cache-timer', key: 'last' } as const, null)
12const now = atom({ plugin: 'cache-timer', key: 'now' } as const, 0)
13const twinkle = atom({ plugin: 'cache-timer', key: 'twinkle' } as const, 0)
14
15// A request that reads the cache twinkles for a moment, counting frames down to nothing.
16const SPARKLE = ['✦', '✧', '⋆', '✧']
17const TWINKLE_MS = 180
18const TWINKLE_FRAMES = 8
19let twinkler: Timer | undefined
20const sparkle = async ($: EngineInterface) => {
21  twinkler?.cancel()
22  await update($, twinkle, () => TWINKLE_FRAMES)
23  twinkler = $.clock.every(TWINKLE_MS, async () => {
24    await update($, twinkle, n => Math.max(0, n - 1))
25    if ((await read($, twinkle)) === 0) twinkler?.cancel()
26  })
27}
28const ttlMin = atom({ plugin: 'cache-timer', key: 'ttlMin' } as const, 60)
29
30
31// "1h 5m" past an hour, "58m" past two minutes, then "1m 40s" and "40s" for the last stretch.
32const span = (ms: number) => {
33  const s = Math.max(0, Math.round(ms / 1000))
34  const [h, m] = [Math.floor(s / 3600), Math.floor((s % 3600) / 60)]
35  return h ? `${h}h ${m}m` : m >= 2 ? `${m}m` : m ? `${m}m ${s % 60}s` : `${s}s`
36}
37
38// Every modz mod places its tile in one shared band: a lead column (the bot), then a column of tiles, then an optional
39// right column. A column with no tiles is not drawn, and columns wrap under each other when the width runs out.
40const BAND = 'modz-band'
41const SLOTS: Record<string, 'lead' | 'left' | 'right'> = {
42  buddy: 'lead',
43  'usage-limits': 'left',
44  'cache-timer': 'left',
45  'model-info': 'left',
46  orchestrator: 'left',
47}
48const ORDER = Object.keys(SLOTS)
49const keyOf = (n: RenderNode) => (typeof n !== 'string' && n.type === 'Box' ? String(n.props?.key ?? '') : '')
50const rank = (n: RenderNode) => {
51  const i = ORDER.indexOf(keyOf(n))
52  return i < 0 ? ORDER.length : i
53}
54const pack = (Box: ElementConstructor<BoxProps>, below: RenderElement, tile: RenderElement) => {
55  const isEmpty = below.type === 'Box' && !below.children?.length
56  const tiles = keyOf(below) === BAND
57    ? (below.type === 'Box' ? below.children ?? [] : []).flatMap(col => (typeof col !== 'string' && col.type === 'Box' ? col.children ?? [] : [col]))
58    : isEmpty ? [] : [below]
59  const all = [...tiles, tile].sort((a, b) => rank(a) - rank(b))
60  const [lead, left, right] = (['lead', 'left', 'right'] as const).map(slot => all.filter(n => (SLOTS[keyOf(n)] ?? 'left') === slot))
61  return (
62    <Box key={BAND} flexDirection="row" flexWrap="wrap" columnGap={3}>
63      {lead!.length > 0 && <Box key="modz-lead" flexDirection="column" justifyContent="center">{lead}</Box>}
64      {left!.length > 0 && <Box key="modz-left" flexDirection="column" flexGrow={right!.length > 0 ? 1 : 0}>{left}</Box>}
65      {right!.length > 0 && <Box key="modz-right" flexDirection="column" alignItems="flex-end">{right}</Box>}
66    </Box>
67  )
68}
69
70
71// The newest main-thread response a transcript file holds, its time and token counts; null when the file is missing, over the
72// 4 MiB $.fs.read cap, or has none.
73type Row = { type?: string; isSidechain?: boolean; timestamp?: string; message?: { usage?: Partial<ModelUsage> } }
74const lastResponse = async ($: EngineInterface, path: string): Promise<Request | null> => {
75  const lines = await $.fs.read(path).then(text => text.split('\n').reverse(), () => [])
76  for (const line of lines) {
77    if (!line.includes('"type":"assistant"')) continue
78    const row = (() => { try { return JSON.parse(line) as Row } catch { return {} as Row } })()
79    const u = row.type === 'assistant' && !row.isSidechain ? row.message?.usage : undefined
80    const at = Date.parse(row.timestamp ?? '')
81    const request = { at, read: u?.cache_read_input_tokens ?? 0, write: u?.cache_creation_input_tokens ?? 0, fresh: u?.input_tokens ?? 0 }
82    if (u && at && request.read + request.write + request.fresh > 0) return request
83  }
84  return null
85}
86
87// A cache that /clear or a resume left behind, or a compaction rewrote, no longer says anything about the next request.
88const forget = ($: EngineInterface) => update($, last, () => null)
89
90export const register: Register = on => {
91  on('session.start', async ($, e, next) => {
92    const started = await next(e)
93    await $.command.register({ name: 'cache-ttl', description: 'Set how long the prompt cache stays warm: 5m or 1h', argumentHint: '5m | 1h' })
94    const ttl = (await $.store.get('ttlMin')) as number | undefined
95    if (ttl) await update($, ttlMin, () => ttl)
96    await update($, now, () => Date.now())
97    $.clock.every(TICK_MS, () => void update($, now, () => Date.now()))
98    return started
99  })
100
101  on('session.end', async ($, e, next) => {
102    if (e.reason === 'clear' || e.reason === 'resume') await forget($)
103    return next(e)
104  })
105
106  on('session.compact', async ($, e, next) => {
107    const compacted = await next(e)
108    if (e.trigger !== 'precompute' && e.agentId === undefined && !compacted.skip) await forget($)
109    return compacted
110  }).catch(($, e, next) => next(e))
111
112  // A resumed transcript's last response says how long ago the cache was last touched, which no other event carries. The
113  // transcript file gives its token counts too; a file too big to read falls back to the live window's counts when the engine
114  // has them, else only the countdown shows. Classic hooks do not run where an organization manages Claude Code, and there a
115  // resumed session shows the placeholders until its first request.
116  on('classic.SessionStart', async ($, e, next) => {
117    const started = await next(e)
118    if (e.source === 'resume' || e.source === 'fork') {
119      const found = await lastResponse($, e.transcript_path)
120      if (found) await update($, last, () => found)
121      else if (e.seconds_since_last_response !== undefined) {
122        const at = Date.now() - e.seconds_since_last_response * 1000
123        const u = await $.session.usage({ breakdown: 'summary' }).then(s => s.context.breakdown?.apiUsage, () => null)
124        await update($, last, () => ({ at, read: u?.cache_read_input_tokens ?? 0, write: u?.cache_creation_input_tokens ?? 0, fresh: u?.input_tokens ?? 0 }))
125      }
126      await update($, now, () => Date.now())
127    }
128    return started
129  }).catch(($, e, next) => next(e))
130
131  on('command.run', { command: 'cache-ttl' }, async ($, e) => {
132    const ttl = TTL_CHOICES[e.args.trim()]
133    const current = (await read($, ttlMin)) === 60 ? '1h' : '5m'
134    if (!ttl) return { text: `Cache ttl is ${current}. Use /cache-ttl 5m or /cache-ttl 1h.` }
135    await update($, ttlMin, () => ttl)
136    await $.store.set('ttlMin', ttl)
137    return { text: `Cache ttl set to ${e.args.trim()}.` }
138  })
139
140  on('turn.step', async function* ($, e, next) {
141    const result = yield* next(e)
142    const u = result.usage
143    if (e.agentId === undefined && u) {
144      const at = Date.now()
145      await update($, last, () => ({ at, read: u.cache_read_input_tokens, write: u.cache_creation_input_tokens, fresh: u.input_tokens }))
146      await update($, now, () => at)
147      if (u.cache_read_input_tokens > 0) await sparkle($)
148    }
149    return result
150  })
151
152  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
153    const below = await next(e)
154    if (e.props.hasSurvey) return below
155    const [r, , ttl, tw] = await Promise.all([read($, last), read($, now), read($, ttlMin), read($, twinkle)])
156    const { Box, Text } = $.ui.resolve(e)
157
158    const total = r ? r.read + r.write + r.fresh : 0
159    const hit = r && total ? Math.floor((r.read * 100) / total) : 0
160    const left = r ? r.at + ttl * 60_000 - Date.now() : 0
161    const isWarm = left > 0
162
163    return pack(Box, below, (
164      <Box key="cache-timer" flexDirection="row">
165        <Text>
166          <Text color={TINT}>{'cache'.padEnd(5)} </Text>
167          {r && total ? <Text bold color={hit >= 90 ? TINT : hit >= 70 ? 'warning' : 'error'}>{hit}%</Text> : <Text dimColor>–</Text>}
168          {tw > 0 && <Text color={TINT}> {SPARKLE[tw % SPARKLE.length]}</Text>}
169          <Text dimColor> · </Text>
170          {r ? <Text color={isWarm ? 'success' : 'error'}>{isWarm ? span(left) : `${span(-left)} ago`}</Text> : <Text dimColor>–</Text>}
171        </Text>
172      </Box>
173    ))
174  })
175}
176
types/index.d.ts 8 lines
1export type Request = { at: number; read: number; write: number; fresh: number }
2
3declare module 'claude-code' {
4  interface PluginState {
5    'cache-timer': { last: Request | null; now: number; ttlMin: number; twinkle: number }
6  }
7}
8